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 |
|---|---|---|---|---|---|
Master coders behave like architects that connect and build upon various design patterns to create a functional whole. One of the most important design patterns is a singleton—a class that has only one instance. You may ask: How does that look like? Let’s have a look at the code implementing a singleton in our interactive code shell:
Exercise: Try to create multiple instances of the singleton class. Can you do it?
Let’s dive into a deeper understanding of the singleton. We’ll discuss this code in our first method, so keep reading!
What’s a Singleton?
A singleton is a class that has only one instance. All variables for the class point to the same instance. It is simple and straight forward to create and use and it is one of the design patterns described by the Gang of Four. After creating the first instance, all other creations point to the first instance created. It also solves the problem of having global access to a resource without using global variables. I like this concise definition from Head First Design Patterns:
The Singleton Pattern ensures a class has only one instance, and provides a global point of access to it.
Why Would You Need a Singleton?
If you are reading this, you likely already have a possible use. Singleton is one of the Gang of Four’s Creational patterns. Read on to determine if its a good candidate for the problem you need to solve.
A singleton can be used to access a common resource like a database or a file. There is a bit of controversy on its use. In fact, the controversy could be described as outright singleton shaming. If that concerns you, I’ve listed some of the objections below with some links. In spite of all that, singletons can be useful and pythonic. From The Zen of Python (Pythonistas say Ohm):
- Simple is better than complex
- Practicality beats purity
Still the objections have merit and may apply to the code you are currently working on. And even if they don’t apply, understanding those objections may give you a better understanding of Object Oriented principals and unit testing.
A singleton may be useful to control access to anything that changes globally when it is used. In addition to databases and files, a singleton may provide benefit for access to these resources:
- Logger
- Thread pools
- caches
- dialog boxes
- An Http client
- handles to preference settings
- objects for logging
- handles for device drivers like printers.
- (?) Any single resource or global collection
A singleton can be used instead of using a global variable. Global variables are potentially messy. Singletons have some advantages over global variables. A singleton can be created with eager or lazy creation. Eager creation can create the resource when the program starts. Lazy creation will create the instance only when it is first needed. Global variables will use an eager creation whether you like it or not. Singletons do not pollute the global namespace.
And finally, a singleton can be a part of a larger design pattern. It may be part of any of the following patterns:
- abstract factory pattern
- builder pattern
- prototype pattern
- facade pattern
- state objects pattern If you have not heard of these, no worries. It won’t affect your understanding of the singleton pattern.
Implementation
The standard C# and Java implementations rely on creating a class with a private constructor. Access to the object is given through a method:
getInstance()
Here is a typical lazy singleton implementation in Java:
public Singleton { private static Singleton theOnlyInstance; private Singleton() {} public static Singleton getInstance() { if (theOnlyInstance) == null){ theOnlyInstance = new Singleton() } return new Singleton(); } }
There are many ways to implement Singleton in Python. I will show all four first and discuss them below.
Method 1: Use __new__
class Singleton: _instance = None def __new__(cls):
It uses the Python dunder
__new__ that was added to Python to provide an alternative object creation method. This is the kind of use case
__new__ was designed for
Pros:
- I believe this implementation is the closest in spirit to the GoF implementation. It will look familiar to anybody familiar with the standard Singleton implementation.
- Easy to understand code meaning is important for teams and maintenance.
- Uses one class to create and implement the Singleton.
Cons:
- In spite of its ‘correctness’ many python coders will have to look up
__new__to understand the object creation specifics. Its enough to know that
__new__instantiates the object.
- Code that normally goes in
__init__can be placed in
__new__.
- In order to work correctly the overridden
__new__must call its parent’s
__new__method. In this case, object is the parent. Instantiaion happens here with this line:
object.__new__(class_, *args, **kwargs)
Method 2: A Decorator
def singleton(Cls): singletons = {} def getinstance(*args, **kwargs): if Cls not in singletons: singletons[Cls] = Cls(*args, **kwargs) return singletons[Cls] return getinstance @singleton class MyClass: def __init__(self): self.val = 3 x = MyClass() y = MyClass() x.val = 42 x is y, y.val, type(MyClass)
Pros
- The code to write the decorator is separate from the class creation.
- It can be reused to make as many singletons as you need.
- The singleton decorator marks an intention that is clear and understandable
Cons
- The call
type(MyClass)will resolve as function.
- Creating a class method in
MyClasswill result in a syntax error.
If you really want to use a decorator and must retain class definition, there is a way. You could use this library:
pip install singleton_decorator
The library
singleton_decorator wraps and renames the singleton class. Alternately you can write your own. Here is an implementation:
def singleton(Cls): class Decorated(Cls): def __init__(self, *args, **kwargs): if hasattr(Cls, '__init__'): Cls.__init__(self, *args, **kwargs) def __repr__(self) : return Cls.__name__ + " obj" __str__ = __repr__ Decorated.__name__ = Cls.__name__ class ClassObject: def __init__(cls): cls.instance = None def __repr__(cls): return Cls.__name__ __str__ = __repr__ def __call__(cls, *args, **kwargs): if not cls.instance: cls.instance = Decorated(*args, **kwargs) return cls.instance return ClassObject() @singleton class MyClass(): pass x = MyClass() y = MyClass() x.val = 42 x is y, y.val
The output is:
(True, 42)
Interactive Exercise: Run the following interactive memory visualization. How many singleton instances do you find?
Method 3: Use Metaclass and Inherit From Type and Override __call__ to Trigger or Filter Instance Creation
class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] class MyClass(metaclass=Singleton): pass x = MyClass() y = MyClass() x.val=4 x is y, y.val
The output is as follows:
(True, 4)
Method 3 creates a new custom metaclass by inheriting from type. MyClass then assigns Singleton as its metadata:
class MyClass(metadata = Singleton):
The mechanics of the Singleton class are interesting. It creates a dictionary to hold the instantiated singleton objects. The dict keys are the class names. In the overridden
__call__ method,
super.__call__ is called to create the class instance. See custom metaclass to better understand the
__call__ method.
Pros
- Singleton code is separate. Multiple singletons can be created using the same
Cons
- Metaclasses remain mysterious for many python coders. Here is what you need to know:
- In this implementation, type is inherited:
class Singleton(type)
- In order to work correctly the overridden
__call__must call its parent’s
__call__method.
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
Method 4: Use a Base Class
class Singleton: _instance = None def __new__(class_, *args, **kwargs): if not isinstance(class_._instance, class_): class_._instance = object.__new__(class_, *args, **kwargs) return class_._instance class MyClass(Singleton): pass x = MyClass() y = MyClass() x.val=4 x is y, y.val
The output is as follows:
(True, 4)
Pros
- Code can be reused to create more singletons
- Uses familiar tools. (Compared to decorators, metaclasses and the
__new__method)
In all four methods, an instance is created the first time it is asked for one. All calls after the first return the first instance.
Singletons in a Threaded Environment
If your Singleton needs to operate in a multi-threaded environment, then your Singleton method needs to be made thread-safe. None of the methods above is thread-safe. The vulnerable code is found between the check of an existing Singleton and the creation of the first instance:
if cls._instance is None: cls._instance = super(Singleton, cls).__new__(cls)
Each implementation has a similar piece of code. To make it thread-safe, this code needs to be synchronized.
with threading.Lock(): if cls._instance is None: cls._instance = super(Singleton, cls).__new__(cls)
This works fine and with the lock in place, the Singleton creation becomes thread-safe. Now, every time a thread runs the code, the
threading.Lock() is called before it checks for an existing instance.
If performance is not an issue, that’s great, but we can do better. The locking mechanism is expensive and it only needs to run the first time. The instance creation only happens once so the lock should happen at most one time. The solution is to place the lock after the check statement. Then add another check after the lock.
import threading ... if cls._instance is None: with threading.Lock(): if cls._instance is None: cls._instance = super(Singleton, cls).__new__(cls)
And that is how to use “Double-checked locking“.
Thread-Safe Version of Method 1
Consider the following modification of method 1:
import threading class Singleton: _instance = None def __new__(cls): if cls._instance is None: with threading.Lock():
The output is:
(True, 42)
To make it thread-safe, we added two lines of code. Each method could be made thread-safe in a similar way
Alternatives to using a Singleton
Use a Module as a Singleton (The Global Object Pattern)
In Python, modules are single, unique, and globally available. The Global Object Pattern is recommended by the Python docs. It simply means to create a separate module and instantiate your object in the module’s global space. Subsequent references just need to import it.
Use Dependency Injection
Generally, this means using composition to provide objects to dependent objects. It can be implemented in countless ways but generally, put dependencies in constructors and avoid creating new instances of objects in business methods.
The Problems With Singletons
Of all 23 patterns in the seminal 1994 book Design Patterns, Singleton is the most used, the most discussed, and the most panned. It’s a bit of a rabbit hole to sift through the thousands of blogs and Stack Overflow posts that talk about it. But after all the Singleton hating, the pattern remains common. Why is that? It’s because conditions that suggest its use are very common: One database, one config file, one thread pool …
The arguments against its use are best stated in some elegant (and old) blog posts that I cannot match. But I will give a summary and links for further reading.
Concise Summary
Paraphrased from Brian Button in Why Singletons are Evil:
- They are generally used as a global instance, why is that so bad? Because you hide the dependencies of your application in your code, instead of exposing them through the interfaces. Making something global to avoid passing it around is a code smell. (That is some effective name-calling. Whatever code smell is, it makes me cringe just a bit and wrinkle my nose as I imagine it).
- no for unit tests. Why? Because each unit test should be independent from the other.
Should You Use Singletons in Your Code?
If you are asking yourself that based on the other peoples’ blogs, you are already in the rabbit hole. The word ‘should’ is not welcome in code design. Use singletons or not and be aware of possible problems. Refactor when there are problems.
Possible Problems to Consider
Tools are for people who know how to use them. In spite of all the bad stuff written about Singletons, people still use them because:
- They fill a need better than the alternatives.
and / or
- They don’t know any better and they are creating problems in their code by using them.
Avoid problems. Don’t be in group 2.
Problems with Singletons are caused because they break the single responsibility rule. They do three things:
- Guarantee only a single instance exists
- Provide global access to that instance
- Provide their own business logic.
- Because they break the single responsibility rule, Singletons may be hard to test
- Inversion of control IoC and dependency injection are patterns meant to overcome this problem in an object-oriented manner that helps to make testable code.
- Singletons may cause tightly coupled code. A global instance that has an inconstant state may require an object to depend on the state of the global object.
- It is an OO principal to Separate Creational Logic from Business Logic. Adhering to this principle “Singletons should never be used”. Again with the word should. Instead, Be Yoda: “Do or do not!“. Base the decision on your own code.
- Memory allocated to a Singleton can’t be freed. This is only a problem it the memory needs to be freed.
- In a garbage collected environment singletons may become a memory management issue.
Further Study
- Brandon Rhodes, The Singleton Pattern
- Miško Hevery, singleton I Love You-But You’re Bringing Me Down. Reposted with comments
- Miško Hevery, Singletons are Pathological Liars
- Miško Hevery, Where have all the singletons gone
- Wikipedia Singleton_pattern
- Michael Safayan, Singleton Anti-Pattern
- Mark Radford Singleton, the anti-pattern
- Alex Miller, Patterns I Hate #1: Singleton
- Scott Densmore/Brian Button, Why Singletons are Evil
- Martin Brampton, Well used singletons are GOOD!
- A discussion edited by Cunningham & Cunningham, Singleton Global Problems
- Robert Nystrom, Design Patterns Revisited: Singleton
- Steve Yegge, Singleton considered stupid
- J.B. Rainsberger Use your singletons wisely
Meta notes — Miško Hevery.
Hevery worked at Google when he wrote these blogs. His blogs were readable, entertaining, informative, provocative, and generally overstated to make a point. If you read his blogs, be sure to read the comments. Singletons are Pathological Liars has a unit testing example that illustrates how singletons can make it difficult to figure out dependency chains and start or test an application. It is a fairly extreme example of abuse, but he makes a valid point:
Singletons are nothing more than global state. Global state makes it so your objects can secretly get hold of things which are not declared in their APIs, and, as a result, Singletons make your APIs into pathological liars.
Of course, he is overstating a bit. Singletons wrap global state in a class and are used for things that are ‘naturally’ global by nature. Generally, Hevery recommends dependency injection to replace Singletons. That simply means objects are handed their dependencies in their constructor.
Where have all the singletons gone makes the point that dependency injection has made it easy to get instances to constructors that require them, which alleviates the underlying need behind the bad, global Singletons decried in the Pathological Liars.
Meta notes — Brandon Rhodes The Singleton Pattern
Python programmers almost never implement the Singleton Pattern as described in the Gang of Four book, whose Singleton class forbids normal instantiation and instead offers a class method that returns the singleton instance. Python is more elegant, and lets a class continue to support the normal syntax for instantiation while defining a custom
__new__()method that returns the singleton instance. But an even more Pythonic approach, if your design forces you to offer global access to a singleton object, is to use The Global Object Pattern instead.
Meta notes — J.B. Rainsberger Use your singletons wisely
Know when to use singletons, and when to leave them behind
J.B. Rainsberger
Published on July 01, 2001 Automated unit testing is most effective when:
- Coupling between classes is only as strong as it needs to be
- It is simple to use mock implementations of collaborating classes in place of production implementations
Singletons know too much
There is one implementation anti-pattern that flourishes in an application with too many singletons: the I know where you live anti-pattern. This occurs when, among collaborating classes, one class knows where to get instances of the other.
Towards acceptible singletons.
Meta notes — Mark Safayan Singleton anti pattern
Instead of using this pattern, simply instantiate a single instance and propagate it to places that use the object as a parameter to make the dependency explicit. | https://blog.finxter.com/how-to-create-a-singleton-in-python/ | CC-MAIN-2020-40 | refinedweb | 2,739 | 57.37 |
- Unresolved Externals errors when using external .lib file
- Name not declared
- FindFirstFile API searches for files based on long and short names
- Cannot set PasW field of crystal report table ???
- MS Visual Studio editing shortcuts
- VB.net grid printing
- Creating a strongly typed object from a basic serialized class
- How to Store values in Registry during Installation.
- Change Start menu and Recyclebin name
- Sqlconnection
- C# Using enum as type in Enum
- Accessing Form Elements through User Controls using AJAX
- Howto get error code from - [System.Net.WebException]?
- accessing same class methods in c#
- User Control in vb.net
- Using Web Services Vs Using Class Libraries
- how to connect a website to a different or another web application
- optional fields in web service structures
- a problem about datagridview scroll
- Creating Report
- Qualified elements in SOAP Body...
- stat doesn't work in vc.net 2003?
- Merging ASP and ASP.Net
- My system not getting shut down properly
- Dynamically adding columns in Crystal Report through C#.Net
- datatype in C#
- Null Web Service Request/Response
- How to catch message before it's sent to the Web Service
- questions
- .net xml file for Excel
- thread not closing
- Installatin problem
- Solution explorer
- Windows Service problems
- USB Detection
- VB.NET: USB Detection
- C Runtime Error R6034
- How to fire async events and c++/clr
- Reading "Long Text" from SQL Server
- standards
- Open WinExplorer from web application
- regexp bugs?
- VC++
- Strip useless whitespace from XML
- Printing with PrintDocument
- How to Access Web Service from VB6 with Intellisense in the IDE?
- C# DateTime
- How specify multiple style sheets for web forms?
- Scrollbars on User Controls
- Established connection aborted and underlying connection closed
- Declaring a user control as a parameter
- recuresivemethod on treview
- Best Practices
- Tool to monitor Web Service calls, data transfer...
- How do apps usually id the version of the cyrrently installed framework?
- DataSet WriteXML aborts
- xsl:Include e xsl:call-template
- xsl:Include e xsl:call-template
- vb.net printing w/o Crystal Reports
- High Memory usage Assembly.Evidence
- C# Allows To Create Structures???
- Access denied
- [X3D]Can anybody help me, pls?
- JIT Error
- Linking problems with managed/unmanaged classes
- Reg : Dynamic Report Creation
- Determine web setup folder and hide a Dialog
- Regarding User Control
- Regarding .net
- Changing skinId on custom ASP.net control HELP!
- Windows application can't exit
- Performance VC++ .NET vs. VC++ 6.0
- dr watson exception 80000007
- Data binding & mapping with XMLBeans
- VB.NET forms getting flicker
- FileGroupDescriptorW and FileContents data formats (C#)
- Processing soap requests without IIS
- DotNet Installer
- Use of machinekey.
- swaping datagrid rows
- problem with running .aspx files on remote server.Urgent help needed.
- Need help filtering dataset table by a value
- Change cursor...
- help me!
- How to make XslCompiledTransform transform &s; as XslTransform does
- copy data in tree into excel?
- Help for Godsake Help me!! How can we do Parsing of Hexdecimel in C# reading string
- WebServices Security...
- unique attribute value
- pass hyperlink1.text value with navigateurl property
- .NET XML Web Service interop
- Initialize DefaultPropertyAttribute for a Object property
- Attribute declaration, invalid schema
- recover missing format text
- C# networking question
- Setup Project (Deployment Project) More UI language
- Dropdownlist prob
- Remoting Server c# --- client c++ ?
- Get character by its number
- How to Display xml from a Database Column
- .Net Problem
- WSE 3.0 Security?
- Getting 'Installing' screen when starting an installed VB.NET app.
- Best practise of throwing errors and defining error contract
- VS2005,VB,BindingNavigator: programmatically moving to record
- New To VB.NET and WMP SDK and need some help
- xml xsd filling question
- How to view textdata or arraydata with crystal report with vb.net
- How to declare & use Global array Language: C#
- Binding control with more than one data source
- How to assign and enter a value in database corresponding to a combobox item.
- using namespace issues
- C++ managed class issue
- Tidy transforms "&" in the source-xml into a "&"
- running .net program without .net framework installation
- changing encoding
- How to eject a CDROM drive on network
- Need help on property hasChildren for WebBrowser class
- how to add and delete rows and columns in flexgrid in vb.net
- how???
- XML Data by Name instead of childNode Array?
- Simple weather view
- in vb.net how to add two projects.
- writing to the 32-bit registry from a 64-bit application (that darn WOW6432Node)
- app.config file
- MDI child form does not show MdiList property in VS2005
- Sunset Date for .NET 1.1 Support
- The application failed to initialize properly (0xc0000005)
- Why Listview ?
- xsl:with-param fails in XSL that accepts arguments from XML control
- What is the point of Google of allowing using importing RSS feeds?
- ManagementObjectSearcher("Select * from Win32_Printer")
- mc++ and pass by reference
- Help with writing select data
- Microsoft Asleep At The Wheel Again: Missing the New Era of CAD
- xsl totals composed from variables
- Swedish to English, Translating Error Messages
- Upload XML Files to Server
- Get List of File Names from specified Directory
- Problem with a XML schema
- Dynamically Load User Control
- How send the mail when user forgot the password
- Stable - Isolated PlugIn Server
- Access dot not web app from outside and inside firewall?
- please help on some general concepts on data c# 2.0 vs2005
- Extended Xlinks
- updater application closed immediatly while using app domain
- Getting at the SOAP exception message in VB.Net
- No transparent of DrawText method in pinvoke
- Sorting with Muenchian Method
- Calling a Web Service Asynchronously - .NET 2.0
- Web Services Compression techniques (PocketPC)
- XML Validation with multiple Schemas in .net
- Assigning Array variables to a list box
- VS.NET 2005: Debug: Go to calling function?
- Outlook 2k3
- Event Raising in Multithreading Environment
- How to specify the browser to use in HttpWebRequest
- help me for connecting MAXDB with Vb.NET
- 'Load Test' item not appearing in "Add New Test"
- vb.net graphs
- Updating a records in VB.net using OLEdb
- Ajax.dll no strong name
- PLZ PLZ Help Me with this : -->Thread Abort Errors in a class library
- ##Help me plz: 15 ComboBox on a form----how to refer to them in a For loop
- No value given for one or more required parameters.
- Cant open crystal report after I publish app. File not loaded and not found.
- Comparing two XML documents.
- Webservices, Class Libraries, and Syncronizing Namespaces
- LoadPostData and RaisePostBackEvent fire many times
- Net conversion from 2003 to 2005 problems...
- what is the difference in link button and Hyperlink
- Using wildcards with MS Access
- Is there a post load event for form?
- Vendor PechaKucha Night announced for XML 2006; hotel reservation deadline November 10
- Vendor PechaKucha Night announced for XML 2006; hotel reservation deadline November 10
- Subclassing
- Control Flow Graphs
- Sending a meeting request from ASP.net 2.0
- Format out put to 2 decimal places
- Error when opening deployed project
- using frames in vb.net
- using reflection to discover a nested structure
- Visual Studio Project Path
- SAX or DOM, graph proccesing
- The Newbie Here : )
- Prime Number Calculation - HELP
- how to obtain filename behind trace listener using TraceSource
- Access User Control from another User control in Winforms - C#
- Variables in XSLT
- More description on the web page - maybe a label?
- Min hardware/software req for a .NET app
- Need help making multiple groupings in a Crystal report
- XmlDataDocument as a datasource for a combobox
- Request.TotalBytes always 0
- Aspose.Excel File Failed to Download
- Visual Studio 6 and 2005 on the same computer - debug problem
- Implementing .h files/#defines in web-based app using c#
- .NET Projects and Code Search
- APPLICATION VS Session
- Help with TCPChannel
- Error Occured
- WTSOpenServer Windows 2000 Professional issue
- Web Service Security and Passing User Credentials
- Replay Attacks in Webservice
- Fast Image Display in C#.net 2005
- accessing same page in a Lan(pls help me out)
- facing problem to "Calling dotnet created Web Services in VB6"
- Calling webservice from 2.0 client
- wants to know about flex grid in vb.net
- Make string-array from checkboxlist
- controls naming in .NET 1.1
- Using stateserver.
- how to bind data to textboxes from database(sql server).
- How to Get Parent Object in case of compostion
- Regarding .Net Application communication with Servlet
- Which is Better DATASET OR DATAREADER
- Huge Floating Point Error
- Embedded Dundas Chart inside Crystal Report?
- Writing 32-bit Registry Keys (WOW6423Node) from 64-bit MSI installer
- Public Key Token
- Error trying to consume dataset from web service
- Beautiful women, aged clones, and Ultimate Fighting Championship
- Web service for FILENET
- How to access files' version numbers on remote servers -WMI, .Net
- Large unexpected memory alloc when intializing jagged array with nullptr
- Databinding to a property on an object that implements IEnumerable
- Transoforming XML via XSLT into a string?
- select nodes with child node A and child node B
- sharedListeners config in app.config file doesn't recognize customlocation attribute
- WHy is C# so much slower than c++???
- how to use web method
- combo control is very slow
- VS 2005 VB.Net Namespace in Multiple files
- .Net 1.1 to 2.0 Issue?
- Create an Unknown Number of ArrayLists
- wrapping a shell around another application
- populate a datagridview from objects
- Get Project System Reference List?
- How/where to store my encoded HTML? In DB? In XML?
- Any advice on how to implement this elegantly?
- preprocessing ASP.NET tags generated by the XML Control
- VB.NET: Sql Syntax
- Code for forgot password in C#.
- Accessing web service -- passing parameters..
- Question about design
- DropDownList Problem
- Stored Procedures and Crystal Reports for .NET 2003
- DropDownList Refuses To Show New SelectedValue
- losing attributes on postback
- losing attributes on postback
- NULL dates show today's date rather than a blank or NULL on form
- CreateElement question
- Sockets: BeginReceiveFrom callback not working (VB.NET)
- XHTML replaced by XML ?
- mixed dll loading problem
- Unable to debug
- still with my ListView issue
- windows XP unable to connect to afp sites
- Conditionally link a library
- ISO Currency code - existing enum in .NET ?
- Security question about IIS and Cassini
- execution behaviour
- Accessing data from a class in main form(program)
- HDC to IntPtr
- Restricting xml schema datatypes by relation?.
- MSI WindowsInstaller.Installer List of products
- MSI WindowsInstaller.Installer List of products
- Cannot run exe to debug DLL in VS.NET 2003 - Unable to start debugging. Unable to start program. - Why???
- Exporting ative type compiled with /CLR
- End process from Task Manager using programming?
- PLs Help
- Msbuild
- Client found response content type of 'text/html', but expected 'text/xml'.
- onBlur vs onChange for <asp:textbox>
- Conditional check of a value inserted by user while installation
- pls help me out
- Dataset and XML
- ListView and property
- Listview and WM_PAINT
- hash_map question
- Deployment Language Pack
- How to build a setup update, that does not uninstall the older version
- Read Wav file & FFT
- Dll is Not Registering propoerly
- Visual Studio
- Design Time Attributes for an user control
- VB.NET: Can't connect to MS SQLserver with Novell
- Need help on WSE2.0 soap attachment
- My program sometimes can't exit normally
- Log4net vs Enterprise Library - Logging Application Block 2.0
- Anyone know how to do CR reports in VS 2005?
- Compress dataset returned from Web Service
- correct notation for parameterized query in TableAdapter??
- Compress dataset returned from Web Service
- Passing XML to web service?
- Beautiful women, aged clones, and Ultimate Fighting Championship
- Web Services configuration
- FTPWebRequest - connection attempts are "flakey" - fails first call, then works
- How to pull the namespaces to the serailized XML Fragment using Xalan-C++ API
- invalid token error
- adding web reference error
- RE: Custom Install/User Interface problem
- System Tray Application
- Web Service Deployment
- Using gernerics Predicate<T> in C++/CLI
- Change directory in Visual Studio .NET Command Prompt
- How can I use GridView or DetailsView to Bind to a DataSet
- dll problem,help me:)
- about dll problem,thank:)
- DLL problems / .NET solutions (?)
- Display from database using multiline text box..How to?
- How to bind datagrid
- xsl:with-param problem under Weblogic 8.1
- Dispaly specific sections of xml document
- Connection from asp.net application to SQL Server 2000 blocked byfirewall
- Screenshots of ActiveX controls in .NET
- Paypal & asp.net
- crystal report toolbar does not display well in my web application project
- ASP.Net Problem
- Converting .Net1.1 app to .Net2.0 app resulted in loss of CLR 2.0 and more
- Building XmlSampleGenerator.dll howto
- post into xslt to change the outcome
- HELP! Printing PDFs in duplex mode.
- Calculate attributes with XSLT
- problem with Path.IsPathRooted when passing just a volume name?
- computer name
- computer name
- good .net 1.1 to .net 2.0 book
- acessing and retrieving contacts from exchange server
- optional attributes
- session variables incrementing with a master page
- How to Change Local Machine IP Address without rebooting the machine using VB.Net
- Cannot Display PDF Retrieved From Sql Server BLOB
- issue with #include
- issue with #include
- HELP The program is in a invalid format, and cannot be run
- XmlValidatingReader in v1.1
- Report Viewer
- Shorthand for namespaces
- key board problem
- How to update a table in VB.net using oledbconnection
- Unique "in use by another process" problem - maybe
- Problem with Embedded Resources (Sound File)
- 2005 Break on Exception in WebService
- what is best way to talk to https webpages within .net? any good librarys for talking to https websites?
- what is best way to talk to https webpages within .net? any good librarys for talking to https websites?
- Freeze datagrid header in windows form
- Deserializing xml into an object using xsl:copy-of
- .NET Remote Debugging
- Mail goes to queue folder
- menu on a tree view node
- wsdl.exe problem
- How do you Manage Production and Development Versions of Applications
- PrintDocument speed is slow
- Custom Interface Screen
- String to complex problem using VB 2005
- ContextMenuStrip and submenus - virtual impossibility??? huh?
- Copying structure to string and back
- Build dynamic context menus for trees
- Windows Media Player
- SmartNavigation and AutoPostBack
- OnDrawColumnHeader and LIstView
- VB6 Soap and .Net web services
- Run Set up
- Error with parameter. Why?
- XsdObjectGen.ex vs Xsd.exe for .NET 2.0 usage
- Run a program on a remote PC with WMI
- How to write XML with any name and type?
- Known File-types Previewer
- Static initializers with option /CLR in dlls
- Edit control balloon tooltip blanks Winforms controls (MFC/.net mi
- Treeview, is there a way to build one dynamically with SQL Data?
- Overhand a function pointer from managed to unmanaged
- Printing Forms having scrollbars
- I have problem dos character set with VB.NET
- remove exceptions
- saving a webpage programatically
- c# Clipboard question
- Need help for Remoting!!
- image Processing
- Excel file to my own XML file in C# 2003
- Problem with Process.GetCurrentProcess() when starting a service
- Web access Failed
- Is it possible to extend system search?
- Is it possible to extend system search?
- differnece b/w Throw; and Throw ex ; where ex is Expection Object
- GDI+ Help Needed in VB.Net
- Event Handling with UserControls
- Schemas, imports and namespaces
- Installation problem VB.net 2005 (windows app)
- 2 XML nodes, 1 xslt
- 'ResourcePool' is not supported on the current platform
- fast user switching on xp
- How to run a Background Job ?
- .NET Installer error
- Scalability questions....
- Form Threads
- Update SQL Table Data using DataGrid
- Missing Libraries names
- Adding Web Reference
- Best approach for Custom ListView
- How i can check my application on lan before uploading
- stl list's const_itertor problem
- Blank Hard drive - How to install Operating System?
- Dynamic form control properties
- Splitting a String
- Use dll created in dotnet using them from vb6
- Resize Window
- Title bar
- Application.StartupPath counterpart in ASP.NET
- Getting the physical path of network drive.
- Can be multiple instances of element used as the root element?
- Unable to delete current record from bindingnavigator
- rowchanged event in datagrid.
- Are DateTime datatypes worth the aggravation?
- How to run the C# Windows application as windows services?
- Passing a keyboard event to an other control
- disable mainmenu merge vb2003
- Graph control
- visual source safe problem
- Yahoo Finance
- trouble passing function pointer
- connect vb.net to maxdb
- WebService and UserControl doesn't work
- How to write array of strings on a binary file
- ListView and GetHeaderCtrl
- settopbox
- Marshal Char** parameter in C function using PInvoke [C#.Net]
- Packaging and Deployment
- Accessing a singleton class from a windows service
- Need help populating crystal report with data from dataset
- Urgent Printing in pocket pc
- Updating a larger site how does it work?
- Printform issues
- XML, XSL and ASP.NET
- Raising an alert
- Export Data to Ms Excel 2000
- An unhandled non-continuable exception was thrown during process load
- Problem with parsing OLEOBJect in .net
- Printing a word as binary
- Assistance please with getting pages to talk to each other
- XML documentation in unmanaged C++
- C# TcpChannel ??
- Removing Certain warning
- Can I fake a parent element in a serializable class
- Invoke and assembly references/folders
- Can I fake a parent element in a serializable class
- Insert one value in my XSLT code
- wsdl.exe - problem with array of complex types
- namespace relative path trouble..
- Can I fake a parent element in a serializable class?
- get 800401f3 if pinvoke, but not in C call on xp only
- Removing Certain warning
- Compact framework woes
- how to set restriction attributes in wsdl file?
- Send XML without SOAPEnvelope wrapper?
- Insert one value in my XSLT code
- Insert one value in my XSLT code
- form design question
- Efficient Queue in C#
- Create a windows-like Service in CF using C#?
- (VB.Net) Using GroupBox
- C#: Problem with communicating via serial port
- Problems when ExecuteReader()
- Receive Error: Unable to Read Data From The Transport Connection
- export database data and some user input to customized xml format using.NetWebService
- export database data and some user input to customized xml format using.NetWebService
- C# to C++.Net conversion
- Need to set datagrid column to readonly based on values
- Project Web Access problems with Tablet PC
- help me! how to store data from excel using vb.net
- XSLT extracting certain descendants to higher level outside of ancestor
- question related to sockets
- Get current logged-in user
- Giving a program permisions
- is C++ a dot net language
- how to use ocx in vc++.net
- XSLT transform of XHTML page content in Internet Explorer
- Using POST method
- handling events of a derived class
- ReadElementContentAsXXX
- Using BSTR's in C#
- Attribute targetNamespace does not match the designated namespace
- operation has timed-out
- Creating a PDF File from .Net
- DataGridView copy and paste rows?
- Calling c# dll's from command line & invoking its methods
- Windows Service Security Problem
- converting html file to pdf file
- Internationalisation
- WSDL to SOAP
- How to Get the Icons That Are Associated with Files in VC.NET
- xml in C#.net
- Difference Between odbcdatareader and odbcdataadapter
- dynamic crystal report generation
- Colspan problem
- [reporting services] Parameters via a web service
- Problem in connectin string
- How to intercept all outgoing SQL Queries?
- A question of style
- Adding text to an image dynamically
- line numbers for datagrid
- C# UserControl for VB6 use
- Sequencing installation
- How mail send through cdosys.dll
- SAX Processing Time
- How to load jpeg file in SqL2000 and how to retrieve from SQL2000.
- get excel cell data to VB.net
- vc is faster, no?
- saving xml in javascript
- Merging two VB.NET projects
- Losing all previous preprocessor symbols when adding one
- XMLSerialization - Do I need it?
- Using LastIndexOf w/ Structure Stored in ArrayList
- Asynchronous Problem in web application
- Reading a checkbox in a Gridview TemplateField.
- XmlTextReader ReadChars can enter an infinate loop when reading st
- xml intellisense
- WSDL.exe & results containing complexType arrays
- Displaying jpegs from SQL Server in a report
- Serialize XML with Qualified or Prefixed Root Element
- incident tracking software
- Problem with MFC extension DLL, threads, and .Net loader lock
- Hover effects, IMessageFilter not working as expected
- the find in a dataview???
- the find in a dataview???
- Pass CString and byte array from native C++ to managed C++
- Converting an array to a buffer
- Finding memory leaks in VB.Net
- *Update a parent from the child
- Operation has timed-out vs IIS Connection Timeout
- C# - Unable to set Rtf property of RichTextBox control
- questions: .NET on other platforms?
- IIS missing Web Service Extensions node
- ObjectDataSources and Web Services
- Identify Which Desktop an App is Running On
- VB.NET: backspace button code?
- Display Image On A Web Page
- cannot load spreadsheet to a StoreFrontdatabase but can do it one item at a time.
- .net
- can excel itselfs export a column to a notepad?
- XML Schema??
- Shortcuts in Code Window
- How to do this
- Http Adapter
- Custom Http Adapter ?
- what is the Factory Rule in .net
- objects in session | https://bytes.com/sitemap/f-312-p-70.html | CC-MAIN-2019-43 | refinedweb | 3,399 | 55.84 |
No, but when I open it in Dependency Walker it doesn't show any functions, and my calling code can't find them either.
I created a new "Class Library" project (VS 2013) and then installed "Unmanaged Exports (DllExport for .Net)" from NuGet. Are there any project settings I need?
Here is my code.
using System; using System.Collections.Generic; using System.Text; using RGiesecke.DllExport; namespace ToolServiceDLL { public class Class1 { [DllExport("addUp", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)] public static double addUp(double num1, double num2) { return num1 + num2; } [DllExport("get5", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)] public static int get5() { return 5; } } }
I found the problem. It has it in the RGiesecke Documentation, but I missed it. In the project settings->Build->Platform target: you can not have it set to "Any CPU". You must have it set to x64 or x86 depending on if you want to use it in a a 64 or 32 bit application.
No,� The .dll builds fine and the CPU match (x86), but the unmanaged program can't get the export function address once the c# dll has been loaded. Its pretty basic right now, but I'm just trying to get it to work. I'll need the imports later on. Any help please, the documentation for the nuget package is quite thin. Thanks
I had a similar problem, but had already set the platform target to x64 and had the following error:
The name 'CallingConvention' does not exist in the current context
I found adding the using directive
System.Runtime.InteropServices resolve the problem.
C# unmanaged DLL Export / Import in C++, Consume Managed C# DLL from Unmanaged C++ EXE - Cannot start the The error you reported states the linker is looking for the function export with You can not do the way you are doing now. Text; using RGiesecke. No functions in C# DLL with RGiesecke.DllExport. 4. Passing data between Python and C# without writing a file. 0. How to call a C# code from python. 2.
This is a good question and worked for me. Just took a bit more time than it should due to the Python side where I made a mistake. Here is the working code in Python3
import sys
import clr
sys.path.insert(0,'C:\\your_path\\Py2NetComm\\bin\\Debug')
clr.AddReference("Py2NetComm")
import ToolServiceDLL as p2n
ret = p2n.Class1.addUp(2,3)
print("addUp:", ret)
DllExport not creating an entry point - c# - csharp, DllExport not creating an entry point - c#. InteropServices; using RGiesecke. NET project that loads TestApi.dll and invokes an exported DLL function The� Yes, it is possible to export functions from a C# dll in much the same way that C++ does it! You need a little help from an add-in Unmanaged Exports (DllExport for .Net) that facilitates this process, or from a similar method such as Exporting functions in C#/VB.NET to native code.
RGiesecke dll Export template - c# - csharp, RGiesecke dll Export template - c#. if I try to register the dll with Regsvr32 I get and error telling me there is no dll entry point. I don't C# Dll - export functions.
DllExport 1.7.3, Quick start: Examples. Unmanaged C++ / C# / Java: 🧪 Demo:� The C# Dll Code runs well without errors and creats me a AddDll.lib and AddDll.dll file. I would like to import this Dll in C++: // CallAdd.h #pragma once #define DllImport __declspec(dllimport) namespace AddDll { class MyAddDll { public: static DllImport double Add(double a, double b); }; }
Call C# DLL from C++ application, object of abstract class type 'ManagedDLL::ICalculator' is not allowed Class1 using System; using RGiesecke. My C# dll function is static and declared as: [ DllExport(ExportName = "GetNumber", CallingConvention = CallingConvention. Fixes to the .lib creation (export names had the real method name in the .lib, not the one that DllExport contained, while the DLL itself exported it correctly) nicer Icon TargetFramework is no longer set to 3.5 but left empty for the IDE to decide what makes sense (VS2005 obviously has no clue about this setting).
- It does not create a DLL, it modifies a DLL. So that did not happen. One nasty trap is that the Nuget package will not install correctly when you don't run VS elevated, failure is silent. Right-click the VS shortcut and select "Run as Administrator".
- I am running as Admin, and it shows "RGiesecke.DllExport.Metadata" in the References. How do I tell if it tries to modify the dll? | https://thetopsites.net/article/56179684.shtml | CC-MAIN-2021-25 | refinedweb | 750 | 67.45 |
#include <sys/ddi.h> int stoi(char **str);
void numtos(unsigned long num, char *s);
Solaris DDI specific (Solaris DDI).
Pointer to a character string to be converted.
Decimal number to be converted to a character string.
Character buffer to hold converted decimal number.
The stoi() function returns the integer value of a string of decimal numeric characters beginning at **str. No overflow checking is done. *str is updated to point at the last character examined.
The numtos() function converts a long into a null-terminated character string. No bounds checking is done. The caller must ensure there is enough space to hold the result.
The stoi() function returns the integer value of the string str.
The stoi() function can be called from user, interrupt, or kernel context.
Writing Device Drivers for Oracle Solaris 11.2
The stoi() function handles only positive integers; it does not handle leading minus signs. | https://docs.oracle.com/cd/E36784_01/html/E36886/numtos-9f.html | CC-MAIN-2018-09 | refinedweb | 150 | 61.02 |
I can’t remember where I learnt this, but I use it all the time and it’s not at all obvious.
When in the minibuffer (at the prompt for
replace-string or
replace-regexp, for example), enter
C-q C-j for a newline (
0x0D,
NL).
Depending on the coding system for the buffer (DOS mode for example), you may also need to use
C-q C-m for carriage return (
0x0D,
CR) – suddenly it makes sense where all those
^Ms come from!
I seem to have faced the same problem more times than losing my keys or running out of toilet paper.
I don’t use emacs but so I use the command dos2unix. Finding a command that performs the inverse I’ll leave as a fun exercise for the reader.
Of course real men use tr.
I’m pretty sure emacs and most decent text editors will auto-detect line endings and do the right thing. And don’t get me started on text editors that insert a Byte Order Mark.
but | http://blench.org/wordpress/2011/10/06/emacs-how-to-search-and-replace-newlines/ | CC-MAIN-2018-05 | refinedweb | 175 | 78.59 |
This tutorial shows you how run a simple application built with TypeORM..
Step 4. Update the connection parameters
Open the
ormconfig.ts file, and edit the ORM configuration parameters:
- Replace the value for
portwith the port to your cluster.
- Replace the value for
usernamewith the user you created earlier.
- Replace the value for
passwordwith the password you created for your user.
At the top of the file, uncomment the
import * as fs from "fs";line.
This line imports the
fsNode module, which enables you to read in the CA cert that you downloaded from the CockroachCloud Console.
Replace the value for
hostwith the name of the CockroachCloud Free host (e.g.,
host: 'free-tier.gcp-us-central1.cockroachlabs.cloud').
Replace the value for
portwith the port to your cluster.
Replace the value for
usernamewith the user you created earlier.
Replace the value for
passwordwith the password you created for your user.
Replace the value for
databasewith the database that you created earlier, suffixed with the name of the cluster (e.g.,
database: '{cluster_name}.bank').
Remove the
ssl: truekey-value pair.
Remove the
extraobject and its contents.
Uncomment the
sslobject with the
cakey-value pair, and edit the
fs.readFileSync('certs/cc-ca.crt').toString()call to use the path to the
cc-ca.crtfile that you downloaded from the CockroachCloud Console.
Step 5. Run the code
Open a terminal window, and install the Node.js pg driver:
$ npm install pg --save
Navigate to the top directory of the application project (e.g.,
hello-world-typescript-typeorm), and initialize the project:
$ npm i
Start the application:
$ npm start
You should see the following output in your terminal:
Inserting a new account into the database... Saved a new account. Printing balances from account 1. Account { id: 1, balance: 1000 } Inserting a new account into the database... Saved a new account. Printing balances from account 2. Account { id: 2, balance: 250 } Transferring 500 from account 1 to account 2. Transfer complete. Printing balances from account 1. Account { id: 1, balance: 500 } Printing balances from account 2. Account { id: 2, balance: 750 }
What's next?
Read more about using the TypeORM.
You might also be interested in the following pages: | https://www.cockroachlabs.com/docs/v21.1/build-a-typescript-app-with-cockroachdb | CC-MAIN-2021-31 | refinedweb | 366 | 60.41 |
This chapter focuses on technical solutions to set up popular deep learning frameworks. First, we provide solutions to set up a stable and flexible environment on local machines and with cloud solutions. Next, all popular Python deep learning frameworks are discussed in detail:
Â
- Setting up a deep learning environment
- Launching an on Amazon Web Services (AWS)
- Launching an on Google Cloud Platform (GCP)
- Installing CUDA and cuDNN
- Installing Anaconda and libraries
- Connecting with Jupyter Notebook
The recent advancements in deep learning can be, to some extent, attributed to the advancements in computing power. The increase in computing power, more specifically the use of GPUs for processing data, has contributed to the leap from shallow neural networks to deeper neural networks. In this chapter, we lay the groundwork for all following chapters by showing you how to set up stable environments for different deep learning frameworks used in this cookbook. There are many open source deep learning frameworks that are used by researchers and in the industry. Each framework has its own benefits and most of them are supported by some big tech company.
By following the steps in this first chapter carefully, you should be able to use local or cloud-based CPUs and GPUs to leverage the recipes in this book. For this book, we've used Jupyter Notebooks to execute all code blocks. These notebooks provide interactive feedback per code block in such a way that it's perfectly suited for storytelling.
The download links in this recipe are intended for an Ubuntu machine or server with a supported NVIDIA GPU. Please change the links and filenames accordingly if needed. You are free to use any other environment, package managers (for example, Docker containers), or versions if needed. However, additional steps may be required.Â
Before we get with training deep learning models, we need to set up our deep learning environment. While it is possible to run deep learning models on CPUs, the speed achieved with GPUs is significantly higher and necessary when running deeper and more complex models.
- First, you need to check whether you have to a CUDA-enabled NVIDIA GPU on your local machine. You can check the overview atÂ.
- If your GPU is listed on that page, you can continue installing
CUDAand
cuDNNif you haven't done that already. Follow the steps in the Installing CUDA and cuDNN section.
- If you don't have to an NVIDIA GPU on your local machine, you can decide to use a cloud solution. Follow the steps in the Launching a cloud solution section.
Amazon Web Services (AWS) is the most cloud solution. If you don't have access to a local GPU or if you prefer to use a server, you can set up an EC2 on AWS. In this recipe, we provide steps to launch a GPU-enabled server.
Before we move on with this recipe, we assume that you already have an account on Amazon AWS and that you are familiar with its platform and the accompanying costs.
- Make sure the region you want to work in gives access to P2 or G3 instances. These instances include NVIDIA K80 GPUs and NVIDIA Tesla M60 GPUs, respectively. The K80 GPU is faster and has more GPU memory than the M60 GPU: 12 GB versus 8 GB.Â
Note
While the NVIDIA K80 and M60 GPUs are powerful GPUs for running deep learning models, these should not be considered state-of-the-art. Other faster GPUs have already been launched by NVIDIA and it takes some time before these are added to cloud solutions. However, a big advantage of these cloud machines is that it is straightforward to scale the number of GPUs attached to a machine; for example, Amazon's p2.16xlarge instance has 16 GPUs.
- There are two when launching an AWS instance. Option 1: You build everything from scratch. Option 2: You use a preconfigured Amazon Machine Image (AMI) from the marketplace. If you choose option 2, you will have to pay costs. For an example, see this AMI atÂ.
- Amazon provides a and up-to-date overview of steps to launch the deep learning AMI atÂ.
- If you want to build the server from scratch, launch a P2 or G3 instance and follow the steps under the Installing CUDA and cuDNN and Installing Anaconda and Libraries recipes.
- Always make sure you stop the running instances when you're done to prevent unnecessary costs.Â
Another popular cloud provider is Google. Its Google Cloud Platform (GCP) is getting more and has as a major benefitâit includes a newer GPU type, NVIDIA P100, with 16 GB of GPU memory. In this recipe, we provide the steps to launch a GPU-enabled compute machine.
- You need to request an increase in the GPU quota before you launch a compute instance with a GPU for the first time. Go toÂ.
- First, select the project you want to use and apply the
Metricand
Regionfilters accordingly. The GPU instances should show up as follows:
Figure 1.1: Google Cloud Platform dashboard for increasing the GPU quotas
- Select the quota you want to change, click on EDIT QUOTAS, and follow the steps.
- You will get an e-mail confirmation when your quota has been increased.
- Afterwards, you can create a GPU-enabled machine.
- When launching a machine, make sure you tick the Allow HTTP traffic and Allow HTTPs traffic boxes if you want to use a Jupyter notebook.Â
This part is if you want to leverage GPUs for deep learning. The CUDA toolkit is specially designed for GPU-accelerated applications, where the compiler is optimized for using math operations. In addition, the
cuDNN libraryâshort for CUDA Deep Neural Network libraryâis a library that accelerates deep learning routines such as convolutions, pooling, and activation on GPUs.
Make sure you've registered for Nvidia's Accelerated Computing Developer Program at before starting with this recipe. Only after will you have access to the files needed to install the
cuDNN library.Â
- We start by downloading NVIDIA with the following command in the terminal (adjust the download link accordingly if needed; make sure you use 8 and not 9 for now):
curl -O
- Next, we unpack the file and update all all packages in the package lists. Afterwards, we remove the downloaded file:
sudo dpkg -i cuda-repo-ubuntu1604_8.0.61-1_amd64.deb sudo apt-get update rm cuda-repo-ubuntu1604_8.0.61-1_amd64.deb
- Now, we're ready to install CUDA with the following command:
sudo apt-get install cuda-8-0
- Next, we need to set the environment variables and add them to the shell script
.bashrc:
echo 'export CUDA_HOME=/usr/local/cuda' >> ~/.bashrc echo 'export PATH=$PATH:$CUDA_HOME/bin' >> ~/.bashrc echo 'export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$CUDA_HOME/lib64' >> ~/.bashrc
- Make sure to reload the shell script afterwards with the following command:
source ~/.bashrc
- You can check whether the 8.0 driver and toolkit are correctly using the following commands in your terminal:
nvcc --version nvidia-smi
The output of the last command should look something like this:
Figure 1.2: Example output of nvidia-smi showing the connected GPU
- Here, we can see that an NVIDIA P100 GPU with 16 GB of memory is correctly connected and ready to use.Â
- We are now ready to install
cuDNN. Make sure the NVIDIA
cuDNNfile is available on the machine, for example, by copying from your local machine to the server if needed. For Google cloud compute engine (make sure you've set up
gcloudand the project and zone are set up correctly), you can use the following command (replace local-directory and instance-name with your own settings):
gcloud compute scp local-directory/cudnn-8.0-linux-x64-v6.0.tgz instance-name
- First we the file before copying to the right as root:
cd tar xzvf cudnn-8.0-linux-x64-v6.0.tgz sudo cp cuda/lib64/* /usr/local/cuda/lib64/ sudo cp cuda/include/cudnn.h /usr/local/cuda/include/
- To clean up our space, we can remove the files we've used for installation, as follows:
rm -rf ~/cuda rm cudnn-8.0-linux-x64-v5.1.tgz
One of the most popular environment managers for users is Anaconda. With Anaconda, it's straightforward to set up, switch, and delete environments. Therefore, one can run Python 2 and Python 3 on the same machine and switch between different installed versions of installed libraries if needed. In this book, we purely focus on Python 3 and every recipe can be run within one environment:
environment-python-deep-learning-cookbook.
- You can directly download the installation file for Anaconda on your machine as follows (adjust your Anaconda file accordingly):
curl -O
- Next, run the bash script (if necessary, adjust the filename accordingly):
bash Anaconda3-4.3.1-Linux-x86_64.sh
Follow all prompts and choose 'yes' when you're asked to to add the PATH to the
.bashrc file (the default is 'no').
- Afterwards, reload the file:
source ~/.bashrc
- Now, let's set up an Anaconda environment. Let's start with copying the files from the GitHub repository and opening the directory:
git clone cd Python-Deep-Learning-Cookbook-Kit
- Create the environment with the following command:
conda env create -f environment-deep-learning-cookbook.yml
- This creates an named
environment-deep-learning-cookbook and installs all libraries and dependencies included in the
.ymlfile. All used in this book are included, for example, NumPy, OpenCV, Jupyter, and scikit-learn.Â
- Activate the environment:
source activate environment-deep-learning-cookbook
- You're now ready to run Python. Follow the next recipe to install Jupyter and the deep learning frameworks used in this book.
As mentioned in the introduction, Notebooks have gained a lot of traction in the last couple of years. Notebooks are an intuitive tool for running blocks of code. When creating the Anaconda environment in the Installing Anaconda and Libraries recipe, we included Jupyter in our list of libraries to install.Â
- If you haven't installed Jupyter yet, you can use the following command in your activated Anaconda environment on the server:
conda install jupyter
- Next, we move back to the terminal on our local machine.
- One option is to access the Notebook running on a server using SSH-tunnelling. For example, when using Google Cloud Platform:
gcloud compute ssh --ssh-flag="-L 8888:localhost:8888" --zone "europe-west1-b" "instance-name"
You're now logged in to the server and port
8888 on your local machine will forward to the server with port
8888.
- Make sure to activate the correct Anaconda environment before proceeding (adjust the name of your environment accordingly):
source activate environment-deep-learning-cookbook
- You can create a dedicated directory for your Jupyter notebooks:
mkdir notebooks cd notebooks
- You can now start the Jupyter environment as follows:
jupyter notebook
This will start Jupyter Notebook on your server. Next, you can go to your local browser and access the notebook with the link provided after starting the notebook, for example,.
One of the mostâif not the mostâpopular frameworks at the moment is TensorFlow. The framework is created, maintained, and used internally by Google. This general open source framework can be used for any numerical computation by using data flow graphs. One of the biggest advantages of using is that you can use the same code and deploy it on your local CPU, GPU, or device. TensorFlow can also be used to run your deep learning model across multiple GPUs and CPUs.
- First, we will show how to install from your terminal (make sure that you adjust the link to the wheel for your and Python accordingly):
pip install --ignore-installed --upgrade
This will install the GPU-enabled version of TensorFlow and the correct dependencies.
- You can now import the TensorFlow library into your Python environment:
import tensorflow as tf
- To provide a dummy dataset, we will use
numpyand the following code:
import numpy as np x_input = np.array([[1,2,3,4,5]]) y_input = np.array([[10]])
- When defining a TensorFlow model, you cannot feed the data directly to your model. You should create a placeholder that acts like an entry point for your data feed:
x = tf.placeholder(tf.float32, [None, 5]) y = tf.placeholder(tf.float32, [None, 1])
- Afterwards, you apply some operations to the placeholder with some variables. For example:
W = tf.Variable(tf.zeros([5, 1])) b = tf.Variable(tf.zeros([1])) y_pred = tf.matmul(x, W)+b
- Next, define a loss function as follows:
loss = tf.reduce_sum(tf.pow((y-y_pred), 2))
- We need to specify the optimizer and the variable that we want to minimize:
train = tf.train.GradientDescentOptimizer(0.0001).minimize(loss)
- In TensorFlow, it's important that you initialize all variables. Therefore, we create a variable called
init:
init = tf.global_variables_initializer()
We should note that this command doesn't initialize the variables yet; this is done when we run a session.
- Next, we create a session and run the training for 10 epochs:
sess = tf.Session() sess.run(init) for i in range(10): feed_dict = {x: x_input, y: y_input} sess.run(train, feed_dict=feed_dict)
- If we also want to extract the costs, we can do so by adding it as follows:
sess = tf.Session() sess.run(init) for i in range(10): feed_dict = {x: x_input, y: y_input} _, loss_value = sess.run([train, loss], feed_dict=feed_dict) print(loss_value)
- If we want to use multiple GPUs, we should specify this explicitly. For example, take this part of code from the TensorFlow documentation:
c = [] for d in ['/gpu:0', '/gpu:1']:) # Creates a session with log_device_placement set to True. sess = tf.Session(config=tf.ConfigProto(log_device_placement=True)) # Runs the op. print(sess.run(sum))
As you can see, this gives a lot of flexibility in how the computations are handled and by which device.
Note
This is just a brief introduction to how TensorFlow works. The granular level of model implementation gives the user a lot of flexibility when implementing networks. However, if you're new to neural networks, it might be overwhelming. That is why the Keras framework--a wrapper on top of TensorFlowâcan be a good alternative for those who want to start building neural networks without getting too much into the details. Therefore, in this book, the first few chapters will mainly focus on Keras, while the more advanced chapters will include more recipes that use other frameworks such as TensorFlow.
Keras is a deep learning framework that is known and adopted by deep learning engineers. It provides a wrapper around the TensorFlow, CNTK, and the Theano frameworks. This wrapper you gives the ability to easily create deep learning models by stacking different types of layers. The power of Keras lies in its simplicity and readability of the code. If you want to use multiple GPUs during training, you need to set the devices in the same way as with TensorFlow.
- We start by installing Keras on our local Anaconda environment as follows:
conda install -c conda-forge keras
Make sure your deep learning environment is activated before executing this command.
- Next, we import
keraslibrary into our Python environment:
from keras.models import Sequential from keras.layers import Dense
This command outputs the used by Keras. By default, the TensorFlow framework is used:
Figure 1.3: Keras prints the backend used
- To provide a dummy dataset, we will use
numpyand the following code:
import numpy as np x_input = np.array([[1,2,3,4,5]]) y_input = np.array([[10]])
- When using sequential mode, it's straightforward to stack multiple layers in Keras. In this example, we use one hidden layer with 32 units and an output layer with one unit:
model = Sequential() model.add(Dense(units=32, input_dim=x_input.shape[1])) model.add(Dense(units=1))
- Next, we need to compile our model. While compiling, we can set different settings such as
lossfunction,
optimizer, and
metrics:
model.compile(loss='mse', optimizer='sgd', metrics=['accuracy'])
- In Keras, you can easily print a summary of your model. It will also show the number of parameters within the defined model:
model.summary()
In the following figure, you can see the summary of our build model:
Figure 1.4: Example of a Keras model summary
- Training the model is straightforward with one command, while simultaneously saving the results to a variable called
history:
history = model.fit(x_input, y_input, epochs=10, batch_size=32)
- For testing, the prediction function can be used after training:
pred = model.predict(x_input, batch_size=128)
Note
In this short introduction to Keras, we have demonstrated how easy it is to implement a neural network in just a couple of lines of code. However, don't confuse simplicity with power. The Keras framework provides much more than we've just demonstrated here and one can adjust their model up to a granular level if needed.
PyTorch is the Python deep learning framework and it's getting a lot of traction lately. PyTorch is the implementation of Torch, which uses Lua. It is by Facebook and is fast thanks to GPU-accelerated tensor computations. A huge benefit of using over other frameworks is that graphs are created on the fly and are not static. This means networks are dynamic and you can adjust your network without having to start over again. As a result, the graph that is created on the fly can be different for each example. PyTorch supports multiple GPUs and you can manually set which computation needs to be performed on which device (CPU or GPU).
- First, we install in our Anaconda environment, as follows:
conda install pytorch torchvision cuda80 -c soumith
If you want to install on another platform, you can have a look at the PyTorch website for clear guidance:Â.
- Let's import PyTorch into our Python environment:
import torch
- While Keras provides higher-level abstraction for building neural networks, PyTorch has this feature built in. This means one can build with higher-level building blocks or can even build the forward and backward pass manually. In this introduction, we will use the higher-level abstraction. First, we need to set the size of our random training data:
batch_size = 32 input_shape = 5 output_shape = 10
- To make use of GPUs, we will cast the tensors as follows:
torch.set_default_tensor_type('torch.cuda.FloatTensor')
This ensures that all computations will use the attached GPU.Â
- We can use this to generate random training data:
from torch.autograd import Variable X = Variable(torch.randn(batch_size, input_shape)) y = Variable(torch.randn(batch_size, output_shape), requires_grad=False)
- We will use a simple neural network having one hidden layer with 32 units and an output layer:
model = torch.nn.Sequential( torch.nn.Linear(input_shape, 32), torch.nn.Linear(32, output_shape), ).cuda()
We use the
.cuda() extension to make sure the model runs on the GPU.Â
- Next, we the MSE loss function:
loss_function = torch.nn.MSELoss()
- We are now ready to start training our model for 10 epochs with the following code:
learning_rate = 0.001 for i in range(10): y_pred = model(x) loss = loss_function(y_pred, y) print(loss.data[0]) # Zero gradients model.zero_grad() loss.backward() # Update weights for param in model.parameters(): param.data -= learning_rate * param.grad.data
Note
The PyTorch framework gives a lot of freedom to implement simple neural networks and more complex deep learning models. What we didn't demonstrate in this introduction, is the use of dynamic graphs in PyTorch. This is a really powerful feature that we will demonstrate in other chapters of this book.
Microsoft also introduced its open source deep framework not too long ago: Microsoft Cognitive Toolkit. This framework is better known as CNTK. is written in C++ for performance reasons and has a Python API. CNTK supports GPUs and multi-GPU usage.Â
- First, we install
CNTKwith
pipas follows:
pip install
Adjust the wheel file if necessary (seeÂ).Â
- After installing CNTK, we can import it into our Python environment:
import cntk
- Let's create some simple dummy data that we can use for training:
import numpy as np x_input = np.array([[1,2,3,4,5]], np.float32) y_input = np.array([[10]], np.float32)
- Next, we need to define the placeholders for the input data:
X = cntk.input_variable(5, np.float32) y = cntk.input_variable(1, np.float32)
- With CNTK, it's straightforward to stack multiple layers. We stack a dense layer with 32 inputs on top of an output layer with 1 output:
from cntk.layers import Dense, Sequential model = Sequential([Dense(32), Dense(1)])(X)
- Next, we define the loss function:
loss = cntk.squared_error(model, y)
- Now, we are ready to finalize our model with an optimizer:
learning_rate = 0.001 trainer = cntk.Trainer(model, (loss), cntk.adagrad(model.parameters, learning_rate))
- Finally, we can train our model as follows:
for epoch in range(10): trainer.train_minibatch({X: x_input, y: y_input})
The MXNet deep learning framework you to build efficient deep learning models in Python. Next to Python, it also let you build models in popular languages as R, Scala, and Julia. Apache MXNet is supported by Amazon and Baidu, amongst others. MXNet has proven to be fast in benchmarks and it supports GPU and multi-GPU usages. By using lazy evaluation, MXNet is able to automatically execute operations in parallel. Furthermore, the MXNet frameworks uses a symbolic interface, called Symbol. This simplifies building neural network architectures.
- To install MXNet on Ubuntu with GPU support, we can use the command in the terminal:
pip install mxnet-cu80==0.11.0
For other platforms and non-GPU support, have a look at.
- Next, we are ready to import
mxnetin our Python environment:
importmxnetasmx
- We create some simple dummy data that we assign to the GPU and CPU:
import numpy as np x_input = mx.nd.empty((1, 5), mx.gpu()) x_input[:] = np.array([[1,2,3,4,5]], np.float32) y_input = mx.nd.empty((1, 5), mx.cpu()) y_input[:] = np.array([[10, 15, 20, 22.5, 25]], np.float32)
- We can easily copy and adjust the data. Where possible MXNet will automatically execute operations in parallel:
x_input w_input = x_input z_input = x_input.copyto(mx.cpu()) x_input += 1 w_input /= 2 z_input *= 2
- We can print the output as follows:
print(x_input.asnumpy()) print(w_input.asnumpy()) print(z_input.asnumpy())
- If we want to feed our data to a model, we should create an iterator first:
batch_size = 1 train_iter = mx.io.NDArrayIter(x_input, y_input, batch_size, shuffle=True, data_name='input', label_name='target')
- Next, we can create the symbols for our model:
X = mx.sym.Variable('input') Y = mx.symbol.Variable('target') fc1 = mx.sym.FullyConnected(data=X, name='fc1', num_hidden = 5) lin_reg = mx.sym.LinearRegressionOutput(data=fc1, label=Y, name="lin_reg")
- Before we can start training, we need to define our model:
model = mx.mod.Module( symbol = lin_reg, data_names=['input'], label_names = ['target'] )
- Let's start training:
model.fit(train_iter, optimizer_params={'learning_rate':0.01, 'momentum': 0.9}, num_epoch=100, batch_end_callback = mx.callback.Speedometer(batch_size, 2))
- To use the trained model for prediction we:
model.predict(train_iter).asnumpy()
Note
We've shortly introduced the MXNet framework. In this introduction, we've demonstrated how easily one can assign variables and computations to a CPU or GPU and how to use the Symbol interface. However, there is much more to explore and the MXNet is a powerful framework for building flexible and efficient deep learning models.
The newest addition to the range of deep learning frameworks is Gluon. Gluon is recently launched by AWS and Microsoft to provide an API simple, easy-to-understand code without the loss of performance. Gluon is already included in the latest release of MXNet and will be available in future releases of CNTK (and other frameworks). Just like Keras, Gluon is a wrapper around other deep learning frameworks. The main difference between Keras and Gluon, is that Gluon will (at first) focus on imperative frameworks.Â
- At the moment,
gluonis included in the latest release of MXNet (follow the steps in Building efficient models with MXNet to install MXNet).Â
- After installing, we can directly import
gluonas follows:
from mxnet import gluon
- Next, we create some dummy data. For this we need the data to be in MXNet's NDArray or Symbol:
import mxnet as mx import numpy as np x_input = mx.nd.empty((1, 5), mx.gpu()) x_input[:] = np.array([[1,2,3,4,5]], np.float32) y_input = mx.nd.empty((1, 5), mx.gpu()) y_input[:] = np.array([[10, 15, 20, 22.5, 25]], np.float32)
- With Gluon, it's really straightforward to build a neural network by stacking layers:
net = gluon.nn.Sequential() with net.name_scope(): net.add(gluon.nn.Dense(16, activation="relu")) net.add(gluon.nn.Dense(len(y_input)))
- Next, we initialize the parameters and we store these on our GPU as follows:
net.collect_params().initialize(mx.init.Normal(), ctx=mx.gpu())
- With the following code we set the loss function and the optimizer:
softmax_cross_entropy = gluon.loss.SoftmaxCrossEntropyLoss() trainer = gluon.Trainer(net.collect_params(), 'adam', {'learning_rate': .1})
- We're ready to start training or model:
n_epochs = 10 for e in range(n_epochs): for i in range(len(x_input)): input = x_input[i] target = y_input[i] with mx.autograd.record(): output = net(input) loss = softmax_cross_entropy(output, target) loss.backward() trainer.step(input.shape[0])
Note
We've shortly demonstrated how to implement a neural network architecture with Gluon. Gluon is a powerful extension that can be used to implement deep learning architectures with clean code. At the same time, there is almost no performance loss when using Gluon.
 | https://www.packtpub.com/product/python-deep-learning-cookbook/9781787125193 | CC-MAIN-2020-40 | refinedweb | 4,251 | 56.55 |
Paul worked for a branch of the Defence Department in Australia, writing reams of C++ using the standard template libraries on a Linux box. On a typical afternoon, Paul checked some code into CVS with a comment:
Fixed bug 7551, see issue report 2119. Tinky Winky is my favourite Teletubby.
The addendum continued a long-running inside joke. At this point, the weird check-in comments were only funny because they were applied so consistently.
“Hey Paul, come over here a second!”
Paul’s friend and fellow developer Stan had initiated an impromptu gathering around his desk. Once Paul joined the huddle, Stan turned back to his computer screen. “I’m getting sick of these warning messages. You know, the ones our compiler throws because our namespace names are longer than 256 characters? I have trouble finding the real errors around these things. Do any of you know how to shut them off?”
Paul also has a lovely red purse.
“I do,” Paul said. “Here, let me show you what I’ve done.”
Paul supplied the name of a header file he’d been working on recently, then pointed to a line near the top. “See that pragma statement? It’ll suppress those warnings during compile time.”
// We don't need these stupid warning messages PMJ #pragma warning( disable : 4507 34 )
“Oh, cool. I’ll try that,” Stan said. “Thanks, Paul!”
Life went on.
The trouble started a few weeks later, during a code review. Paul was asked to attend as an impartial reviewer for a project he had no involvement with. When he sat down in the meeting room, Burt the project manager was already there, giving him narrowed eyes.
“Paul,” Burt began, “are your initials PMJ?”
Paul frowned. “Yes… why?”
“The research scientists on my team are complaining that the word ‘stupid’ appears at the start of almost every header file.”
“What does this have to do with me?” Paul asked.
“Well, you’ve been touching all this code.” Burt brought up a Word document on his laptop, which was projected onto a screen in the meeting room. “I compiled some samples the scientists showed me. This right here, for instance…”
Paul blinked at the offending screenshot, which displayed the following two lines:
// We don't need these stupid warning messages PMJ #pragma warning( disable : 4507 34 )
“Oh! That’s just code for suppressing warning messages during compile time,” Paul said. “I wasn’t the one who put it in here. One of the other developers must’ve copied and pasted it in wholesale.”
“‘Stupid?’” Burt demanded and accused all at once.
“That’s just a comment. It doesn’t actually do anything.”
“It makes the scientists angry,” Burt snapped. “It’s inappropriate- and it’s everywhere! They’re questioning the entire code base and the quality of our in-house software! I think we should take this offline for further discussion.” His glowering lifted as more project members filtered into the room for the code review.
A few days later, Paul was roped into a meeting with Burt, his own boss, and a very offended research scientist.
“Stupid! Do you think national defense is stupid?” the scientist fumed. “Do you think I’m too stupid not to notice? What good is the code in that stupid file, anyway?”
“I didn’t touch all those files,” Paul tried to explain.
“You initialed every line!” the scientist cried.
“Check CVS. I wasn’t the one checking in those changes!” Paul returned. “And who cares anyway, it’s just a stupid comment! It doesn’t do anything!”
“Again with the stupid! It reflects an attitude that is rude and demoralizing. How would you like it if I called your work stupid? Oh wait, I see you already did!”
“Let’s calm down here,” Paul’s boss intervened. “Paul, you said it’s a comment, right? Taking it out won’t change the behavior?”
“No, course not.”
“Well, then that means it’d be no problem for you to remove the word ‘stupid’ wherever it appears in the code base- right?” His boss smiled with the glow of a self-assured master diplomat.
It turned out Paul’s fellow developers had copied the warning suppression code to hundreds of files. Paul wrote a shell script that nuked all occurrences of the offending word and his initials, which he ran during a couple of code base merges when he had everything checked out.
Disaster averted- or so Paul thought. Paul’s boss reared his head again a few days later, frowning. “Is Tinky Winky really your favorite Teletubby? If you think you had too many meetings about ‘stupid’, think about how many I had. You’d better edit the log.” | http://thedailywtf.com/articles/a-stupid-comment | CC-MAIN-2018-05 | refinedweb | 788 | 77.43 |
Appendix A
c and d
Windows XP Professional supports ClearType, a new text display technology that triples the horizontal resolution available for rendering text through software. This feature provides a clearer text display on an LCD screen with digital interface.
Shortcuts, 60 days
The Fast User Switching feature allows multiple users to share a computer without requiring each user to close all running applications and log off before another user can log on to the computer.
6.0
The Compatible Hardware and Software feature provides you with current and comprehensive hardware and software compatibility information so that you can feel confident that your upgrade recommendation will be correct.
Use My Computer Properties. Click Start, and then click Help And Support. In the Help And Support Center window, under Pick A Task, click Use Tools To View Your Computer Information And Diagnose Problems. Under Tools, click My Computer Information, and then click View General System Information About This Computer. Under Specifications the BIOS version is listed.
The Windows Help system uses HTML to format and display information, so with an Internet connection, you can search for every occurrence of a word or phrase across all Windows compiled HTML Help files.
In the Help And Support Center window, under Pick A Task, click Use Tools To View Your Computer Information And Diagnose Problems. Under Tools, click My Computer Information, and then click View Advanced System Information. Under What Do You Want To Do, click View Computer Information For Another Computer. The View Remote Computer - Web Page dialog box appears, which allows you to specify the path to the remote computer for which you want to view information. When you are viewing the information on the remote computer, click Find Information About The Hardware Installed On This Computer to determine the model and driver for the network adapter. Repeat this process for all computers in the workgroup.
a and d
A domain controller is a computer running Windows 2000 Server that is configured as a domain controller so that it can manage all security-related aspects of user and domain interactions.
Directory, Active Directory service
Domain
When you log on locally to a computer, you can access the appropriate resources on that computer and you can perform specific system tasks. What you can do when logged on locally to a computer is determined by the access token assigned to the user account you used to log on. The access token is your identification for that local computer; it contains your security settings. These security settings allow you to access specific resources on that computer and to perform specific system tasks.
When you log on locally to a computer, its security subsystem uses the local security database to authenticate the user name and password you entered. When you log on to a domain, a domain controller uses the directory to authenticate the user name and password you entered.
You use the User Accounts program located in Control Panel to configure Windows XP Professional to display the Log On To Windows dialog box. The User Accounts program contains the Change The Way Users Log On Or Off task that you use.
a, b, and d
a and c
The minimum amount of memory required to install Windows XP Professional is 64 MB, and the recommended amount of memory is 128 MB.
a
On the Microsoft Web site at
a, c, and d
a and d
63 characters
Yes. To change the computer name after installation is complete, click Start, click My Computer, click View System Information, click the Computer Name tab, and then click Change.
b and c
a, b, c, and d
There are four components. The Client for Microsoft Networks allows your computer to access network resources. File and Printer Sharing for Microsoft Networks allows other computers to access file and print resources on your computer. The QoS Packet Scheduler helps provide a guaranteed delivery system for network traffic, such as TCP/IP packets. The TCP/IP is the default networking protocol that allows your computer to communicate over LANs and WANs.
b, c, and d
a
WINNT32.EXE with the /checkupgradeonly switch
/noreboot
/makelocalsource
a and c
Upgrade your computer to Windows 98 first, and then upgrade to Windows XP Professional.
b and c
Use the Windows XP Professional Compatibility tool.
a and d
First, verify that a domain controller is running and online, and then verify that the server running the DNS service is running and online. If both servers are online, verify that the network adapter card and protocol settings are correctly set and that the network cable is plugged into the network adapter card.
Use a different CD-ROM. (To request a replacement CD-ROM, contact Microsoft or your vendor.) You can also try using a different computer and CD-ROM drive. If you can read the CD-ROM on a different computer, you can do an over-the-network installation.
Only on the computer on which the local user account is created.
You should create it on one of the domain controllers. You should not use local user accounts on Windows XP Professional computers that are part of a domain.
a and b
b and d
Click Start, click Control Panel, and then click User Accounts. In the User Accounts window, click the Guest icon. In the What Do You Want To Change About The Guest Account window, click Turn Off The Guest Account. The Guest Account is now disabled.
20
They are valid as long as they are not on the same computer. In fact, in a workgroup, you must create the same user account on each computer in the workgroup that you want the user to be able to access.
128, 8
a and c
b and c
The User Accounts window appears.
What type of account is User3?
The account type for User3 is Limited Account.
How does the password appear on the screen? Why?
The password is displayed as asterisks as you type. This prevents others from viewing the password as you enter it.
What happens?
A Logon Message dialog box appears, informing you that you are required to change your password at first logon.
c and d
a and c
a and d
Account Disabled
What happens? Why?
A User Accounts dialog box appears with the message Windows Cannot Change The Password. You set the User Cannot Change Password option for User1.
Never, because the Account Is Locked Out check box is unavailable when the account is active and is not locked out of the system. The system locks out a user if the user exceeds the limit for the number of failed logon attempts.
b and d
a and b
c and d
First, you must create and share a folder in which to store all home folders on a network server. Second, for the shared folder, remove the default Full Control permission from the Everyone group and assign Full Control to the Users group for users that will reside in this shared folder. Third, provide the path to the user's home folder in the shared home directory folder in the Profile tab of the Properties dialog box for the user account.
A group is a collection of user accounts. A group simplifies administration by allowing you to assign permissions and rights to a group of users rather than to each individual user account.
Permissions
On the computer on which the local group is created
c and d
a and b
a and c
Built-in local groups give rights to perform system tasks on a single computer, such as backing up and restoring files, changing the system time, and administering system resources. Some examples of built-in local groups are Administrators, Backup Operators, Guests, Power Users, Replicator, and Users.
Built-in system groups do not have specific memberships that you can modify, but they can represent different users at different times, depending on how a user gains access to a computer or resource. You do not see system groups when you administer groups, but they are available for use when you assign rights and permissions to resources. Some examples of built-in system groups are Everyone, Authenticated Users, Creator Owner, Network, Interactive, Anonymous Logon, and Dialup.
Application, transport, Internet, and network interface. The protocols that map to the application layer allow applications to gain access to the network. The protocols that map to the transport layer provide communication sessions between computers. The protocols that map to the Internet layer encapsulate packets into Internet datagrams and run all the necessary routing algorithms. The protocols that map to the network interface layer put frames on the wire and pull frames off the wire.
c and d
b and d
IGMP maps to the Internet layer and provides multicasting.
Multicasting is the process of sending a message simultaneously to more than one destination. IP multicast traffic is sent to a single MAC address but is processed by multiple hosts.
TCP and UDP
a and c
There is a pause while Windows XP Professional attempts to locate a DHCP server on the network.
What message appears, and what does it indicate?
The message is as follows: An error occurred while renewing interface Local Area Connection: The semaphore timeout period has expired. This error message indicates that Windows XP Professional could not renew the TCP/IP configuration.
Is this the same IP address assigned to your computer in Exercise 3? Why or why not?
No, this is not the same IP address assigned to the computer in Exercise 3. It is not the same address because this address is assigned by the Windows XP Professional Automatic Private IP Addressing.
Were you successful? Why or why not?
No, you would not be successful. Your computer has an address assigned by Automatic Private IP Addressing and the test computer is on a different subnet.
You can assign static IP addresses if there are no DHCP servers on the network, or you can use the Automatic Private IP Addressing feature. You should assign a static IP address to selected network computers, such as the computer running the DHCP Service. The computer running the DHCP Service cannot be a DHCP client, so it must have a static IP address.
b and c
A subnet mask blocks out part of the IP address so that TCP/IP can distinguish the network ID from the host ID.
True
b and c
The default gateway might be missing or incorrect. You specify the default gateway in the Internet Protocol (TCP/IP) Properties dialog box (in the Network And Internet Connections dialog box under Network Connections). Other possibilities are that the default gateway is offline or the subnet mask is incorrect.
Automatic Private IP Addressing of Windows XP Professional has assigned your computer Pro1. This means that the local DHCP server is not configured properly or cannot be reached from your computer.
Windows XP Professional displays the Select Network Protocol dialog box.
What protocols can you install?
Network Monitor Driver and NWLink IPX/SPX/NetBIOS Compatible Transport Protocol. Network Monitor Driver enables Network Monitor to receive frames (also called packets) from the local network adapter. You can use the frames to detect and troubleshoot problems on LANs.
What type of frame detection is selected by default?
Auto Detect
What other frame types are listed?
Ethernet 802.2, Ethernet 802.3, Ethernet II, and Ethernet SNAP
Why is the Network Number option now active?
Each frame type configured on a network adapter card requires a network number.
What is the network number and frame type for the LAN?
The network number is 00000000 and the frame type is 802.2. Answers may vary.
Although the NWLink implementation in Windows XP Professional can automatically select a frame type for IPX/SPX-compatible protocols, it can automatically detect only one frame type. This network uses two frame types. To resolve the problem, you must manually configure the additional frame type (802.3).
On the client, start a command prompt. At the command prompt, type command and then click OK to open a command prompt. In the Run dialog box, type ipxroute config and then press Enter. Verify that the network number and frame type in the Network and Frame columns are correct for your installation.
a, b, and d
c
The Advanced Settings dialog box appears.
What is the order of the protocols listed under Client For Microsoft Networks?
The NWLink IPX/SPX/NetBIOS Compatible Transport Protocol was the last protocol installed, so it is the first one listed. Internet Protocol (TCP/IP) is listed second.
Binding is the process of linking network components on different levels to enable communication between those components.
You specify the binding order to optimize network performance. For example, a computer running Windows XP Professional has both TCP/IP and NWLink IPX/SPX installed. However, most of the servers to which this computer connects are running only TCP/IP. You would adjust the binding order so that the workstation binding to TCP/IP is listed before the workstation bindings for NWLink IPX/SPX. In this way, when a user attempts to connect to a server, Client for Microsoft Networks first attempts to establish the connection using TCP/IP.
A network component can be bound to one or more network components above or below it. This is important because the services that each component provides can be shared by all other components that are bound to it. For example, a network adapter card can be bound to more than one network protocol at a time.
NDIS provides the capability to bind multiple protocols to multiple network adapter card drivers. The version in Windows XP Professional is 5.1.
DNS is a naming system that is used in TCP/IP networks to translate computer names to IP addresses. DNS makes it easy to locate computers and other resources on IP-based networks.
a and d
b and d
Zones; zone
A forward lookup query is the resolving of a user-friendly DNS domain name to an IP address. To resolve a forward lookup query, a client passes a lookup query to its local name server. If the local name server can resolve the query, it returns the IP address for the name so the client can contact it. If the local name server cannot resolve the query, it passes the query on to one of the DNS root servers. The DNS root server sends back a referral to a name server that can resolve the request. The local name server sends the request to the name server it was referred to by the DNS root server. An IP address is returned to the local name server and the local name server sends the IP address to the client.
b and d
c and d
A HOSTS file is a manually maintained local file that contains host-to-IP address and NetBIOS-to-IP name resolution. You use a HOSTS file for networks without access to a DNS name server to provide host-to-IP address and NetBIOS-to-IP name resolution for applications and services.
c and d
a, b, and c
This option allows you to specify a list of domains to try when there is a query for an unqualified name. Queries are limited to the domains that you listed.
Active Directory
A directory service is a network service that identifies all resources on a network and makes them accessible to users and applications.
Active Directory organizes resources hierarchically in domains. The domain is the basic unit of replication and security in a Windows 2000 network. All domain controllers in a domain are peers, so you can make changes to any domain controller, and the updates are replicated to all other domain controllers in the domain.
Active Directory simplifies administration by providing a single point of administration for all objects on the network, so an administrator can log on to one computer and administer objects on any computer in the network.
DNS
Grouping resources logically enables you to find a resource by its name rather than its physical location. Because you group resources logically, Active Directory makes the network's physical structure transparent to users.
object
d
Forest; domain trees
b
Domain controllers; sites
The Active Directory schema defines objects that can be stored in Active Directory. The schema is a list of definitions that determines the kinds of objects and the type of information about those objects that can be stored in Active Directory.
a and b
DN
GUID
In a contiguous namespace, the name of the child object in an object hierarchy always contains the name of the parent domain. A tree is a contiguous namespace. In a disjointed namespace, the names of a parent object and of a child of the same parent object are not directly related to one another. A forest is a disjointed namespace.
Local printers
No. A print server is a computer that manages one or more printers on a network. The print server receives and processes documents from client computers. If you have a computer running Windows XP Professional and it has a shared printer attached to it, it is by definition a print server. However, if the print server will manage many heavily used printers, Microsoft recommends a dedicated print server and most dedicated print servers run one of the Windows Server products.
b
Printer driver
a, b, c, and d
b and d
c and d
The default printer is the printer used for all Windows-based applications. You would select this option so that you do not have to set a printer for each application. The first time that you add a printer to the print server, this option does not appear because the printer is automatically selected as the default printer.
The first time that you add a printer to a computer, this option does not appear. The printer is automatically selected as the default printer.
b and c
b and d
By default, all users can connect to that printer.
a, b, c, and d
a, b, and d
a and d
The Find Printers feature is not available in the Search Assistant unless you are logged on to a Windows 2000 domain. If you are using a stand-alone computer or one that is in a workgroup, the Find Printers component is not available.
Sharing a printer allows other users on the network to use the printer. In a network with a high volume of printing, it decreases the time that documents wait on the print server. It simplifies administration because you can administer multiple printers simultaneously.
In the Properties dialog box for the printer, in the Sharing tab, click Share Name and type in a share name.
b and c
Creating virtual printers that print to the same physical printer and varying the printer priority allows you to set priorities among groups of documents that all print on the same physical printer. Users can send critical documents to a high-priority virtual printer and noncritical documents to a lower priority virtual printer. The critical documents always print first, even though there is only one physical printer.
Click Start, click Control Panel, and click Printers And Other Hardware. In the Printers And Other Hardware window, under Troubleshooters, click Printers. The Help And Support Services window appears with the printing troubleshooter displayed.
Verify that all print devices in the printer pool are identical or that they use the same printer driver.
Try defragmenting the print server's disk and check that there is adequate space for temporary files on the hard disk.
There might not be enough memory to print the document, so consider adding memory to the print server. The printer might not have enough toner, so try replacing the printer's toner cartridge.
Managing printers, managing documents, troubleshooting printers, and performing tasks that require the Manage Printers permission
Permissions
a
a
b and d | http://etutorials.org/Microsoft+Products/microsoft+windows+xp+professional+training+kit/Appendix+A+-+Questions+and+Answers/ | CC-MAIN-2017-30 | refinedweb | 3,328 | 54.12 |
How to Build a Fullstack App with Next.js, Prisma, and PostgreSQL
Create a fullstack application with Next.js, Prisma, PostgreSQL, and deploy to Vercel.
Prisma is a next-generation ORM that can be used to acccess a database in Node.js and TypeScript applications. In this guide, you'll learn how to implement a fullstack sample blogging application using the following technologies:
- Next.js as the React framework
- Next.js API routes for server-side API routes as the backend
- Prisma as the ORM for migrations and database access
- PostgreSQL as the database
- NextAuth.js for authentication via GitHub (OAuth)
- TypeScript as the programming language
- Vercel for deployment
You'll take advantage of the flexible rendering capabilities of Next.js by using Static-Site Generation (SSG) and Server-Side Rendering (SSR) where it makes sense. At the end, you will deploy the app to Vercel.
Prerequisites
To successfully finish this guide, you'll need:
- Node.js
- A PostgreSQL Database (set up a free PostgreSQL database on Heroku)
- A GitHub Account (to create an OAuth app)
- A Vercel Account (to deploy the app)
Step 1: Set up your Next.js starter project
Navigate into a directory of your choice and run the following command in your terminal to set up a new Next.js project:
npx create-next-app --example blogr-nextjs-prisma
Create and download the starter project from the repo into a new folder.
You can now navigate into the directory and launch the app:
cd blogr-nextjs-prisma && npm run dev
Start the Next.js application at.
Here's what it looks like at the moment:
Current state of the application.
The app currently displays hardcoded data that's returned from
getStaticProps in the
index.ts file. Over the course of the next few sections, you'll change this so that the data is returned from an actual database.
Step 2: Set up Prisma and connect your PostgreSQL database
For the purpose of this guide, you'll use a free PosgtreSQL database hosted on Heroku. Follow the steps in this guide to create one.
Alternatively, you can also use a local PostgreSQL database. However, once you reach the deployment step of this guide, you'll need a hosted database so that it can be accessed from the application when it's deployed on Vercel.
Next, you will set up Prisma and connect it to your PostgreSQL database. Start by installing the Prisma CLI via npm:
npm install prisma --save-dev
Install the Prisma CLI.
Now, you can use the Prisma CLI to bootstrap a basic Prisma setup using the following command:
npx prisma init
Initialize Prisma inside your application.
This creates the following files inside a new
prisma directory:
schema.prisma: Your main Prisma configuration file that will contain your database schema
.env: A dotenv file to define the database connection URL and other sensitive info as environment variables
Open the
.env file and replace the dummy connection URL with the connection URL of your PostgreSQL datababase. For example, if your database is hosted on Heroku, the URL might look as follows:
// .env DATABASE"
An example of your Database connection URL string.
Step 3. Create your database schema with Prisma
In this step, you'll create the tables in your database using the Prisma CLI.
Add the following model definitions to your
schema.prisma so that it looks like this:
// schema.prisma datasource db { provider = "postgresql" url = env("DATABASE_URL") } generator client { provider = "prisma-client-js" } model Post { id Int @default(autoincrement()) @id title String content String? published Boolean @default(false) author User? @relation(fields: [authorId], references: [id]) authorId Int? } model User { id Int @default(autoincrement()) @id name String? email String? @unique createdAt DateTime @default(now()) @map(name: "created_at") updatedAt DateTime @updatedAt @map(name: "updated_at") posts Post[] @@map(name: "users") }
The Prisma schema.
This Prisma schema defines two models, each of which will map to a table in the underlying database:
User and
Post. Notice that there's also a relation (one-to-many) between the two models, via the
author field on
posts field on
User.
To actually create the tables in your database, you now can use the following command of the Prisma CLI:
npx prisma db push
Create the tables in your database based on your Prisma schema.
You should see the following output:
Environment variables loaded from /Users/nikolasburk/Desktop/nextjs-guide/blogr-starter/.env Prisma schema loaded from prisma/schema.prisma 🚀 Your database is now in sync with your schema. Done in 2.10s
Output from pushing your Prisma schema to your database.
Congratulations, the tables have been created! Go ahead and add some initial dummy data using Prisma Studio. Run the following command:
npx prisma studio
Open Prisma Studio, a GUI for modifying your database.
Use Prisma Studio's interface to create a new
User and
Post record and connect them via their relation fields.
Create a new `User` record
Create a new `Post` record and connect it to the `User` record
Step 3. Install and generate Prisma Client
Before you can access your database from Next.js using Prisma, you first need to install Prisma Client in your app. You can install it via npm as follows:
npm install @prisma/client
Install the Prisma Client package.
Because Prisma Client is tailored to your own schema, you need to update it every time your Prisma schema file is changing by running the following command:
npx prisma generate
Regenerate your Prisma Schema.
You'll use a single
PrismaClient instance that you can import into any file where it's needed. The instance will be created in a
prisma.ts file inside the
lib/ directory. Go ahead and create the missing directory and file:
mkdir lib && touch lib/prisma.ts
Create a new folder for the Prisma library.
Now, add the following code to this file:
// lib/prisma.ts import { PrismaClient } from '@prisma/client'; let prisma: PrismaClient; if (process.env.NODE_ENV === 'production') { prisma = new PrismaClient(); } else { if (!global.prisma) { global.prisma = new PrismaClient(); } prisma = global.prisma; } export default prisma;
Create a connection to your Prisma Client.
Now, whenever you need access to your database you can import the
prisma instance into the file where it's needed.
Step 4. Update the existing views to load data from the database
The blog post feed that's implemented in
pages/index.tsx and the post detail view in
pages/p/[id].tsx are currently returning hardcoded data. In this step, you'll adjust the implementation to return data from the database using Prisma Client.
Open
pages/index.tsx and add the following code right below the existing
import declarations:
// pages/index.tsx import prisma from '../lib/prisma';
Import your Prisma Client.
Your
prisma instance will be your interface to the database when you want to read and write data in it. You can for example create a new
User record by calling
prisma.user.create() or retrieve all the
Post records from the database with
prisma.post.findMany(). For an overview of the full Prisma Client API, visit the Prisma docs.
Now you can replace the hardcoded
feed object in
getStaticProps inside
index.tsx with a proper call to the database:
// index.tsx export const getStaticProps: GetStaticProps = async () => { const feed = await prisma.post.findMany({ where: { published: true }, include: { author: { select: { name: true }, }, }, }); return { props: { feed } }; };
Find all published posts in your database.
There are two things to note about the Prisma Client query:
- A
wherefilter is specified to include only
Postrecords where
publishedis
true
- The
nameof the
authorof the
Postrecord is queried as well and will be included in the returned objects
Before running the app, head over the to the
/pages/p/[id].tsx and adjust the implementation there as well to read the correct
Post record from the database.
This page uses
getServerSideProps (SSR) instead of
getStaticProps (SSG). This is because the data is dynamic, it depends on the
id of the
Post that's requested in the URL. For example, the view on route
/p/42 displays the
Post where the
id is
42.
Like before, you first need to import Prisma Client on the page:
// pages/p/[id].tsx import prisma from '../../lib/prisma';
Import your Prisma Client.
Now you can update the implementation of
getServerSideProps to retrieve the proper post from the database and make it available to your frontend via the component's
props:
// pages/p/[id].tsx export const getServerSideProps: GetServerSideProps = async ({ params }) => { const post = await prisma.post.findUnique({ where: { id: Number(params?.id) || -1, }, include: { author: { select: { name: true }, }, }, }); return { props: post, }; };
Find a specific post based on the ID.
That's it! If your app is not running any more, you can restart it with the following command:
npm run dev
Start your application at.
Otherwise, save the files and open the app at in your browser.
The
Post record will be displayed as follows:
Your newly published post.
You can also click on the post to navigate to its detail view.
Step 5. Set up GitHub authentication with NextAuth
In this step, you will add GitHub authentication to the app. Once that functionality is available, you'll add more features to the app, such that authenticated users can create, publish and delete posts via the UI.
As a first step, go ahead and install the NextAuth.js library in your app:
npm install next-auth
Install the NextAuth library.
Next, you need to change your database schema to add the missing tables that are required by NextAuth.
To change your database schema, you can manually make changes to your Prisma schema and then run the
prisma db push command again. Open
schema.prisma and adjust the models in it to look as follows:
// schema.prisma model Post { id Int @default(autoincrement()) @id title String content String? published Boolean @default(false) author User? @relation(fields: [authorId], references: [id]) authorId Int? } model User { id Int @default(autoincrement()) @id name String? email String? @unique emailVerified DateTime? @map(name: "email_verified") image String? createdAt DateTime @default(now()) @map(name: "created_at") updatedAt DateTime @updatedAt @map(name: "updated_at") posts Post[] @@map(name: "users") } model Account { id Int @default(autoincrement()) @id compoundId String @unique @map(name: "compound_id") userId Int @map(name: "user_id") providerType String @map(name: "provider_type") providerId String @map(name: "provider_id") providerAccountId String @map(name: "provider_account_id") refreshToken String? @map(name: "refresh_token") accessToken String? @map(name: "access_token") accessTokenExpires DateTime? @map(name: "access_token_expires") createdAt DateTime @default(now()) @map(name: "created_at") updatedAt DateTime @default(now()) @map(name: "updated_at") @@index([providerAccountId], name: "providerAccountId") @@index([providerId], name: "providerId") @@index([userId], name: "userId") @@map(name: "accounts") } model Session { id Int @default(autoincrement()) @id userId Int @map(name: "user_id") expires DateTime sessionToken String @unique @map(name: "session_token") accessToken String @unique @map(name: "access_token") createdAt DateTime @default(now()) @map(name: "created_at") updatedAt DateTime @default(now()) @map(name: "updated_at") @@map(name: "sessions") }
The Prisma schema.
To learn more about these models, visit the NextAuth.js docs.
Now you can adjust your database schema by creating the actual tables in the database. Run the following command:
npx prisma db push
Update the tables in your database based on your Prisma schema.
Since you're using GitHub authentication, you also need to create a new OAuth app on GitHub. First, log into your GitHub account. Then, navigate to Settings, then open to Developer Settings, then switch to OAuth Apps.
Create a new OAuth application inside GitHub.
Clicking on the Register a new application (or New OAuth App) button will redirect you to a registration form to fill out some information for your app. The Authorization callback URL should be the Next.js
/api/auth route:.
An important thing to note here is that the Authorization callback URL field only supports a single URL, unlike e.g. Auth0, which allows you to add additional callback URLs separated with a comma. This means if you want to deploy your app later with a production URL, you will need to set up a new GitHub OAuth app.
Ensure your Authorization callback URL is correct.
Click on the Register application button, and then you will be able to find your newly generated Client ID and Client Secret. Copy and paste this info into the
.env file in the root directory as the
GITHUB_ID and
GITHUB_SECRET env vars. Also set the
NEXTAUTH_URL to the same value of the Authorization callback URL thar you configured on GitHub:
# .env # GitHub OAuth GITHUB_ID=6bafeb321963449bdf51 GITHUB_SECRET=509298c32faa283f28679ad6de6f86b2472e1bff NEXTAUTH_URL=
The completed .env file.
Step 5. Add Log In functionality
The login button and some other UI components will be added to the
Header.tsx file. Open the file and paste the following code into it:
// Header.tsx import React from 'react'; import Link from 'next/link'; import { useRouter } from 'next/router'; import { signOut, useSession } from 'next-auth/client'; const Header: React.FC = () => { const router = useRouter(); const isActive: (pathname: string) => boolean = (pathname) => router.pathname === pathname; const [session, loading] = useSession(); let> ); let right = null; if (loading) {> ); right = ( <div className="right"> <p>Validating session ...</p> <style jsx>{` .right { margin-left: auto; } `}</style> </div> ); } if (!session) { right = ( <div className="right"> <Link href="/api/auth/signin"> <a data-active={isActive('/signup')}>Log in</a> </Link> <style jsx>{` a { text-decoration: none; color: var(--geist-foreground); display: inline-block; } a + a { margin-left: 1rem; } .right { margin-left: auto; } .right a { border: 1px solid var(--geist-foreground); padding: 0.5rem 1rem; border-radius: 3px; } `}</style> </div> ); } if (session) { left = ( <div className="left"> <Link href="/"> <a className="bold" data-active={isActive('/')}> Feed </a> </Link> <Link href="/drafts"> <a data-active={isActive('/drafts')}>My drafts</a> </Link> <style jsx>{` .bold { font-weight: bold; } a { text-decoration: none; color: var(--geist-foreground); display: inline-block; } .left a[data-active='true'] { color: gray; } a + a { margin-left: 1rem; } `}</style> </div> ); right = ( <div className="right"> <p> {session.user.name} ({session.user.email}) </p> <Link href="/create"> <button> <a>New post</a> </button> </Link> <button onClick={() => signOut()}> <a>Log out</a> </button> <style jsx>{` a { text-decoration: none; color: var(--geist-foreground); display: inline-block; } p { display: inline-block; font-size: 13px; padding-right: 1rem; } a + a { margin-left: 1rem; } .right { margin-left: auto; } .right a { border: 1px solid var(--geist-foreground); padding: 0.5rem 1rem; border-radius: 3px; } button { border: none; } `}</style> </div> ); } return ( <nav> {left} {right} <style jsx>{` nav { display: flex; padding: 2rem; align-items: center; } `}</style> </nav> ); }; export default Header;
Allow the user to log in through the Header.
Here's an overview of how the header is going to render:
- If no user is authenticated, a Log in button will be shown.
- If a user is authenticated, My drafts, New Post and Log out buttons will be shown.
You can already run the app to validate that this works by running
npm run dev, you'll find that the Log in button is now shown. However, if you click it, it does navigate you to but Next.js is going to render a 404 page for you.
That's because NextAuth.js requires you to set up a a specific route for authentication. You'll do that next.
Create a new directory and a new file in the
pages/api directory:
mkdir -p pages/api/auth && touch pages/api/auth/[...nextauth].ts
Create a new directory and API route.
In this new
pages/api/auth/[...nextauth].ts file, you now need to add the following boilerplate to configure your NextAuth.js setup with your GitHub OAuth credentials and the Prisma adapter:
// pages/api/auth/[...nextauth].ts import { NextApiHandler } from 'next'; import NextAuth from 'next-auth'; import Providers from 'next-auth/providers'; import Adapters from 'next-auth/adapters'; import prisma from '../../../lib/prisma'; const authHandler: NextApiHandler = (req, res) => NextAuth(req, res, options); export default authHandler; const options = { providers: [ Providers.GitHub({ clientId: process.env.GITHUB_ID, clientSecret: process.env.GITHUB_SECRET, }), ], adapter: Adapters.Prisma.Adapter({ prisma }), secret: process.env.SECRET, };
Set up NextAuth, including the Prisma Adapter.
Once the code is added, you can navigate to again. This time, the Sign in with GitHub button is shown.
If you click it, you're forwarded to GitHub, where you can authenticate with your GitHub credentials. Once the authentication is done, you'll be redirected back into the app.
npm run dev.
The header layout has now changed to display the buttons for authenticated users.
The Header displaying a log out button.
Step 6. Add new post functionality
In this step, you'll implement a way for a user to create a new post. The user can use this feature by clicking the New post button once they're authenticated.
The button already forwards to the
/create route, however, this currently leads to a 404 because that route is not implemented yet.
To fix that, create a new file in the pages directory that's called
create.tsx:
touch pages/create.tsx
Create a new file for creating posts.
Now, add the following code to the newly created file:
// pages/create.tsx import React, { useState } from 'react'; import Layout from '../components/Layout'; import Router from 'next/router'; const Draft: React.FC = () => { const [title, setTitle] = useState(''); const [content, setContent] = useState(''); const submitData = async (e: React.SyntheticEvent) => { e.preventDefault(); // TODO // You will implement this next ... }; return ( <Layout> <div> <form onSubmit={submitData}> <h1>New Draft</h1> <input autoFocus onChange={(e) => setTitle(e.target.value)} <a className="back" href="#" onClick={() => Router.push('/')}> or Cancel </a> </form> </div> <style jsx>{` .page { background: var(--geist-background); padding: 3rem; display: flex; justify-content: center; align-items: center; } input[type='text'], textarea { width: 100%; padding: 0.5rem; margin: 0.5rem 0; border-radius: 0.25rem; border: 0.125rem solid rgba(0, 0, 0, 0.2); } input[type='submit'] { background: #ececec; border: 0; padding: 1rem 2rem; } .back { margin-left: 1rem; } `}</style> </Layout> ); }; export default Draft;
A new component to create posts.
This page is wrapped by the
Layout component so that it still includes the
Header and any other generic UI components.
It renders a simple form with several input fields. When submitted, the (right now empty)
submitData function is called. In that function, you need to pass the data from the React component to an API route which can then handle the actual storage of the new post data in the database.
Here's how you can implement the function:
// /pages/create.tsx const submitData = async (e: React.SyntheticEvent) => { e.preventDefault(); try { const body = { title, content }; await fetch('/api/post', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), }); await Router.push('/drafts'); } catch (error) { console.error(error); } };
Call your API route to create a post.
In this code, you're using the
title and
content properties that are extracted from the component state using
useState and submit them via an HTTP POST request to the
api/post API route.
Afterwards, you're redirecting the user to the
/drafts page so that they can immediately see their newly created draft. If you run the app, the
/create route renders the following UI:
Create a new draft.
Note however that the implementation doesn't quite work yet because neither
api/post nor the
/drafts route exist so far. You'll implement these next.
First, let's make sure your backend can handle the POST request that's submitted by the user. Thanks to the Next.js API routes feature, you don't have to "leave your Next.js app" to implement such functionality but instead you can add it to your
pages/api directory.
Create a new directory called
post with a new file called
index.ts:
mkdir -p pages/api/post && touch pages/api/post/index.ts
Create a new API route to create a post.
pages/api/post.ts` instead of taking the detour with an extra directory and an
index.tsfile. The reason why you're not doing it that way is because you'll need to add a dynamic route for HTTP
DELETErequests at the
api/postroute later as well. So, in order to save some refactoring later, you're already structuring the files in the required way.
Now, add the following code to
pages/api/post/index.ts:
// pages/api/post/index.ts import { getSession } from 'next-auth/client'; import prisma from '../../../lib/prisma'; // POST /api/post // Required fields in body: title // Optional fields in body: content export default async function handle(req, res) { const { title, content } = req.body; const session = await getSession({ req }); const result = await prisma.post.create({ data: { title: title, content: content, author: { connect: { email: session?.user?.email } }, }, }); res.json(result); }
Update the API route to modify the database using the Prisma Client.
This code implements the handler function for any requests coming in at the
/api/post/ route. The implementation does the following: First it extracts the
title and
cotent from the body of the incoming HTTP POST request. After that, it checks whether the request is coming from an authenticated user with the
getSession helper function from NextAuth.js. And finally, it uses Prisma Client to create a new
Post record in the database.
You can now test this functionality by opening the app, making sure you're authenticated and create a new post with title and content:
Testing creating a new post via the API Route.
Once you click Create, the
Post record will be added to the database. Note that the
/drafts route that you're being redirected to right after the creation still renders a 404, that will be fixed soon. However, if you run Prisma Studio again with
npx prisma studio, you'll see that the new
Post record has been added to the database.
Step 6. Add drafts functionality
In this step, you'll add a new page to the app that allows an authenticated user to view their current drafts.
This page can't be statically rendered because it depends on a user who is authenticated. Pages like this that get their data dynamically based on an authenticated users are a great use case for server-side rendering (SSR) via
getServerSideProps.
First, create a new file in the
pages directory and call it
drafts.tsx:
touch pages/drafts.tsx
Create a new page for your drafts.
Next, add the following code to that file:
// pages/drafts.tsx import React from 'react'; import { GetServerSideProps } from 'next'; import Layout from '../components/Layout'; import Post, { PostProps } from '../components/Post'; import { useSession, getSession } from 'next-auth/client'; import prisma from '../lib/prisma'; export const getServerSideProps: GetServerSideProps = async ({ req, res }) => { const session = await getSession({ req }); if (!session) { res.statusCode = 403; return { props: { drafts: [] } }; } const drafts = await prisma.post.findMany({ where: { author: { email: session.user.email }, published: false, }, include: { author: { select: { name: true }, }, }, }); return { props: { drafts }, }; }; type Props = { drafts: PostProps[]; }; const Drafts: React.FC<Props> = (props) => { const [session] = useSession(); if (!session) { return ( <Layout> <h1>My Drafts</h1> <div>You need to be authenticated to view this page.</div> </Layout> ); } return ( <Layout> <div className="page"> <h1>My Drafts</h1> <main> {props.drafts.map((post) => ( <div key={post.id} <Post post={post} /> </div> ))} </main> </div> <style jsx>{` .post { background: var(--geist-background); transition: box-shadow 0.1s ease-in; } .post:hover { box-shadow: 1px 1px 3px #aaa; } .post + .post { margin-top: 2rem; } `}</style> </Layout> ); }; export default Drafts;
Update the Draft page to show a list of drafts.
In this React component, you're rendering a list of "drafts" of the authenticated user. The drafts are retrieved from the database during server-side rendering, because the database query with Prisma Client is executed in
getServerSideProps. The data is then made available to the React component via its
props.
To make this code work, you also need to make a quick change in your application's root file
_app.tsx and wrap your current root component with a
Provider from the
next-auth/client package. Open the file and replace its current contents with the following code:
// _app.tsx import { Provider } from 'next-auth/client'; import { AppProps } from 'next/app'; const App = ({ Component, pageProps }: AppProps) => { return ( <Provider session={pageProps.session}> <Component {...pageProps} /> </Provider> ); }; export default App;
Wrap your application with the NextAuth Provider.
If you now navigate to the My drafts section of the app, you'll see the unpublished post that you created before:
Completed drafts page.
Step 7. Add Publish functionality
To "move" the draft to the public feed view, you need to be able to "publish" it – that is, setting the
published field of a
Post record to
true. This functionality will be implemented in the post detail view that currently lives in
pages/p/[id].tsx.
The functionality will be implemented via an HTTP PUT request that'll be sent to a
api/publish route in your "Next.js backend". Go ahead and implement that route first.
Create a new directory inside the
pages/api directory called
publish. Then create a new file called
[id].ts in the new directory:
mkdir -p pages/api/publish && touch pages/api/publish/[id].ts
Create a new API route to publish a post.
Now, add the following code to the newly created file:
// pages/api/publish/[id].ts import prisma from '../../../lib/prisma'; // PUT /api/publish/:id export default async function handle(req, res) { const postId = req.query.id; const post = await prisma.post.update({ where: { id: Number(postId) }, data: { published: true }, }); res.json(post); }
Update the API route to modify the database using the Prisma Client.
This is the implementation of an API route handler which retrieves the ID of a
Post from the URL and then uses Prisma Client's
update method to set the
published field of the
Post record to
true.
Next, you'll implement the functionality on the frontend in the
pages/p/[id].tsx file. Open up the file and replace its contents with the following:
// pages/p/[id].tsx import React from 'react'; import { GetServerSideProps } from 'next'; import ReactMarkdown from 'react-markdown'; import Layout from '../../components/Layout'; import Router from 'next/router'; import { PostProps } from '../../components/Post'; import { useSession } from 'next-auth/client'; import prisma from '../../lib/prisma'; export const getServerSideProps: GetServerSideProps = async ({ params }) => { const post = await prisma.post.findUnique({ where: { id: Number(params?.id) || -1, }, include: { author: { select: { name: true, email: true }, }, }, }); return { props: post, }; }; async function publishPost(id: number): Promise<void> { await fetch(`{id}`, { method: 'PUT', }); await Router.push('/'); } const Post: React.FC<PostProps> = (props) => { const [session, loading] = useSession(); if (loading) { return <div>Authenticating ...</div>; } const userHasValidSession = Boolean(session); const postBelongsToUser = session?.user?.email === props.author?.email; let title = props.title; if (!props.published) { title = `${title} (Draft)`; } return ( <Layout> <div> <h2>{title}</h2> <p>By {props?.author?.name || 'Unknown author'}</p> <ReactMarkdown source={props.content} /> {!props.published && userHasValidSession && postBelongsToUser && ( <button onClick={() => publishPost(props.id)}>Publish</button> )} </div> <style jsx>{` .page { background: var(--geist-background); padding: 2rem; } .actions { margin-top: 2rem; } button { background: #ececec; border: 0; border-radius: 0.125rem; padding: 1rem 2rem; } button + button { margin-left: 1rem; } `}</style> </Layout> ); }; export default Post;
Update the Post component to handle publishing via the API Route.
This code adds the
publishPost function to the React component which is responsible for sending the HTTP PUT request to the API route you just implemented. The
render function of the component is also adjusted to check whether the user is authenticated, and if that's the case, it'll display the Publish button in the post detail view as well:
The publish button shown for a post.
If you click the button, you will be redirected to the public feed and the post will be displayed there!
getStaticPropsto retrieve the data for this view. If you want it to be updated "immediately", consider changing
getStaticPropsto
getServerSidePropsor using Incremental Static Regeneration.
Step 8. Add Delete functionality
The last piece of functionality you'll implement in this guide is to enable users to delete existing
Post records. You'll follow a similar approach as for the "publish" functionality by first implementing the API route handler on the backend, and then adjust your frontend to make use of the new route!
Create a new file in the
pages/api/post directory and call it
[id].ts:
touch pages/api/post/[id].ts
Create a new API route to delete a post.
Now, add the following code to it:
// pages/api/post/[id].ts import prisma from '../../../lib/prisma'; // DELETE /api/post/:id export default async function handle(req, res) { const postId = req.query.id; if (req.method === 'DELETE') { const post = await prisma.post.delete({ where: { id: Number(postId) }, }); res.json(post); } else { throw new Error( `The HTTP ${req.method} method is not supported at this route.`, ); } }
Update the API route to modify the database using the Prisma Client.
This code handles HTTP
DELETE requests that are coming in via the
/api/post/:id URL. The route handler then retrieves the
id of the
Post record from the URL and uses Prisma Client to delete this record in the database.
To make use of this feature on the frontend, you again need to adjust the post detail view. Open
pages/p/[id].tsx and insert the following function right below the
publishPost function:
// pages/p/[id].tsx async function deletePost(id: number): Promise<void> { await fetch(`{id}`, { method: 'DELETE', }); Router.push('/'); }
Update the Post component to handle deleting via the API Route.
Now, you can follow a similar approach with the Delete button as you did with the Publish button and render it only if the user is authenticated. To achieve this, you can add this code directly in the
return part of the
Post component right below where the Publish button is rendered:
// pages/p/[id].tsx { !props.published && userHasValidSession && postBelongsToUser && ( <button onClick={() => publishPost(props.id)}>Publish</button> ); } { userHasValidSession && postBelongsToUser && ( <button onClick={() => deletePost(props.id)}>Delete</button> ); }
Logic to determine whether to show the publish and delete buttons.
You can now try out the new functionality by creating a new draft, navigating to its detail view and then clicking the newly appearing Delete button:
The Delete button showing on the post page.
Step 9. Deploy to Vercel
In this final step, you're going to deploy the app to Vercel from a GitHub repo.
Before you can deploy, you need to:
- Create another OAuth app on GitHub
- Create a new GitHub repo and push your project to it
To start with the OAuth app, go back to step Step 5. Set up GitHub authentication with NextAuth and follow the steps to create another OAuth app via the GitHub UI.
This time, the Authorization Callback URL needs to match the domain of your future Vercel deployment which will be based on the Vercel project name. As a Vercel project name, you will choose
blogr-nextjs-prisma prepended with your first and lastname:
FIRSTNAME-LASTNAME-blogr-nextjs-prisma. For example, if you're called "Jane Doe", your project name should be
jane-doe-blogr-nextjs-prisma.
The Authorization Callback URL must therefore be set to. Once you created the application, adjust your
.env file and set the Client ID as the
GITHUB_ID env var and a Client secret as the
GITHUB_SECRET env var. The
NEXTAUTH_URL env var needs to be set to the same value as the Authorization Callback URL on GitHub:.
Update the Authorization callback URL.
Next, create a new GitHub repository with the same name, e.g.
jane-doe-blogr-nextjs-prisma. Now, copy the three terminal commands from the bottom section that says ...or push an existing repository from the command line, it should look similar to this:
git remote add origin git@github.com:janedoe/jane-doe-blogr-nextjs-prisma.git git branch -M main git push -u origin main
Push to an existing repository.
You now should have your new repository ready at, e.g..
With the GitHub repo in place, you can now import it to Vercel in order to deploy the app:
Now, provide the URL of your GitHub repo in the text field:
Import a git repository to Vercel.
Click Continue. The next screen requires you to set the environment variables for your production deployment:
Add environment variables to Vercel.
Here's what you need to provide:
DATABASE_URL: Copy this value directly from your
.envfile
GITHUB_ID: Set this to the Client ID of the GitHub OAuth app you just created
GITHUB_SECRET: Set this to the Client Secret of the GitHub OAuth app you just created
NEXTAUTH_URL: Set this to the Authorization Callback URL of the GitHub OAuth app you just created
Once all environment variables are set, hit Deploy. Your app is now being deployed to Vercel. Once it's ready, Vercel will show you the following success screen:
Your application deployed to Vercel.
You can click the Visit button to view the deployed version of your fullstack app 🎉
Conclusion
In this guide, you learned how to build and deploy a fullstack application using Next.js, Prisma, and PostgreSQL. If you ran into issue or have any questions about this guide, feel free to raise them on GitHub or drop them in the Prisma Slack. | https://vercel.com/guides/nextjs-prisma-postgres | CC-MAIN-2021-39 | refinedweb | 5,472 | 57.77 |
Damn you, you are right ;)
Updated!
Thanks!!!
Search Criteria
Package Details: drumgizmo-git 0.9.8.1.r363.g9aa7d52-1
Dependencies (5)
Required by (0)
Sources (2)
Latest Comments
sekret commented on 2015-07-13 17:42
Damn you, you are right ;)
SpotlightKid commented on 2015-07-13 13:54
Namcap reports a missing dependency on zita-resampler, which seems accurate.
sekret commented on 2015-04-12 10:14
Thanks for your honesty :) I unflagged it.
SpotlightKid commented on 2015-04-11 16:37
Sorry, I clicked the "Flag as out-of date" link accidentally, and I can't seem to undo the action :(
sekret commented on 2015-04-10 20:18
Thanks man, updated! I'll leave the check function out for the time being.
SpotlightKid commented on 2015-04-10 12:13
I get the following error while compiling:
test.cc:27:34: schwerwiegender Fehler: cppunit/XmlOutputter.h: Datei oder Verzeichnis nicht gefunden
#include <cppunit/XmlOutputter.h>
It seems that 'cppunit' is missing from depends or makedepends. But even if I install it (cppunit) from 'extra', I get another error at the linking stage because of undefined references related to cppunit. Maybe the package version is too old?
Anyway, I was able to build the package with the --nocheck option to makepkg.
sekret commented on 2014-09-20 07:17
For 0.9.6.r1.g32d9c87-1 namcap tells me that libao and qt4 are not needed. Sounds strange to me.. | https://aur.archlinux.org/packages/drumgizmo-git/ | CC-MAIN-2016-36 | refinedweb | 243 | 67.35 |
Weather data on outernet is downloaded once a day. That's why your data says 01:00. The online version uses data that is updated more frequently. I do have to say that I like a 3 hour accumulation prediction. BTW I think you may have given away your location to the internet.
Hey guys, I just upgraded my Outernet CHIP!
Feedback on the install process:If you extract the 'OuternetFlasher-disk1.iso' file from the skylark VM, and boot it from a DVD, it works without a hitch on a lot of computers.It also works on older computers that can't handle a virtual machine!
Feedback for Skylark: I liked the old layout... maybe there could be an option for switching themes?Like the old one could be 'ORX_Basic' and the skylark one could be 'Skylark_Basic'
Flashed Skylark 1.0 to the CHIP. Couple of comments:It does not work well on the IPAD/IOS at all. The Librarian version works better here.Having issues with the WIfi. Getting "unable to connect" errors even though strong signal and physically next to the CHIP. Takes several hardboots to get it working. If I drop the wifi connection and later try to reconnect .... back to the "unable" errors again.
The weather app works well, as does the APRS and News viewers.
Also, how do I log into the 'guest' account? And I want to change my password when I log into the administrator account.
I found that both the orx and skylark firmwares work 500% better when you connect it to a router.
The CHIP doesn't get as hot, and everything is much faster. It's probably because having a wifi hotspot is WAAAY more resource intensive.
Also, I can't access most text fields on Android, so I had to put my chip next to my computer to set up the wifi (the hotspot doesn't go through walls!)
wow, what's that cool current measurement gadget?
It is a USB multimeter! I love it. YZXstudio 1270 USB Power Meter.. Think I paid $39 on Amazon. You can get it with Bluetooth also. They run from $12 and up. Handy for checking USB charging currentsand voltage. You would be surprised at the poorly designed chargers and power supplies out there.
I had an issue with changing the password via ssh and then trying to log in via the Browser. While the password was good for ssh shell login, it wasn't good for the web server.
The solution was to use the passwd command line option "-a MD5":ssh -l outernet 192.168.1.xxxsudo shpasswd -a MD5 outernet
The way to check for the algorithm is to look at the number behind the first dollar sign in the file /etc/shadow under outernet. For the MD5 algorithm, it's a "$1".
/M
Just a quick update after being out of town for a week.
First, for those of you having issues with files that contain question marks (usually right before the .html) you can use the following command to clean them from the system:
find -type f -name '*\?.html' -print0 | xargs -0 rm
As for my receiver's status sitting untouched for a week:
[Skylark][[email protected][email protected]
The cache seems a bit big....
It is a beautiful sunny day here in Florida....
Oh I forgot another issue I noticed reported was the chip turning itself off seemingly at random. There is a setting change with the power regulator that fixed that issue for me.
Here is some information about the CHIP power system and others having issues (along with workarounds):
What worked for me was setting the power regulator to "no limit":
Please read all the information before making changes to your CHIP. A CHIP set to "no limit" can damage your USB ports on your PC (or worse) given the right conditions.
A quick update on this problem - - I received a replacement CHIP from @Syed today and installed it without a hitch. The new CHIPs come with Skylark 4.2 installed, so you don't have to flash it. My Alpha Lantern is all buttoned up again with a ferrite isolation choke and perking along like gang busters
I took other's advice and repaired the bad CHIP. I completely removed the white battery plug and cleaned the pin holes, then re soldered the plug back. It took a few tries to get the solder to flow thru the holes, but in the end it worked fine. It was able to verify continuity from the black pin buss to the plug.
Just to reiterate the initial symptom for others, wiggling the Boston Power connection on the CHIP (breaking continuity) in the Alpha Lantern was enough to disrupt the CHIP's operation and shut it down. You do not, however, need an external battery to run the CHIP. You can power up the chip from a USB power cord fine, but if you get a power glitch - - you'll get a shutdown/reboot. I like the Boston Power idea because it allows me to move an energized Lantern around without having to plug it in to a wall wart.
Ken
After not being able to flash (a good 20 tries with different combinations) I swapped to a different CHIP. Flashed the 1st time no problems. Keep in mind I have flashed both of my CHIPs in FEL mode before. Yet something happened to the 2nd one that doesn't allow it to be seen in FEL mode ever anymore.
I had exactly the same problem, and @Syed replaced the CHIP. The CHIP turned out to be bad. Ken
But it has a QC Sticker on it. It can't be bad. grin Hopefully the production version CHIPs are more reliable.
Ask @Syed for another one. He wants you to be happy. Ken
Are the CHIPs shipping still the Alpha v0x21 ones?
Glad to hear it is working now.
@neil Not sure if the above is of any interest to you. Here is the code of you want it.It will show you the SNR, RSSI and the lock state, then it will show you what is currently in the carousel and then at the bottom it will show you the latest APRS messages.
import requestsTunerStatus = requests.get('').json()
print TunerStatus['result']['snr'] , " SNR"print TunerStatus['result']['rssi'] , " RSSI"print TunerStatus['result']['state'] , " STATE"print ""print "Here is what file is in the carousel";print ""print TunerStatus['result']['transfers']
aprs = requests.get ('').json()print ""print "Latest APRS Messages"print ""print aprs['result']
Cool!Thanks heaps.. I will be in the same place as the Outernet receiver this week, so i may be able to "Play" if I get some time away from my work...
After running the "Librarian" for a day, I just flashed to "Skylark" and I am not sure I like it...There appears to be no way to use the file manager without login. And I cannot change the password.I liked that visitors on the local HAMNET could look at the downloaded files, and I had my own passwordto guard the system settings.Now, everyone who visits has to login, and the password can be found on internet.But then they can also change all settings, see my WiFi password, etc.So I have blocked outside access in the firewall for now...Please restore the old way of having read-only access without login, and a settable user/passwordfor setup and administration.
Am I the only one having issues scrolling in Skylark UI with iPad? | http://forums.outernet.is/t/skylark-v1-0-new-outernet-firmware/2928?page=13 | CC-MAIN-2017-26 | refinedweb | 1,263 | 74.9 |
Turn an IRC bot into an automated quiz show
host. Compete with your friends to be first to answer each
question.
If
your channel ever seems to lack excitement, you can rev up the
enjoyment factor by introducing a trivia bot
that asks questions and waits for someone to respond with the correct
answer. Most trivia bots ask a single question and wait for someone
to give the correct answer. When the correct answer has been given,
the bot will ask another question.
This hack will show you how to make a basic trivia bot that stores
all of its questions and answers in a text file. More advanced trivia
bots can let you store the total scores for each user and may even
have time limits for each question.
To make
your trivia bot easy to extend, you should create a
Question class, so each question (and answer) can
be stored in a Question object. The
Question class also provides an
isCorrect method, so you can see if a candidate
answer is correct.
Create a file called Question.java:
public class Question {
private String question;
private String answer;
public Question(String question, String answer) {
this.question = question;
this.answer = answer;
}
public String toString( ) {
return question;
}
public String getAnswer( ) {
return answer;
}
public boolean isCorrect(String a) {
return answer.equalsIgnoreCase(a);
}
}
The TriviaBot class will be used to maintain a
collection of Question objects. Each time a new
question is asked, it will be chosen randomly from this collection.
As soon as the trivia bot joins a channel, it will ask a question.
Whenever someone sends a message to the channel, the trivia bot will
check to see if it matches the answer for the current question. If
the answer is correct, the trivia bot will announce the sender of
that message as being the winner.
This trivia bot will also allow users to say the
"clue" command. If anybody
says "clue" in the channel, the
trivia bot will respond by showing how many letters are in the
answer. It does this by replacing each letter in the answer with a
* character and sending it to the channel. So if
the correct answer is "Internet Relay
Chat," the bot will send the following to the
channel:
<Jibbler> clue
<TriviaBot> Clue: ******** ***** ****
This class extends PircBot to connect to IRC and
uses the Random class in the
java.util package to generate
random question numbers.
Create a file called
TriviaBot.java:
import org.jibble.pircbot.*;
import java.util.*;
public class TriviaBot extends PircBot {
private Question currentQuestion = null;
private ArrayList questions = new ArrayList( );
private static Random rand = new Random( );
public TriviaBot(String name) {
setName(name);
}
public void addQuestion(Question question) {
questions.add(question);
}
public void onJoin(String channel, String sender,
String login, String hostname) {
if (sender.equals(getNick( ))) {
setNextQuestion(channel);
}
}
public void onMessage(String channel, String sender, String login,
String hostname, String message) {
message = message.toLowerCase( ).trim( );
if (currentQuestion.isCorrect(message)) {
sendMessage(channel, sender + " is the winner, with the correct"
+ "answer of" + currentQuestion.getAnswer( ));
setNextQuestion(channel);
}
else if (message.equalsIgnoreCase("clue")) {
String clue = currentQuestion.getAnswer( );
clue = clue.replaceAll("[^\\ ]", "*");
sendMessage(channel, "Clue: " + clue);
}
}
private void setNextQuestion(String channel) {
currentQuestion = (Question) questions.get(rand.nextInt(questions.size( )));
sendMessage(channel, "Next question: " + currentQuestion);
}
}
The TriviaBot class uses an
ArrayList to store each
Question object. New questions can be added to the
bot with the addQuestion method. The
setNextQuestion method is used to pick a random
question and announce it to the channel.
The onJoin method is overridden and will be called
whenever the bot joins a channel. The bot will then ask the first
randomly picked question.
The onMessage method is overridden and will be
called whenever someone sends a message to the channel. If the
message matches the correct answer for the current question, the bot
will announce that the sender won and it will then pose the next
question and carry on as before. If anybody sends the
"clue" command, the bot will send
the clue to the channel.
This bot will be near to useless
without a large bundle of questions to ask. For now though, you can
just make up a few questions to test the bot, then add more later.
Each line of the text file will contain a question and an answer. The
| character is used to separate each question and
its answer.
Create a file called quiz.txt and add some
questions:
What is the square root of 81?|9
What does IRC stand for?|Internet Relay Chat
What is "bot" short for?|robot
To make the bot turn each line of this file into a Question object,
you must parse the contents before the bot connects to a server. You
can add this little bit of code to the main method, which
instantiates the bot.
Create
TriviaBotMain.java:
import java.io.*;
public class TriviaBotMain {
public static void main(String[] args) throws Exception {
TriviaBot bot = new TriviaBot("TriviaBot");
// Read the questions from the file and add them to the bot.
BufferedReader reader = new BufferedReader(
new FileReader("./quiz.txt"));
String line;
while ((line = reader.readLine( )) != null) {
String[] tokens = line.split("\\|");
if (tokens.length == 2) {
Question question = new Question(tokens[0], tokens[1]);
bot.addQuestion(question);
}
}
bot.setVerbose(true);
bot.connect("irc.freenode.net");
bot.joinChannel("#irchacks");
}
}
Compile the hack like so:
C:\java\TriviaBot> javac -classpath .;pircbot.jar *.java
Run the bot like so:
C:\java\TriviaBot> java -classpath .;pircbot.jar TriviaBotMain
The bot will then start up.
When the bot starts up, it will read the questions from
quiz.txt, connect to the server, and join the
channel #irchacks, as shown in Figure 9-3.
Note that without modification, this bot is suitable only for use in
a single channel. This is because it stores the current question in a
single field (currentQuestion), while multiple
channel support would entail having a different variable for each
channel. One way to make it suitable for use in multiple channels is
to replace this simple variable with a HashMap, which is indexed by
the channel name. This approach is implemented in the WelcomeBot
[Hack #64] . | http://books.gigatux.nl/mirror/irchacks/059600687X/irchks-CHP-9-SECT-4.html | CC-MAIN-2018-22 | refinedweb | 1,012 | 65.93 |
VOL 24 / ISSUE 01 / 13 JANUARY 2022 / £4.49
FIT and WEALTHY
Six funds to whip portfolios into shape
BOOHOO:
Why investors in online fashion play are shedding tears
Your interests and ours, deeply aligned. For over 150 years we have been earning our investors’ trust, and earning them 50 consecutive years of dividend growth. For decades we’ve been investing responsibly in quality companies around the world to have a positive impact on the earth too. Find out more at
fandcit.com/future Capital is at risk and investors may not get back the original amount invested.
Responsible for our future
BMO Asset Management Limited is authorised and regulated by the Financial Conduct Authority. Registered Office: Exchange House, Primrose Street, London EC2A 2NY. Registered in England & Wales No 517895. 1573649 (09/21). UK
Contents EDITOR’S
CFA UK Publication of the Year CFA UK Journalism Awards 2019
News Provider of the Year (Highly Commended) CFA UK Journalism Awards 2020
05 VIEW
An antidote to New Year investing resolutions
06 NEWS
Fed minutes unsettle bond and equity markets / The impact of Kazakhstan unrest on shares and commodities / Holidays surge sparks rampant rally for travel sector stocks / Housebuilders hit by surprise escalation in cladding costs
11
GREAT IDEAS
New: Temple Bar Investment Trust / DWF Updates: Odyssean Investment Trust / Cordiant Digital Infrastructure / FRP Advisory Group
17
FEATURE
Fit and wealthy: Six funds to whip portfolios into shape
23 FEATURE
There are big obstacles to a Boohoo recovery
27 FEATURE
New listing ADF brings touch of Hollywood glamour to the market
28 FUNDS
The top performing European funds and trusts
30 FEATURE
Three ways to beat the professionals
32 FEATURE
Greggs is not a buy at this price despite overtaking McDonald’s
UNDER THE
34 BONNET
Latest deal at newly focused DCC set to boost growth and margins
38 ASK TOM
What are the paying-in rules for an untouched SIPP?
PERSONAL
39 FINANCE 41
RUSS MOULD
45 INDEX
Key personal finance dates for your 2022 diary The least and most popular stocks heading into 2022.
13 January 2022 | SHARES |
3
SIPPs | ISAs | Funds | Shares
RETIREMENT YOUR WAY?
Open our low-cost Self-Invested Personal Pension for total flexibility and control over your retirement with free drawdown. youinvest.co.uk
Capital at risk. Pension rules apply.
EDITOR’S VIEW
An antidote to New Year investing resolutions Don’t put too much pressure on yourself at the start of 2022
T
raditionally.
By Tom Sieber Deputy Editor
13 January 2022 | SHARES |
5
NEWS
Fed minutes unsettle bond and equity markets The change in Fed language suggests it is trying to make up for lost time%.
6
| SHARES | 13 January 2022. [MGam]
NEWS
The impact of Kazakhstan unrest on shares and commodities The stocks affected by escalating violence in the central Asian state and what might happen next
T
Kazakhstan has 12% of the world’s uranium resources and accounted for 43% of 2019 global output Source: World Nuclear Association. [TS] 13 January 2022 | SHARES |
7
NEWS
Holidays surge sparks rampant rally for travel sector stocks Airlines, package holiday firm, cruises are all seeing huge demand
A
fter nearly two years of heavy losses, the travel sector is showing serious signs of bouncing back, despite the ongoing drag of the Omicron variant. Increased vaccination rates, pent-up demand and accumulated savings are helping to spur demand for global tourism nations roll back border restrictions. Organisations from across the travel industry welcomed the UK Government’s decision to ditch pre-departure tests for arrivals into England from 9 January, with Brits returning home also now able to use cheap lateral flow Covid tests rather than booking expensive PCR tests. ‘The removal of pre-departure tests and replacing day two PCRs with more affordable antigen testing will significantly boost the UK tourism sector and help both it and the whole UK economy recover much faster than expected,’ said Julia Simpson, World Travel & Tourism Council chief executive. This has spurred demand for airline and holidays stocks, the UK travel sector up more than 3% in the early days of 2022. Yet the travel rally really set in before Christmas. During the past month, shares
in BA-owner International Consolidated Airlines (IAG) have jumped 19%. Budget flyers EasyJet (EZJ) and Wizz Air (WIZZ) have posted similar gains, while Jet2 (JET2:AIM), which provides package holidays and flights to tourists and is one of Shares top picks for 2022, is up 23%. TUI (TUI), Carnival (CCL) and Saga (SAGA) are all up by double digits too, yet this may be merely the prelude to even greater share price gains across the sector this year. ‘An industry-wide recovery in short-haul leisure travel is expected this summer, reaching pre-Covid levels,’ said analysts at Numis. ‘Many holidaymakers would not have been overseas in three years implying material pent-up demand.’ Last week EasyJet said it saw bookings for some destinations surge 400%, with overall flight demand up 200%, with demand for classic holiday hotspots like the Canary Islands, Alicante and Malaga up sharply. Numis calculates that the broader sector has underperformed the FTSE All-Share index by 8% since the first quarter of 2020. [SF]
Travel stocks fly higher 25
22.9%
20
19.8%
19.2%
15
One-month performance
15.9% 11.4%
10 5 0
8
Jet2
| SHARES | 13 January 2022
EasyJet
Interna onal Consolidated Airlines
TUI
Carnival Source: SharePad, data to 11 January 2022
NEWS
Housebuilders hit by surprise escalation in cladding costs Monday’s tumble wiped more than £1.5 billion off share valuations
S
hareholders in the big six major UK housebuilders received a rude awakening on Monday after the sector lost more than £1.5 billion in value after the government unexpectedly said it could force them to fix cladding issues on high-rise buildings at an estimated cost of up to £4 billion. The hardest-hit stocks were Persimmon (PSN) and Barratt Developments (BDEV), down 5.3% and 4.9% respectively for a combined loss of almost £850 million, although the damage extended across the sector with smaller developers such as Redrow (RDW) and Vistry (VTY) also losing around £100 million each in market value. Cladding on tower blocks has been a major political issue since the Grenfell disaster in June 2017. The cost of making blocks safe is meant to be met by the freeholder who owns the building, but in many cases has been passed to the leaseholders who own the individual flats. The Government previously pledged more than £5 billion to fund the removal of unsafe cladding from the highest-risk building, those over 18 metres high, to be paid for in part by a levy on developers. To that end, it introduced a 4% tax on the profits of large residential property developers from April 2022, which analysts estimate could take up to a decade to raise £2 billion. However, the Department for Levelling Up, Housing and Communications this week upped the ante considerably, giving companies a deadline of early March to agree a fully funded plan of action, including remediating unsafe cladding on buildings between 11 metres and 18 metres, with an estimated cost of a further £4 billion. Secretary of state Michael Gove warned the Government would take ‘all steps necessary to
make this happen, including restricting access to government funding and future procurements, the use of planning powers and the pursuit of companies through the courts’. The levy is supposed to be voluntary, but if the companies refuse to comply the Government ‘will if necessary impose a solution in law’ according to the statement. The housebuilders are hardly able to push back against the Government by claiming poverty given they have been shelling out bumper dividends to shareholders for the last couple of years. They have also been strong beneficiaries of state-backed initiatives like the Help to Buy scheme which have helped boost demand. The new levy could constrain these special dividends, which have been a key reason for many investors to hold the shares until now. Building materials supplier Kingspan (KGP), which wasn’t cited in the statement but which supplied some of the insulation used on the Grenfell tower, saw its shares slide 5% to €96.30 on Monday, wiping over €900 million off its market value. [IC]
13 January 2022 | SHARES |
9
Play the rotation into value stocks with Temple Bar Tech names are out of fashion as investors seek lower rated shares offering ‘jam today’
J
anuary has seen a rotation in the market, with investors moving out of technology-related stocks and into more value style investments where the story is all about slow to medium growth today, not super levels of growth in the future. The UK market has quite a few stocks that fall under the value category – namely immediate profit and cash flow, or ‘jam today’, trading on undemanding ratings versus the ‘jam tomorrow’ of many more speculative tech stocks. The fact investors are looking at the value space again bodes well for Temple Bar Investment Trust (TMPL) as it specialises in investing in value-style stocks. ROTATION REASONS Tech stocks have fallen out favour with investors due to expectations for rising interest rates. A lot of tech companies trade on high valuations with the hope of large profit growth in the future rather than now, and these types of stocks are very sensitive to rising rates. The market works out what a future stream of cash flow or earnings is worth today and bond yield and interest rate expectations play a key role in this calculation. Higher interest rates reduce the present value of the expected cash flow, so investors
TEMPLE BAR INVESTMENT TRUST (TMPL) £11.87
BUY Market cap:
£782 million
don’t want to pay as much for tech-related stocks. That’s why you have seen movements such as a 15% fall in Tesla and a 13% decline in investment trust Allianz Technology (ATT) so far this year. NEW MANAGER Temple Bar Investment Trust saw a change in manager just over a year ago, coinciding with another rally in value stocks. Its shares hitched a ride with this rally until June 2021 when the market started to switch back to favouring higher growthorientated stocks, leaving the trust’s share price to lose momentum. However, Temple Bar’s shares perked up in late 2021 when expectations increased for interest rate hikes, together with a resurgence in Covid cases. Investors started to seek
safety in seemingly more boring companies and that trend has accelerated in 2022. Not only is Temple Bar’s style back in favour, but investors are able to access its portfolio for less than the market value of the underlying holdings. That’s because its shares continue to trade at a discount to net asset value, the latest being 7.9% versus a 12-month average of 6.8% according to Winterflood. One possible explanation behind the lingering discount to NAV is that value as a style has been out of favour for much of the past decade and so the market might think the current rotation won’t last long. That’s a risk for prospective investors to consider. INVESTMENT PROCESS Temple Bar is managed by RWC and the goal is to provide a 13 January 2022 | SHARES |
11
greater total return (share price gains and dividends) than the FTSE All-Share index. RWC considers a company’s growth prospects and sustainable levels for profit margins and then calculates an intrinsic value for the business. It looks to invest when the shares trade below this intrinsic value. A lot of companies are cheap for a reason and RWC is keen to avoid so-called ‘value traps’ where the businesses could stay cheap for a long time because of structural issues. Instead, it looks for companies on cheap ratings which have a strong enough balance sheet to survive any short-term problems. ‘The value opportunity arises because investors have an irrational dislike of a business, or misunderstand it, or are too focused on short-term problems, for example,’ explains QuotedData, an investment trust research specialist. QuotedData says that just as some investors become over-exuberant about some stocks, they become overly pessimistic about others, which creates value opportunities. The challenge is sifting through the pack and seeing which ones 12
| SHARES | 13 January 2022
can bounce back. The investment trust’s portfolio has large positions in energy, materials and financials – all sectors which tend to do well when the value investment style comes into fashion. PORTFOLIO HOLDINGS Oil and gas companies Royal Dutch Shell (RDSB), BP (BP.) and Paris-listed TotalEnergies are among the biggest holdings in the Temple Bar portfolio. These companies generate lots of cash, which is used to reduce debt, fund dividends and share buybacks, and help finance expansion into renewable energy. Life insurance provider Aviva (AV.) is a top 10 holding for Temple Bar. James Pearse, an analyst at investment bank Jefferies, believes that following the recent disposals of Aviva’s non-core overseas businesses, it has enough surplus capital to return £5 billion to investors this year. One might expect this money to be split between special dividends and share buybacks. Temple Bar also has a stake in media group WPP (WPP) which last year benefited
from a recovery in advertising spend. Trading on 13.5 times forecast earnings for 2022, WPP’s valuation is ‘extremely modest for a well-managed, market-leading, global player experiencing robust trading and offering the prospect of strong medium-term growth and cash generation,’ says broker Shore Capital. ‘We also note that, based on consensus forecasts, it is trading on an EV/EBITDA discount to its international peers despite offering the prospect of superior earnings growth. Our fair value estimate is currently £16.24 suggesting substantial upside potential (from the current £11.69 trading price).’ Other holdings in the Temple Bar portfolio include Vodafone (VOD), Marks & Spencer (MKS) and Royal Mail (RMG). The trust targeted a minimum of 39p in dividends for the 2021 financial year, with three quarterly payments of 9.75p having already been paid. While we expect dividend growth from the trust in the future, for now investors should use guidance for 2021’s payment as an indication of how much income the stock could provide in 2022, namely a yield in the region of 3.3%. [DC]
Legal services leader DWF is set for share price upside The business has come a long way since it listed in 2019
L
egalrelated
DWF BUY (DWF) 114p
Net assets: £372 million. [IC]
13 January 2022 | SHARES |
13
ODYSSEAN INVESTMENT CORDIANT DIGITAL INFRASTRUCTURE.
(CORD) 108p
Gain to date: 2.9% Original entry point: Buy at 105p, 13 May 2021
INVESTOR AND DIGITAL specialist in mid-market data centres, mobile communications, broadcast towers, and fibre optic networks, Cordiant Digital Infrastructure (CORD) delivered a total shareholder return of 9.5% in the first half to 30 September 2021. The trust finished the period with a net asset value of 102p per ordinary share, which means the shares trade at a premium of around 6%. The company is targeting a 4p dividend per share for the financial year to 31 March 2023, three years ahead of the schedule communicated at the time of the initial public offering in February. The trust has now fully deployed its cash following recent purchases of Emitel and DataGryd, a multi-asset Polish platform and a concentrated hub of internet connectivity in New York, respectively. This means that the C-shares that were created via a £185 million placing in June 2021 will convert into ordinary shares on 20 January. The company is planning to conduct a £200 million placing at a 6.6% discount to the share price to satisfy a follow-up funding requirement in the portfolio.
%
SHARES SAYS: Keep buying Odyssean. [JC] 14
| SHARES | 13 January 2022
SHARES SAYS: The experienced management team is delivering on promises made at the time of the listing. [MGam]
FRP ADVISORY GROUP . [MGar]
13 January 2022 | SHARES |
15.
FIT and WEALTHY
Six funds to whip portfolios into shape
By the Shares team
I
nvesting. 13 January 2022 | SHARES |
17
20S/30S/40S/50S LOOKING FOR GROWTH, MEDIUM RISK APPETITE FIDELITY GLOBAL SPECIAL SITUATIONS (B8HT715) 18
| SHARES | 13 January 2022teens. 13 January 2022 | SHARES |
19]
RIT CAPITAL (RCP) £27.25
20
| SHARES | 13 January 2022house] 13 January 2022 | SHARES |
21,
22
| SHARES | 13 January 2022]
FEATURE
There are big obstacles to a Boohoo recovery The digital fast fashion retailer is cheap for a reason amid slowing growth, supply chain pain and Chinese competition
I
nvestors.
(BOO:AIM) Share price 109.4p Market cap £1.5
13 January 2022 | SHARES |
23
FEATURE
2%, 24
| SHARES | 13 January 2022
2% 3%
FEATUREpriced multibrand, 13 January 2022 | SHARES |
25
FEATURE Boohoo forward PE multiple. By James Crux Funds and Investment Trusts Editor.
FEATURE
New listing ADF brings touch of Hollywood glamour to the market Company provides production equipment to film and TV giants
T
he first new company to list on the junior market this year is also one of the most colourful. Facilities by ADF (ADF:AIM), which raised £18.4 million last week valuing the firm at £38 million, services the multi-billion pound UK film and television industry. Established in the early 1990s, the company is the number one provider of premium production facilities like make-up, costume and artiste accommodation trailers with a 35% share of the high-end television market thanks to its fleet of over 500 vehicles. It has worked with all the leading production companies including the BBC, ITV (ITV), Netflix, Sky, Disney, HBO and Apple, and was involved in major TV series including The Crown, Gangs of London and Peaky Blinders. The firm’s average revenue per production has more than doubled in the last three years to £607,000 as programmes and films have become longer and more complex. According to the BFI (British Film Institute), spending on filmmaking and high-end TV in the UK hit £6 billion last year, more than double the amount in 2020 which admittedly was impacted by Covid restrictions.
For ADF, 2020 revenue was £8 million against nearer £16 million in 2019, but 2021 saw a dramatic rebound with the firm garnering £11.5 million of revenues in the first half alone, putting it on track to top £20 million for the full year. The recovery in EBITDA (earnings before interest, taxes, depreciation and amortisation) was even more impressive thanks to a combination of higher prices and higher fleet utilisation, with the increased revenues generated translating straight into earnings. Due to the material increase in the consumption of film and TV through streaming services, all the major US streaming companies have set up permanent bases in the UK taking out studio leases of 10 years or more. This has driven the uptake of ADF’s services with the firm’s production fleet already almost fully booked for this year and
customers having to book up to seven months in advance. Proceeds from the listing are therefore being used to buy more equipment to satisfy the ever-increasing demand. ‘Producers need our vehicles on set, on time, all the time’, says chairman John Richards. Ultimately, the group has ambitions to grow its annual revenue to £100 million, ‘but that isn’t going to happen organically’ admits Richards. While it already has a large chunk of the UK market, there is scope to take further share with small local bolt-on acquisitions. There is also the potential to expand into complementary services like transporting lighting and sound equipment and props, making ADF a ‘one-stop shop’ for its film and TV clients. By Ian Conway Companies Editor
13 January 2022 | SHARES |
27
The top performing European funds and trusts How the best managers take advantage of opportunities on the Continent
T
he performance of the top Europe (ex-UK) funds is proof that the European equity market offers a multitude of opportunities for active investors to acquire overlooked and undervalued growth companies. The BlackRock Greater Europe Investment Trust (BRGE) is a £676 million fund with two comanagers. Stefan Gries covers developed European markets (90% of the portfolio); and Sam
28
| SHARES | 13 January 2022
Vecht covers emerging European markets (10% of the portfolio). Gries’ investment approach is to be ‘an investor in businesses not a trader in shares’. Shares are chosen on the basis of bottom up fundamental analysis. On a sector basis, the fund has consistent heavy exposures to technology, consumer discretionary, industrials and healthcare companies. ASML which makes equipment to support chip manufacturers, is
the largest position in the fund. Gries likes its high market share, pricing power and strong order book visibility. BlackRock Greater Europe’s net asset value total returns rank first out of eight funds in the AIC Europe sector over the last one, three, five and 10 years, and have also outpaced the broader European stock market over these periods. DIVERSIFIED APPROACH The £542 million Ballie Gifford European Growth Trust (BGEU) aims to achieve long-term capital growth from a diversified portfolio of European equities. The fund is co-managed by Stephen Paice and Moritz Sitte who invest in high quality, growth orientated companies with a strong competitive position. These businesses have a tendency to be managed by owner-operators. A key point of differentiation is the fund’s ability to invest in private companies, although its current 4.5% weighting to non-public investments is relatively modest. The portfolio is relatively concentrated with between 30 and 60 listed and private companies. Paice and Sitte are big advocates of asset light digital platforms that benefit from network effects (a process whereby increased numbers of people or participants improve
cap bias. Fund managers Carlos Moreno and Thomas Brown look for companies with high and accelerating sales growth. This can be from new products, market share gains, new markets or pricing power. They demand a high rate of return on capital, and evidence that this will be sustained over the long term. Moreno and Brown believe that stock markets are poor at understanding long term change. As a result, they adopt a bottom up stock picking approach over the long term, being five years or more. ‘This means traipsing around Europe on EasyJet flights looking for businesses you think are going to be a lot bigger in the future’. Swiss industrial manufacturer Interoll is a significant holding in the fund. It supplies products including rollers, conveyors and pallet flow solutions for courier and postal services. Clients include Coca-Cola and Amazon. Moreno believes ‘Interoll is a brilliant play on the movement of small packages’.
the value of a good or service). Adyen, a Dutch company which is disrupting the traditional payments industry is a good example of this, and represents the second largest holding in the fund. Adyen makes it possible for companies such as Uber, Spotify and Netflix to accept payment from consumers around the world, using a variety of different payment methods. This enables
companies to scale quickly, which previously was not possible. In marked contrast to its competitors, Adyen has built its technology from scratch which confers a powerful competitive advantage. MID CAP FOCUS The Premier Miton European Opportunities Fund (BZ2K2M8) is a £2.39 billion fund investing in European companies with a mid-
HIGH QUALITY GROWTH The objective of Comgest Growth ex-UK (BQ1YBM1) is to create a portfolio consisting of high-quality growth companies. The fund is aimed at investors with a long-term investment horizon. Comgest fund manager Alistair Wittet explains ‘we like sectors with defensive growth characteristics and healthcare is an excellent example of this’. By Mark Gardner Senior Reporter
13 January 2022 | SHARES |
29
FEATURE
Three ways to beat the professionals DIY investors have several advantages over fund managers
D
o it yourself investors are taking on the professionals in record numbers and many are beating fund manager professionals. The number of people investing their own money has boomed during the pandemic thanks to low-cost platforms giving people easy and cheap access to the stock market. In 2021, DIY investor numbers hit seven million for the first time, according to research firm Boring Money, taking control of their own retirement savings and long-term investments through SIPPs and ISAs. It is easy to believe that the armies of analysts, reams for financial data and access to senior executives at companies will always favour professional investors. Yet retail investors have several edges of their own, and taking advantage of them can lead to superior investment returns. 1. LETTING THE WINNERS RUN Risk management is important, whether you’re investing your own money or managing a large portfolio. But individuals can go about managing risk differently. Funds follow strict portfolio management guidelines, such as not allowing a single stock to exceed a fixed percentage of the total portfolio. This means fund managers need to regularly
30
| SHARES | 13 January 2022
trim their most successful investments. For example, Scottish Mortgage (SMT), one of the UK’s most successful long-range investors, sold down its stake in Tesla despite the share price continuing to rally through 2021. Yes, judicious profit taking can be sensible, but DIY investors can decide for themselves when, or even if, they want to do that.
2. THINKING TRULY LONG-TERM Actively managed funds are typically benchmarked against an index or fund peers, with manager bonuses often tied to annual performance goals. This can lead to making decisions based on meeting shorter-term targets rather than value creation over the long haul. Retail investors are not hindered by benchmark chasing and can concentrate solely on generating great real returns over multiple years. True, some funds encourage real longerterm thinking, asking that their performance be judged over, say, five years but they cannot always rely that patience will be shown during less successful periods.
FEATURE 3. LARGE GAINS FROM SMALL STAKES Funds can trade companies with large market caps without issue but they are often forced to miss out on smaller, less liquid stocks because they cannot meaningfully invest. For the average DIY investors, this will seldom be a problem so they have a far bigger pool of potential stocks to buy. There are specialist small company funds, but even these can become victims of their own success, becoming so large that managing decent-sized smaller company stakes can become too big a drain on resources. These are simple factors that favour the DIY investor, and many already use them to their advantage. In 2020, soon after the pandemic first took hold, investment bank Goldman Sachs ran a study that compared stocks favoured by retail investors versus popular fund manager selections – and the DIY crowd came out on top. Covering the period between 23 March 2020 and mid-June 2020, retail investor picks produced an average 61% return versus the professionals’ 45% increase. The S&P 500 rose 36% in the same period, the FTSE 100 gained 14.5%. There are examples of ordinary
investors going against the market mood recently too. For example, over the past month retail investors using the AJ Bell investment platform have been snapping up shares in oil giants BP (BP.) and Royal Dutch Shell (RDSB), airlines International Consolidated Airlines (IAG) and EasyJet (EZJ), Cineworld (CINE), Lloyds Bank (LLOY) and Imperial Brands (IMB), companies all exposed one way or another to economic recovery, loosening restrictions on travel, rising interest rates and rotation into unloved stocks. It’s early days but so far so good for most of these calls. For example, Imperial Brands has risen nearly 3.5% over the past month and investors have scooped up a stock that offers an implied dividend yield in excess of 8%, BP is more than 7% higher, Lloyds is up 14%. EasyJet has surged by more
than a quarter in less than a month with travel restrictions significantly loosened for Brits.
And, again, Tesla has been a long-term favourite of DIY investors both in the US and in the UK, a company that has been called overvalued by many fund managers for years yet whose stock continues to defy gravity, rallying 720% in 2020 and another 50% last year. DISCLAIMER: Financial services company AJ Bell referenced in this article owns Shares magazine. The author (Steven Frazer) and editor (Tom Sieber) of this article own shares in AJ Bell. Steven Frazer also owns shares in Scottish Mortgage mentioned in this article. By Steven Frazer News Editor
13 January 2022 | SHARES |
31
FEATURE
Greggs is not a buy at this price despite overtaking McDonald’s The food-on-the-go firm faces some big challenges as a new boss prepares to take over
G
reggs’ (GRG) products might be good value, but its shares are not at the current price of £31.71. While this is a great business, investors need to wait for a cheap entry point before considering the shares. The company has bounced back from the pandemic and enjoyed a very good 2021. Research by Lumina Intelligence suggests Greggs even overtook McDonald’s to become the market leader in UK food-to-go in the 12 weeks to 28 November with a 10.7% share. Sadly, it seems as if all the good news is fully baked into its share price, and then some. The shares now trade on 28.8 times forecast earnings for the January 2023 financial year, having nearly trebled from their September 2020 lows below £12 in the wake of the pandemic. In Shares’ opinion, Greggs should
32
| SHARES | 13 January 2022
trade below a price to earnings ratio of 25-times. Its shares fell 6% on 6 January despite saying its full-year results would be slightly ahead of previous forecasts. The slump reflected an extremely demanding valuation for what remains, for all its attributes, a single-digit margin business in
a competitive and economically sensitive sector. Also not helping sentiment was some caution on recent trading amid the emergence of Omicron. Ambitious five-year targets, set by outgoing CEO Roger Whiteside and his management team in October 2021, will have to be delivered by his
FEATURE
Whiteside’s a winner: why Currie has big shoes to fill
Share price total return under Roger Whiteside*
Increase in total sales under Roger Whiteside**
647%
67.3%
*From 4 February 2013 to 6 January 2022
** Increase in total sales from January 2013 financial year to January 2022
replacement, Roisin Currie. An internal appointment, she will assume the reins in May 2022 with Whiteside having completed a highly successful nine-year stretch. Typically, an incoming chief executive will look to reset expectations to set a lower bar which they can clear and thereby
win over the market. Instead, Currie must execute on the existing plan to double turnover to around £2.4 billion by 2026 by expanding to 3,000 sites, from the current 2,181. She must also oversee the development of new opportunities including deliveries and evening walk-in
sales as well as the development of a loyalty-based app. These initiatives will require significant investment. Greggs could find achieving its goals challenging for several reasons. In the near term the company could be affected by supply chain and staffing issues while in the medium to longer term a rising cost of living for customers and a potentially permanent shift towards hybrid working could stymie its ambitions. If people aren’t in the office as much, then footfall for Greggs’ town and city centre outlets will be lower. Mitigating this to a certain extent is Greggs’ strong footprint in more suburban and residential areas where it could benefit from so-called ‘food to go home’ sales. By Tom Sieber Deputy Editor
13 January 2022 | SHARES |
33
Latest deal at newly focused DCC set to boost growth and margins Diversified distributor has increased its footprint in the US and the technology space
O
nce.
34
| SHARES | 13 January 2022
3% refueling. 13 January 2022 | SHARES |
35 (businessto 36
| SHARES | 13 January 2022added. By Ian Conway Companies Editor
Kavango Resources is an exploration group targeting the discovery of mineral deposits in Botswana. The company’s operating segment include Exploration and Corporate.
Sovereign Metals is a mineral exploration company. It is engaged in the mineral exploration, identification, and appraisal of resource projects.
More to be announced
The webinar can be accessed on any device by registering using the link above
Event details
Presentations to start at 18:00 GMT
Lisa Frankel media.events@ajbell.co.uk
Register for free now
What are the paying-in rules for an untouched SIPP? A reader approaching 70 is eager to understand the best options for managing retirement savings I have two SIPPs and one defined benefit pension. This year I have withdrawn the 25% tax-free lump sum from one of my SIPPs and later this tax year, when I reach 70, I will have to draw on my defined benefit pension. What is my maximum contribution to the SIPP which has not yet been accessed? Is it £4,000 or £40,000? With my defined benefit pension, does it make financial sense to take the 25% lump sum or leave it all in the pension scheme to give a higher annual pension? I do not need the cash and would invest any that I drew down. My marginal tax rate this year is 45% but it will drop to 40% next year. Nicholas Tom Selby, AJ Bell Head of Retirement Policy says:
The maximum you can pay into your pension(s) each year will depend on your personal circumstances and apply across all your registered pension schemes. In 2021/22 the maximum annual allowance anyone can enjoy, including employer contributions, personal contributions and tax relief, is £40,000. 38
| SHARES | 13 January 2022
Personal pension contributions that benefit from tax relief are limited to 100% of your earnings. The £4,000 money purchase annual allowance or MPAA only kicks in if you take flexible income withdrawals from a defined contribution pension like a SIPP. This includes taking an income via drawdown or ad-hoc lump sums, also sometimes referred to as UFPLS. If you only take your 25% tax-free cash or take an income from an annuity or a defined benefit pension this will not trigger the MPAA. If you are a very high earner, it’s possible the annual allowance ‘taper’ will affect how much you can save in a pension each year. You can read more about how the taper works here. Tax-free cash from defined benefit schemes works slightly differently to defined contribution schemes such as SIPPs. In a SIPP you are usually entitled to 25% of the value of your fund (up to the lifetime allowance, which is currently £1,073,100) and you choose an income route for the remainder of the pot. In a defined benefit scheme, the maximum is still usually 25% of the value of your total
benefits but it can be provided in two ways, either as a separate lump sum or by giving up or ‘commuting’ some of your guaranteed income. In terms of tax-free cash that reduces your guaranteed income, whether taking it is the best course of action will depend on a variety of factors including how much defined benefit income you must give up in return, your other income sources, marginal tax rate and life expectancy..
Helping you with money issues
PERSONAL FINANCE
Key personal finance dates for your 2022 diary Get clued up on what’s in store for the year ahead
T
his year is bringing a whole host of changes to personal finances, from the introduction of a new tax to certain paper notes being phased out. Here’s a run-through of what’s happening in 2022 and the key finance dates for your diary.
Train fares increased by 3.8% at the start of the year, which means commuters will be paying more for their season tickets. The increase is determined by the RPI measure of inflation from July last year, but passengers will be relieved a more current figure isn’t used, as RPI inflation is now above 7%. The move represents the largest increase in a decade, and will do little to encourage employees back to the office. January also brings a small tweak to inheritance tax rules, which means that people who died and were domiciled in the UK and who aren’t liable to pay inheritance tax will no longer have to submit full accounts and reams of paperwork.
energy price cap will rise to. The change won’t come in until April, but many households will be keen to hear how much their bills will rise by. One estimate from analysts at Cornwall Insight has it rising by 50%, meaning the average household usage will rise to more than £1,900 a year. Also in February is the next decision from the Bank of England on interest rates, with all eyes on whether they increase rates again, after raising them to 0.25% in December.
The main event in February is the announcement of what the
April brings the tax year end, which usually comes with a host
of tax rate changes. This year most allowances have been frozen, so people won’t get the benefit of an increased income tax band, personal allowance, Isa allowance or pensions lifetime allowance, among others. The biggest change is the introduction of a new health and social care levy, which effectively means a 1.5 percentage point increase in National Insurance. It means that the National Insurance rate will increase from 12% to 13.25% on earnings between the ‘primary’ income threshold (currently £9,568 per year) and the ‘upper’ income threshold (currently £50,270 per year), and from 2% to 3.25% on earnings above £50,270. The costs will also increase 13 January 2022 | SHARES |
39
PERSONAL FINANCE for employers. This extra tax will also be due on dividends, with the rate increasing by 1.5 percentage points for every income tax level, so it will stand at 8.75% for basic-rate payers, 33.75% for higher-rate payers and 39.35% for additional rate payers. This tax is only due on incomepaying investments that aren’t in an ISA or pension, so it means some may decide to shovel some of their investments into their ISA before the tax year end, to avoid some of the impact. April will also bring pay rises for many, as the state pension will rise by 3.1%, taking the ‘old’ basic state pension from £137.60 per week to £141.85 per week and the ‘new’ flat-rate state pension from £179.60 per week to £185.15 per week. The National
Helping you with money issues
Living Wage will also increase – the rates vary depending on the age of the worker, but for those aged 23 and over it will rise from £8.91 to £9.50.
This will be the last month you can use the old style £20 and £50 notes, as from 30 September they will be withdrawn – so time to raid your piggy banks and look down the back of the sofa.
The final month of the year will bring the end of the mortgage guarantee scheme, which the government introduced for 95% mortgages to help encourage lenders to give money to riskier borrowers. The Government may decide to extend the scheme though. By Laura Suter AJ Bell Head of Personal Finance
READ MORE STORIES ON OUR WEBSITE Shares publishes news and features on its website in addition to content that appears in the weekly digital magazine. THE LATEST STORIES INCLUDE: TERRY SMITH SLAMS UNDERPERFORMER UNILEVER
ANALYST TAKE ON DARKTRACE GUIDANCE HIKE; STOCK SURGES
SHARESMAGAZINE.CO.UK SIGN UP FOR OUR DAILY EMAIL 19 August 2021 | SHARES | 40 40 | SHARESFor | 13 January the2022 latest investment news delivered to your inbox
RUSS MOULD
AJ Bell Investment Director
The least and most popular stocks heading into 2022 Identifying the firms which analysts love and those they hate can be a useful exercise
E
very year this column tracks the ratings put on stocks across the FTSE 100 and FTSE 350 by the investment banks which provide research on the UK equity market. And what catches the eye this year is that the analyst community is the most bullish it has ever been since our first survey back in 2015, based on stock-specific, public recommendations. As we enter 2022, 57% of all stock ratings are buys and just 9% are sells for constituents of the FTSE 100, the highest and lowest scores over the past eight years. For the FTSE 350 index 59% of all recommendations are positive ratings and just 8% negative ones. Without endorsing these views, it is worth asking if investors should consider this is a signal to buy more London-traded stocks or actually a warning to cut exposure to UK equities. Momentum players may feel inclined to go with the positive flow. Contrarians may take the opposite view as they bear in mind legendary investor John Templeton’s maxim that ‘bull markets are founded on pessimism, grow on scepticism, mature on optimism and die on euphoria’.
A way to research which path may be the best to follow is to assess the efficacy of individual recommendations. TRACK AND TRACE This column has back-tested the performance on the most and least popular stocks at the start of a year, as measured by the percentages of ‘buy’ and ‘sell’ ratings attributed to them by analysts. The bad news is the analysts’ top picks failed to beat the FTSE 100 index in 2015, 2016, 2017, 2018, 2020 and now 2021, despite all of their diligence. This is not to poke fun at the analysts. It just shows how hard picking individual stocks can be, even if it is your full-time job (and this column should know, having been an equity analyst at a leading investment bank from 1993 to 2005). To further the case for the defence, the degree of underperformance was relatively modest and eight of the 10 most popular names, based on ‘buy’ ratings, provided positive total returns. Better still in 2021, the least popular names in the FTSE 100 did badly. Knowing which names to avoid can be every bit as valuable as knowing which names to buy, if not more so.
13 January 2022 | SHARES |
41
RUSS MOULD
AJ Bell Investment Director Analysts can also take satisfaction from how their labours worked out across the FTSE 350. When it came to the broader index, their 10 most popular names massively outperformed and the least popular 10 stocks massively underperformed. Six of the least-favoured names produced negative
total returns even as the FTSE 350 generated a comfortable mid-teens percentage advance, so the research there was spot on. Brokers’ top FTSE 350 picks beat the index and the least popular names underperformed it in 2021
Brokers’ top FTSE 100 picks lagged the index in 2021 but the least popular names underperformed to a greater degree
THE WAY AHEAD The ultimate conclusion still probably has to be that broker research needs to be treated with a degree 42
| SHARES | 13 January 2022
RUSS MOULD
AJ Bell Investment Director of caution (assuming that investors can get their hands on it in the first place). Anyone prepared to pick their own stocks rather than pay a fund manager or tracker fund to do it for them simply must do their own research on individual companies before they even think about buying or selling any of its shares. At best, broker research may be a useful filter, at worst a contrarian indicator, especially given
Warren Buffett’s observation that ‘you cannot buy what is popular and do well’. With that maxim in mind, investors might like to know which stocks are most liked – and disliked – by analysts at the start of 2022. The two tables below list the names which investors may wish to analyse in greater depth, or simply avoid altogether, depending upon their view of the value of the research provided.
The 10 most and least popular FTSE 100 stocks with analysts at the start of 2022
The 10 most and least popular FTSE 350 stocks with analysts at the start of 2022
13 January 2022 | SHARES |
43 A drug delivery technology company focused on improving the bio-delivery and bio-distribution of medicines. Midatech is progressing a pipeline of differentiated therapeutics in areas of high unmet need for the benefit of patients.
TinyBuild (TBLD) Jaz Salati, Head of M&A and IR A video games publisher and developer with global operations. Its strategic focus is in creating long-lasting IP by partnering with video games developers, establishing a stable platform on which to build multigame and multimedia franchises.
Visit the Shares website for the latest company presentations, market commentary, fund manager interviews and explore our extensive video archive.
CLICK TO PLAY EACH VIDEO
SPOTLIGHT
INDEX Main Market
Royal Mail
AO World
23
Aviva
12
Barratt Developments BP British American Tobacco Carnival Cineworld
9 12, 31 21 8 31
Saga
8
TUI
8
Unilever
21
Vistry
9
Vodafone
12
Wizz Air
8
WPP
12 Investment Trusts
DCC
34
DWF
13
East Star Resources EasyJet
7 8, 31
Greggs
32
Imperial Brands
31
International Consolidated Airlines
8, 31
Jet2
8
Kingspan
9
Lloyds Bank
31
Marks & Spencer
12
Nostrum Oil & Gas
7
Persimmon
9
Polymetal
7
Redrow
9
Royal Dutch Shell
7, 12, 31
Funds
12
Allianz Technology
11
Baillie Gifford European Growth Trust
28
Bankers
19
BlackRock Greater Europe Investment Trust
28
Cordiant Digital Infrastructure
14
Geiger Counter
7
Odyssean Investment Trust
14
RIT Capital
20
Scottish Mortgage
30
Strategic Equity Capital
14
Temple Bar Investment Trust
11
AIM ASOS
23
Boohoo
23
Allianz Strategic Bond Fund
22
Comgest Growth ex-UK
29
Fidelity Global Special Situations
18
Yellow Cake
7:
COMPANIES EDITOR
23
29
WHO WE ARE
7
Gear4Music
Premier Miton European Opportunities Fund
Trading updates: 17 Jan: DP Poland, Taylor Wimpey. 18 Jan: Carr’s, Energean, Hays, Henry Boot, Hotel Chocolat, Integrafin, Rio Tinto. 19 Jan: Antofagasta, Audioboom, BHP, Burberry, Centammin, Diploma, Galliford Try, JD Wetherspoon, Liontrust Asset Management, Midwich, QinetiQ. 20 Jan: Associated British Foods, CMC Markets, Headlam, Kier, Luceco, N Brown, Paypoint, Premier Foods, Workspace. 21 Jan: Close Brothers, Record.
Central Asian Metals
15
18
Half-year results: 18 Jan: Kromek. 19 Jan: Ilika, Superdry, Time Finance. 21 Jan: TheWorks.co.uk
James Crux @SharesMagJames
27
Liontrust Global Innovation
Full-year results: 18 Jan: Pressure Technologies, Ramsdens, Watkin Jones. 19 Jan: Crest Nicholson. 20 Jan: Blue Prism, Ibstock.
7
FRP Advisory
21
KEY ANNOUNCEMENTS OVER THE NEXT WEEK
Caspian Sunrise
Facilities by ADF
Guinness Global Equity Income
SENIOR REPORTER:
Mark Gardner.
13 January 2022 | SHARES |
45 | https://issuu.com/shares-magazine/docs/youinvest_shares_130122?fr=sYzNjYzQ1MjMxMzA | CC-MAIN-2022-21 | refinedweb | 7,830 | 57.1 |
Saying Hello In React Native
React Native and Expo makes it easy to write cross-platform mobile apps. Let us start with a hello world.#code , #nodejs , #rn , #react
I have been blogging about React.js for sometime. One of the reasons I started learning React.js is to learn React Native, so that I can create native mobile apps for multiple platforms.
React-native is still evolving — react.js is at v16.0, while react-native is only at v0.49. Still, a large ecosystem has already developed with tools, third-party plugins, and marketplace. One of the development tool is Expo.
Usually you would need a Mac to develop iOS apps. With Expo, you can develop iOS apps without Mac, though you would need an iOS device to test the app. Expo offers two products: a development tool with which you can develop react-native mobile apps, and a mobile app with which you can preview your app as you develop.
Getting started with Expo is easy.
- Go to their home page and download the tool for your platform — Mac, Linux, or Windows.
- Install react-native (which in turn will require node.js).
With these two, you are ready for your first react-native mobile app.
Click on Project->New Project, and enter a folder name for your new project. Expo will automatically create folders and files for the new project. After creating the necessary folders and files, Expo will open the project. Once opened, it will display:
Project opened! You can now use the “Share” or “Device” buttons to view your project.
Click on “Device” and then you can open on iOS simulator. You will see the app opened in the simulator.
If you don’t have Mac machine but have iOS device, then you can use your iOS device to view your new app. Download the Expo app from App Store. Then click on “Share” button the IDE. It will show a QR code. Scan it from the Expo mobile app. It will open your new app. It will even refresh when you modify the code.
You can follow similar step to test the app on Android devices. If you have not installed the Android simulator but have an Android device, download the Android app from the Play Store. Follow the steps as like for iOS to view the app on Android phone.
Now that we have seen the app, let us modify it to display “Hello World”.
Expo would’ve created the below directory structure.
. ├── App.js ├── app.json ├── assets ├── node_modules └── package.json
We have to modify
App.js. Open it in your favorite text editor. You’ll see the following code:', }, });
Go ahead and change the text inside
<Text></Text> element to:
<Text>Hello World!</Text>
Now the default component should look like this.
export default class App extends React.Component { render() { return ( <View style={styles.container}> <Text>Hello World!</Text> </View> ); } }
When you save the file, Expo will automatically compile and refresh the simulator (and apps opened via Expo mobile app).
You should see
Hello World!.
That is your first cross-platform mobile app. Aren’t you happy?
Subscribe via below form to get notified whenever I write a new post.
This is part of Learn React Native series | https://prudentdevs.club/hello-rn | CC-MAIN-2019-18 | refinedweb | 546 | 69.68 |
Memo
Take and organize notes like text messages.
Multiple Linear Regression Analysis is just like Simple Linear Regression but with one or more predictors. For example, high school GPA of a college student may be used to predict the students success in college. However, we know that there are other factors that can better predict students college success. Multiple linear regression allows us to make such predictions.
The general additive multiple regression model equation is described as followed:
y = Bo + B1x1 + B2x2 + ... + BnXn + error
Where the standard error is denoted as epsilon
In multiple linear regression, parameter estimates are determined by the principle of least squares.
Sum of Squared Error:
SSE += (y[i] - y_hat)**2 where
y[i] is
the observed value while
y_hat is the predicted
value.
Sum of Squared Regression:
SSR += (y_hat - mean_y)**2 where
y_hat is the predicted value and
mean_y is the mean of the observations.
Sum of Squared Totals:
SST += (y[i] - mean_y)**2 where
y[i] is
the observed value and the
mean_y is the mean of the
observed values.
Mean Squared Regression:
MSR = SSR / k where k is the number of predictors
Mean Squared Error:
MSE = SSE / (n - (k + 1)) where
k is the
number of predictors and
n is the number of
observations.
Coefficient of Determination:
1 - (sse / sst). The coefficient of determination
describes how much of the data influences the line of best fit. A
number that is close to 1 means that the points all lie close to
the regression line.
Before we proceed to interpret the model, we first have to perform the Global F-test; to help us verify that the output would indeed depend on at least one of the variables. The significance of the global f-test has the following hypothesis:
Ho : B1 = B2 = ... = Bk = 0 Ha : At least one of Bj != 0
Test Statistic or F-test: for a
multiple linear regresion is as followed:
F = MSR / MSE where the degrees of freedom is
k and
n - (k + 1). If the F value is
larger than the significance level (usually 0.05 if not
specified), we reject the null hypothesis; meaning that the
response is dependent on at least one of the predictors. Therefor,
we can proceed to interpret the multiple regresion model.
There can be instances in which one of the variables in a multiple
linear regression model will be categorical. Ideally we would
break up the
n categories into
n dummy
variables. For example, suppose we are trying to predict the
success of a college student based on GPA and major (Economics,
Math, and Computer Science). GPA will be denoted as
x1 and a student majoring in Economics, Math, and
Computer Science will be denoted as
x2, x3, and x4 respectively.
x2 = 1 if major is economics x2 = 0 otherwise x3 = 1 if major is math x3 = 0 otherwise x4 = 1 if major is computer science x4 = 0 otherwise
Our model would look something like this
y = B0 + B1x1 + B2x2 + B3x3 + B4x4
SKLearn is a machine learning library for Python and R. It's known for its friendliness to beginners without the compromise for efficiency and accuracy.
Before we begin, make sure you have SKLearn installed in your machine. You can learn how to install SKLearn here
You will also need to install Python in your device. You can learn how to install Python here
Lastly, you'll need a good text editor or IDE. I personally use Jupyter Notebooks or Sublime Text 3; but you are free to use whatever works for you. If you want to tryout Jupyter notebooks, the installation guide is here or Sublime Text 3 is here
For a sample of
n = 20 individuals, we have
measurements of
y = body fat,
x1 = triceps skinfold thickness,
x2 = thigh circumference, and
x3 = midarm circumference.
First we import our python libraries
from sklearn.linear_model import LinearRegression import numpy as np
The data will be using is listed below. Feel free to copy the data
or download the textfile here. Each row
in
X is an independent observation (predictors)
ordered by
[triceps skinfold thickness, thigh circumference, midarm
circumference]
and
y is our body fat (response).
X = np.array([[19.5, 43.1, 29.1], [24.7, 49.8, 28.2], [30.7, 51.9, 37.0], [29.8, 54.3, 31.1], [19.1, 42.2, 30.9], [25.6, 53.9, 23.7], [31.4, 58.5, 27.6], [27.9, 52.1, 30.6], [22.1, 49.9, 23.2], [25.5, 53.5, 24.8], [31.1, 56.6, 30.0], [30.4, 56.7, 28.3], [18.7, 46.5, 23.0], [19.7, 44.2, 28.6], [14.6, 42.7, 21.3], [29.5, 54.4, 30.1], [27.7, 55.3, 25.7], [30.2, 58.6, 24.6], [22.7, 48.2, 27.1], [25.2, 51.0, 27.5]]) y = np.array([[11.9,22.8,18.7,20.1,12.9,21.7,27.1,25.4,21.3,19.3,25.4,27.2,11.7,17.8,12.8,23.9,22.6,25.4,14.8,21.1]]).T
Using SKLearn, we want to use the
LinearRegression() function and fit the model.
regression_model = LinearRegression().fit(X,y)
From our
regression_model, we can print out our
intercepts and coefficients to complete our multiple linear
regression model.
B0 = regression_model.intercept_ B = regression_model.coef_ print(B0, B)
After running your code, your intercept and coefficients should look something like this
[117.08469478] [[ 4.33409201 -2.85684794 -2.18606025]]
We can also use the
predict() function to predict the
individuals body fat by inputing values for triceps skinfold
thickness, thigh circumference, midarm circumference.
prediction = reg.predict([[19.5, 43.1, 29.1]]) print(prediction)
[[20.21884106]]
Before we interpret the model, lets perform the Global F-test to verify that predicting the body fat would indeed depend on at least one of the predictors. Recall the Parameter Estimations above. We need to calculate the sum of squares before calculating the f value. Create a function that will calculate the sum of squares.
def get_sum_of_squares(): ssr = 0 sse = 0 sst = 0 mean_y = np.mean(y) for i in range(20): y_hat = regression_model.predict([X[i]]) ssr += (y_hat - mean_y)**2 sse += (y[i][0] - y_hat)**2 sst += (y[i][0] - mean_y)**2 return (ssr, sse, sst) sum_of_squares = get_sum_of_squares()
If you want to check your function to see if you get the right numbers, this is my output.
ssr = 396.98461183, sse = 98.40488817, sst = 495.3894999999999 # Don't worry about format
Create a function to calculate the global F-test
def global_f_test(): n = len(yy) k = 3 ssr = ss[0] sse = ss[1] msr = ssr / k mse = sse / (n - (k + 1)) return msr / mse
Your global F-test should be:
[[21.5157123]] which is
significantly higher than the significant value (it was not
specified so by default, our significant value is 0.05). Therefor,
we can proceed to interpret the model.
From Step 3, we know the y-intercept is
117.08469478 and our
b1,
b2,
and
b3 are
4.33409201,
-2.85684794, and
-2.18606025 respectively. Our fitted model would look
like this:
y = 4.33409201(x1) + -2.85684794(x2) + -2.18606025(x3) + 117.08469478
Here we can interpret that
• For every unit increase of the thickness of an individuals triceps, we expect an increase in body fat by 4.33%
• For every unit increase of the thickness of an individuals thighs, we expect a decrease in body fat by -2.85%
• For every unit increase of the thickness of an individuals midarm, we expect a decrease in body fat by -2.19%
Just for practice, we can calculate the coefficient of determination. Recall the coefficient of determination formula under Parameter Estimation.
def coefficient_of_determination(): sse = ss[1] sst = ss[2] return 1 - (sse / sst)
coefficient of determination = [[0.80135855]]
The value is close to 1, therefor we can say that most of the points lie close to the regression line.
Sum of Squares Formula from 365datascience.com
F-test for Linear Regression from DePaul University Steve D. Jost | https://articlesbycyril.com/statistics/multiple-linear-regression-with-sklearn.html | CC-MAIN-2019-43 | refinedweb | 1,354 | 62.38 |
Type: Posts; User: Labyrinth
Awesome, it works! Thanks a bunch! How very elegant. I will study + learn from it.
Neat use of cin type space skipping + ifstream c.str.
I'm surprised it could be simplified still...
I tried to run the MSVC debugger, but it just exists after inputting the filenames and gives me no information. I'm not familiar with debuggers so I was looking at some GDB commands but I'm still not...
I'm trying to write a simple console app, it reads input from two files, does some math with them, and outputs the results into a new file.
The files have data that looks like this:
5.96735...
Ok cool. It works without crashing now. Thanks for your help I really appreciate it. The LPBYTE thing is fixed.
One issue I am having is that it won't let me click the 'x' to close it though. It...
Yes it should! I put rabbit there to remind me to go back and fix it at some point lol. Thanks.
Right ok. Fixed.
Are you saying that I shouldn't send a WM_PAINT message, or that I'm not...
#include "stdafx.h"
#include "inter2.h"
#include <iostream>
#include <Strsafe.h>
#define MAX_LOADSTRING 100
// Global Variables:
HINSTANCE hInst;
TCHAR szTitle[MAX_LOADSTRING];
Any ideas?
What needs to be done to get data.mouse.lLastX updated live on the screen?
Here's the code now after I've been poking at it.
#include "stdafx.h"
Ok, bit of a rewrite :-)
#include "stdafx.h"
#include "inter2.h"
#include <Strsafe.h>
#include <iostream>
//#include <sstream>
//#include <string>
Yikes. If it's easier I could just have a program that displays a window with text and have it update with the mouse movement ala direct x mouserate checker.
I'm not sure I trust anything other...
I changed RegisterRawInputDevices(Rid, 2, sizeof(Rid[0])) == FALSE)
to RegisterRawInputDevices(Rid, 1, sizeof(Rid[0])) == FALSE)
Now I don't get the 1004 error, hopefully that's because the...
I am a novice programmer trying to create the following application:
1. Can just be a simple CLI program.
2. Gets mouse input from WM_Input, not for buttons just whatever the mouse sends... | http://forums.codeguru.com/search.php?s=453769201a7cdc266d3b9c9278820666&searchid=6442563 | CC-MAIN-2015-11 | refinedweb | 368 | 78.04 |
Difference between revisions of "Development/Tutorials/Plasma4/QML/API"
Revision as of 10:35, 26 November 2012
Contents
- 1 Introduction to the Plasmoid QML Declarative API
- 2 Properties exported from the main QML item
- 3 Main Plasma QML Classes
- 3.1 Data Engines
- 3.2 Popup Applet
- 3.3 Plasma Themes
- 3.4 Top Level windows
- 3.5 Containments
- 4 Plasma QtComponents (4.8)
- 5 QtExtraComponents based upon the Plasma JavaScript engine, making the API of the JavaScript part identical to the one of the JavaScript plasmoids engine. To see the api of the global Plasmoid object, see the JavaScript API documentation. (TODO: the JavaScript api page should probably be copied and stripped down the imperative bits not present there, it would make it harder to update tough) The most important API for using graphical widgets is the Plasma QtComp. 0.1"
-() make your own." } } }
Popup Applet
So you want your QML applet to be a popup applet, like the device notifier (an icon in the panel shows and expands the applet)?
Why, that's easy.
To change your plasmoid from being a regular boring one, in your metadata.desktop, simply change this following line:
ServiceTypes=Plasma/Applet
To:
ServiceTypes=Plasma/Applet,Plasma/PopupApplet
Then in the main QML item's Component.onCompleted, do:
plasmoid.popupIcon = "konqueror"
If you want to use other elements instead of an icon when collapsed in a panel, use the compactRepresentation property in the root Item.
Plasma Themes
Theme
This class instantiable from QML provides access to the Plasma Theme colors and other facilities such as fonts. From KDE 4.8 a Theme instance is always present given the org.kde.plasma.core plugin was imported, is not necessary to create it by hand. It has the following properties:
- String themeName )
- size mSize the size, width and height of an uppercase "M" in this font (read only)
Theme is also used to control icon sizes, with the property iconSize.
import QtQuick 1.1 import org.kde.plasma.core 0.1 it possible to use Plasma tooltips with any QML item.
Properties:
- Item target: the QML item we want to show a tooltip of
- String mainText
- String subText
- String image: freedesktop compliant icon name as image of the tooltip ) | https://techbase.kde.org/index.php?title=Development/Tutorials/Plasma4/QML/API&diff=next&oldid=76846&printable=yes | CC-MAIN-2020-40 | refinedweb | 373 | 57.67 |
Your browser does not seem to support JavaScript. As a result, your viewing experience will be diminished, and you have been placed in read-only mode.
Please download a browser that supports JavaScript, or enable it if it's disabled (i.e. NoScript).
So I am in the process of learning how Python and scripting in C4D works.
Working with this interesting tutorial series, but have falled down at the first hurdle: nothing seems to run from the expression editor.
I have run scripts successfully from the Script Manager, but nothing so far from the Expression Editor.
All I have is:
a cube with a python tag
The following code:
import c4d
import sys
#Welcome to the world of Python
def main():
print sys.version
It runs fine in the command line and in the script manager, but not the expression editor looking at the python tag on the cube.
Any suggestions where I may have gone wrong?
R21.207 (Build RB303831)
You may want to make a viewport visible.
Apparently, your viewport is somewhere in the background. Under those circumstances, the evaluation of the object tree seems to skip a beat... C4D seems to be thinking "hey, if you don't wanna see my results, I won't bother doing anything"
I verified this on my system - no viewport, no output!
(Don't ask me why Maxon is doing that, I don't have access to the inner code...)
The code actually works fine for me being in a Python Tag on a Cube. When the scene is refreshed, the tag is executed, and the console shows the version line.
What's happening (or not happening) on your side? Remember that you need to trigger the execution of the tag by doing something in the scene like selecting or forwarding the timeline; the execution context is different from the script manager (where you explicitly trigger the execution by clicking "Execute"). With a tag, the execution is bound to the evaluation of the scene tree.
Video here
Above is a quick screen grab of me trying to run it.
Interesting - not even pressing Execute in the Expression Editor creates an output if the viewport is not visible. Duh, I would have expected that. Maybe it's an actual bug.
Bringing the viewport into focus worked... wow, I had a feeling it was something simple like that! | https://plugincafe.maxon.net/topic/12405/trouble-with-expression-editor | CC-MAIN-2021-39 | refinedweb | 396 | 72.76 |
XQuery Prolog
Applies To: SQL Server 2014, SQL Server 2016 Preview
Topic Status: Some information in this topic is preview and subject to change in future releases. Preview information describes new features or changes to existing features in Microsoft SQL Server 2016 Community Technology Preview 2 (CTP2).
An XQuery query is made up of a prolog and a body. The XQuery prolog is a series of declarations and definitions that together create the required environment for query processing. In SQL Server, the XQuery prolog can include namespace declarations. The XQuery body is made up of a sequence of expressions that specify the intended query result.
For example, the following XQuery is specified against the Instructions column of xml type that stores manufacturing instructions as XML. The query retrieves the manufacturing instructions for the work center location 10. The query() method of the xml data type is used to specify the XQuery.
Note the following from the previous query:
The XQuery prolog includes a namespace prefix (AWMI) declaration, (namespace AWMI="";.
The declare namespace keyword defines a namespace prefix that is used later in the query body.
/AWMI:root/AWMI:Location[@LocationID="10"] is the query body.
A namespace declaration defines a prefix and associates it with a namespace URI, as shown in the following query. In the query, CatalogDescription is an xml type column.
In specifying XQuery against this column, the query prolog specifies the declare namespace declaration to associate the prefix PD, product description, with the namespace URI. This prefix is then used in the query body instead of the namespace URI. The nodes in the resulting XML are in the namespace associated with the namespace URI.
To improve query readability, you can declare namespaces by using WITH XMLNAMESPACES instead of declaring prefix and namespace binding in the query prolog by using declare namespace.
For more information, see, Add Namespaces to Queries with WITH XMLNAMESPACES.
Default Namespace Declaration
Instead of declaring a namespace prefix by using the declare namespace declaration, you can use the declare default element namespace declaration to bind a default namespace for element names. In this case, you do not specify any prefix.
In the following example, the path expression in the query body does not specify a namespace prefix. By default, all element names belong to the default namespace specified in the prolog.
You can declare a default namespace by using WITH XMLNAMESPACES: | https://msdn.microsoft.com/en-us/library/ms175178.aspx | CC-MAIN-2015-48 | refinedweb | 397 | 54.93 |
CURLMOPT_PUSHFUNCTION explained
NAME
CURLMOPT_PUSHFUNCTION - callback that approves or denies server pushes
SYNOPSIS
#include <curl/curl.h> char *curl_pushheader_bynum(struct curl_pushheaders *h, size_t num); char *curl_pushheader_byname(struct curl_pushheaders *h, const char *name); int curl_push_callback(CURL *parent, CURL *easy, size_t num_headers, struct curl_pushheaders *headers, void *userp); CURLMcode curl_multi_setopt(CURLM *handle, CURLMOPT_PUSHFUNCTION, curl_push_callback func);
DESCRIPTION
This callback gets called when a new HTTP/2 stream is being pushed by the server (using the PUSH_PROMISE frame). If no push callback is set, all offered pushes will be denied automatically.
CALLBACK DESCRIPTION
The callback gets its arguments like this:
parent is the handle of the stream on which this push arrives. The new handle has been duphandle()d from the parent, meaning that it has gotten all its options inherited. It is then up to the application to alter any options if desired.
easy is a newly created handle that represents this upcoming transfer.
num_headers is the number of name+value pairs that was received and can be accessed
headers is a handle used to access push headers using the accessor functions described below. This only accesses and provides the PUSH_PROMISE headers, the normal response headers will be provided in the header callback as usual.
userp is the pointer set with CURLMOPT_PUSHDATA
If the callback returns CURL_PUSH_OK, the 'easy' handle will be added to the multi handle, the callback must not do that by itself.
The callback can access PUSH_PROMISE headers with two accessor functions. These functions can only be used from within this callback and they can only access the PUSH_PROMISE headers. The normal response headers will be passed to the header callback for pushed streams just as for normal streams.
Returns the header at index 'num' (or NULL). The returned pointer points to a "name:value" string that will be freed when this callback returns.
Returns the value for the given header name (or NULL). This is a shortcut so that the application doesn't have to loop through all headers to find the one it is interested in. The data pointed will be freed when this callback returns. If more than one header field use the same name, this returns only the first one.
CALLBACK RETURN VALUE
The application has accepted the stream and it can now start receiving data, the ownership of the CURL handle has been taken over by the application.
The callback denies the stream and no data for this will reach the application, the easy handle will be destroyed by libcurl.
Returning this will reject the pushed stream and return an error back on the parent stream making it get closed with an error. (Added in curl 7.72.0)
All other return codes are reserved for future use.
DEFAULT
PROTOCOLS
EXAMPLE
/* only allow pushes for file names starting with "push-" */ int push_callback(CURL *parent, CURL *easy, size_t num_headers, struct curl_pushheaders *headers, void *userp) { char *headp; int *transfers = (int *)userp; FILE *out; headp = curl_pushheader_byname(headers, ":path"); if(headp && !strncmp(headp, "/push-", 6)) { fprintf(stderr, "The PATH is %s\n", headp); /* save the push here */ out = fopen("pushed-stream", "wb"); /* write to this file */ curl_easy_setopt(easy, CURLOPT_WRITEDATA, out); (*transfers)++; /* one more */ return CURL_PUSH_OK; } return CURL_PUSH_DENY; } curl_multi_setopt(multi, CURLMOPT_PUSHFUNCTION, push_callback); curl_multi_setopt(multi, CURLMOPT_PUSHDATA, &counter);
AVAILABILITY
RETURN VALUE
Returns CURLM_OK if the option is supported, and CURLM_UNKNOWN_OPTION if not.
SEE ALSO
CURLMOPT_PUSHDATA(3), CURLMOPT_PIPELINING(3), CURLOPT_PIPEWAIT(3), RFC7540
This HTML page was made with roffit. | https://curl.se/libcurl/c/CURLMOPT_PUSHFUNCTION.html | CC-MAIN-2020-50 | refinedweb | 564 | 51.28 |
Advanced setup: Sleeping and waking up remotely
You can skip this portion if you don't intend to do any power management, but this could be something worth doing after you are set up with networked renders. It's also a good example of how you can get a render queue manager feature without a render manager. Since I do my batch renders from a command line script—actually, I cheat a little, and my V-Ray Tuner script writes them for me—I like to add a few things to the batch script to give me added notifications via Growl...

…and to put all the machines to sleep once the jobs are done so I use as little energy as possible. If you’re looking to get up and running with command line renders without having to point to the long full path (/Applications/Autodesk/Maya2014/Maya.app/Contents/MacOS/Render or "/Applications/CINEMA 4D R12/CINEMA 4D.app/Contents/MacOS/CINEMA 4D"
for example), I wrote a guide for OS X here, and that setup workflow also applies to other applications other than Maya. There is a good guide for Maya and Windows here, and that also applies to other applications, like Cinema 4D.
Basically, the idea is the same for all: you use a PATH variable to point your system to the folder with the binary that does the rendering, open a terminal/command prompt, and type Render /path/to/yourfile.mb and you’re rendering. If you are using a renderer like V-Ray or mental ray that is configured to automatically use the referenced muscle, then these command renders will use all those machines as well.
To get your host machine to sleep at the end of the batch, you simply add the sleep command for your respective OS at the end of the executable batch script. So if I’m rendering the first 24 frames of an animation for mental ray for Maya on any given platform and want to sleep the machine at the end, my executable plain text batch file would look like this:
Mac:
Render -r mr -s 1 -e 24 /path/to/file.mb
osascript -e 'tell application "Finder" to sleep'
Windows (local command prompt syntax):
Render -r mr -s 1 -e 24 C:\path\to\file.mb (command prompt syntax)
%windir%\\system32\\rundll32.exe PowrProf.dll, SetSuspendState 0,1,0
Windows (Cygwin/ssh syntax):
/cygdrive/c/Program\ Files/Autodesk/Maya2015/bin/Render -r mr -s 1 -e 24 /path/to/file.mb
shutdown /p
You can set up the Cygwin PATH variable for the Render binary in the same way as you do for Linux or OS X, since all three use the BASH shell by default. Here is an outline of the Cygwin power management commands.
Linux:
Render -r mr -s 1 -e 24 /path/to/file.mb
sudo /usr/sbin/pm-suspend
Since retyping all of these sleep commands gets tedious and remembering them is worse, look into making an alias to it and for other long commands or to binary paths you may forget. To sleep my machines, regardless of platform, I just type "sm" in the terminal or over ssh.
Linux being Linux, and because criminal masterminds love nothing more than to maliciously put computers to sleep, you have to be root to sleep the machine from the command line. Since you don’t want to render as root, you’ll need to do two things to get that portion of the script working for normal users: set up your user with sudo (do as root) permissions and disable the prompt for permission to run the pm-suspend command with sudo (you won’t be around when it pops up to ask for permission to do that at the end of the render). Both of these edits are to the “sudoers" file, and that is accessed by typing “visudo” as the root user from the terminal or ssh (this is the same in OS X, if you’re wondering, but you don’t need to be root to sleep a Mac from the command line). Remember, if you hate the vi control scheme, you can do this from the Linux GUI with gedit with "gedit /etc/sudoers" or with nano ("nano /etc/sudoers").
First, we'll add that pm-suspend command to the list of commands that can be executed without a prompt. Since visudo is basically an alias of the vi text editor, the way you do that is by hitting the i key to enter editing mode. Scroll down a bit and on a new line without anything before it, put this, where “notwen” is your non-root user name.
%notwen ALL=(ALL) NOPASSWD:/usr/sbin/pm-suspend
The spaces between the text are single tabs. Then, while you’re at it, give yourself sudo permissions to run anything as root by adding another line with the following:
%notwen ALL=(ALL) ALL
If you mess up, you can quit visudo/vi/vim without saving changes by hitting escape, typing q! and then enter. To save your changes, hit escape, type :wq and hit enter. Now you no longer need to use the root user just to execute something as root; you can just type "sudo /the/command" and it will do the command as root. And you won't be asked to enter a password to sleep the CentOS machine with pm-suspend.
Sending a sleep command to a renderer
Let's quickly outline how you can get our really great "green" render farm feature to dispatch those sleep commands to the renderers. You make a text file with your render commands and then send separate commands to say “sleep now” and forward those to the muscle before you finally put the host machine to sleep.
This does, however, require one more step to set up to execute without a prompt, because, like the Linux sleep command, you're not going to be around to enter your login info when this command goes through. In order to prevent your OS X/Linux/Windows Cygwin machine from prompting you to enter a password every time you log in, you need to set up an ssh key pair. There are tons of tutorials for this, and you can use the SSH 2 one here. It's a really simple process, and it's worth doing even if you don't plan on using the sleep stuff below, because you can then securely log into your machine without being prompted, and you do that frequently when managing a rendering network.
With our ssh key pair set up, we can now send commands to the render machines to sleep at any time. So pretending that we have a Mac OS X host, an OS X renderer, a Windows renderer with Cygwin, and a CentOS Linux renderer, our V-Ray for Maya render batch with sleep commands would look like this:
##our render jobs that will use all renderers:
Render -r vray -s 1 -e 200 /path/to/file.mb
Render -r vray -s 1 -e 1000 /path/to/file2.mb
##CentOS sleep at end of batch:
ssh -t -t myuser@10.0.1.9 'sudo /usr/sbin/pm-suspend' &
##OS X slave sleep at end of batch:
ssh -t -t myuser@10.0.1.10 'osascript -e 'tell application "Finder" to sleep'' &
##Cygwin Windows slave sleep at end of batch:
ssh -t -t myuser@10.0.1.18 'shutdown /p' &
##My growlnotify command. This might be sent to my phone if I'm using Prowl
growlnotify -n "Maya Render" -I /Applications/Autodesk/maya2014/Maya.app -m Maya Render Done!
##A little wait to make sure the sleep commands and growl stuff was dispatched before sleeping the master:
sleep 5
##Mac host sleep at end of batch:
osascript -e 'tell application "Finder" to sleep'
So that file could be a reusable render template with just the first line changed. The "&" at the end of the sleep commands tells BASH to do the task in the background, so you aren't waiting around for feedback to move on to the next task. If you put it at the end of the render task line, it would sleep all the machines while you just started the render, because it would move on to the next line in the script.
Waking your renderers
Since we can't assume that we're in the same room with our muscle, and we're far too cool to power on a machine with a button, here is a quick way to wake those sleepers with a Python script. There are plenty of GUI WoL (wake on LAN) programs if you want them, but remember that you might want to do this stuff from a remote location, and loading VNC to do GUI stuff is much slower than doing it from a command line and ssh. With the MAC addresses you recorded at the start of this piece, replace the zeroes in the '\x00\x00\x00\x00\x00\x00' line with separate MAC address fields, and, if your local machine IPs are 192.168.1.x, replace the Apple Airport style 10.0.1.255 local IP with 192.168.1.255. It's a broadcast IP, not the IP of the renderer itself, so only the MAC address changes for different machines on the same subnet:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.sendto('\xff'*6 + '\x00\x00\x00\x00\x00\x00'*16, ('10.0.1.255', 80))
Save that in an executable plain text file, and now you can wake your render slave with a simple command:
python /path/to/wakeCentOSSlave.py
You now have a pretty serious little render network with green features. Toss those sleep and wake commands into a script within your host CG program, and you don't even need to drop into the terminal to administer those machines:

You must login or create an account to comment. | http://arstechnica.com/information-technology/2014/05/how-to-network-lots-of-dumb-computing-muscle-in-a-fast-efficient-render-farm/5/ | CC-MAIN-2015-48 | refinedweb | 1,679 | 63.83 |
Using the TemplateWriterTask to write files¶
A common task in scientific workflows is to write an input file in a format that can be read by a program, and then execute that program. When automating the same program for different inputs (like different molecules or sections of a galaxy), slight modifications to the input file are needed. This tutorial introduces the built-in TemplateWriterTask as a method for writing input files (or any other type of templated file).
We presented an example of using the TemplateWriterTask and subsequently running a program in the Firetask tutorial. If you didn’t already complete the first part of that tutorial, we suggest you do that first. This tutorial contains more details on how the TemplateWriterTask works.
Note
The TemplateWriterTask is uses the Jinja2 templating engine, which provides a simple, extensible templating language.
A simple template - variable substitutions¶
We introduced a simple template in the Firetask tutorial. Let’s explore this template in more detail.
Navigate to the template writer tutorial directory in your installation directory:
cd <INSTALL_DIR>/fw_tutorials/templatewritertask
Look inside the file
simple_template_copy.txt:
option1 = {{opt1}} option2 = {{opt2}}
Note
The template file can be any text file, with any extension (or no extension at all). The actual template file is stored within the FireWorks code, so modifying this copy of a file won’t have any effect (more on this later in the tutorial).
Most of the template file is interpreted literally and is static. However, the text inside double curly braces
{{and
}}are variables that will be replaced later on by other text.
We set the variables opt1 and opt2 using a Context. This is a dictionary that contains specific values for these parameters. Let’s see how this is defined by looking inside
fw_template.yaml:
spec: _tasks: - _fw_name: TemplateWriterTask template_file: simple_template.txt context: opt1: 5.0 opt2: fast method output_file: inputs.txt
Note that we have specified a
template_file, a
context, and an
output_file. All three of these parameters are needed to use the TemplateWriterTask.
In the Firework above, we are setting opt1 to 5.0 and opt2 to “fast method”. If we wanted to change these parameters, we can create a file like
fw_template2.yaml:
spec: _tasks: - _fw_name: TemplateWriterTask template_file: simple_template.txt context: opt1: 10.0 opt2: stable method output_file: inputs.txt
This second Firework is identical to the first, except that we have changed the value of variables opt1 and opt2. Thus, we have only changed the parameter values we care about when creating a new Firework. In addition, one could easily perform searches based on opt1 and opt2 values using MongoDB’s built-in search capabilities.
Let’s reset the database, add these FireWorks to the LaunchPad, and then execute them:
lpad reset lpad add fw_template.yaml lpad add fw_template2.yaml rlaunch --silencer rapidfire
If all went well, you should have two
launcher_subdirectories. Each directory contains a file called
inputs.txtthat uses the same template file but different Contexts to create unique input files. Recall from the Firetask tutorial that you could use a multi-task Firework to subsequently run a code that processes the input file to produce useful outputs.
A more advanced template - if/then and for¶
Template files are not restricted to simple variable substitutions with curly braces. You can also define if/then statements and for loops that process array-like items. This can make your templates more flexible, for example writing an input tag only if a certain variable is present in the Context.
Staying in the template writer tutorial directory, look inside the file
advanced_template_copy.txt:
option1 = {{opt1}} option2 = {{opt2}} {% if optparam %}OPTIONAL PARAMETER {{ optparam }}{% endif %} LOOP PARAMETERS {% for param in param_list %}{{ param }} {% endfor %}
Note
The actual template file is stored within the FireWorks code, so modifying this copy of a file won’t have any effect (more on this later in the tutorial).
Note that this template contains some additional tags. In particular, in between
{%and
%}we have some code that contains if/then statements and a for loop.
A Context for this template is in
fw_advanced.yaml:
spec: _tasks: - _fw_name: TemplateWriterTask context: opt1: 5.0 opt2: fast method optparam: true param_list: - 1 - 2 - 3 - 4 output_file: inputs_advanced.txt template_file: advanced_template.txt
Let’s run this Firework and examine what happens:
lpad reset lpad add fw_advanced.yaml rlaunch --silencer singleshot
You’ll notice that we’ve iterated over our loop, and the optional parameter is indeed written to
inputs_advanced.txt.
Now, try deleting the line containing the
optparamand repeating the launch process. You’ll see that the lines pertaining to the
OPTIONAL PARAMETERare no longer written!
Therefore, with Jinja2’s templating language we can write fairly general templates. While variable substitutions, if/then statements, and for loops should cover the majority of cases, you can see even more features in the official Jinja2 documentation. For example, you can use template inheritance or insert templates into other templates.
Writing your own templates¶
When writing your own templates, you have a few options on where to store the templates so they can be read by FireWorks. Note that all the worker computers using the templates must have the most recent templates installed locally.
Option 1: The user_objects directory of the FireWorks code¶
The default place that FireWorks looks for templates is in the
user_objects/firetasks/templates directory of your FireWorks installation. Indeed, the
simple_template.txt and
advanced_template.txt files used in this tutorial are stored there (that’s why modifying the tutorial files has no effect on the result). Any templates you put in this directory (or its subdirectories) will be read by FireWorks; just put the relative path of your template as the
template_file parameter.
Note
If you do not know how to find the correct directory, type
lpad version. Then navigate to the install directory, then
cd fireworks/user_objects/firetasks/templates.
Option 2: Set the template directory in FWConfig¶
If you do not want to store your templates within the FireWorks code, you can set a template directory in the FWConfig. Just set the parameter
TEMPLATE_DIR to point to the location of your templates. Then the
template_file parameter you pass to your FireWorks will be relative to this path. Remember to do this for all your workers!
Additional options¶
In addition to
template_file,
context, and
output_file, the following options can be passed into
TemplateWriterTask:
-
append- append to the output file, rather than overwriting it
-
template_dir- this is actually a third option for setting your template dir
The _use_global_spec option¶
By default, the parameters for the TemplateWriterTask should be defined within the
_task section of the spec corresponding to the TemplateWriterTask, TemplateWriterTasks within the same Firework.
Python example¶
A runnable Python example illustrating the use of templates was given in the Firetask tutorial. | https://pythonhosted.org/FireWorks/templatewritertask.html | CC-MAIN-2017-13 | refinedweb | 1,122 | 55.95 |
A student I know asked me to help him find a bug in a C++ program that was using a brute force approach to finding all primes between 1 and n. The problem wasn't hard to find, and not very interesting. But with a few spare minutes on a Sunday I rewrote his C++ program using "C'ish Perl", and in so doing seem to have stumbled into a real bug.
Here's an example of the initial Perl code, which is almost an exact literal translation of the C++ code, and which DOES NOT exhibit the bad behavior:
use strict;
use warnings;
use v5.12;
use constant TOP => 1000000;
say "1 is prime.";
say "2 is prime.";
my $found = 2; # We already found 1 and 2.
for( my $i = 3; $i < TOP; $i += 2 ) {
my $qualifies = 1;
for( my $j = $i - 2; $j > 1; $j -= 2 ) {
if( $i % $j == 0 ){
$qualifies = 0;
}
}
if( $qualifies ) {
say "$i is prime.";
$found++;
}
}
say "Found $found primes between 1 and ", TOP, ".\n";
[download]
The C++ version:
#include <iostream>
using namespace std;
// First 501 primes are found from 1 to 3571
const int SEARCH_TO = 1000000;
const int SEARCH_START = 3;
/*
* You can double check by comparing with the link below:
*
* to verify accuracy.
*/
int main() {
cout << "1 is a prime number." << endl;
cout << "2 is a prime number." << endl;
int found = 2;
int i;
for ( i = SEARCH_START; i < SEARCH_TO; i+=2 ) {
int qualifies = 1;
for ( int j = i-2 ; j > 1; j-=2 ){
if ( i % j == 0 ) {
qualifies = 0;
break;
}
}
if ( qualifies ) {
cout << i << " is a prime number." <<endl;
found++;
}
}
cout << "Found " << found << " primes in range "
<< 1 << " to " << SEARCH_TO << ".\n";
return 0;
}
[download]
...and that worked fine; no bad behavior. Then I decided to look at it without a flag, by labeling the outer loop and using "next LABEL" to short circuit to it. Here is an example:
use strict;
use warnings;
use v5.12;
use constant TOP => 1000000;
say "1 is prime.";
say "2 is prime.";
my $found = 2; # We already found 1 and 2.
OUTER: for( my $i = 3; $i < TOP; $i += 2 ) {
for( my $j = $i - 2; $j > 1; $j -= 2 ) {
( not $i % $j ) && next OUTER;
}
say "$i is prime.";
$found++;
}
say "Found $found primes between 1 and ", TOP, ".\n";
[download]
After watching numbers scroll past me for a few moments I hit CTRL-C (windows console), and was surprised to get an error message from the "this shouldn't happen" category:
..... (long list of primes omitted )....
59753 is prime.
59771 is prime.
59779 is prime.
59791 is prime.
59797 is prime.
59809 is prime. <-------I hit CTRL-C after this iteration.
Out of memory!
Use of uninitialized value $j in modulus (%) at primes.pl line 17.
Use of uninitialized value $i in modulus (%) at primes.pl line 17.
Illegal modulus zero at primes.pl line 17.
Free to wrong pool 2f4d50 not 1000 during global destruction.
[download]
I ran it a few other times. Sometimes there was no problem. Sometimes the output from the end of the run had a bunch of "line noise" after the last prime. And a couple times it said, "Panic..." with a similar error message.
This post isn't about how to efficiently generate primes, or how to write such code elegantly. I'll be the first to admit this is a C-ish style approach, and the algorithm used is dumb brute force.
The question is, does anyone know why there's an error occurring here? The errors generated really are in the category of errors that we shouldn't see. Since I can't produce it on 100% of the runs, I don't know how to wrap it all in a test that would demonstrate the bug reliably. If I could at least generate it 100% of the time (and without requiring the intervention of "CTRL-C" keyboard input) I might be able to send in a meaningful bug report.
Update: A couple of responses (as well as my own testing on Linux) have led me to believe this problem is not going to manifest itself on Linux. While I haven't heard from any Mac users, I suspect this is a problem only under a Windows environment. Whether or not it's limited to Strawberry Perl, or only to version 5.12.3, I don't know yet.
Dave
In reply to "Free to wrong pool" error.
by davido
Hell yes!
Definitely not
I guess so
I guess not
Results (42 votes),
past polls | http://www.perlmonks.org/?parent=930504;node_id=3333 | CC-MAIN-2014-52 | refinedweb | 753 | 84.17 |
Back
You have to initialize your classifier first and then train it for a long time with
clf= some.classifier()
clf.fit(x,y)
After this you can opt for any of the two options-
1. Using Pickle
import picklewith open('file.pkl', 'wb') as f: pickle.dump(clf, f)with open('file.pkl', 'rb') as f: clf = pickle.load(f)
import pickle
with open('file.pkl', 'wb') as f:
pickle.dump(clf, f)
with open('file.pkl', 'rb') as f:
clf = pickle.load(f)
2. Using Joblib
from sklearn.externals import joblibjoblib.dump(clf, 'filename.pkl')clf = joblib.load('filename.pkl')
from sklearn.externals import joblib
joblib.dump(clf, 'filename.pkl')
clf = joblib.load('filename.pkl'). | https://intellipaat.com/community/319/save-classifier-to-disk-in-scikit-learn | CC-MAIN-2021-43 | refinedweb | 117 | 57.53 |
Hello, i am looking for a PackageCompiler instruction for humans, because it seems to me that there are a lot of links in internet but it is difficult to find the most simple case : own simple script that print something translated to executable. But i am not able to find it … also looking inside this forum …
I have added PackageCompiler to Julia, ok.
I am on windows 10.
If i have my simple script called
hello.jl
with inside a simple print
println("Hello first build!")
After have done this:
import Pkg Pkg.add('PackageCompiler')
What should i do to get this
hello.exe
Many thanks… | https://discourse.julialang.org/t/packagecompiler-for-having-a-simple-exe/35071 | CC-MAIN-2022-21 | refinedweb | 106 | 67.15 |
)
> december 2003
Filter by Day:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
Can't stop the Movie
Posted by mok at 12/31/2003 10:07:07 PM
I have made a 355 Frame movie with soundtrack for insertion in my website ( ? PUNCH the Hitchhiker button) the movie plays through just fine - its a little jerky because it's slowed down animated still frames, but it more or less does what I want for...
more >>
Flash MX Pro 2004 - where is telltarget?
Posted by TripapHoniC at 12/31/2003 9:57:52 PM
Hello all. I am a FLASH 5 person and recently started working with FLASH MX Pro 2004 ED. The UI is definitely a bit different and as I go to tell a button to play movie clip, I find myself not able to. I have been out of development for about a year and I seem to recall using telltarget to load a...
more >>
Flash MX Pro ver 7.0 to 7.0.1!?!?
Posted by Aelia at 12/31/2003 9:56:35 PM
I just upgraded my Flash MX Professional 7.0 to the new 7.0.1. Now anything I created in the older versions of MX Professional will not open up in the new version!?!? I keep getting "Unexpected file format". Just wondering if anyone experienced the same problem? ...
more >>
How can I link to a iframe from a flash button?
Posted by heinerken at 12/31/2003 7:43:21 PM
I have created a template with a iframe in the body surrounded by three flash movies, all is well untilI tried to change the iframe from my flash movie. Below is the code from the html button that worked in the same setup. I would appreciate any help. <a href="javascript:;" onClick="Lvl_targetI...
more >>
How are ShockWave movies created? With Flash?
Posted by thisisreallyfunky at 12/31/2003 7:13:11 PM
I am not sure about the Flash Player and the Shockwave player differences and how a Shockwave file is created. At first I thought it was simple: a .fla played in Flash players and a .swf played in Shockwave player. But, I am not sure. Thanks for a reply. ...
more >>
Urgent: Playing music MOD's in future Flash Player v8
Posted by IzzySoft at 12/31/2003 6:45:20 PM
I would have to say that One of the Most Annoying things I've come across is 5 second samples that loop endlessly. When are music modules going to be supported already? Would someone be so kind enough to point out to MM that music is just as important as graphics!!! And music modules (MOD, ...
more >>
NEW FLASH GAME DEVELOPED. LOOKING FOR FEEDBACK.
Posted by davo-bean at 12/31/2003 6:42:50 PM
I have been working on a little game for a couple of months now and I have Beta version that I need feedback on. It's fairly simple, but I think fun. Here is the url: dave.vergemedia.com/war/ Please send me feedback through the email provided on the site. Thanks so much. - david z. ...
more >>
no Stereo rendering SWF-movie sound??
Posted by tb0l1nder at 12/31/2003 5:17:05 PM
This is kind of a 2-part question: In summary: 1) how do I 'switch off' Flash's internal codec if I'm using 3rd party codecs? 2) why am I only getting mono sound from either aiff or mp3 original soundtracks? In researching why I can't seem to get FlashMX to create a stereo soundtrack from ...
more >>
Don't see what you're looking for? Search DevelopmentNow.com.
Shape Layer Transparency
Posted by Chris NO[at]SPAM DealerImpact at 12/31/2003 4:59:22 PM
I have a shape and it is moving across a background, but I can't find a transparency option. I have to choose a color, which won't work because it won't look good on this graphic background. Any suggestions? ...
more >>
Lack on Normal Mode Irritating (k)
Posted by W. Kirk Lutz at 12/31/2003 4:58:03 PM
Trying to create a very simple button. But as a designer, I'm a little lacking in the ActionScript area. WHY did they get rid of Normal Mode? I always thought that upgrades were supposed to make things better and hopefully easier. Not the case here. Anyway here is the ActionScript I wrote...
more >>
Content on Frame 1 ?
Posted by Rob Solberg at 12/31/2003 3:31:57 PM
Hello...Happy New Year everyone... I am having a strange problem with a Flash movie. The first frame of the movie is 500k in size. However, the first frame on my timeline is tiny...just some text and a vector image. So it appears that Flash is exporting a large part of the movie's contents ...
more >>
loadMovie in different rows
Posted by .::herman at 12/31/2003 3:11:47 PM
how to make the loader (MC) (instance name: loaderS) put 3 pic in each line ??? Now all the pic will be loaded in the same row (pic size: 100px * 100px) I want each row to have 3 pic only. Thx so much ..::herman for (i=1; i<8; i++) { loadMovie("images/pic"+i+".jpg", "moviePlayer.loade...
more >>
Playing Random Images w/Fade
Posted by gnevius at 12/31/2003 1:43:35 PM
Hello Fellow Flashers! I am trying to accomplish a particular effect with a Flash file. What I need to do is have a set of 5 images fade in and out in a random fashion. This is part of a "banner" graphic that will be appearing on a web page. I can accomplish this very quickly and easily in another ...
more >>
import nice scroll bar into flash mx 2004 professional
Posted by JiZhang at 12/31/2003 1:06:32 PM
There is a nice scroll bar in flash communication server sample file: "sample_room.fla" How can I export and then import it into flash mx 2004 professional? Previously I just export it as .swc file and put it under directory "Flash MX 2004\en\First Run\Components\UI Components\". It doesn't wo...
more >>
flash mx 2004 professional Button State (bug?)
Posted by JiZhang at 12/31/2003 12:55:37 PM
There is a "Button" components in UI components library. I give the button an instance name say "sample_btn" I used Actionsript like : sample_btn.setEnabled(false); // this works, it disable the button but sample_btn.setEnabled(true); // this doesn't work basically once the button is...
more >>
Needed Urgently- a basic CDROM
Posted by tichbelly at 12/31/2003 12:10:40 PM
...
more >>
multithreaded, data-driven, with icons menubar needed urgently
Posted by Masha Sopkina at 12/31/2003 9:33:50 AM
hi all i need a flash top menubar component for my project. the one i found at: was just what i needed, but it seems like there is no way to have it functioning without internet, and since my project is an offline one - i discovered i could not use that menu. what a sham...
more >>
Movie clip not playing. Pls help!!!
Posted by navedansari at 12/31/2003 7:54:05 AM
I want to run a movie clip on button press but i m anable what can i do pls help me. Movie clip is running on holding the button. i want to run movie clip in single click. ...
more >>
Text display problem after export
Posted by synthcomposer at 12/31/2003 5:58:11 AM
Greetings, I'm still pretty new to Flash, especially MX2004. I began my project (a map) using Flash 4. Now that I have MX2004, all of the text (_sans, static not dynamic) displays much larger after exporting. It looks fine in Flash, but when previewing and exporting as .swf it displays much mo...
more >>
loadmovie issue
Posted by fmurray at 12/31/2003 3:33:50 AM
I have a shell file, there are 4 buttons that are supposed to load 4 seperate external files. This works on my computer, but when I upload it, and try it on the web, it does not load the external files. what is going on? on (release) { unloadMovie("images"); } on(release){ _root.images....
more >>
macromedia.com Menu System
Posted by Biginnir at 12/31/2003 3:32:19 AM
I'm a newbe to flash and I want to make the top menu that macromedia.com has made. Any advices from the gurus? ...
more >>
go to url and close popup..
Posted by donedeal at 12/31/2003 3:31:29 AM
Hi, Hopefully somebody can help me with this problem. I?ve opened a popup browser window with a ?flash tour? in it. At the end of the tour I?ve got a button that I want to do the following: Go to an URL in the browser that opened the popup window and then close the popup window. Is this ...
more >>
Custom buttons foe video control in Professional
Posted by richcoy at 12/31/2003 1:26:51 AM
I did a search in the forum and did not see an answer so here is my question... Can anyone direct me to a tutorial/explanation on how to create custom buttons for controlling video (volume, play, pause, ff, rew) in a Flash presentation. The built in controls are nice but do not match my presen...
more >>
Please help - navigation bar (build on flash 6)
Posted by felsantana at 12/31/2003 12:52:37 AM
I've build a menu bar using flash 6. I did it following a template for a menu bar (similar to macromedia.com one) To build it i also had to modify an .xml template which serves as the source file. I can go ahead and test movie & see it, but when i put it in dreamweaver it doesn't work......it see...
more >>
Moving symbol to cursor position
Posted by xentrix at 12/31/2003 12:16:17 AM
Hi, I have an element in my current project which is an animated symbol. At a certain point in the animation I would like this symbol to 'become' the mouse, so the user has control of it from then on in. I can make the symbol change and 'become' the mouse no problem, but it jumps from it's curren...
more >>
blank spaces in textfields
Posted by ritpas at 12/30/2003 11:57:35 PM
Hi, I create a text field whose dat are retrieved from a database through php. As there are several columns, I programmed a little script setting the tab index of the next column and based on the number of the caracters of the previous column. It looks fine and seems to work, but I observe that...
more >>
Is this possible JS->PHP flash detection
Posted by mark at 12/30/2003 11:55:18 PM
Hi, I want to be able to detect flash with javascript and then have php do something like: <?php if ($flash=="yes") { print ("<img src="image.jpg"); } else if ($flash=="no") { print ("<emded flash swf etc...>"); ?> I know its possible to do redirects to different HTML pages ...
more >>
Updating variables in duplicateMovieClip levels
Posted by javman at 12/30/2003 11:50:17 PM
I am making a digital measuring tape, and am well on the way to having it going but I need help. //I used the following code to create the lines on the measuring tape. basex = _root.one._x; ht= _root.one._height; for(i=0; i <101; i++){ one.duplicateMovieClip ("line_" + i, 120+i); this["lin...
more >>
Flash overlay disables underlying text box
Posted by cf_code_warrior at 12/30/2003 10:26:02 PM
Our graphics department decided to spiff up our web site for the season. With snowflakes. However, with it enabled, we cannot click on the search text box "underneath" the Flash layer. Is this a known problem? Is there a workaround? Thanks, Robert Syndrome can be seen at http://...
more >>
Masking with draw commands
Posted by okself at 12/30/2003 10:00:59 PM
I want to use draw commands to create a mask. So, I had them draw inside a movieclip on a layer that masks another movieclip. This causes Flash player 7.0 r19 to crash, and in 6.0 r79 it just doesn't work. I noticed that if I draw on the masker movieclip, then that will work as a mask, but nothin...
more >>
Dynamic text files
Posted by JoeDziner at 12/30/2003 9:41:06 PM
Hello group!! I am learning how to create a dynamic text field that will display the contents of a text file. I closely followed a simple tutorial in the Flash MX Savvy book with no luck using my files. (I used their tutorial files and they worked fine - until I changed the content of a file...
more >>
Reading from / Writing to text files out of Flash
Posted by schubby2 NO[at]SPAM gmx.net at 12/30/2003 9:30:16 PM
Does anyone know a Flash sample which reads and/or writes something to/from a text file? I read somewhere that this is possible in general but never found a sample. Carl ...
more >>
Flash Banner
Posted by calvincky at 12/30/2003 9:24:22 PM
How to create floating flash banner over the content? ...
more >>
td background under swf w/no plugin?
Posted by mark at 12/30/2003 9:23:27 PM
If I have code like this <tr> <td background="myimage.jpg" height="100" width="100"><EMBED Src="MOVIE.SWF" object blah blah etcc...</EMBED></td> </tr> </table> what will a user see who doesn't not have the plugin installed? ...
more >>
Hey Urami
Posted by gangof4 at 12/30/2003 9:18:49 PM
Bill Mitchell at CNN sent me a cartoon similar to the one at: You can see that it has motion to it (it's a gif file), though in a regular image browser you don't see the motion--only the first scene. Yet in PowerPoint you do see the mo...
more >>
flash exe files stored online??
Posted by flashscooter1 at 12/30/2003 8:51:48 PM
I need help on storing flash exe file online for an online presentation. I have created the swf file but don't know how to place them online to be veiwed. My company currently has a powerpoint presentation online which I have redesigned with flash. I dont understand how to set up the files so the ...
more >>
Dragging Symbol to Center Point - Short Cut?
Posted by Pixi at 12/30/2003 8:36:19 PM
Is there a shortcut to make a Symbol go right to the center of the Stage when dragging it from the Library? ...without having to click on the Align Tool over and over again? ...
more >>
Can't Break an N
Posted by Slapfish at 12/30/2003 8:29:19 PM
I am having the strangest problem. I am working on a logo that includes a capital letter N. For some reason when I select the N and attempt to Break Apart the letter it disappears from the screen. The other letters in the logo don't do it, nor do N's in other fonts. Another strange thing about it is...
more >>
Creating Clean Buttons
Posted by david_here at 12/30/2003 8:27:24 PM
All, Sorry for the boring question, but i'm having difficulty and cant seem to figure this one out. I am trying to create a button with text so that when it is moused-over, it changes colors. The only thing that i cant seem to figure out is -- sometimes the font is a bit blurred and sometim...
more >>
Learning Interactions MX to MX2004
Posted by andrewvshields at 12/30/2003 7:40:59 PM
I created a Drag and Drop with the Drag and Drop component in Flash. When I modify the target image, the drop images will not stick to it when I test it. The generic target images remain functional. Also, the labels for the Check Answer and Reset buttons disappear when testing. Is this a problem wit...
more >>
Is this possible?
Posted by Master Cheif at 12/30/2003 7:23:58 PM
OK I know this can be done on the internet so I would assume it is even easier if I am doing this on my hard drive but I don't know.... I created a flash file that keeps statistics for a game me and my buddies play, like win %, average points per game ect What I'm needing to do is save the varia...
more >>
jumping images
Posted by rhian at 12/30/2003 7:09:45 PM
Hello, I don't know if anyone can help? I've created a movie clip that has a fade-in fade out sequence with two jpegs. When I test the movie in flash the images jump despite the fact that I have set the y and x axis of each instance to zero. It's fine when I view this in the browser in dreamweaver...
more >>
Load Status Bar
Posted by plockyer at 12/30/2003 5:48:26 PM
I am looking for a premade generic loading bar for a splash page... I am terrible with flash. Does anyone know where I could find one, or have on you would be willing to give me? Paul ...
more >>
Car wheel spinning
Posted by tichbelly at 12/30/2003 5:45:40 PM
i'm pretty new to flash and can't remember at all how to make a car go accross the screen with it's wheels turning! i did have an idiot proof tutorial but i've lost it, so if anyone could help me out, you'd have to tell me pretty much from scatch though! jenny xtichbelly@hotmail.com ...
more >>
? on Flash MX 2004 Common Library
Posted by geekygURL at 12/30/2003 5:13:14 PM
I am using Flash MX 2004. When I choose Window > Other Panels > Common Libraries, there is no Sound library listed. Buttons, Class, and Learning Interactions are there, but no Sound. In Flash MX, I could access the Sound common library by choose Window > Common Libraries > Sound. I can't find ...
more >>
array2 = array1 isn't working
Posted by Dunja at 12/30/2003 4:27:46 PM
Hey, If you don't mind, i've got a question... working with flash since the flash 4 times.. but i got myself wondering now.. i must admid i've always found a way to go around arrays.. but well.. you just need them :) i want to use array2 = array1 , when i do this i get array2 to have a value ...
more >>
Database information
Posted by Rickkkkk at 12/30/2003 2:53:15 PM
Hi all ! What is the best technics to connect to a database ? I want to do the interface with flash mx and I (maybe) gonna use .net to transfer my data to the database. I think that using XML with this, it's gonna be faster to play with the data. What about the RDBMSResolver ??? (comes w...
more >>
importing a jpeg inside a movieclip
Posted by Jean-noël et/ou Nathalie Lafargue at 12/30/2003 2:28:05 PM
Hi everybody (happy new year, etc.) I'm trying to download a jpeg from my flash movie I can download into a movieclip instance, with "loadmovie" but I'd like to download my image in a movieclip-in-the-library, not on-the-stage. My image has to appear in three different locations on the stage As...
more >>
Flash MX Crashing in OS 10.3.2
Posted by Pixi at 12/30/2003 2:15:23 PM
Flash MX Crashing in OS 10.3.2 Does anyone else have this problem? Anyone know what causes it? It happens quite frequently, especially when I first begin working. After I relaunch a few times it seems to improve but does still crash during the day. ...
more >>
normal mode AS
Posted by nkraf at 12/30/2003 1:34:06 PM
anyone know how do i use normal AS mode in flash MX pro 04 ? i can seem to find that on the AS panel ... thanks ...
more >>
·
·
groups
Questions? Comments? Contact the
d
n | http://www.developmentnow.com/g/68_2003_12_0_0_0/macromedia-flash.htm | crawl-001 | refinedweb | 3,445 | 82.24 |
01-04-2017 05:03 PM
My previous post gets me so close to working with the NXOpen.UF module in Python, but I am missing something important. I do not think I'm using tags correctly yet. See if you can help me with this problem:
import NXOpen import NXOpen.Annotations import NXOpen.BlockStyler import NXOpen.Drawings import NXOpen.UF theSession = NXOpen.Session.GetSession() theUI = NXOpen.UI.GetUI() theUFSession = NXOpen.UF.UFSession.GetUFSession workPart = theSession.Parts.Work allNoteObjects = workPart.Notes for thisNote in allNoteObjects: thisLayer = thisNote.Layer #to filter by layer thisOrigin = thisNote.AnnotationOrigin #to filter by location thisTag = thisNote.Tag #the regular Python object tag np1 = NXOpen.UF.Tag(thisNote) #the UF session object tag thisType, thisSubtype = NXOpen.UF.Obj.AskTypeAndSubtype(np1)
(This is a snippet of code I've sanitized to just show the problem area.)
According to the documentation of the NXOpen Python wrapper here:...
the value passed in AskTypeAndSubtype() as np1 is supposed to be a tag.
At first, I tried passing in thisTag as np1, but that gave an error saying it was an int, not an object:
The code as pictured above is getting the tag from the UF session, but I get this error message:
So, that is the right way to pass a tag, but now it looks like it really wanted an object, not a tag? But I can't figure out how to get the object from the tag. I've tried passing thisNote, but it complains that is the wrong type of object, like this:
Note, the NXOpen Python documentation online does not include anything about UF.Tag(), I lifted it from someone elses' example.
Solved! Go to Solution.
01-04-2017 05:07 PM
The second error box is supposed to have this image:
01-04-2017 05:23 PM
You're not using the UFSession object, you're just referencing the class. Change:
thisType, thisSubtype = NXOpen.UF.Obj.AskTypeAndSubtype(np1)
to:
thisType, thisSubtype = theUFSession.Obj.AskTypeAndSubtype(thisNote.Tag)
01-04-2017 05:32 PM
I changed it to this:
thisType, thisSubtype = theUFSession.Obj.AskTypeAndSubtype(thisNote.Tag)
Then I get this error:
01-04-2017 05:35 PM
BUT I just noticed that I needed this:
theUFSession = NXOpen.UF.UFSession.GetUFSession()
not this, which is what I have above:
theUFSession = NXOpen.UF.UFSession.GetUFSession
THAT seems to work when I include it with your fix. | https://community.plm.automation.siemens.com/t5/NX-Programming-Customization-Forum/Using-Tags-correctly-between-NXOpen-Python-and-wrapped-Open-C/td-p/383876 | CC-MAIN-2017-39 | refinedweb | 398 | 52.46 |
.
From someone that knows little/nothing about the capabilities of digital frames: Are there digital frames that can run Air apps? Or for that matter one that supports the Flash Player? I know some of the Sony frames run Windows but unclear what you can actually do with them in terms of apps.
I’ve not seen anything that runs a real version of Windows. I don’t believe there are any standard consumer frames that can run air apps.
Thanks for confirming. An “AirFrame” would be nice but probably ends up with hardware being at least a netbook (eeePC).
Doug, your attachment seems to be broken, I guess the webtier compiler is trying to compile it instead of allowing the download.
@Joo – Thanks, I didn’t test the download. I’ve zipped it and you can get it now.
The camera data is multipart HTTP, in this case also known as MJPEG. There is no need to guess at the JPEG location in the stream. See “Motion JPEG Formats” section of. Thanks for the component, I’m also new to Flex and needed something like this.
Hi,
I have problem with access streams from remote web server. crossdomain.xml file is ok, I can access other media files – such as normal JPGs via Image component. But your component fails with Error #2044: Unhandled securityError:. text=Error #2048: Security sandbox violation: cannot load data from mysite:80.
at webcamImage()[C:JavaworkspaceFlexCrossRoadssrcwebcamImage.mxml:15]
at mx.core::Container/createComponentFromDescriptor()[C:autobuild3.2.0frameworksprojectsframeworksrcmxcoreContainer.as:3579]
at mx.core::Container/createComponentsFromDescriptors()[C:autobuild3.2.0frameworksprojectsframeworksrcmxcoreContainer.as:3493]
at mx.containers::ViewStack/instantiateSelectedChild()[C:autobuild3.2.0frameworksprojectsframeworksrcmxcontainersViewStack.as:1140]
at mx.containers::ViewStack/commitProperties()[C:autobuild3.2.0frameworksprojectsframeworksrcmxcontainersViewStack.as:664]
at mx.core::UIComponent/validateProperties()[C:autobuild3.2.0frameworksprojectsframeworksrcmxcoreUIComponent.as:5807]
at mx.managers::LayoutManager/validateProperties()[C:autobuild3.2.0frameworksprojectsframeworksrcmxmanagersLayoutManager.as:539]
at mx.managers::LayoutManager/doPhasedInstantiation()[C:autobuild3.2.0frameworksprojectsframeworksrcmxmanagersLayoutManager.as:689]
at Function/
at mx.core::UIComponent/callLaterDispatcher2()[C:autobuild3.2.0frameworksprojectsframeworksrcmxcoreUIComponent.as:8628]
at mx.core::UIComponent/callLaterDispatcher()[C:autobuild3.2.0frameworksprojectsframeworksrcmxcoreUIComponent.as:8568]
at flash.utils::Timer/_timerDispatch()
at flash.utils::Timer/tick()
@Bedy – I’ve got to be honest, I’m not really quite sure why this would be. I use this component to access data on another domain from where the video was displayed. I havn’t used it in a while, but I don’t recall having to supply a crossdomain.xml file or anything else.
Hi Doug, gimme a help buddie!
I’m not an expert in Flex, but I followed exactly your tips, but I still can’t see images on the screen.
I created a new project and a component with your code. After that, I created an application file that has an instance of this component (like you wrote!).
But when I run script, nothing shows up on the screen, no images! Debbuging I saw that script is working fine, but nothing appears on the screen… Can you give me a explanation how to set properly imagens to take visible, please?
Thanks!
Rodolfo Reis
Hi Doug –
Could you please tell me, what is HOST in your code?
The thing is that all I got is URL, which returns me MJPEG stream. This url is “×480&compression=30”.
Is that possible to stream it with Flash/Flex in the same approach you have been using?
Thanks in advance.
JUBRvn ltqkswdxhaod, [url=]ryrbpgwznioq[/url], [link=]kftgehkxanam[/link],
Nice work,
The multipart respsone does contain what the boundary string for the document will be so you could parse that instead of assuming
“–video boundary–”
In my experience “–my boundary” as far more common.
Regards,
Erik
Found the swf file on my axis 213ptz on the same folder of mjpeg:
baseurl/mjpg/video.mjpg
can be:
baseurl/mjpg/video.swf
and it works easy!
Hello,
I installed the component in /src/components, loaded the components using:
xmlns:components=”components.*”
and call the component using
My network camera is visible using this in a browser:×480
But the flex page is not showing anything.
What am I doing wrong?
Thanks a lot
The problem will only be solved if there’s a possibility of adding a crossdomain.xml file to the camera’s web server OR by making the flash player think it’s coming from there by proxying through a server such that serves up the file and then having a pass throuh proxy that accesses the camera like
The reason it worked for the author is that the access of the server was to localhost. Flash allows accesses from localhost to sockets without considering this a security violation.
Hope this helps.
I think Bill is exactly correct here. As indicated in the post, I’m fairly new to Flex programming. I never even finished this project, beyond creating the webcamImage component. Thus, I never tried to host this on the web or anything of the sort. It DID work for me. But I think that it’s because it was an AIR application running locally.
Like Bill says, you should be able to use something like Apache’s modproxy to proxy the request to the camera through a domain you can add the crossdomain.xml file to.
Sorry for the general abandonware of this component! I hope some people are able to get some use out of it.
This is an old post, but I just thought I’d let you know that instead of looking for a video boundary to find the end of a jpg, you can just look for the next ending JPG bytes (FF D9) like you are looking for the beginning bytes (FF D8).
The problem I have while using this is speed. I’m not sure if my camera sends back data faster or bigger images than yours, but whenever I have the connection open the GUI freezes, and responds if I close it.
Also, shouldn’t the line
httpRequest += “Host: localhost:80rn”;
be
httpRequest += “Host:” + host + “:” + port”rn”;
?
httpRequest += “Host:” + host + “:” + port + “rn”;
Hi how can y use this in IE. Do you have any example. I try use this in IE and can’t see anything, but if a execute in flash mx works well.
Hi, I wrote this entry more than a year ago and have since pretty much ignored it. However, it still gets a good number of comments on a regular basis. I never expected this. A lot of people seem to have problems with the component. I can probably expand on this, but I want to know how people are using this. What do you need? What do you want? Why mjpeg streams?
And @Andre, I think your question was addressed in earlier comments. Specifically, the component, when served via the web, won’t be able to make requests to hosts other than that which served it. You might be able to use something like a proxy configuration in Apache to forward the request to your camera.
Anyhow people – let me know what you need and I’ll see if I can’t make something a bit more useful.
blu-ray…
Good post and it appears they are moving in the direction you suggest….
The component download link is broken. Is the component still available anywhere?
Better late than never: I’ve fixed the download link.
Thank you for updating the link!
I got it working, even though it’s a bit slow and flickery. Looking for the jpeg end marker, or using the headers Content-Length value might improve speed.
Anyone using a Foscam: the video boundary is “–ipcamera” as in:
–ipcamera
Content-Type: image/jpeg
Content-Length: 38648
As for the flash player security: As long as you run this app from your own pc as opposed to hosting it on a webserver everything is fine. As soon as you publish the swf on a server the webcam will need to provide a valid policy file.
Does this code really works? I have downloaded and tested and no works at all!!
But if it works, good luck!
I’ve tried a version of this and have made it work in a flex ‘AIR’ application which is not bound by crossdomain issues. It also works well on the android 🙂
If anyone ever finds a way to also capture the raw .wav file that some camera’s provide (sound)… let me know
2 classes here – Mjpeg.as and Base64
package
{
import com.dynamicflash.util.Base64;
import flash.display.Loader;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.media.Sound;
import flash.net.Socket;
import flash.utils.ByteArray;
//import mx.utils.Base64Encoder;
//import mx.utils.Base64Decoder;
/**
* This is a class used to view a MJPEG
* @author Josh Chernoff | GFX Complex
*
*/
public class MJPEG extends Loader
{
private var _user:String; //Auth user name
private var _pass:String; //Auth user password
private var _host:String; //host server of stream
private var _port:int; //port of stream
private var _file:String; //Location of MJPEG
private var _start:int = 0; //marker for start of jpg
private var webcamSocket:Socket = new Socket(); //socket connection
private var imageBuffer:ByteArray = new ByteArray(); //image holder
private var outputSnd:Sound = new Sound();
//private var myEncoder:Base64Encoder = new Base64Encoder();
//private var tim = myEncoder.toString();
/**
* Create’s a new instance of the MJPEG class. Note that due a sandbox security problem, unless you can place a crossdomain.xml
* on the host server you will only be able to use this class in your AIR applications.
*
* @example import MJPEG;
* var cam:MJPEG = new MJPEG(“192.168.0.100”, “/img/video.mjpeg”, 80);
* addChild(cam);
*
* @param host:String | Host of the server. Do not include protocol
* @param file:String | Path to the file on the server. Start with a forward slash
* @param port:int | Port of the host server;
* @param user:String | User name for Auth
* @param pass:String | User password for Auth
*/
public function MJPEG (host:String, file:String, port:int = 80, user:String = null, pass:String = null )
{
_host = host;
_file = file;
_port = port;
_user = user;
_pass = pass;
webcamSocket.addEventListener(Event.CONNECT, handleConnect);
webcamSocket.addEventListener(IOErrorEvent.IO_ERROR, unableToConnect);
webcamSocket.addEventListener(ProgressEvent.SOCKET_DATA, handleData);
//outputSnd.addEventListener(SampleDataEvent.SAMPLE_DATA, processSound);
webcamSocket.connect(host, port);
}
private function unableToConnect(e:Event):void{
trace(“error”);
dispatchEvent(new Event(“videoError”));
}
private function handleConnect(e:Event):void
{
// we’re connected send a request
var httpRequest:String = “GET “+_file+” HTTP/1.1rn”;
httpRequest+= “Host: localhost:80rn”;
if(_user != null && _pass != null){
var source:String = String(_user + “:” + _pass);
var auth:String = Base64.encode(source);
httpRequest += “Authorization: Basic ” + auth.toString()+ “rn”; //NOTE THIS MAY NEEED TO BE EDITED TO WORK WITH YOUR CAM
}
httpRequest+=”Connection: keep-alivernrn”;
webcamSocket.writeMultiByte(httpRequest, “us-ascii”);
}
private function handleData(e:ProgressEvent):void {
//trace(“Got Data!” + e);
// get the data that we received.
// append the data to our imageBuffer
webcamSocket.readBytes(imageBuffer, imageBuffer.length);
if (imageBuffer.length 1) {
if(_start == 0){
//Check for start of JPG
for (x; x < imageBuffer.length – 1; x++) {
// get the first two bytes.
imageBuffer.position = x;
imageBuffer.readBytes(startMarker, 0, 2);
//Check for end of JPG
if (startMarker[0] == 255 && startMarker[1] == 216) {
_start = x;
break;
}
}
}
for (x; x 0) {
// Create new data buffer and populate next 3 bytes from data
dataBuffer = new Array();
for (var i:uint = 0; i 0; i++) {
dataBuffer[i] = data.readUnsignedByte();
}
// Convert to data buffer Base64 character positions and
// store in output buffer
outputBuffer[0] = (dataBuffer[0] & 0xfc) >> 2;
outputBuffer[1] = ((dataBuffer[0] & 0x03) <> 4);
outputBuffer[2] = ((dataBuffer[1] & 0x0f) <> 6);
outputBuffer[3] = dataBuffer[2] & 0x3f;
// If data buffer was short (i.e not 3 characters) then set
// end character indexes in data buffer to index of ‘=’ symbol.
// This is necessary because Base64 data is always a multiple of
// 4 bytes and is basses with ‘=’ symbols.
for (var j:uint = dataBuffer.length; j < 3; j++) {
outputBuffer[j + 1] = 64;
}
// Loop through output buffer and add Base64 characters to
// encoded data string for each character.
for (var k:uint = 0; k < outputBuffer.length; k++) {
output += BASE64_CHARS.charAt(outputBuffer[k]);
}
}
// Return encoded data
return output;
}
public static function decode(data:String):String {
// Decode data to ByteArray
var bytes:ByteArray = decodeToByteArray(data);
// Convert to string and return
return bytes.readUTFBytes(bytes.length);
}
public static function decodeToByteArray(data:String):ByteArray {
// Initialise output ByteArray for decoded data
var output:ByteArray = new ByteArray();
// Create data and output buffers
var dataBuffer:Array = new Array(4);
var outputBuffer:Array = new Array(3);
// While there are data bytes left to be processed
for (var i:uint = 0; i < data.length; i += 4) {
// Populate data buffer with position of Base64 characters for
// next 4 bytes from encoded data
for (var j:uint = 0; j < 4 && i + j < data.length; j++) {
dataBuffer[j] = BASE64_CHARS.indexOf(data.charAt(i + j));
}
// Decode data buffer back into bytes
outputBuffer[0] = (dataBuffer[0] <> 4);
outputBuffer[1] = ((dataBuffer[1] & 0x0f) <> 2);
outputBuffer[2] = ((dataBuffer[2] & 0x03) << 6) + dataBuffer[3];
// Add all non-padded bytes in output buffer to decoded data
for (var k:uint = 0; k < outputBuffer.length; k++) {
if (dataBuffer[k+1] == 64) break;
output.writeByte(outputBuffer[k]);
}
}
// Rewind decoded data ByteArray
output.position = 0;
// Return decoded data
return output;
}
public function Base64() {
throw new Error("Base64 class is static container only");
}
}
}
Hmm, where did Tim’s comment go ? (which I got from the “Notify me of followup comments via e-mail”) Even though that code didn’t work, and was severely altered in the process of posting/mailing.
There it is..
myvideo downloader…
[…]Viewing MJPEG Streams in Flex – Alagad Ally[…]… | https://doughughes.net/2008/12/16/viewing-mjpeg-streams-in-flex/ | CC-MAIN-2022-40 | refinedweb | 2,251 | 58.58 |
To become a better React developer, you don't always have to learn an entirely new, challenging skill. You can instantly improve your React code in a few minutes by using the powerful features your development tools make available.
Some of the biggest improvements in your work as React developer take the smallest amount of time to learn. Make an effort today to apply these tips and I guarantee you'll save many hours of tedious work in your daily coding, plus you'll enjoy coding with React much more.
Here are five shortcuts that you can take advantage of right now to become a more productive React coder.
These tips largely feature how to get more out of your code editor. The code editor I use is Visual Studio Code, which is very popular among React developers. If you want to use VSCode, you can download it for free at code.visualstudio.com. Note that these features are available in virtually all code editors.
1. Tired of writing closing tags for every JSX element? Use Emmet.
As a React developer, you write a lot of JSX elements, most of which consist of an opening and closing tag.
If you don't have Emmet setup with React, you have to write both of these tags by hand for every element. A far better approach is to use a tool called Emmet, which automatically creates the closing tag whenever you create the opening one.
To setup Emmet with React in VSCode:
- Go to Code (at the top of your screen), then Preferences, then Settings in VSCode
- In the options on the left, select Extensions, then Emmet
- Scroll to the Include Languages section, add in the item input, javascript and in the value input, javascriptreact and hit Add Item
And just like that, Emmet has sped up your coding by 100%:
2. Tired of formatting your code by hand? Use Prettier.
Can you count the number of times your code hasn't been aligned probably so you tried to adjust the spacing yourself? I don't want to even think about how much time I've spent formatting my own code!
If you're still trying to format your code manually, you need Prettier.
Prettier is aptly named: it turns your misaligned code into a much prettier, formatted version.
Prettier is available as a devDependency for individual JavaScript projects or you can use it across all of your projects with the Prettier VSCode extension. The benefit of using the VSCode extension is that you can automatically format your JavaScript code every time you hit save.
Here's how to setup Prettier to use across all your projects in VSCode:
- Go to Code, then Preferences, then Extensions
- Search for prettier in the search input and hit enter (it should be the first one to come up)
- Select the extension, then hit Install (and possibly Reload to apply the extension)
- Go to Code, then Preferences, then Settings
- Search for Format on Save and select the checkbox next to the format on save option
Now all of the code you write will be formatted perfectly, every time you save:
3. Do you write out every single component you make? Use React snippets.
Creating many things in React and in JavaScript projects in general requires a lot of boilerplate. Every time you write a component you have to type out every part of it – import React, create a function, and export it from your file.
Do you get tired of having to do this? We all do. That's why snippets for React exist.
To avoid all the extra work of writing the same code again and again, use React snippets. Snippets allow you to use keyboard shortcuts to instantly write every part of your React code instead of having to type it all out manually.
For example, instead of writing
import React from 'react' you can just write
imr and hit the Tab key to instantly create the same thing. Snippets are a huge timesaver.
Here's how to use React Snippets in VSCode:
- Go to Code, then Settings, then Extensions
- Search for React Snippets. There are many good snippet extensions to choose from.
- When you have a snippet extension installed, take a look at the shortcuts available and write the best ones down.
- When you type a shortcut, wait for the suggestion to appear in your code editor and then hit Tab (you can arrow through the list if you want a different one)
You'll be shocked at how quickly you can make your components now:
4. Do you import all your components manually? Use auto import instead.
One of the most tedious things to do in creating React apps is importing packages and components from other files.
It's very repetitive and can take a significant amount of energy to import every single thing by hand (plus to correct when you make a typo).
Instead of having to remember, find, and manually import your components and packages, let your code editor do it for you. You can auto import whatever you like by selecting what you want to import by pressing the Tab key.
Here's how to auto import packages and components in VSCode:
- Go to Code, then Preferences, then Settings
- Search auto import and make sure the Enable Auto Import checkbox is selected
- Go back into your project, write the name of what you want to import, arrow through the options the editor suggests, and hit Tab to instantly create an import statement for it.
When you use auto import, it makes working with projects of any scale easier, because you no longer spend half of your time writing import statements.
5. Do you manually remove your unused imports? Use the organize imports shortcut.
Along with having Prettier for all of the code that we write, VSCode gives us a shortcut called organize imports that does just that. In fact, it does two things:
- It alphabetically organizes our import statements
- It removes unused import statements (instantly fixes linting warnings about unused imports)
And best of all, this shortcut requires no setup. Here's how to use it:
- Go to View, then Command Palette.
- Your imports should now be organized and any unused imports removed.
Note that you can use the keyboard shortcut
command/control + shift + o as well.
<< | https://www.freecodecamp.org/news/react-shortcuts-that-will-instantly-boost-your-productivity/ | CC-MAIN-2021-43 | refinedweb | 1,058 | 68.1 |
Update 14th Nov 2008. I've just released a script which does all this configuration in one or two command lines: HVRemote
So far, I’ve covered the following Hyper-V Remote Management scenarios:
But the questions keep coming. Part number five covers the case of a domain joined Vista client connecting to a remote server in a workgroup. And the reason for all these posts? To configure both machines to overcome the error: “Hyper-V Remote Management: You do not have the requested permission to complete this task. Contact the administrator of the authorization policy for the computer ‘COMPUTERNAME’” message when you start Hyper-V Manager remotely. IMPORTANT: Before anything else, I am going to assume you already have DNS setup correctly. If you can’t resolve the remote server machine using nslookup on the Vista machine, fix that now. Nothing will work unless that is right. One shortcut I do take in the walkthrough is to make the server with the Hyper-V role enabled a full install. See part three for how that affects you if your server is a core installation. I’m not going to provide great detail about exactly what to click in each step – it’s all been covered in the previous posts, so please refer back. Let’s make this walkthrough a little more interesting, by making it more representative of a real-world deployment by locking down the access permissions to a specific user/group (rather than 'administrator'). I’m going to have a domain user, “domain1\john” with password “johnhoward” connecting to a workgroup remote server with the Hyper-V role enabled where a local user “john” with password “john” exists. (And no, these are no reflection on my real passwords. It’s purely for demonstration only and to show you that password matching isn’t needed to make this work). Step 1. Create the user accounts (Domain Controller & Hyper-V enabled Server) On my domain controller, I’ve created an account "domain1\john" using Active Directory Users and Computers. Note that I am not making this account an administrator anywhere. Just a regular Joe User. On the Hyper-V enabled server, I’ve created the account workgroup\john using the net user command. I’ve also created a group called “Remote Hyper-V Admins”, and added the local workgroup “john” account to that group. Step 2. Enable Firewall WMI Rules (on Hyper-V enabled server) Run the following command as an administrative user on the server: 'netsh advfirewall firewall set rule group=”Windows Management Instrumentation (WMI)” new enable=yes' Step 3. Allow authenticated remote DCOM access (on Hyper-V enabled server) Here I’ve added the “john” account to the “Distributed COM Users” group. Unfortunately, in a workgroup environment, you can’t nest groups, but the “Remote Hyper-V Admins” group will come in useful later.. Step 5. Configure AZMan (on server) Here I’ve granted “Remote Hyper-V Admins” authorization rights to be Hyper-V administrators. See step 5 in part one for full details. REBOOT SERVER.
Step 6. Create a firewall exception for MMC (on client) To save repeating myself, this is identical to Part two, step 6. Step 7. Allow anonymous callbacks (on client) To save repeating myself, this is identical to Part two, step 7. Step 8. Set credentials for the remote server (on client) This is the gem of information you need. I’m logging onto the client machine as “john”, a standard domain user. The client has LUA enabled, as it should. From a non-elevated command prompt (that’s important), use cmdkey to store credentials for accessing the remote machine using the following syntax: “cmdkey /add remoteserver /user:remoteserver\username /pass” Of utmost importance, is the option passed to the /user parameter: - you must specify it as remoteserver\username, not just username. So in my walkthrough, I entered “cmdkey /add jhoward-hp2 /user:jhoward-hp2\john /pass” as the remote machine is called jhoward-hp2.
Step 9. Run Hyper-V Manager (on client) Start Hyper-V Manager from Control Panel/Administrative Tools (or \program files\Hyper-V\virtmgmt.msc). If you are using a pre-release version of Hyper-V and have not previously accepted the EULA, accept it now. You will notice that once you create a virtual machine and open Virtual Machine Connection, you will be prompted for credentials. At this point, use the credentials on the remote machine (john, password john in my example).
And “Voila”
So I’m very nearly there. I just need to write up the scenario of the Client being in a workgroup and the Server being domain joined. Part six to follow soon…. Cheers, John.
Update 14th Nov 2008. I've just released a script which does all this configuration in one or two command lines: HVRemote
If you would like to receive an email when updates are made to this post, please register here
RSS
... and the client being in a workgroup and the server being in a different one. :)
I'll run through all of this stuff tomorrow or the day after, when I get time to get back to this and see how it all goes. But there's nothing here that's much different from the previous info that's leaving Ryan and myself in the situation where WMI Control shows "Root" and no namespaces under it.
Anyway, I'll see what happens when I try this all again!
Thanks for your efforts. I just wonder if Microsoft really intended such a convoluted procedure to manage a Core box...
John this is great. Actually this is a real scenario environment.
You're great!
?
Michael A - This is AZMan configuration by the sound of it (step 5 above). Did you add your user account to the Administrator under role assignments? As you're running server core, you'll need to jump through the hoops for AZMan configuration I described in part 3 (sorry!).
John,
Thanks for the this great guide! I'm still amazed how people figure this stuff out.
I think I may have found a mistake in Step 4. In step 4 you say "See step 5 in part one for more information" but when I went to look at it, none of the screen shots matched up. I did some looking and found the similar screenshots in Step 4 of Part 1.
Is this correct?
Thanks Again,
-Howard
Thanks Howard - yes, my mistake - I've corrected it above. I did indeed mean step 4 of part 1.
Cheers,
Makes for really good reading
But I am stuck at Step 4.
the WMI just keeps tellimg me access denied
any ideas
Maritn (Martin?)
What's the domain/workgroup combination you're hitting when you get this error? Is it domain client to workgroup server as described in this walkthrough? Just want to double-check.
I'm assuming you're doing this step on the server, not remotely on the client? If so, are you running as a local administrator? I suspect that is the most likely cause.
It is Martin yes (I still type looking at my fingers not the screen)
the client is a Domain Vista Box and the Core server in a workgroup so I am trying to run the mmc from the snap in on the client this is when I connect the computer management snap in then browse to WMI, then when I right click it comes up access denied.
as I am not very big on command line stuff (but trying to learn) it is very frustrating I have copied all 5 of the walkthrough's onto paper to get all the steps in the right order.
Thanks in Advance
Martin
Don't forget, you can also use RemoteApp on the 2008 server where hyper-v is installed. You can pubish both the vmconnect and the virtmgmt. My laptop is not part of the domain, and i have no problems connecting.
Hey Bev,
Neat trick using RemoteApp, except for one problem: Hyper-V Connect to Virtual Machine doesn't work with Terminal Services. How did you resolve that?
Hi John,
Thanks for the great series of articles on configuring machines to remotely manage Hyper-V!
Using your articles as a guide, I figured out how to do the 6th scenario: workgroup client talking to domain bound server. Notes are here:
-Danny
I'm trying to setup Hyper-V manager in a domain environment but I'm getting a slightly different error message to those you have covered here. When I open Hyper-V Manager on the client, I get the message:
"Access denied. Unable to establish communication between 'CLIENT' and 'SERVER'."
This appears in the Virtual Machines panel. The client and server are connect to the same unmanaged switch with no firewalls other than the window firewall in default configuration on both machines. My user is a local machine administrator on both machines (with UAC running). Other services such as remote desktop between the machines works without problems.
I followed the steps in Part 4 of your guide, except for the WMI Control section, as when I inspected the settings the
user already had the necessary access due to being a server local machine administrator.
The two operations I can perform successfully in Hyper-V manager from the client are using the Hyper-V Settings and the Virtual Network Manager features, but everything else fails with the above message, usually at the end of a wizard.
Thanks for any help you can offer.
Paul - this error generally indicates you have not configured the DCOM settings on the client machine. See Part 2, step 7. That should resolve the issue.
Thanks John, that was indeed the problem. Looks like that step is necessary in the domain scenario as well as the workgroup scenario.
Thanks for this. Any help on what I believe to be an issue with connecting from a 32bit Vista client to the 64bit Hyper-V instance? Connection works fine from x64 W2008 but get the usual 'Cannot connect to RPC service' error when trying to connect from 32bit Vista.
David?
Bruce - you are correct. If both machines are domain members in the same domain, anonymous callback does not need to be configured. You should be able to add the user account to the Distributed COM Users group for the callback..
Thank you again, it was the missing of KB950050 on the server. Now, finally, I'am creating the first VM. And now I can go home to take my deserved beer :-)!!
Sigh ... :-(\root\virtualization in the namespace; server\user and appropriate password in the credentials.
Query
select * from msvm_computersystem
apply
Do you get any results back?
Joe - with the caveat that I have not tried this specific configuration, I believe there should be no need to allow anonymous callback if there is two way trust between seperate forests..
James - the mapping comes from Step 8 above. However, I was using a full installation of server rather than server core, so the earlier steps must be done remotely in that instance. To enable remote management for core to enable those steps remotely, see 'allow'?
Hola Una herramienta imprescindible para configurar los servidores con Hyper-V para que se puedan administra?
oso - have you removed the cmdkey setting on the client? (cmdkey /delete:servername) (?)
I'm trying to do "Step 4. Allow authenticate users to remote WMI namespaces (on server) " on Hyper-V Server (not 2008). All I have is command line. Is there a way I can do this without the GUI?
Thanks.
Thanks Ken, so glad you found HVRemote useful and appreciate I can't cover every eventuality and configuration :)?
Peterd - yes, Windows 2000 server *with SP4* is supported in single processor only mode. Are you running SP4, have you installed the integration services and what bugcheck are you hitting?
Zach - I'll drop you an email.
Zippy - can you email me the output of hvremote /show on both boxes, plus a ping -4 by name attempt in each direction. (Link at the top of the page)
Comment Policy: No HTML allowed. URIs and line breaks are converted automatically. Your e–mail address will not show up on any public page.
Senior Program Manager, Hyper-V team, Windows Core Operating System Division. | http://blogs.technet.com/jhoward/archive/2008/04/04/part-5-domain-client-to-workgroup-server-hyper-v-remote-management-you-do-not-have-the-requested-permission-to-complete-this-task-contact-the-administrator-of-the-authorization-policy-for-the-computer-computername.aspx | crawl-002 | refinedweb | 2,050 | 63.8 |
Class-based Fabric scripts via a Python metaprogramming hack
This is a hack to enable the definition of Fabric tasks as methods in a class instead of just as module level functions. This class-based approach provides the benefits of inheritance and method overriding.
I have a history of using object-oriented techniques in places they weren't meant to be used. This one was not all my idea, so may Andrew get any blame he deserves. Here's the story:
We had several Fabric scripts which violated DRY. Andrew wished for a class-based Fabric script. We discussed ideas. Stackoverflow answered my questions. I hacked. Stackoverflow fixed it for me. I made one more tweak and here it is:
util.py:
import inspect import sys def add_class_methods_as_module_level_functions_for_fabric(instance, module_name): ''' Utility to take the methods of the instance of a class, instance, and add them as functions to a module, module_name, so that Fabric can find and call them. Call this at the bottom of a module after the class definition. ''' # get the module as an object module_obj = sys.modules[module_name] # Iterate over the methods of the class and dynamically create a function # for each method that calls the method and add it to the current module for method in inspect.getmembers(instance, predicate=inspect.ismethod): method_name, method_obj = method if not method_name.startswith('_'): # get the bound method func = getattr(instance, method_name) # add the function to the current module setattr(module_obj, method_name, func)
As the docstring says, this function takes the methods of a class instance and adds them as functions to the module (fabfile.py) so Fabric an find and call them. Here is an example.
base.py:
from fabric import api as fab class Deployment(object): name = '' local_file = '' remote_file = '' def base_task1(self): 'base task 1' fab.run('svn export /path/to/{self.name}'.format(self=self)) def base_task2(self): 'base task 2' fab.put(self.local_file, self.remote_file)
fabfile.py:
import base import util from fabric import api as fab class _MyWebsiteDeployment(base.Deployment): name = 'my_website' local_file = '/local/path/to/my_website/file' remote_file = '/remote/path/to/my_website/file' def my_website_task(self): 'my website task' fab.run('echo "I am special"') instance = _MyWebsiteDeployment() util.add_class_methods_as_module_level_functions_for_fabric(instance, __name__)
Running
fab -l gives:
$ fab -l Available commands: base_task1 base task 1 base_task2 base task 2 my_website_task my website task
- Notes on sshfs on Ubuntu — posted 2010-04-05
Nice stuff. Exactly what I needed. Thanks for doing the hard work and posting!
Thank you very much. Was looking for days on how to do this. My file has grown to be very huge already.
This is awesome, exactly what I'm looking for!! Thanks! | https://www.saltycrane.com/blog/2010/09/class-based-fabric-scripts-metaprogramming-hack/ | CC-MAIN-2019-30 | refinedweb | 443 | 58.79 |
Entity
public
abstract
@interface
Entity
implements
Annotation
Marks a class as an entity. This class will have a mapping SQLite table in the database.
Each entity must have at least 1 field annotated with
PrimaryKey.
You can also use
primaryKeys() attribute to define the primary key.
Each entity must either have a no-arg constructor or a constructor whose parameters match
fields (based on type and name). Constructor does not have to receive all fields as parameters
but if a field is not passed into the constructor, it should either be public or have a public
setter. If a matching constructor is available, Room will always use it. If you don't want it
to use a constructor, you can annotate it with
Ignore.
When a class is marked as an Entity, all of its fields are persisted. If you would like to
exclude some of its fields, you can mark them with
Ignore.
If a field is
transient, it is automatically ignored unless it is annotated with
ColumnInfo,
Embedded or
Relation.
Example:
@Entity public class Song { @PrimaryKey private final long id; private final String name; @ColumnInfo(name = "release_year") private final int releaseYear; public Song(long id, String name, int releaseYear) { this.id = id; this.name = name; this.releaseYear = releaseYear; } public int getId() { return id; } public String getName() { return name; } public int getReleaseYear() { return releaseYear; } }
See also:
Summary
Public methods
foreignKeys
public ForeignKey[] foreignKeys ()
List of
ForeignKey constraints on this entity.
ignoredColumns
public String[] ignoredColumns ()
The list of column names that should be ignored by Room.
Normally, you can use
Ignore, but this is useful for ignoring fields inherited from
parents.
Columns that are part of an
Embedded field can not be individually ignored. To ignore
columns from an inherited
Embedded field, use the name of the field.
inheritSuperIndices
public boolean inheritSuperIndices ()
If set to
true, any Index defined in parent classes of this class will be carried
over to the current
Entity. Note that if you set this to
true, even if the
Entity has a parent which sets this value to
false, the
Entity will
still inherit indices from it and its parents.
When the
Entity inherits an index from the parent, it is always renamed with
the default naming schema since SQLite does not allow using the same index name in
multiple tables. See
Index for the details of the default name.
By default, indices defined in parent classes are dropped to avoid unexpected indices.
When this happens, you will receive a
RoomWarnings.INDEX_FROM_PARENT_FIELD_IS_DROPPED
or
RoomWarnings.INDEX_FROM_PARENT_IS_DROPPED warning during compilation.
primaryKeys
public String[] primaryKeys ()
The list of Primary Key column names.
If you would like to define an auto generated primary key, you can use
PrimaryKey
annotation on the field with
PrimaryKey.autoGenerate() set to
true.
tableName
public String tableName ()
The table name in the SQLite database. If not set, defaults to the class name. | https://developer.android.com/reference/androidx/room/Entity?hl=vi | CC-MAIN-2021-39 | refinedweb | 478 | 56.66 |
Opening.
As far as I can tell your code never actually flushes (write to disk) or closes the file. This means that any changes will not be visible until
theFileis removed (which happens when you run a new script, because then Pythonista will wipe the Python environment by default). When working with files it's usually best to use the
withstatement, which will ensure that the file is always properly written and closed:
with open("some_file.txt", "a") as f: f.write("some text\n") # ... any code that uses the file (f) ... print("Done!")
Note that the file object (
f) can only be used inside the
withblock. Once that block is exited,
fbecomes unusable. This means that any code that uses
fneeds to be in the
withblock.
(By the way, see this link on how to post code blocks on the forums.)
Not sure if this what you after @Oak. I am very new, but still trying to help as many help me. So take it with a grain of salt
import location, os.path __FILE_DIR__ = os.path.expanduser('~/Documents/') __FNAME__ = 'CoordinatesList.txt' __MY_FILE__ = __FILE_DIR__ + __FNAME__ if not os.path.exists(__MY_FILE__): theFile = open(__MY_FILE__, 'w') is_new_file = '' else: theFile = open(__MY_FILE__, 'a') is_new_file = '\n' location.start_updates() myCoords=location.get_location() location.stop_updates() longitude=str(myCoords['longitude']) latitude=str(myCoords['latitude']) theFile.write(is_new_file) theFile.write(longitude) theFile.write('\n') theFile.write(latitude) theFile.close()
- polymerchm
I thinks the issue might be not closing the file across calls.
try:
import location,time location.start_updates() mycoords = location.get_location() location.stop_updates() with open('coordinates.txt','a') as fh: fh.write(str(mycoords)+'\n'+str(time.ctime())+'\n')
This worked fine for me, but did keep jumping back to pythonista rather than remaining in Safari. Also to better format your code for markdown, use the following approach:
```python
your code snippet here
```
in your posts to the forum
Thank you all, you were most certainly right! File was not closing. I have fixed it now by simply using <code> with open </code> for the file.
Thanks again!
- polymerchm
Talk about great minds think alike!!!
- galewinston
This post is deleted!last edited by ccc | https://forum.omz-software.com/topic/1762/opening-file-for-append-issue/2 | CC-MAIN-2022-05 | refinedweb | 358 | 60.72 |
Making SOAP Web Service Requests With ColdFusion And CFHTTP
I get a large number of people asking me how to make SOAP web service requests using ColdFusion features like CFInvoke and CreateObject( "webservice" ). Typically, these methods works just as advertised, encapsulating SOAP requests (and responses) in a clean, easy to use ColdFusion wrapper. Of course, that's not the cases that these people are asking me about; typically, people want to know how to get CFInvoke or CreateObject() to work with a particularly complicated API.
There's no doubt that ColdFusion has some excellent (if only slightly outdated) SOAP functionality. But when things get too complicated, I find it's often easier to execute and maintain SOAP requests when you drop down into the raw XML and manual HTTP post. This kind of SOAP handling gives you complete control over all aspects of both the request and the response and leaves no mystery as to how data types should be translated.
To demonstrate this, let me walk through a SOAP request to Campaign Monitor's newsletter subscription API. Given any WSDL file, you should be able to figure out (with some determination) what kind of SOAP request a particular method call is expecting. Depending on the complexity of the given WSDL file, this could be a simple task or a total nightmare. Luckily, most professional APIs provide solid documentation complete with sample XML request and response values. The following screenshot is taken directly off of the Campaign Monitor API url and is typical (in nature) of the kind of documentation I have found with many API providers:
As you can see, the first XML document is a sample of the SOAP request you need to make; the second XML document is a sample of the SOAP response you will get. In addition to the XML, the API documentation also defines the SOAPAction that must be included with the request - take note of this as it will become a required Header value in our CFHTTP post.
Once we have this documentation in hand, all we have to do is formulate our own XML document and post it to the API using ColdFusion's CFHTTP and CFHTTPParam tags:
- <!---
- We are going to subscribe to Campaing Monitor using the
- AddAndResubscribe actions. This is a SOAP-based method that
- requires the following XML body.
- --->
- <cfsavecontent variable="soapBody">
- <cfoutput>
- <?xml version="1.0" encoding="utf-8"?>
- <soap:Envelope
- xmlns:xsi=""
- xmlns:xsd=""
- xmlns:
- <soap:Body>
- <Subscriber.AddAndResubscribe
-
- <ApiKey>#campaignMonitorKey#</ApiKey>
- <ListID>#campaignMonitorList#</ListID>
- <Name></Name>
- </Subscriber.AddAndResubscribe>
- </soap:Body>
- </soap:Envelope>
- </cfoutput>
- </cfsavecontent>
- <!---
- Now that we have our SOAP body defined, we need to post it as
- a SOAP request to the Campaign Monitor website. Notice that
- when I POST the SOAP request, I am NOT required to append the
- "WSDL" flag to the target URL (this is only required when you
- actually want to get the web service definition).
- --->
- <cfhttp
- url=""
- method="post"
-
- <!---
- Most SOAP action require some sort of SOAP Action header
- to be used.
- --->
- <cfhttpparam
- type="header"
- name="SOAPAction"
- value=""
- />
- <!---
- I typically use this header because CHTTP cannot handle
- GZIP encoding. This "no-compression" directive tells the
- server not to pass back GZIPed content.
- --->
- <cfhttpparam
- type="header"
- name="accept-encoding"
- value="no-compression"
- />
- <!---
- When posting the SOAP body, I use the CFHTTPParam type of
- XML. This does two things: it posts the XML as a the BODY
- and sets the mime-type to be XML.
- NOTE: Be sure to Trim() your XML since XML data cannot be
- parsed with leading whitespace.
- --->
- <cfhttpparam
- type="xml"
- value="#trim( soapBody )#"
- />
- </cfhttp>
- <!---
- When the HTTP response comes back, our SOAP response will be
- in the FileContent atribute. SOAP always returns valid XML,
- even if there was an error (assuming the error was NOT in the
- communication, but rather in the data).
- --->
- <cfif find( "200", httpResponse.statusCode )>
- <!--- Parse the XML SOAP response. --->
- <cfset soapResponse = xmlParse( httpResponse.fileContent ) />
- <!---
- Query for the response nodes using XPath. Because the
- SOAP XML document has name spaces, querying the document
- becomes a little funky. Rather than accessing the node
- name directly, we have to use its local-name().
- --->
- <cfset responseNodes = xmlSearch(
- soapResponse,
- "//*[ local-name() = 'Subscriber.AddAndResubscribeResult' ]"
- ) />
- <!---
- Once we have the response node, we can use our typical
- ColdFusion struct-style XML node access.
- --->
- <cfoutput>
- Code: #responseNodes[ 1 ].Code.xmlText#
- <br />
- Success: #responseNodes[ 1 ].Message.xmlText#
- </cfoutput>
- </cfif>
Here, we are defining our SOAP request in the content buffer, soapBody. This XML variable is then posted to the Campaign Monitor API using CFHTTP. Notice that when I post to the API, I am not using the "WSDL" URL flag; this is only needed when we actually want to retrieve the web service definition (as is typically required by the ColdFusion SOAP wrappers). Since we are posting the raw XML, no additional web service definition is required.
The SOAPAction value that I mentioned before is now being included as a Header value using ColdFusion's CFHTTPParam tag. If you look at the previous screenshot of the API sample, you will notice that the SOAPAction value is surrounded by double quotes. While this is not required for the Campaign Monitor API, I am pretty sure that I remember running into a few situations where adding the quotes to the SOAPAction was critical:
- <cfhttpparam type="header" name="SOAPAction" value="""....""" />
Notice the extra, escaped double quotes in the Value attribute.
Once we have posted the SOAP XML, we need to handle the SOAP response..
When the SOAP response comes back, it should look something like this:
As a final caveat, because the SOAP XML response has name-spaced nodes, querying the document becomes a bit more complicated; rather than using standard node names in your XPATH, you have to query for "*" (any node) and check its local-name(). I don't care for this approach, but it seems to be the easiest way to deal with name spaces.
When we run the above code, we get the following output:
Code: 0
Success: Success
As you can see, we were able to post the SOAP XML and parse its response without any problems.
ColdFusion provides some really great SOAP functionality; API wrappers like CFInvoke and CreateObject( "webservice" ) allow for seamless integration of SOAP web service requests into your ColdFusion code. When APIs get more complicated, however, these wrappers start to break down. Luckily, in times like that, ColdFusion also makes it easy for us to drop down into the raw XML and make manual SOAP HTTP requests. And, if you encapsulate all of this into a ColdFusion component, you end up, once again, with a nice API wrapper. () to make a call to the web service and route request trough TCP Monitor (part of Axis and as such already installed with ColdFusion).
Here's shortcut that I usually use to start TCP Monitor (I've downloaded latest version of Axis)
C:\jdk1.5.0_08\bin\java.exe -cp "C:\Program Files\axis-1_4\lib\axis.jar" org.apache.axis.utils.tcpmon 12345
Hope this helps.
Tero
@Tero,
I agree, regarding the low complexity of an API that necessitates XML. Generally, I only use XML. I almost never even check to see if the ColdFusion wrappers work; to me, the XML just seems more straightforward.
I'll have to check out the SoapUI stuff. that SOAP stands for SOrry Ass Protocol.
@Arthur,
If you want to publish SOAP web services in ColdFusion, it is just about the easiest thing every. All you have to do is create a CFC with "remote" access methods (it's an attribute on the CFFunction tag). That will automatically make the cfc/method a SOAP web service; CF will create the stub files for you and provide the WSDL files at request with the "?wsdl" flag.
already pre-established, it's 95% working, but just hard to get one little part of it working... I have the urge to just go in tweak the SOAP xml going over the wire, but there is no easy way to do that. I saw your other related post where you are doing just that for an image watermark-- interesting stuff.
@Arthur,
If you are working with an existing request format, you might want to just expose a CFM file as a remote web service (there's nothing technically different from a standard web page). Basically, you're gonna create a page that returns XML content rather than HTML content. The tricky thing there is that you have to manually form a SOAP XML response packet. Of course, since that is a standard, you can look it up for examples.
That's sucks though, that you have to conform to someone else's request given that *you* are the one exposing the web service :) look at the headers that are being sent (by posting to a script on my own server and looking at the CGI vars) I can see CF is adding its own list to the header.
HTTP_ACCEPT_ENCODING=no-compression, deflate, gzip, x-gzip, compress, x-compress
I presume the web service I am accessing are looking for the presence of gzip, as opposed to the presence of no-compression.
Any ideas how I can get CF to stop adding a list of encodings it doesn't support?
Thanks
Dave
I'm having a similar problem to Arthur - Our webservice is basically a listener there to receive results back from a 3rd Party supplier
I successfully created the calls & dealt with the responses to create the order using the code you supplied but the response is just an acknowledgement that the order has been received - The actual results come back asynch - Hence the listener
If I send the response XML from my test harness - the code works exactly as I'm expecting - It falls over when it hits a db call but thats fine as it's only test data - It does however read and parse the XML correctly however when it's sent directly from the supplier using their C# setup it falls over at the point where I'm trying to do a read (to dump out a copy of the response to the local file system before processing) on the XML document that's been sent
We don't receive any errors in our exception log but the calling service gets an error
ErrorMessage=Unable to send API Result to EPSL:
faultstring=coldfusion.xml.rpc.CFCInvocationException:
[coldfusion.runtime.CfJspPage$ArrayBoundException : The element at position 1 cannot be
found.];detail=*coldfusion.xml.rpc.CFCInvocationException:
[coldfusion.runtime.CfJspPage$ArrayBoundException : The element at position 1 cannot be found.]
at
coldfusion.xml.rpc.CFComponentSkeleton.__createCFCInvocationExceptio
n(CFComponentSkeleton.java:723)
at
coldfusion.xml.rpc.CFComponentSkeleton.__invoke(CFComponentSkeleto
n.java:670)
at
sol.SolServiceListener.SolReceiveResult(........
This is a very weird error and is the only thing standing in our way to getting the whole thing working - we've tested the rest of the system - just as usual a weird integration problem!
@David,
Hmmm, I was not aware that ColdFusion was adding additional headers on top of the accept-encoding that you were sending. I am not sure I have any better advice. What kind of error are you getting? Typically, in my experience, the GZIP encoding issue returns a Failure to Connect or some sort of mime-type issue. Is that what you were getting?
@Jo,
Is the calling server a ColdFusion server? Or just the one hosting the web service? This error is clearly ColdFusion-based, so I was hoping that might help us narrow it down.
That's right Ben, it was the failure to connect issue.
I resolved it in the end by purchasing the CFXHTTP5 tag - that allowed me to control exactly which headers were being sent.
Hi Ben,
The calling server is a C# one sending the XML in a SOAP envelope - My webservice at the other end working as the listener is Coldfusion - We've done a bit more investigation and found that the underlying object that Coldfusion uses for the XML is a org.apache.xerces.dom.DeferredDocumentImpl -
This works fine when I use my test harness (which is my local dev Coldfusion server) but when the remote system sends the SOAP envelope - Coldfusion doesn't seem to be able to read it correctly and returns a seemingly null object
I've tried making use of the underlying java methods but they return null and I've tried getting the toString() of the object and parsing that but that is empty as well
The only real clue I have that might help is the WSDL supplied to us by the supplier
In my Coldfusion generated wsdl - the object is being defined as
<element name="SOL_Result" type="apachesoap:Document"/>
whereas in the suppliers original wsdl - it is defined as
<xs:element
I don't know how to deal with this object difference - It's obviously significant - I don't know (because I've only just asked the question)whether they send the result out as an XML string or as this pre-defined object
I'm going to run WSDL2Java and get a copy of the equivalent Java TSOL_Result object and see if that makes any difference
I've actually now managed to get something working with the supplier WSDL - the service accepts calls to it - However the object created from the SOAP envelope sent is still empty - I'm not sure Coldfusion actually likes the suppliers WSDL as it has alot of complex type definitions in it
I'm completely at a standstill as how to progress with this - It is usually just so easy with Coldfusion but when it doesn't work boy doesn't it work big time!
@David,
I wish I knew more about what was going wrong; in the past, the accept encoding trick has always worked for me. Good to know that at least something was able to fix it on your end.
@Jo,
That's super irritating. With SOAP, I typically create the requests via CFSaveContent and CFHTTP. However, I am not sure that I've ever actually manually created a SOAP response; as such, letting ColdFusion handle that would be the easiest approach. And, when that's not working, that's super frustrating. I wish I had a better suggestion (other than to add to the complaining).
by doing that...
Thanks Arthur - Thats more or less the conclusion I'd come to - I'm currently writing in Java natively which I'm actually rather enjoying because my background is Java
My colleague found an interesting article about the possible problem - It's to do with needing to flatten the WSDL so that Coldfusion and other languages can deal with the stuff generated out of WCF
What happened to Webservices & XML being the definitive method of communication across disparate systems!
cfhttp response is located in it's FileContent property ????
You can't imagine how many times I had to work with cfinvoke and it's complex responses and their weird classes deserialization because I did not know this !!!
Thank you Ben!
@Dmitry,
No problem my man. You should be able to just parse the SOAP response into XML and be able to access all the nodes that way. The only thing you have to be careful of is the namespaces which require you to use some funky xmlSearch() XPath (local-name()).
I finally got to the bottom of my problem - the fact was that the WSDL was full of complex types that Axis didn't like - I should have been able to receive it as a struct but that just didn't work so it had to stay as an XML input
So what we ended up having to do and its blindingly obvious once you know! Is the following
<cfset soapreq = GetSOAPRequest()>
<cfset soapResponse=XmlParse(soapreq)>
This can then be accessed using the XPath expression
<cfset responseNodes = xmlSearch( soapResponse,"//*[ local-name()='SOL_Result']" )/>
And off you go! Days of scratching your head already solved by a little used Coldfusion tag!
Just need to add - we still did have to get the external service to clean up their WSDL and flatten it as per the article I posted before
@Jo,
Glad you got it working. I've never had a lot of luck using the SOAP methods (getSOAPRequest(), getSOAPResponse(), isSOAPRequest(), etc.) in ColdFUsion. I just never seem to want to use them in the right place. It's like you can only use them IF you are already using SOAP wrappers. But, it seems like they would be most useful when you are not using SOAP already... maybe I just don't really understand what they are supposed to be used for.
@Ben,
Using soap is pretty simple when working with Java objects:
<cfset objServerXMLHttp.open("POST", "", False) />
<cfset objServerXMLHttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8") />
<cfset objServerXMLHttp.setRequestHeader("SOAPAction", "") />
<cfset objServerXMLHttp.send("#myXMLrequest#") />
<cfset objDOM = objServerXMLHttp.responseXML />
<cfset lv_xml = xmlparse(objDom.xml) />
@Dmitry,
I'll have to take a look at that. Typically, I just use CFHTTP, but I check out more Java-based approaches.
Thank you for this Ben, it worked like a charm!
@Jason,
Awesome my man! Glad to help. SOAP is definitely a funky beast to harness sometimes.
Hi Ben just wondering if you had an luck getting this request with the more complex Campaign Monitor requests that require SOAP such as passing custom fields.
This particular method is the similar to the one used in your example however it also allows an array of custom fields to be passed through.
I had the previous non custom fields SOAP request working fine, but it seems even with half a dozen cfhttparam headers I can't get this to be accepted and continue to get Bad Request responses and Unable to determine Mime Type?
Code I am using is as follows:
<cfhttp url="" method="post" result="httpResponse">
<cfhttpparam type="header" name="content-type" value="text/xml">
<cfhttpparam type="header" name="SOAPAction" value="">
<cfhttpparam type="header" name="content-length" value="#len(arguments.soapxml)#">
<cfhttpparam type="header" name="charset" value="utf-8">
<cfhttpparam type="header" name="Accept-Encoding" value="*" />
<cfhttpparam type="Header" name="TE" value="deflate;q=0">
<cfhttpparam type="xml" value="#arguments.soapxml#">
</cfhttp
Cheers
Phil
@Phil,
That's actually the SOAP action we use a lot in our apps - the resubscribe with custom fields. Let me ask you something - are you using CF7 by any chance? I've had very odd CF7 behaviors with making SOAP requests where like 100 requests will work and then suddenly, out of nowhere, I'll start getting crazy errors like, "Body cannot be empty" for the rest of the page request. Same code works perfectly in CF8 and CF9. soap tags to it before validating the xml with it?Any help is appreciated.
@Jasmine,
How do you handle the invalid XML if it does not validate? I am just asking because I am trying to understand your workflow. I guess what I'm asking is, why do you every have invalid XML? And, if you do, what is the benefit of validating vs. just handling web service invocation errors?
Awesome, this is exactly what i was needing!! am loving campaign monitor too. thanks ben. another great article.
@Mike,
Yeah, quality stuff, right. I've been very happy with their service. They also have a great feature where you can test the look/feel of your outgoing newlsetters in like 20 different mail clients. It costs like $5 per test, but well worth it if you have some mission critical stuff.
I am curious to know if there is a proper way to handle a lack of any cfhttp reply?
We recently moved to cfhttp SOAP for a payment system (thank you for this great article) and they require us to code for a secondary gateway that "should" ONLY be used if the primary is down.
When I inquired if a 200 reply was considered their valid reply, I was informed that any reply from them had to be handled on my end, and the failover should only work on a lack of reply.
I'll be honest, I'm pretty sure I've not done this before. Would that not be generally a cfhttp timeout?
Is there a way to capture this and work on it?
I currently encapsulate my cfhttp SOAP request and reply in a cftry, and then handle any responses I don't like.
Frank
@Frank,
Yeah, that would be a timeout issue. I am not sure what the timeout is by default - I don't think there is one - it will just hang (and then probably the page will timeout if it every returned).
It sounds like you are on the right track: put the first CFHTTP in a CFTry with a meaningful timeout and then in the CFCatch, you can perform your failover CFHTTP.
@Frank,
You can try something like this:
<cfhttp timeout="1" url="">
<cfif CFHTTP.statuscode is "408 Request Time-out">
Timeout
<cfelse>
<cfdump var="#CFHTTP#">
</cfif>
Or you could use throwonerror="true". Unfortunately that doesn't return specific type for timeout so I guess I'd actually use my example instead.
That works with CF7, I wouldn't be surprised if that would be different for other versions.
Tero
@Ben Nadel,
OK, and that's what I suspected.
My understanding is, it is an instant transaction. I send, you reply. If you fail to reply, I wait until I die. However, during this waiting time, I assume ColdFusion keeps the connection open waiting for a response.
Now, unless I misunderstood, if there is no way to timeout a cfhttp request before the page times out, then my only option is for the page to try and capture its own page time out and deal with that. Is that possible?
@Tero Pikala,
Ug, wow how did I miss that? The 408 reply I mean.
I considered a cfhttp timeout. As you pointed out, if I force a timeout on cfhttp, it has to be before the script times out but after their page times out. Otherwise I run the risk (rare as it may be) to timeout on my end, then get a reply on their end, and miss it.
:)
Let me run a test request to see if it will trigger a 408 reply. Hopefully.
Thanks!
@Frank,
I think there is a certain amount of "reasonable performance" assumption you can make when dealing with a system. If you connect to a 3rd party API that is supposed to be fast, you shouldn't have to give them a 10 minute timeout period (that's simply not reasonable performance). Giving them a buffer is, however, good. You can use CFSetting to give your processing page a timeout and then give the CFHTTP timeout a smaller value than that (to ensure you have time to react).
// 3 minute page timeout.
<cfsetting requesttimeout="#(3 * 60)#" />
// 2 minute CFHTTP timeout.
<cfhttp timeout="#(2 * 60)#" />
If you think you're gonna need more time than that, then it really becomes a game of chicken, to some degree (who can wait longer).
Hi Ben,
Sorry for the late reply all the responses were going into my Junk and i just noticed! gah.
Ok I'm actually using CF8 but the issue wasn't related to the SOAP request structure at all, but poor response by Campaign Monitor. Basically i had sent my SOAP request along with the custom fields and was getting a HTTP 400, Invalid Mime Type error. After a bit of Trial and error it seemed to work fine with the custom fields array removed so the issue was with the custom fields. I had all white space trimmed and followed the documentation on the format with square brackets but what i didn't realise was that if you are sending a custom field that contains multiple options (multi select or checkbox), then you need to append a colon onto the field name you are passing or it throws a HTTP 400??? For example I had [ChestExercises] and it wanted to see [ChestExercises:]
So my custom fields would be as follows for a sample with 1 standard custom field and a multi-select custom field:
<CustomFields>
<SubscriberCustomField>
<Key>[WorkoutDate]</Key>
<Value>2010-05-08</Value>
</SubscriberCustomField>
<SubscriberCustomField>
<Key>[ChestExercises:]</Key>
<Value>Bench Press</Value>
</SubscriberCustomField>
<SubscriberCustomField>
<Key>[ChestExercises:]</Key>
<Value>Dumbbell Flyes</Value>
</SubscriberCustomField>
<SubscriberCustomField>
<Key>[ChestExercises:]</Key>
<Value>Dips</Value>
</SubscriberCustomField>
</CustomFields>
Hope that helps anyone who runs into the same issue.
Cheers
Phil
@Phil,
I have only sent simple, single custom values so I have not run into this before; thanks for posting the follow-up - I am sure this will come in handy! "Connection Failure" error. In the error details the value is "Connection Reset".
<cfhttp url="#SecretServiceShh.asmx?wsdl#" method="POST" resolveurl="yes" useragent="#cgi.HTTP_USER_AGENT#" charset="utf-8" result="httpResponse" >
<cfhttpparam type="Header" name="Accept-Encoding" value="deflate;q=0">
<cfhttpparam type="Header" name="TE" value="deflate;q=0">
<cfhttpparam type="header" name="charset" value="utf-8">
<cfhttpparam type="header" name="content-type" value="application/xml; charset=utf-8">
<cfhttpparam type="header" name="content-length" value="#len(trim(soapRequest))#">
<cfhttpparam type="xml" name="body" value="#trim(soapRequest)#">
</cfhttp>
Any help would be appreciated.
Thx,
MC Layaway
@MC,
I've never run into that situation before. Now, when you say that someone moves through the form quickly, are you saying your making like a CFHTTP every minute? Or are we talking like every 10 seconds? I wonder if there is some throttling being put in place somewhere. this.
Thanks for the help Homey,
MC Layaway Fo Life;)
@MC,
This is typically how I send complex data to a .NET web service. I've run into various problems having to do with compression or special SLL certificates; but, those always fail on every request. I have no idea why some requests would work and some would fail.
I am stumped. to use)!
Then, Ta Da! Along comes Ben with his exquisitely simple approach.
Bravo. Thanks.
RLS
@Randy,
Awesome! I'm so glad this could help. ColdFusion does provide SOAP wrappers; but, I find the raw XML and CFHTTP to be so much easier to use in most cases. Glad you got things sorted out.
Hello Ben,
I have a component that works great in ColdFusion using <cfinvoke> Now I need to call it from .Net but I can't get the wsdl when I typed this: all I get is a blank page.
I am using Coldfusion 7, do you know if this a configuration problem? if so what changes do I need to make?
Here is part of my function so you can see that I am using access="remote":
<cffunction name="createDatasources" returntype="string" output="no" access="remote" >
Thank you,
Juan
@Juan,
Are you saying that calling the createDataSources.cfc from ColdFusion works fine; but, calling the same CFC from .NET does not? Are you using the onRequest() event handler in Application.cfc? Try looking at your ColdFusion logs to see if there is an error taking place.
When you make a request for the WSDL file, the FORM scope doesn't exist. If you have any references to the FORM scope in the onRequestStart() event handler, this will cause an error.
@Ben,
After I moved the component createDataSources.cfc to "C:\Inetpub\wwwroot\cfide" it worked. Now I am able to open the wsdl and to include it in ASP.NET.
Thank you.
@Juan,
I'm glad you got it working. on the service to wrap the error message into the object? CF has no way to by pass the 500 error and parse the cfhttp.filecontent
HTTP/1.1 500 Internal Server Error
Server: Resin/4.0.1
Accept: text/xml, text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
SOAPAction: ""
Content-Type: text/xml; charset=utf-8
Content-Length: 589
Date: Tue, 12 Oct 2010 23:48:38 GMT
<SOAP-ENV:Envelope xmlns:<SOAP-ENV:Header/><SOAP-ENV:Body><SOAP-ENV:Fault><faultcode>SOAP-ENV:Server</faultcode><faultstring xml:PreparedStatementCallback; SQL [select * from blah blah...]; Conversion failed when converting from a character string to uniqueidentifier.; nested exception is java.sql.SQLException: Conversion failed when converting from a character string to uniqueidentifier.</faultstring></SOAP-ENV:Fault></SOAP-ENV:Body></SOAP-ENV:Envelope>
Brilliant! This is the best way to connect to SAP webservices. Thanks!
@Anil,
That's an interesting looking error. It looks like you might be trying to convert a remote data type to a ColdFusion query object or something? Have you figured it out (I know this comment is a bit old)?
@Mike,
Glad you like it! This is the only way I approach SOAP APIs these days :)
Spent *hours* figuring out why my header param for SOAPAction didn't get passed through. Finally figured it out: you have to pass it in quotes. So in CF that would be:
Now it works like a charm. Just in case someone runs into the same problem.
A very nice program for figuring out how to get your SOAP requests right is soapUI -
I downloaded the Pro trial, but there is also a free version. Not sure what the latter can do though.
Cheers - Lomeos
@Bart,
Yeah, it's interesting you mention that. In my code example, I am not using the double-quotes; but, if you look toward the end of the blog post, you'll see that I mention that some web services apparently need this to quoted as a value. I am not sure why there is a discrepancy between different sites. I used to always double-quote the value (after hours of debugging like yourself). Probably best to just always do it. Sorry for giving a somewhat misleading demo code :)
Thanks Ben,
Once again another wonderfully crafted blog post.
I had started with this blog post
But looking at the SOAP request it seems to me to be easy enough to manually create. But I was not sure what to do next.
This was the missing key for me.
Love your work! assistance can be billable.
I just feel like im in a bit of a rut and my deadline is really tight.
Thanks in advance.
not so much for those of us who landed here (as I frequently do) looking for our daily dosage of Ben Nadel wisdom, but more for those looking for a quick way to parse out .NET web service results, have a look at this here
The problem with publishing CF web services to be consumed by anything other than CF is that it generates an awful SOAP responses.
Instead of
<element1>
<element2>
<param1>value</param1>
<param2>value</param2>
</element>
</element1>
you get something like
<element attribute1="value" attribute2="value" attribute3="value">
and it is quite a PITA for anyone else to work with.
Try using SOAPUI on your own CF web services and you will see what I mean.
Thanks for another valuable post Ben!
I am consuming a web service using your described method utilizing cfhttp. Sadly this web service also requires that I maintain session state. Is it possible to set a header that mimics: setMaintainSession(true).
Thanks
Thanks Ben for this post, was doing some work with the eBay API and this helped me get over the hump! You Rock!
Thanks Ben for the insights on this slippery slope.
The parsing of returned XML elements with xmlSearch using local-name() really saved me from a grisly death by headache!
:) of all my issue, when I made the web service call using cfinvoke I was returned an object with available methods (found this by using cfdump). Accessing those methods (cfoutput) simply returned what looked like a memory reference, something like "com.domain.". What I have found is that you can get to the actual values of the SOAP response by referencing those get functions that are returned in the cfdump. I was seeing that memory reference because the returned value was a complex type. As I kept cfdump'ing those get functions I finally got to the simple types that I could access directly. So you can use something like "returnVariableName.getStatus().getStatusCode()" to get the actual data values.
This seems like a huge breakthrough to me although I am sure it is not. I just have not found any articles online speaking to this method of getting the data. Every article I found mentions using cfhttp and parsing the XML to get the data; which obviously works. Since there is such a lack of information out there on this method I am wondering if I am missing something. It sure seems easier to call the get methods instead of traversing the XML. Do you have any insight on this?
Once again, Ben Nadel's code and blog making my life easier!
Thank you so much, Ben, for this information. It helped me work past a probem that has been plaguing me for days! I needed to get the Values for given Keys out of 100s of nodes structured just like this:
You mention "our typical ColdFusion struct-style XML node access," but to somebody new, it is not all that typical! I had never worked with XML before last week; each time I encountered a new problem, it was your blog that more often than not provided the answer or pointed me in the right direction.
It really says something about your willingness and ability to help others when a post from years ago still generates useful responses. So again -- THANK YOU!
@Miguel --
I think I am in the same boat as you. I was able to access high-level info using
and similar. I get all of the login info that way; I would then craft a SOAP envelope as follows:
I then post the SOAP (soapBody) to the web service using Ben's method:
And finally parse the result into something I can work with:
As far as calling get methods rather than traversing the XML, I agree, it definitely does seem easier. But at some point you'll most likely drill down to a method that returns a bunch of identically named elements as an array of arrays. At which point, calling methods and looping through to find the value of some given key begins to break down.
That approach might also not work so well if for whatever reason, you cannot use cfinvoke.
Just wanted to say thanks for this, Ben. Not only did it work, it worked the first try! receive a session timeout error every time. Working with a NS tech, they said the problem is that the cookies are not being sent on one row and that I need to use the Axis SetMaintainSession(true) to properly collect and regurgitate the cookies on each request. The problem is we have already written everything (all lookups, adds, deletes, etc the functionality to do things in NS) as XMl and have it all working with your cfhttp component, but only if we pass the credentials in every soap.header, not using the ssoLogin with the cookies.
The question is if there is a way to modify your cfc to somehow invoke the setMaintainSession and use the apache methods to pass the cookies rather than the cfhttp param so that we do not have to rewrite all of our code and use the wsdl stubs from the netsuite api.
Hope that makes sense and you can shed some light on this one for me.
Thanks so much,
Matt
Simply ... THANK YOU!!!!!!! the API without having to make a stub of their ginormous wsdl. If anyone ever needs help with it we hope to put a cfc on riaforge at some point to help others who feel as helpless as we did.
Peace
Matt
I want to generate empty requests and responses conforming to a given WSDL using web method and End Point URL dynamically in the code. Is there any way regarding this???ting each individual field by itself.
Here is a screenshot of the dump:
I am trying to just output the service tag xmltext but it is erroring out when I do it.
When I run:
Service Tag: #responseNodes[1].ServiceTag.xmlText#
I get the following error:
Element SERVICETAG.XMLTEXT is undefined in a Java object of type class coldfusion.xml.XmlNodeMap referenced as ''
Any ideas on what this means or how to get by this?
@spacerobot,
Unbelievable. I figured it out! I was doing the xmlsearch to the wrong spot in the file.
What if I want to show the nodes or values of the id? Here's a part of the code:
Trying this can't solve it:."
I am working with an API that does not follow this rule. I am getting an access denied error (still working with the sys-admin on that), and the error DOES come back as a SOAP reponse in the filecontent variable...however, I am getting a 500 response code instead of 200.
We have been using this method for a long time to invoke complex web services from PeopleSoft.
Basically we do invoke the first method thru cfhttp to create the request-- and the second cfhttp to use that request number to get the details/result of the web first call. This is how PeopleSoft works when you publish a Component Interface as a web service. This has been working for such a long time on CF9.
Anyhow, recently, we are testing our web service calls on CF10. There is an additional 4-5 sec delay when we call these two cfhttp in consequently on CF10. If we split the cfhttp calls into two different requests (assuming that we have the request number necessary for the second call) both individually takes less than .5 sec. which is like how it used to be.
But when they are called consequently, first cfhhtp call takes less than .5 sec while the second takes as much as 5 or 6 seconds.
Any idea what is going on? extra sleep time between those two calls?
Thanks in advance for any pointers.
-K
@Kivanc,
Did u sort that issue out?
I'll be doing something similar shortly for a new client. Would you mind sharing a snippet that consumes a PeopleSoft service? chinabuy01@yahoo.com
Hi Ben
What if a website uses HTTPS as webservice?
I got this error when I try to connect a HTTPS site:
ErrorDetail I/O Exception: peer not authenticated
Filecontent Connection Failure
I can access that site var SOAPUI tool.
And here is my code:
<cfhttp url="#urlAPI#" method="post" result="response" throwOnError="false">
<cfhttpparam type="header" name="SOAPAction" value=""/>
<cfhttpparam type="header" name="accept-encoding" value="no-compression"/>
<cfhttpparam type="xml" value="#Trim(soapBody)#"/>
</cfhttp>
Hope you can help me.
Ben, you once again saved my bacon at work. Thank you, thank you, thank you!
I know this is an OLD post, but after fighting my way through a SOAP response, I found this LIFESAVER of a cfc and thought I would share. It converts XML to a CF Object, in my case structs of structs of arrays of structs....ad nauseum. Hope this helps someone out as much as it helped me.
Now, where did I put that aspirin?
M
Hello,
could anybody help me with my SOAP-call-problem? Whatever I post to the billsafe-API I get back the API itself. I've tried everything and have no more ideas.. Problem is described here:
and here:
Thank you
Sebastian | http://www.bennadel.com/blog/1809-making-soap-web-service-requests-with-coldfusion-and-cfhttp.htm?_rewrite | CC-MAIN-2015-48 | refinedweb | 6,588 | 62.48 |
Double Question Mark in C#
This article will introduce double question mark meaning in C#.
Use the
?? Operator as a Null Coalescing Operator in C
We use the
?? operator as a null coalescing operator in C#. It returns the value of its left-hand operand if it isn’t null. If it is null, then it evaluates the right-hand operand and returns its result. The
?? operator does not evaluate its right-hand operand if the left-hand operand evaluates to non-null. The correct syntax to use this symbol is as follows.
A ?? B
In the above example,
B is returned if
A is null.
The program below shows how we can use the null coalescing operator.
using System; public class Program { public static void Main() { int? a = null; int b = a ?? 10; Console.WriteLine(b); } }
Output:
10
In the above code, we can see that the value of
b is 10 as
a is null.
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page. | https://www.delftstack.com/howto/csharp/csharp-double-question-mark/ | CC-MAIN-2021-43 | refinedweb | 193 | 66.54 |
Footnotes
Note that I'm kind of creating my own problem to solve in this specific case, because I tend to extend STL in this way. It is possible in many cases to follow the example of istream_iterator and encapsulate the start of the enumeration in the constructor of the nondefault iterator; Boost's file-system enumeration component works in this way. But this is a logical disconnect that troubles me too much to follow the leadyou may well see it differently.
This is the approach taken by John in his Boost-compatible implementation of RangeLib, although he relies more on the explicit qualification of the RangeLib algorithm namespace boost::rtl::rng::for_each.
Much hard-won experience with Java's import x.* also contributes to my loathing for the indiscriminate introduction of names into namespaces. Herb Sutter and I have an ongoing difference of opinion on this point. Fortunately for Herb, he is vastly more knowledgeable and erudite on C++ than I am. Fortunately, for me, this is my book and I can write what I like.
This applies to all templates, not just template algorithms and functors.
If those three tell you your code is wrong, the odds are good that you're doing something wrong.
There were a few weeks between starting this chapter and doing the final version. In that short time I forgot how this worked, and I wrote it!
John was also a one of the reviewers for this book.
You can fit more angels on the head of a pin than you can find software engineers who wouldn't argue over a blade of grass. Notwithstanding that, John and I are in a reasonable state of agreement. You can see the differences in our interpretation of the concept, and understand the different design principles and implementation mechanisms in our implementations, because John's expansive and impressive Boost-compatible implementation of the Range concept is included on the CD along with my own STLSoft version.
Except if we were to point it high into the top of memory and then iterate until it reached 0, but this would result in an access violation on many platforms, so the issue is moot.
This is a general implementation naming policy, which helps to avoid clashes that can occur when the "outer" function and the implementing "inner" functions have the same name, and there are multiple overloads of the "outer" function. Different compilers have different aptitudes for resolving such things, so the simplest solution is to avoid it, and name the implementing "inner" functions unambiguously.
Although you'll have noted that I managed to overcome my squeamishness in Chapter 25. | http://www.informit.com/articles/article.aspx?p=345948&seqNum=6 | CC-MAIN-2019-09 | refinedweb | 442 | 50.77 |
Login Create account Language Chinese Spanish Japanese Korean Portuguese Ask a question Spaces Default Help Room META Moderators Topics Questions Users Badges Home / 0 Question by princeadj14 · Dec 03, Actual meaning of 'After all' Figuring out why I'm going over hard-drive quota I changed one method signature and broke 25,000 other classes.'? have a peek here
Can You Add a Multiple of a Matrix Row to itself? Comment Add comment · Show 1 · Share 10 |3000 characters needed characters left characters exceeded ▼ Viewable by all users Viewable by moderators Viewable by moderators and the original poster Go and walk 1000 miles now!") elif float(miles) >= 10: print("You are very healthy! Join them; it only takes a minute: Sign up ValueError: could not convert string to float: id up vote 15 down vote favorite 2 I'm running the following python script: #!/usr/bin/python
Instead, you should create new variables of the correct type, which you use for the GUI. This will return true if parsing is successful. Can you give me an example of how to do this? –geop_sed Nov 1 '11 at 18:00 1 What if there were 199 cells at a certain time? Why cast an A-lister for Groot?
Draw some mountain peaks Real numbers which are writable as a differences of two transcendental numbers What is the simplest way to put some text at the beginning of a line Im rather new to this and im coming from AS3 where you can typecast toString when ever i like. time2 cell2_1 cell2_2 ... Could Not Convert String To Float Matplotlib asked 1 year ago viewed 820 times active 1 year ago Related 3836What is the difference between String and string in C#?2308Read/convert an InputStream to a String882How do I check if
Cxu oni estas "en" aux "sur" foto? Valueerror Could Not Convert String To Float Pandas more hot questions question feed lang-cs about us tour help blog chat data legal privacy policy work here advertising info mobile contact us feedback Technology Life / Arts Culture / Recreation Homepage Subject Comment About text formats Anonymous format Allowed HTML tags:
Lines and paragraphs break automatically. his explanation This is the code in text format: print("Welcome to Healthometer, powered by Python...") miles = input("How many miles can you walk?: ") if float(miles) <= 0: print("Who do you think you
Were the Smurfs the first to smurf their smurfs? Could Not Convert String To Float Date For troubleshooting common problems with Unity 5.x Editor (including Win 10). Storage of a material that passes through non-living matter How did early mathematicians make it without Set theory? public class TestStandAlone { /** * This method is to main * @param args void */ public static void main(String[] args) { // TODO Auto-generated method stub try { Float f1=152.32f;
Singular cohomology and birational equivalence Interconnectivity Is it possible to bleed brakes without using floor jack? Mysterious creeper-like explosions Seasonal Challenge (Contributions from TeXing Dead Welcome) Tank-Fighting Alien Work done by gravity Why does Friedberg say that the role of the determinant is less central than in Valueerror Could Not Convert String To Float Python Login Create account Forums Answers Feedback Issue Tracker Blog Evangelists User Groups Navigation Home Unity Industries Showcase Learn Community Forums Answers Feedback Issue Tracker Blog Evangelists User Groups Get Unity Asset Valueerror Could Not Convert String To Float Numpy I would start by trying to find out something unique about the data to be able to differentiate it.
Which movie series are referenced in XKCD comic 1568? navigate here Keep it up!") elif float(miles) > 0 and miles < 10: print("Good. Word or phrase for "using excessive amount of technology to solve a low-tech task" Is it safe to use cheap USB data cables? n-dimensional circles! Could Not Convert String To Float None
Does sputtering butter mean that water is present? Maybe i should say this is the least effective method and the worse coding practice but, fun to use, float val=10.0; String str=val+""; the empty quotes, add a null string to No exception is thrown. share|improve this answer answered Mar 24 at 18:41 Anmol Thukral 11 add a comment| Your Answer draft saved draft discarded Sign up or log in Sign up using Google Sign
Here is the code: As you can see, the program asks for how many miles you can walk and gives you a response depending on what you type in. Could Not Convert String To Float Sklearn If you are a new user, check out our FAQ for more information. Very useful thanks!
I cleaned your code up a tad: #!/usr/bin/python import os, sys from scipy import stats import numpy as np for index, line in enumerate(open('data2.txt', 'r').readlines()): w = line.split(' ') l1 = more stack exchange communities company blog Stack Exchange Inbox Reputation and Badges sign up log in tour help Tour Start here for a quick overview of the site Help Center Detailed If you are a moderator, see our Moderator Guidelines page. Valueerror Could Not Convert String To Float Scikit Related Questions The name 'Joystick' does not denote a valid type ('not found') 2 Answers Material doesn't have a color property '_Color' 4 Answers Converting some C# pseudo code to UnityScript....
How to convert numbers to currency values? When you try it in interactive prompt you are trying only first line, so best way is to print the line where you are getting this error and you will know String valueFromTable = "25"; Float valueCalculated =25.0; I tried from float to string: String sSelectivityRate = String.valueOf(valueCalculated ); but the assertion fails java string types number-formatting data-type-conversion share|improve this question edited What now?
Browse other questions tagged python text or ask your own question. I have a txt file that is generated from a fortran program. Solutions? Surely a double would be better? –MightyLampshade Apr 28 '14 at 12:38 add a comment| 10 Answers 10 active oldest votes up vote 3 down vote You need to do float
Is it unethical to poorly translate an exam from Dutch to English and then present it to the English speaking students? What are 'hacker fares' at a flight search-engine? Caveat: If a timing data has exactly 100 cell values (101 columns), the output of this function will be wrong unless an additional newline exists before the next timing row, e.g. Not the answer you're looking for?
Not the answer you're looking for? Hot Network Questions Is there a name for the (anti- ) pattern of passing parameters that will only be used several levels deep in the call chain? Join them; it only takes a minute: Sign up Cannot convert type 'string' to 'float' up vote 1 down vote favorite I am getting this error: Cannot convert type 'string' to When eventually it succeeds, it'll break from the loop and go to the code you put lower down.
I get undefied type 'Float' (I'm in a weird java environment though, openhab scripts) –Jonathan Leaders Feb 5 '15 at 13:25 add a comment| up vote 21 down vote Float to What is the value of TextBox_item_price.Text exactly? –Soner Gönül Mar 27 '14 at 9:05 2 Wow.. Editing the csv solves this issue for now but if nulls are found in the data you would get an error. #4 | Posted 3 years ago Permalink Chelsey MacNeill Posts You need to print row[11] and see exactly what you are passing –Padraic Cunningham Jan 17 '15 at 1:48 @Tabbz,except (ValueError,TypeError): will catch the TypeError but you should really
Is it acceptable to ask an unknown professor outside my dept for help in a related field during his office hours? Player claims their wizard character knows everything (from books). A simple solution to figuring out where this occurs would be to add a try/except to the for-loop: for i in range(0,N): w=f[i].split() l1=w[1:8] l2=w[8:15] try: list1=[float(x) for x in l1] | http://hiflytech.com/string-to/cannot-convert-from-string-to-float.html | CC-MAIN-2018-09 | refinedweb | 1,360 | 58.21 |
Mouse gesture commands enrich the UI of an application. They are very easy to learn and intuitive for the user. There are some postings on CodeProject that address mouse gestures in one way or the other way (unfortunately, I didn't get the AI ones running), so I thought to offer my solution to the CP community. I first saw a mouse gestures functionality in the very early 90s in a CAD kernel package written in C that I used in a project.
This article gives you the possibility to add mouse gesture functionality in your .NET project in a very easy way. It offers the following advanteges:
raising an event to respond to when a mouse gesture is entered
It doesn't really need to be said but first we have to capture the mouse movement/position. Once done, these x/y positions can be analysed to find an appropriate mouse gesture command.
The idea of finding a mouse gesture is as follows:
MouseDown
MouseUp
Example:
Path: 0, 1, 2, 3, 4, 5, 4, 10, 9, 15, 14, 20, 19, 18, 24, 30, 31, 32, 33, 34, 35Key: ABCDEFEKJPOUTSYefghij
With this solution a specific command has several keys — one key for every possible path for a mouse gesture. That means the more fields we divide the bounding rectangle into, the more keys a command needs to be found. A more complicated mouse gesture consists of a longer path which ends in more possible keys.
As we can see, a very important point is the number of rectangles we divide the bounding rectangle into. If the number is too small, we will not have enough fields to differentiate similar mouse gestures. To illustrate this, imagine the smallest possible divider equal to 1 to divide each side of the bounding rectangle; in other words, not to divide the bounding rectangle. So every mouse gesture's path is 0, no matter if it's just a point or millions of movements. On the other side, if we divide the rectangle into too many fields, there are lots of path's which are very similar.
I made several tests with different dividers for the bounding rectangle and finaly used 6 as the best avarage which gets 36 fields.
The key should be as short as possible, because we will have many of them for one command as more complex a mouse gesture is. Because mouse gestures are not limited to a certain length or movements, we don't know how long the key can get. The simplest solution is to use a string that consists of the Base64 encoded field numbers — the path.
Class MouseGestureData has no code, it just holds the variables that are the same for all MouseGesture instances. It is implemented with the singleton pattern as Microsoft suggests on MSDN. It has a private constructor and the member properties can be accessed using the public static readonly Instance variable.
MouseGestureData
MouseGesture
Instance
Class MouseGesture is the main class and does all the important work. The only constructor takes two arguments. The first one is a reference to a Control object. This object is the parent control in which the mouse gesture is working in. The constructor registers to the MouseUp, MouseMove and MouseDown events of the parent control and all its containing controls that are allowed. Argument two is a List<Type> list that tells which type of controls are allowed. If it is null, the list returned by method GetDefaultAllowedControls() is used. The idea is to allow all kind of "container controls" meaning that these are controls that "show" some sort of the parent control's background and not having selectable elements and not being data entering controls. The default allows Label, GroupBox, PictureBox, ProgressBar, ScrollableControl and TabControl.
MouseGesture
Control
MouseUp
MouseMove
List<Type>
null
GetDefaultAllowedControls()
Label
GroupBox
PictureBox
ProgressBar
ScrollableControl
TabControl
In the class MouseGesture, you can define different properties needed to start capturing the mouse positions and to trigger mouse gesture commands. MouseButtonTrigger defines the mouse button that must be pressed down to trigger/start and stop capturing the mouse positions. This means the mouse button that raises the MouseDown and MouseUp events must be equal to this property. Also all mouse button states must be equal to MouseButtonMask and the modifier keys (ctrl, shift, alt) must be equal to ModifierKeyMask when staring the capturing.
MouseButtonTrigger
MouseButtonMask
ModifierKeyMask
private void OnMouseDown( object sender, MouseEventArgs e )
{
// only enter capturing if...
if( !_bCapturing && // ...not capturing in
// progress
e.Button == _data.MouseButtonTrigger && // ...the button pressed last
// to trigger
Control.MouseButtons == _data.MouseButtonMask && // ...this/these button/s
// pressed together
Control.ModifierKeys == _data.ModifierKeyMask // ...this/these modifier
// key/s (shift/ctrl/alt)
)
{
// capturing mouse positions starts here
...
}
}
The default is only the right mouse button to be pressed. But with the additional properties MouseButtonMask and ModifierKeyMask, we could, for instance, start capturing when 1st the left mouse button is pressed and kept and 2nd the right mouse key is pressed:
MouseButtonTrigger = MouseButtons.Right;
MouseButtonMask = MouseBottons.Left | MouseButtons.Right
Or the ctrl-key plus the right mouse botton is pressed:
MouseButtonTrigger = MouseButtons.Right;
MouseButtonMask = MouseButtons.Right
ModifierKeyMask = Keys.Control;
It is possible to give the user a visual feedback when the mouse positions are captured. It is done in three levels. The first level is that we show a window on which we draw the mouse gesture. This window has no frame, but we setup the Opacity and BackColor to show the user that the imput window has changed. Property WindowAppearance defines how to show the window:
Opacity
BackColor
WindowAppearance
None
FullScreenOpaque
ParentOpaque
ParentClear
The second level for the visual feedback is drawing the mouse positions and is defined in property GestureAppearance.
GestureAppearance
The third level is some properties that define if the bounding rectangle, the grid and the path of the mouse gesture should be drawn and its colors. There is also a property that defines for how much longer the capturing window should be shown after capturing the mouse position is finished.
The analysis of the captured mouse positions is straightforward, there isn't really any tricky code behind it. But there are two properties to mention. Property MinimumMovement defines a minimum number of pixels the mouse has to be moved to create a key and lookup for an appropriate command. Property UnidimensionalLimit defines the minimum width or height for a field in which the bounding rectangle is divided to. This is done because it is almost impossible to enter an orthogonal movement (in x or y direction) with a mouse. This was the only part where I saw a possibility to reduce the number of keys for a command.
MinimumMovement
UnidimensionalLimit
Once capturing in the mouse positions is started and the MouseButtonTrigger is released, on MouseUp event, the mouse positions are analysed. After this MouseGesture raises event MouseGestureEntered, no matter if it found a key and it's appropriate command. It even raises the event if it was an invalid mouse movement. MouseGestureEventArgs of delegate MouseGestureEventHandler has the following properties:
MouseGestureEntered
MouseGestureEventArgs
MouseGestureEventHandler
Key
string.Empty
Command
Bounds
These values of the last MouseGestureEntered event can be read from the MouseGesture object properties starting with "Last".
This class holds a Dictionary with the key/command pairs. It hides the dictionary to be able to make checks on the operations; i.e. not throwing an exception if a key already exists. It also implements reading from and writing to file in XML format. It's done in a structured way (one command with multiple keys) instead of a flat way (one entry for each key/command pair).
Dictionary
You can draw mouse gestures on the manager form on all "container controls" (as explained above) plus the list control on the second tab. The allowed controls are set to default. When an event raises, it is visualized in the group box bellow the tabs: Red means no valid mouse gesture, green means a valied mouse gesture was entered and its key generated, but no appropriate command was found, whereas blue means that a command was found.
Tab Parameter allows the setting of all the possible properties of MouseGestureData. You can draw mouse gestures on the tab. Play around with the parameters to immediately see the effects.
Tab Keys & Commands allows you to manage everything around keys and commands. Select or type in a command in the drop down combo box Commands to see all appropriate keys in the list bellow it. Group box Selected key shows the current/selected key as a stretched thumb and lets you delete it from the list.
Button Delete all asks for a confirmation before deleting all keys/commands from the list.Buttons Import and Export do just what'd you expect from them.Button Copy Cmd allows you to copy all keys of the selected command to a new one, while mirroring or rotating them.
Probably the most important button is the Add Mouse Gesture at the top right border of the tab. It is a button style check box and when pressed, every valid mouse gesture you draw on tab Keys & Commands (must be visible) is added to the current command. It is immediately selected on the list box, so you can delete if right afterwards if you are not happy with it. If you want to add a new command, just enter its name in the drop down combo box and start drawing the mouse gestures. (Unfortunately, the first character typed in the combo box is not acceppted, IMO a .NET problem).
Consecutive cmd in group box Total counters is increased everytime a valid command is found and is set to 0 if not. It can be used while teaching new mouse gestures to get an idea of how god the system already is.
Using the DcamMouseGesture functionality just needs a few lines of code after adding a reference to DcamMouseGesture.dll in your project:
DcamMouseGesture
MouseGestureEvent
That's it! Here is an example with the minimum of steps needed (unnecessary VS code deleted):
// a) Refer to namespace "DcamMouseGesture"
using DcamMouseGesture;
namespace WindowsFormsApplication
{
public partial class Form1 : Form
{
MouseGesture _mg;
public Form1()
{
InitializeComponent();
// b) Load a file with the commands and keys once in your application
MouseGestureData.Instance.Commands.ReadFile(
Environment.CurrentDirectory + @"\MouseGestureCommands.xml" );
// c) For each Form you want to use mouse gestures...
_mg = new MouseGesture( this, null );
_mg.MouseGestureEntered += new MouseGestureEventHandler(
OnMouseGestureEntered );
}
private void OnMouseGestureEntered( object sender, MouseGestureEventArgs e )
{
// d) In your registered MouseGestureEventHandler, handle the commands
// you want
MessageBox.Show( string.Format( "OnMouseGestureEntered:\n" +
" Command:\t{0}\n" +
" Key:\t\t{1}\n" +
" Control:\t\t{2}\n" +
" Bounds:\t\t{3}",
e.Command, e.Key, e.Control,
e.Bounds.ToString() ) );
}
}
}
The downloadable source code is a .NET 2.0 solution created in Visual Studion 2008 Standard Edition. I used the new feature auto-implemented proberties wherever possible. So if you want to use the source code in an older version of Visual Studio, you have to declare these as member variables and it's appropriate properties.
2008-05-12 - V1.0
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
return new List<Type>() { typeof( Label ), typeof( GroupBox ), typeof( PictureBox ),
typeof( ProgressBar ), typeof( ScrollableControl ), typeof( TabControl ), typeof( WebBrowser) };
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | http://www.codeproject.com/Articles/26104/Adding-Mouse-Gesture-Functionality-to-Your-NET-App?msg=2564337 | CC-MAIN-2015-48 | refinedweb | 1,908 | 53.21 |
Database Connection Error
Hi,
I want to Connect My sqlite database to my program
i wrote below code,but In any situation program say Connected!
Even when i changed database name
my db in my root of program.
only when i change the db url in my code,program say error!
what is the problem?
and what i must do?
code:
#include "mainwindow.h" #include <QApplication> #include "QSqlDatabase" #include <QMessageBox> int main(int argc, char *argv[]) { QApplication a(argc, argv); QSqlDatabase db= QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName("webappsstore.sql"); if(!db.open()) { QMessageBox msg; msg.setText("Faild!"); msg.exec(); }else{ QMessageBox msg; msg.setText("Connected!"); msg.exec(); } MainWindow w; w.show(); return a.exec(); }
- SGaist Lifetime Qt Champion last edited by
Hi,
Because with SQLite, if you don't give the path to an existing database file, a new one will be created. But that will only happen if you don't try to open in a read-only folder. You can get the error with QSqlDatabase::lastError.
- mrjj Lifetime Qt Champion last edited by
just a note
in c++ when you use \ you must use 2 \
so if u had
something like
db.setDatabaseName("c:\myproject\webappsstore.sql");
it might have worked if u did
db.setDatabaseName("c:/myproject/webappsstore.sql");
its just a note. might not been your issue :)
- mrjj Lifetime Qt Champion last edited by | https://forum.qt.io/topic/66341/database-connection-error/5 | CC-MAIN-2019-43 | refinedweb | 228 | 60.51 |
Programming With Types in C#
This is a transcript of a recent talk that I gave during Level Up Week, Redgate’s internal conference.
The idea behind this talk comes from learning about types while at Portland State University. We all find different subjects that resonate with us. For me, the idea of defining errors out of existence with the type system struct me as important. Why should I, a software engineer, have to hold extra information about my program in my head? Compilers are smart pieces of code, and they can keep track of more information than I can; why not encode facts about my programs such that a compiler can verify things for me?
Throughout this article, when I mention specific data types I’ll be speaking directly about C#’s type system.
What even is a type?
I know it’s cliché to start a presentation or article with a definition, but I think it’s essential to agree on what we’re talking about.
Types describe the allowed values that a particular variable can have. If I have a value with the type
int I know that value will be an integral value in the range -2,147,483,648 to 2,147,483,647. Likewise, a
uint will hold an unsigned integral value in the range 0 to 4,294,967,295. Some data types, like
string are more complex: a
string holds zero or more Unicode graphemes or
null.
Types also describe the allowed operations that can be performed on a particular variable in a program. We’ll get to that in a bit.
I’d like to introduce you to an example class that represents a server:
public class Server {
public string Name { get; }
public string IpAddress { get; }
public Server(string name, string ipAddress) {
Name = name;
IpAddress = ipAddress;
}
}
This class tells me that two strings identify a server, and those two strings can be any allowed string. Are any of the following servers valid in the real world?
var s1 = new Server(null, null);
// imagine the entire text of A Tale of Two Cities is the ipAddress
var s2 = new Server("💩", "It was the best of times");
var s3 = new Server("localhost", "127.0.0.1");
Based on the definition of our class, all three of these are perfectly fine servers. Our program would compile, but who knows what would happen at runtime when we attempt to connect to a
null IP address.
More importantly, we know that the definition of
Server is incorrect. RFC-1123 says that a hostname must be ASCII (specifically, only the lower 7-bits of ASCII are allowed). Likewise, IPv4 addresses have a well-defined format, they’re not arbitrary strings. With this information at hand, I’ll take a stab at refining the
Server class.
public class Server {
public [DisallowNull] string Name { get; }
public [DisallowNull] string IpAddress { get; } public Server([DisallowNull] string name, [DisallowNull] string ipAddress) {
Name = name;
IpAddress = ipAddress;
}
}
This new vision of a server tells me a little bit more. Two strings identify a server, and neither of those strings can be
null. This is some progress. (We can, of course, get the same effect by using C# 8’s nullable reference types feature, but I wanted to make the lack of
null explicit here.)
// This no longer compiles!
// var s1 = new Server(null, null);// But this pile of 💩 still does
var s2 = new Server("💩", "It was the best of times");
var s3 = new Server("localhost", "127.0.0.1");
We’ve defined
null values out of existence for the
Server class, but it’s still possible to use both an invalid hostname and an invalid IP address. I’ll address the IP address first by using the
IPAddress class. This ensures that whoever is using our
Server class has verified that the IP address is correct.
using System.Net;public class Server {
public [DisallowNull] string Name { get; }
public [DisallowNull] IPAddress IpAddress { get; } public Server([DisallowNull] string name, [DisallowNull] IPAddress ipAddress) {
Name = name;
IpAddress = ipAddress;
}
}
By using the
IPAddress type on both the property and argument, we’re saying that consumers of this class must ensure that the IP address being used is both non-null and a valid member of the
IPAddress type. We’ve achieved some level of victory - in our original example, only
s3 is a valid
Server!
// This no longer compiles!
// var s1 = new Server(null, null);// But this pile of 💩 will no longer compile!
// var s2 = new Server("💩", "It was the best of times");
var s3 = new Server("localhost", "127.0.0.1");
Unfortunately, we could still create a server with a valid IP address and 💩 as the hostname. There’s one more refinement needed to this class: we need to make sure that the hostname is only in the range of values allowed by RFC-1123. To keep things simple, I will artificially limit the space we’re working with to Netbios names.
using System.Net;public class Server {
public [DisallowNull] NetbiosName Name { get; }
public [DisallowNull] IPAddress IpAddress { get; } public Server([DisallowNull] NetbiosName name,
[DisallowNull] IPAddress ipAddress) {
Name = name;
IpAddress = ipAddress;
}
}
At this point, we’ve defined a type that says a server is identified by a Netbios name and an IP address, so long as they both are not null. To be more robust, we might poke around in
System.Net until we find a more flexible type than
NetbiosName, but I think this works for the purposes of this example.
When thinking about a type, it can be helpful to think about the type as a house or building. We want the type to describe only the values that belong. Picking the correct data types as we design our own type ensures that I only represent valid data in my program. This also has the side effect of documenting interfaces, as much as it’s possible, through code.
Self-documenting code
Rather than wax eloquent on my vision of self-documenting code, I’m going to build a vision of self-documenting code step-by-step. Quick question, though: what does the following code tell you about itself?
public object foo(object o)
It’s tempting to compare this to the identity function (that would be
public T id(T t)). From the definition of
foo, we don’t know what that function does and we would have to read the documentation (assuming the developer wrote any) or read the actual code. Neither of those situations is ideal. Documentation is important, but we need to remember that the first piece of documentation that any developer encounters is the function signature.
Creating self-documenting code, step-by-step
In this next section, I’m going to take you on a journey where we take a piece of pseudocode and refine it into a strongly-typed piece of self-documenting code.
int? GetLicenseCount(Server server)
We know that
GetLicenseCount takes a
Server (which is identified by a
NetbiosName and
IPAdress). The surprising result is the nullable
int as return value. We have to either read documentation or else infer meaning from this return type. Ultimately, this raises questions like:
- What does it mean to have
nulllicenses?
- What about having zero licenses?
- What does a negative result mean?
- What does the number even mean at this point?
If this were production code (which it isn’t), I would have to seek out the documentation to understand what
int? means. If there was no documentation, for some reason, I would have to dig into the source code to understand the meaning behind
int?.
In a perfect world, we would be able to encapsulate any valid response from a call as a type. When constructed explicitly and using types, we can represent all valid responses of
GetLicenseCount as something called a “sum type” or “discriminated union”. (C# is eventually going to get support for discriminated unions, but support is also available via
language-ext. I’ll be working in plain old C# here.)
// We don't want to instantiate a "raw" license count
public abstract class LicenseCount {}
// If you don't have any licenses, let's make that happen
public sealed class Unlicensed : LicenseCount {}
// Likewise, let's make it possitle to represent an infinity of licenses
public sealed class UnlimitedLicense : LicenseCount {}
// Finally we get to a countable number of licenses
public sealed class LimitedLicense : LicenseCount {
// Just an enumeratino for "per seat" and "per CPU"
public LicenseUnit LicenseUnit;
public uint LicenseCount;
}// Which lets me change the original function to
LicenseCount GetLicenseCount(Server server)
Looking at the above code, we can now tell a lot about what’s happening just from the types we’ve given our data.
- A server consists of a valid, non-null NetBIOS name and a valid, non-null IP address.
- There are three kinds of license: unlicensed, unlimited licenses, and a limited license.
- The limited license is a count of licenses and a description of the thing to count.
The
GetLicenseCount function now mostly documents itself using our new
LicenseCount class hierarchy. Some documentation might be warranted if there’s weird math going on behind the scenes, but this is otherwise clear. As a side effect, consumers of
GetLicenseCount will have to pattern match over the return type. I like to think of this as extra insurance that developers (me in two weeks) will do the right thing with the return type. By encoding additional information in the type, the code prevents a 0 indicating “no usable licenses” from being confused with a 0 indicating a “you need to give us money so you’ll have licenses”.
Phantom Types
Phantom types were something I first discovered while learning about typestate analysis. Typestate analysis isn’t important here, but what is important is that we can use a phantom type to encode extra information about our types to better describe the program that’s executing. Rust by Example has a good explanation:
A phantom type parameter is one that doesn’t show up at runtime, but is checked statically (and only) at compile time.
Data types can use extra generic type parameters to act as markers or to perform type checking at compile time. These extra parameters hold no storage values, and have no runtime behavior.
N.B. While the phantom type parameter is erased in Rust, it’s still present in C#.
Reviewing the
LicenseCount that I created previously, I can see that I’ve made a critical mistake. It’s possible do some silly things with a
LicenseCount that won’t get caught until the code throws a runtime exception, which is precisely what we’re trying to avoid. Don’t believe me?
var serverLicenseCount = new LimitedLicense {
LicenseCount = 12,
LicenseUnit = LicenseUnit.Server
};// Ignore just how bad this pattern is, OK?
// I'm making a point.
var userCount = GetUserLicenses(serverLicenseCount);
I’m sure you, dear reader, noticed the mistake I made in passing a
LimitedLicense for a server to the
GetUserLicenses function. In a larger change, this error might not be so easy to spot. In theory, code review should catch this problem. And, in theory, we could make
GetUserLicenses throw a runtime exception. But I’d like to make it so incorrect code can’t even compile.
Step 1: The phantom type
In the original
LimitedLicense class, the enumeration discriminates the type of license (per server or per user). Instead of using an enumeration, we can move the license into a type!
public abstract class LicenseUnit {}
public sealed class UserLicense : LicenseUnit {}
public sealed class ServerLicense : LicenseUnit {}
Step 2: Limiting
LimitedLicense
Now I can limit the
LimitedLicense even further using the power of generics:
public sealed class LimitedLicense<TLicenseUnit> : LicenseCount
where TLicenseUnit : LicenseUnit
{
public uint LicenseCount;
}
Step 3: Typing the method
At this point, all of the important information about what kind of license someone has is encoded in the type. Now that the kind of license is part of the type, it is impossible to do the wrong thing and try to get the user license count for a server-based license:
public uint GetUserLicenses(LimitedLicense<UserLicense> l)
{
return l.LicenseCount;
}// This will compile
var ul = new LimitedLicense<UserLicense> { LicenseCount = 42 };
var x = GetUserLicenseCount(ul);// This will not compile
var sl = new LimitedLicense<ServerLicense> { LicenseCount = 42 };
var y = GetUserLicenseCount(sl);
There’s a slight naming problem:
GetUserLicenseCount implies the existence of similarly named functions for the other subclass of
LicenseCount. While it’s tempting to create a function that accepts any subclass of
LicenseCount, that’s a good idea.
- What number should that function return for an
UnlimitedLicense? It can’t return
Double.PositiveInfinitybecause the
LimitedLicenseis storing the number of licenses as an unsigned integer.
- What number should that function return for an
Unlicensed? It can’t return
0 because 0 is a number and someone might add 1 to 0 and then the
Unlicenseduser will suddenly have a license.
- It’s not a great idea to use a switch here because there is no built-in way (that I know of) to make sure that pattern matches over types include all possible subclasses.
The solution, it turns out, is easier than you might think: overloads!
public uint GetLicenseCount(LimitedLicense<UserLicense> l)
{
// Do something awesome
}public uint GetLicenseCount(LimitedLicense<ServerLicense> l)
{
// Do something awesome, but different
}
Passing anything other than
LimitedLicense will fail compilation. Unrepresentable states (the count of infinite licenses) can’t be represented in the program. Things that should be counted can still be counted. If I add a new license type, I don’t have to worry about that new type falling through the
switch and triggering an exception (because it’s common to add exceptions to the default case) or, worse, doing something unexpected.
One last example: data validation
At the beginning of the last section I mentioned that I first encountered the idea of phantom types while learning about typestate analysis. In typestate analysis types get decorated with additional state (that’s still part of the type) to ensure that programs aren’t doing things like writing to uninitialized memory. The typestate is a state machine of allowed states; functions in the program only accept types that are in the correct typestate. This prevents the programmer from doing things like writing to uninitialized memory or trying to read past the end of a file.
I’m going to demonstrate how we can turn form validation into a workflow enforced by C#’s type system. C# doesn’t support typestate analysis, but it turns out that we can get the benefits of typestate analysis using phantom types.
I’m going to start off with a very simple system. Assume that form data can be in one of three states:
- Unvalidated
- Validated
- Invalid
From here, it’s obvious that I can create a phantom type to represent these three states of a form:
public abstract class ValidationStatus {}
public sealed class Unvalidated : ValidationStatus {}
public sealed class Valid : ValidationStatus {}
public sealed class Invalid : ValidationStatus {}
I am assuming that the data I want comes from a
string. What’s going on here really doesn’t matter, but what we do know is that we can’t trust the contents until they’ve been validated. But, first, we have to make a form!) { /* ... */ }
}
I need a way to validate the
FormData. While it’s possible to parse the string in the constructor for
FormData that would leave me in the unenviable position of having to throw an exception in the constructor. Instead, I’ve created a
FormData<Unvalidated>. It doesn’t make sense to submit unvalidated data and, as I’ll show in a little bit, the submit function will only accept a
FormData<Valid>.
I can get from unvalidated data to validated data like this: Either<FormData<Invalid>, FormData<Valid>>
Validate(FormData<Unvalidated> formData)
{
// do something interesting
}
}
When a particular
FormData is goes through the
Validate function, I want to take appropriate action based on whether or not the
FormData is valid or invalid. Rather than throw an exception for flow control, I will use an
Either type as the return from
Validate.
Either is used to represent the result of computation that is either correct or an error. From the Haskell documentation of Either: “by convention, the
Left constructor is used to hold an error value and the
Right constructor is used to hold a correct value (mnemonic: “right” also means “correct”).” By using
Either I’m returning a meaningful value to the consumer of
Validate;
Either lets the consumer know that this function could error.
Here’s what validating
FormData might look like:
var fd = FormData.MakeData(theData);
// fd is now FormData<Unvalidated>var result = FormData.Validate(fd);// now we can look at the Either and react appropriately
if (result.IsLeft) {
var invalid = result.Left();
// TODO: tell the user what they did wrong
} else {
var valid = result.Right();
// Assuming that we have:
// public void Submit(FormData<Valid> data)
Submit(valid);
}
What do I get from all of this?
FormData<T> can use some internal representation of data that nobody needs to know about. All developers need to know is that a
FormData is constructed it from a
string and that, because of the construction of
Submit, there’s no way to submit data in any state other than
Valid. Callers must first validate form data before submitting it; a
FormData<Valid> cannot be constructed apart from through the functions provided. Finally, only data in the appropriate state can move through the program.
It’s also easy to add new validation status to
ValidationStatus:
public abstract class ValidationStatus {}
public sealed class Unvalidated : ValidationStatus {}
public sealed class InProgress : ValidationStatus {}
public sealed class Completed : ValidationStatus {}
public sealed class Valid : ValidationStatus {}
public sealed class Invalid : ValidationStatus {}
And then enforce those new states in code: FormData<InProgress> SaveProgress(FormData<Unvalidated> formData) { /* ... */ }
public static FormData<InProgress> SaveProgress(FormData<InProgress> formData) { /* ... */ } public static FormData<Completed> CompleteForm(FormData<InProgress> formData) { /* ... */ } public static Either<FormData<Invalid>, FormData<Valid>>
Validate(FormData<Completed> formData)
{
// do something interesting
}
}
And now our program has encoded a state machine in our types. It becomes easy to add more states by adding additional subclasses of the abstract base class. It becomes straightforward to refactor the program and I know that when the program compiles, data will move from between the appropriate states. If the program doesn’t compile… well, I’ve made the compiler into a state machine validator and I can use the errors to make it easy to find and fix mistakes.
Limiting functionality
We’re almost to the end, I promise… But first, I’m going to limit functionality even more.
The
LicenseCount example already worked to limit functionality. That makes makes sense. After all, types limit functionality by describing what’s allowable. In the case of the
LicenseCount I’ve made it possible to only compare to license counts when they are:
- The same type
- And of the same generic type.
Which really means that I can’t go ahead and compare a user-based license to a server-based license. This code below won’t compile:
var uc = new LimitedLicense<UserLicense> { LicenseCount = 42 };
var sc = new LimitedLicense<ServerLicense> { LicenseCount = 42 };// This won't compile, they're not the same type!
var same = (uc == sc);
Since my fancy
LimitedLicense is just a wrapper around a
uint it stands to reason that I can wrap other less strict types to make stricter types. Usernames are strings. But there are some limitations to how programmers should interact with usernames:
- It doesn’t make sense to use a
StartsWithon usernames.
- Likewise, other developers shouldn’t be taking arbitrary substrings of usernames.
- Or even just using less than/greater than (this is less clear, but stay with me).
I’m going to limit the usefulness of usernames in my (fictitious) application by creating a class just for usernames:
public sealed class Username
{
private readonly string _username; public Username(string username)
{
_username = username;
}
}
If I want to compare two
Usernames, what do I really want to compare? I want to compare whatever the identifying bits are for a
Username. This might be the string of the actual username, a precomputed hash, or something else. The important bit is that I don’t want any way to accidentally compare the wrong chunks of data in the program. To solve this, I’m going to use an
Id<T>.
What’s an
Id<T>? In this case, it’s an arbitrary type that exists only to compare two
Ts.
public sealed class Id<T> : IEquatable<Id<T>>
where T : IIdentifiable
{
private readonly int _id; public Id(T t)
{
_id = t.Identify();
} public bool Equals(Id<T> other)
{
return id == other._id;
}
// TODO: Don't forget to implement Equals(Object) and GetHashCode()
}
What’s
IIdentifiable? I made it up. It’s some interface we have that produces the unique identifying bits of an object. The idea behind using an
Id<T> and an
IIdentifiable is to push the concept of comparison out to an implementation that only deals with the idea of equality comparison.
Username never needs to implement
IEquatable directly or, better, we can make a direct comparison of
Usernames always return
false and get developers to always use
Id<Username> for the comparison.
Wrapping up
We learned a few things on this journey. One is that types limit what a program can do by describing a set of allowed values and defining a set of allowed operations. Types also add to the richness of code; the type
Username is more descriptive than
string. These richer type names also provide some built-in documentation when reviewing code.
Effective use of types can add the benefit of eliminating unrepresentable states. In the licensing example, the state machine we create prevents a developer from submitting invalid form data. If a developer does try to submit bad data, the program won’t compile. Types can turn runtime errors into compilation failures, letting us catch errors before they reach users.
Of course, this comes at a cost. Data must be poked and prodded to ensure that it’s in the right shape to pass through the program. At each stage, the developer has to make decisions about how to work with the possibility of error. The examples get more complex as the article progresses. With richness of types, code may begin to feel more complex.
This is a trade-off: as software engineers we can choose the level of rigor to apply to our programs. By carefully and selectively considering where we use stronger and richer types we can apply Postel’s principle and be conservative in what we do and liberal in what we accept from others.
Photo by Amy Shamblen on Unsplash | https://medium.com/ingeniouslysimple/programming-with-types-in-c-eec85832a88e?source=collection_home---2------7----------------------- | CC-MAIN-2021-39 | refinedweb | 3,776 | 52.39 |
>> Ive been having a devil of a time trying to get boost python to do the >> right thing when I try to manipulate C++ objects with weak pointers. >[Nat] Maybe I'm missing something, but where in the short test case do >you mention weak pointers? the enable_shared_from_this template embeds a weak_ptr into XYZ, sorry if that wasnt clear. >> /* *************************************************** */ >> #include <boost/python.hpp> >> #include <boost/shared_ptr.hpp> >> #include <boost/enable_shared_from_this.hpp> >> >> using namespace std; >> using namespace boost; >> using namespace python; >> >> struct XYZ >> : public enable_shared_from_this<XYZ> >> { >> >> static shared_ptr<XYZ> construct() >> { >> s_instance = new XYZ; >> shared_ptr<XYZ> xyz( s_instance ); >> // return a shared_ptr that manages the python object >> return extract< shared_ptr<XYZ> >( object(xyz) ); > >[Nat] I'm floored by the three lines above, especially that last line. a little hackish, i agree. however, since bp does some magic with shared_ptr deleters, the shared_ptr extracted in the the last line is not in general the same as the one created in the line previous. c++ objects instantiated by bp get passed to c++ with the correct deleter set, but in this project objects are instantiated by an abstract factory in c++ and manipulated in python. > >This feels like a modified singleton pattern. What do you want the >lifespan of the managed XYZ object to be? If you want it to persist for >the remainder of the program, why use shared_ptr? If you want it to >vanish when the last outstanding reference has been dropped, why make it >resemble a singleton? in this case im just using s_instance as a place to stick a known-good instance pointer. the "real" code is a complicated subject-observer tree where destruction of an observer causes deregistration from the subject. the problem occurs when it comes time to iterate over elements of the tree - in returning an element to python, it is necessary to pin the embedded weak_ptr. what i see then is a use count of 0, a positive weak count, and an object has not been destroyed. i believe that bp is still creating a new shared_ptr count somewhere even though that shouldnt be necessary (from what i understand) after the way we constructed our initial shared_ptr. >But even if you want to retain the XYZ* s_instance, why wouldn't you >code construct() to set s_instance and then return get()? Why does the >first case behave so very differently from every other case? essentially thats whats happening. except that what we are really initializing is not s_instance, but the embedded weak_ptr. as a side effect of the gymnastics in construct, shared_from_this should return the _python_ weak_ptr thanks zac -- View this message in context: Sent from the Python - c++-sig mailing list archive at Nabble.com. | https://mail.python.org/pipermail/cplusplus-sig/2007-July/012288.html | CC-MAIN-2018-05 | refinedweb | 448 | 60.95 |
i'm just trying to familiarize my self with C, anyhow, i am trying to create a program which will automatically login for me into the swinburne site (for example). except, i have absolutely no idea how to use the postmessage function in "windows.h". please note, although i am doing programming (undergraduate), this is neither related to homework or assignment/project, this is something i set for myself, since i really don't understand this postmessage function.
alright, here is the code i have so far:
#include <stdio.h> #include <stdlib.h> #include <windows.h> int main () { ShellExecute(NULL, "open", "", NULL, NULL, SW_SHOWNORMAL); Sleep (20000); postmessage (???) /* i have inserted the '???' since i have no idea what to do. */ return 0; }
without the 'postmessage' it works fine.
now, i have looked at this website, but, honestly, i do not understand a word of it.
ps: my default browser is firefox, and i'm on win7 (home)
so here is my two questions:
1) could anyone help me with this postmessage function? (or provide me with a link to something that will help me)
2) this is still related, a function to send a keystroke, for instant, in vb, there is sendkeys.keystroke (....), is there such a similar thing in C? (again, a link will suffice, but i did not find any link to help me here)
thank you in advance =) | http://www.dreamincode.net/forums/topic/315474-questions-regarding-postmessage-and-keystroke/ | CC-MAIN-2017-09 | refinedweb | 230 | 73.47 |
Before we start talking about the Hadoop Stack, let us take a step back and try to understand what led to the origins to the Hadoop.
Problem – With the prolification of the internet, the amount of data stored growing up. Lets take an example of a search engine (like Google), that needs to index the large of amount of data that is being generated. The search engine crawls and indexes the data. The index data is stored and retrieval from a single storage device. As the data generated grows, the search index data will keep on increasing.
As the number of queries to access data increase, the current file system I/O becomes inadequate to retrieve large amounts of data simuntaneously. Further, the model of one large single storage starts becoming a bottleneck. To overcome the problem, we move the file system from a single disk storage to a clustered file system. But as the amount of data keeps growing the underlying data that can go one one machine starts to become a bottleneck.
As data reaches TB’s, existing file system based solutions starts faltering. Data access, multiple writers, large file sizes soon become a problem in scaling up the system.
Solution – To overcome the problems, an distributed file system was concieved that provided solution to the above problems. The solution tackled the problem as
- When dealing with large files, I/O becomes a big bottleneck. So, we divide the files into small blocks and store in multiple machines. [Block Storage]
- When we need to read the file, the client sends a request to multiple machines, each machine sends a block of file which is then combined together to pierce the whole file.
- With the advent of block storage, the data access becomes distributed and leads to a faster retrieval/write
- As the data blocks are stored on multiple machines, it helps in removing single point of failure by having the same block on multiple machines. Meaning, if one machine goes, the client can request the block from another machine.
Now, any solution that implements file storage as blocks needs to have the following characteristics
- Manage the meta data information – Since the file gets broken into multiple blocks, somebody needs to keep track of no of blocks and storage of these blocks on different machines [NameNode]
- Manage the stored blocks of data and fulfill the read/write requests [DataNodes]
So, in the context of Hadoop –The NameNode is the arbitrator and repository for all metadata. The NameNode executes file system namespace operations like opening, closing, and renaming files and directories. It also determines the mapping of blocks to DataNodes. DataNodes are responsible for serving read and write requests from the file system’s clients. The DataNodes also perform block creation, deletion, and replication upon instruction from the NameNode. All these component together form the Distributed File System called as HDFS (Hadoop Distributed File System).
Reference –
HDFS has an inbuild redundancy and replication feature that makes sure that any failure of the machine can be dealt without any loss of data. The HDFS balances itself whenever a new data node is added to the cluster or any of the existing datanode fails.
In addition to the distributed file system called HDFS (Hadoop Distributed File System), there are 2 other core components
- Hadoop Common – are set of utilities that support the Hadoop subprojects. Hadoop Common includes FileSystem, RPC, and serialization libraries.
- Hadoop MapReduce – is a programming model and software framework for writing applications that rapidly process vast amounts of data in parallel on large clusters of compute nodes
So, effectively, when you start working with Hadoop, HDFS and Hadoop MapReduce are the first 2 things you encounter. I will cover MapReduce in subsequent posts.
Reference: HDFS for dummies from our JCG partner Munish K Gupta at the Tech Spot blog. | http://www.javacodegeeks.com/2012/05/hdfs-for-dummies.html | CC-MAIN-2015-35 | refinedweb | 639 | 59.23 |
Stephen J. Turnbull wrote: >Mark Sapiro writes: > > CJ Keist wrote: > > > >I simply commented out the for p loop: > > > > > > #for p in $(PACKAGES); \ > > > That is a perfectly acceptable workaround, but the question is why > > doesn't your make properly handle > > > > for p in ; do ... ; done > >Because make doesn't (shouldn't) do anything with commands except >substitute make variables, then pass them to the shell. Bourne shells >require the tokens following "in" to constitute a list. The idiom for >an empty list is the empty string. > >One way to handle this in GNU Make is > >ifeq($(PACKAGES),) >endif > >(Untested, IIRC -- the point is that make doesn't care about the >quotation marks at all, so it passes the literal string '""' to the >shell as the value of the make variable PACKAGES.) I agree that the underlying issue is with the shell, but in at least these bash versions: GNU bash, version 3.2.49(22)-release (i686-pc-cygwin) GNU bash, version 3.2.48(1)-release (i386-apple-darwin10.0) GNU bash, version 3.1.17(1)-release (i686-redhat-linux-gnu) the construct for p in ; do echo Huh? $p ; done is accepted and does nothing. Further, since 2.1.12, the 'normal' value of PACKAGES in this Makefile is null, and this is the first report of this problem I've seen. If there are in fact versions of sh/bash that don't accept the "for p in ;" construct, then I'd like to fix this in the Makefile, but I'd like to have a way to a) see the failure, and b) test the fix. -- Mark Sapiro <mark at msapiro.net> The highway is for gamblers, San Francisco Bay Area, California better use your sense - B. Dylan | http://mail.python.org/pipermail/mailman-users/2010-August/070058.html | CC-MAIN-2013-20 | refinedweb | 292 | 79.3 |
ro.sync.ecss.extensions.commons.operations.ChangeAttributeOperation
If you set the attribute's namespace here (i.e.), Oxygen shows up an error message:
The attribute does not have a valid xml name: ":rend"
A valid attribute name must match the standard specification.
It's seems, that Oxygen has a problem with the "http://" in the namespace. Without this "http://", the attribut is inserted correctly with the namespace-prefix.
If you don't set the namespace, all works fine, but the attribute is in the namespace of the belonging element. That's intended in our case, so it isn't a problem in the moment. | https://www.oxygenxml.com/forum/topic7222.html | CC-MAIN-2018-17 | refinedweb | 104 | 56.05 |
内容纲要
示例:
判断字符串是否由字母数字下划线组成:
using System; using System.Diagnostics; using System.Text.RegularExpressions; namespace ConsoleApp6 { class Program { static Regex regex = new Regex(@"^[A-Za-z0-9]+$"); static void Main(string[] args) { string[] a = new string[] { "Absdbkbs", "asdf4642`", "fsdg4654fs4", "r23fwegf34", "e23rwef,", "fewfsg35453453", "545345415", "dalsjfiose2", "dasfwetr23`", "dsaf5454-"}; System.Threading.Thread.Sleep(5000); Stopwatch watch = new Stopwatch(); watch.Start(); for (int i = 0; i < 1_0_0000; i++) { for (int k = 0; k < a.Length; k++) { var tmp = IsNumAndEnCh(a[k]); } } watch.Stop(); Console.WriteLine("执行10 0000 * 10 正则表达式验证:" + watch.ElapsedMilliseconds); watch.Restart(); for (int i = 0; i < 1_0_0000; i++) { for (int k = 0; k < a.Length; k++) { var tmp = IsHas(a[k]); } } watch.Stop(); Console.WriteLine("执行10 0000 * 10 C#代码验证:" + watch.ElapsedMilliseconds); Console.ReadKey(); } /// <summary> /// 判断输入的字符串是否只包含数字和英文字母 /// </summary> /// <param name="input"></param> /// <returns></returns> public static bool IsNumAndEnCh(string input) { return regex.IsMatch(input); } public static bool IsHas(string input) { ReadOnlySpan<char> span = input.AsSpan(); for (int i = 0; i < span.Length; i++) { if (!char.IsLetterOrDigit(span[i])) return false; } return true; } } }
输出结果是
执行10 0000 * 10 正则表达式验证:986 执行10 0000 * 10 C#代码验证:237
原生代码确实比正则表达式快。 am commenting to let.
Regards for all your efforts that you have put in this. Very interesting info. | https://www.whuanle.cn/archives/716 | CC-MAIN-2021-39 | refinedweb | 198 | 53.98 |
This was another new shield for the Wemos called the Ambient light Shield , this time its based around the BH1750FVI digital Ambient Light Sensor
Lets look at some info about the sensor
BH1750FVI ).
●Features
1) I2C )
10) It is possible to select 2 type of I2C slave-address.
11) Adjustable measurement result for influence of optical window ( It is possible to detect min. 0.11 lx, max. 100000 lx by using this function. )
12) Small measurement variation (+/- 20%)
13) The influence of infrared is very small.
Being an I2C device it uses D1 and D2 on the Wemos mini
Code
You need to install the following library for this example :
#include <Wire.h> #include <BH1750.h> BH1750 lightMeter(0x23); void setup(){ Serial.begin(9600); // Initialize the I2C bus Wire.begin(); if (lightMeter.begin(BH1750::CONTINUOUS_HIGH_RES_MODE)) { Serial.println(F("BH1750 Advanced begin")); } else { Serial.println(F("Error initialising BH1750")); } } void loop() { uint16_t lux = lightMeter.readLightLevel(); Serial.print("Light: "); Serial.print(lux); Serial.println(" lx"); delay(1000); }
Output
Open the serial monitor, cover the sensor, shine light on the sensor and so on to see the readings change, you can see where I covered it completely reading 0 lx
Light: 29 lx
Light: 29 lx
Light: 22 lx
Light: 0 lx
Light: 0 lx
Light: 20 lx
Light: 18 lx
Light: 28 lx
Light: 27 lx
Link | http://www.esp8266learning.com/esp8266-and-ambient-light-shield-example.php | CC-MAIN-2019-47 | refinedweb | 225 | 56.86 |
A pipeline library for Python that cuts down your boilerplate code.
Tubo is a library that provides a simple pipeline system for Python.
Unix pipe system is an excellent example of the concept of separation of responsibility. Each utility does a single thing well. This increases readability, maintainability of code and code reuse. Tubo wants to bring this abstraction to Python.
pip install tubo
You have a source of iterable items and you want to perform various operations on them. In a Unix-like system you would write something like this:
cat foo.txt | op1 | op2 | op3
Using Tubo, instead, you would use Python and you would write something like this:
>>> output = tubo.pipeline(file('foo.txt'), op1, op2, op3)
And the output would be available for you, to print it or to further transform it as you prefer. The advantage is that you can write the operations in Python, giving you a lot of flexibility.
The central part of Tubo is the method
tubo.pipeline. It accepts an arbitrary number of arguments, the first being a data source and the following being operations on iterable data, defined using python generators.
Each operation should `yield` something, so that the following operation can work.
Example: capitalize words that contain a
i letter.
text = ['italy', 'germany', 'brazil', 'france', 'england', 'argentina', 'peru', 'united states', 'australia', 'sweden', 'china', 'poland', 'portugal'] def capitalize(lines): for line in lines: for word in line.split(","): yield word.capitalize() def filter_wordwith_i(words): for word in words: if 'i' in word: yield word output = tubo.pipeline( text, filter_wordwith_i, capitalize, )
At this point, output is an iterable, and we can do anything we want with it. We can print it or further transform it.
Sometimes, you need to write functions that take two or more inputs, and process them. In this case, you need to write an operation that accepts a list of iterables.
Example: interleave lines from two or more files (such as the utility
paste)
def interleave(listoflines): for lines in itertools.izip(*listoflines): yield ''.join(lines) output = tubo.pipeline( (file('file1.txt'), file('file2.txt')), interleave )
Once you have your pipeline, it’s time to consume it.
tubo.consume(output) # Equivalent to: # # for element in output: # pass
This consumes the iterator at C-speed, and uses this recipe.
def uniq(lines): seen = set() for line in lines: if line not in seen: seen.add(line) yield line def reverse_string(lines): for line in lines: yield ''.join(reversed(line)) def append_nlines(lines): for nlines, line in enumerate(lines): yield line yield "\nTotal Number of lines: {}".format(nlines+1) output = tubo.pipeline( open(filename), uniq, reverse_string, append_nlines, )
When we need to merge two inputs, or two results of different pipes, we will use the functions
merge and
merge_longest, which will
def select_Nth_word(N, lines): for line in lines: yield line.split(' ')[N] select_first_word = functools.partial(select_Nth_word, 0) select_second_word = functools.partial(select_Nth_word, 1) def concatenate(words): for word1, word2 in words: yield "{} {}".format(word1, word2) pipeline1 = tubo.pipeline( open(fname1), select_first_word, ) pipeline2 = tubo.pipeline( open(fname2), select_second_word, ) output = tubo.pipeline( tubo.merge( pipeline1, pipeline2, ), concatenate )
The library was inspired from a post by Christoph Rauch.
Now works for Python3. Wheel added.
Initial concept.
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/tubo/ | CC-MAIN-2017-26 | refinedweb | 552 | 59.09 |
Automated Unit Testing Frameworks
JUnit in Action
In this section, I will show you a step by step example to write JUnit tests. To run this example, you need to obtain JUnit from its official site at. Installing JUnit is very simple; just unzip the downloaded file and place junit.jar in your CLASSPATH.
The class to be tested is a Java Queue class as presented in the article "Queue: A missed java.util Class." The public interface to the Queue class is shown in Listing 1.
public class Queue { private LinkedList items; public Queue() ... public Object enqueue (Object element) ... public Object dequeue ( ) ... public int size ( ) ... public boolean empty ( ) ... public void clear ( ) ... }
Step 1: Imports
You need to import the junit.framework package to write your test case.
import junit.framework.*;
Step 2: Implement a Test Case
A test case is a class derived from junit.framework.TestCase.
public class TestQueue extends TestCase { public TestQueue (String name) { super (name); } public static void main ( String[] args) { junit.textui.TestRunner.run (suite()); } }
Just use the constructor to invoke the TestCase constructor. The main() method is used to run the test runner textual interface.
Step 4: Define and Initialize the Fixture
In this example, we need to create two Queue objects, an empty queue and a queue of three Integer objects. Each test in the test case may send some messages to one of the two objects. So, we have to re-initialize the two objects before running each test. In other test cases, you also may need to tear down some objects after running each test (for example, close a network or database connection). JUnit provides two methods, setUp() and tearDown(), that you can override in your test case to initialize and tear down any member variables in the test case.
To implement the TestQueue fixture, add two private Queue references and override the setUp () method.
private Queue empty_queue; private Queue queue; protected void setUp() { empty_queue = new Queue(); queue = new Queue (); queue.enqueue (new Integer (1)); queue.enqueue (new Integer (2)); queue.enqueue (new Integer (3)); }
Step 5: Compose a Test Suite
Add the following static method to your test case.
public static Test suite() { return new TestSuite(TestQueue.class); }
This way, you will make use of the JUnit Reflection-driven API and you will be restricted to start the name of any test with the word "test." In addition, you can't assume anything about the order in which your tests will be run.
If you want to force a specific order of tests, not use the test's naming convention, run some other tests from other test cases, or eliminate some tests in the test case. You may write some code like this:
public static Test suite ( ) { TestSuite suite= new TestSuite("Customized Test Suite"); suite.addTest(new TestSuite(TestQueue.class)); suite.addTest(TestQueue2.suite()); return suite; }
Page 2 of 3
This article was originally published on June 23,... | https://www.developer.com/java/ent/article.php/10933_3372151_2/Automated-Unit-Testing-Frameworks.htm | CC-MAIN-2020-34 | refinedweb | 488 | 66.13 |
May I ask, what does += mean? Sorry got lost in the woods. I keep seeing this in the forums and seems to always work like a concatenating function?
16/18 Using String Lists in Functions
Hi,
+= is the shorthand assignment operator. If you type
a += b, it means
a = a + b. Similarly we have
-=,
*= and
%=
n = ["Michael", "Lieberman"] def join_strings(words): result = " " for i in range(len(words)): result += words[i] return result# Add your function here print join_strings(n)
I saw error as
Oops, try again. join_strings(['x', 'y', 'z', 'a']) returned ' xyza' instead of 'xyza'
Hi there - this bit's the problem:
- Inside the function, create a variable called result and set it to "", an empty string.
It looks like when you're creating the variable result it has a space in the string.
Because of this, the space appears before the name. Apart from that it looks good. Get rid of the space in the string and you should be okay.
Hi blogninja25344,
I am facing issues with the following code where I have remove the space between the "" , but I am getting only the first string printed. The code and the outputs are added below:
Code:
n = ["Michael", "Lieberman"]
Add your function here
def join_strings(words):
result=""
for i in range(len(words)):
result+=words[i]
return result
print join_strings(n)
Output:
Michael
None
Oops, try again.
join_strings(['x', 'y', 'z', 'a']) returned 'x' instead of 'xyza' | https://discuss.codecademy.com/t/16-18-using-string-lists-in-functions/38254 | CC-MAIN-2018-34 | refinedweb | 241 | 80.51 |
openaustralia.org API Python client package
Project Description
Release History Download Files
This is a python wrapper for the OpenAustralia API.
NOTE: This isn’t officially affiliated with the OpenAustralia project. It’s just something I’m playing around with. Suggestions / contributions towards making this more useful are welcome.
Installation
From source
python setup.py install
pip
pip install openaustralia
Usage
from openaustralia import OpenAustralia oa = OpenAustralia("YOUR KEY") search = oa.get_hansard("barnacles") search['rows'].pop(0)
Source code
You can get the code here:
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/openaustralia/ | CC-MAIN-2017-43 | refinedweb | 106 | 59.5 |
Contents
Modern computers process vast amounts of data that represent various aspects of the world. Data processing is often organized into pipelines of manipulations on sequential streams of data. In this chapter, we consider a suite of techniques process and manipulate data streams.
In Chapter 2, we introduced a sequence interface, implemented in Python by built-in data types such as tuple and list. Sequences supported two core operations: querying their length and accessing an element by index. However, representing sequential data using the sequence abstraction has two important limitations. The first is that a sequence of length n typically takes up an amount of memory proportional to n. Therefore, the longer a sequence is, the more memory it takes to represent it.
The second limitation of sequences is that sequences can only represent datasets of known, finite length. Many sequential collections that we may want to represent do not have a well-defined length, and some are even infinite. Two mathematical examples of infinite sequences are the positive integers and the Fibonacci numbers. Sequential data sets of unbounded length also appear in other computational domains. For instance, the sequence of all emails ever written grows longer with every second and therefore does not have a fixed length. Likewise, the sequence of telephone calls sent through a cell tower, the sequence of mouse movements made by a computer user, and the sequence of acceleration measurements from sensors on an aircraft all extend without bound as the world evolves.
In this chapter, we introduce new constructs for working with sequential data that are designed to accommodate collections of unknown or unbounded length, while using limited memory.
The central observation that will lead us to efficient processing of sequential data is that a sequence can be represented using programming constructs without each element being stored explicitly in the memory of the computer. To put this idea into practice, we will construct objects that provides access to all of the elements of some sequential dataset that an application may desire, but without computing all of those elements in advance and storing them.
A simple example of this idea arises in the range sequence type introduced in Chapter 2. A range represents a consecutive, bounded sequence of integers. However, it is not the case that each element of that sequence is represented explicitly in memory. Instead, when an element is requested from a range, it is computed. Hence, we can represent very large ranges of integers without using large blocks of memory. Only the end points of the range are stored as part of the range object, and elements are computed on the fly.
>>> r = range(10000, 1000000000) >>> r[45006230] 45016230
In this example, not all 999,990,000 integers in this range are stored when the range instance is constructed. Instead, the range object adds the first element 10,000 to the index 45,006,230 to produce the element 45,016,230. Computing values on demand, rather than retrieving them from an existing representation, is an example of lazy computation. Computer science is a discipline that celebrates laziness as an important computational tool.
An iterator is an object that provides sequential access to an underlying sequential dataset. Iterators are built-in objects in many programming languages, including Python. The iterator abstraction has two components: a mechanism for retrieving the next element in some underlying series of elements and a mechanism for signaling that the end of the series has been reached and no further elements remain. In programming languages with built-in object systems, this abstraction typically corresponds to a particular interface that can be implemented by classes. The Python interface for iterators is described in the next section.
The usefulness of iterators is derived from the fact that the underlying series of data for an iterator may not be represented explicitly in memory. An iterator provides a mechanism for considering each of a series of values in turn, but all of those elements do not need to be stored simultaneously. Instead, when the next element is requested from an iterator, that element may be computed on demand instead of being retrieved from an existing memory source.
Ranges are able to compute the elements of a sequence lazily because the sequence represented is uniform, and any element is easy to compute from the starting and ending bounds of the range. Iterators allow for lazy generation of a much broader class of underlying sequential datasets, because they do not need to provide access to arbitrary elements of the underlying series. Instead, they must only compute the next element of the series, in order, each time another element is requested. While not as flexible as accessing arbitrary elements of a sequence (called random access), sequential access to sequential data series is often sufficient for data processing applications.
The Python iterator interface includes two messages. The __next__ message queries the iterator for the next element of the underlying series that it represents. In response to invoking __next__ as a method, an iterator can perform arbitrary computation in order to either retrieve or compute the next element in an underlying series. Calls to __next__ make a mutating change to the iterator: they advance the position of the iterator. Hence, multiple calls to __next__ will return sequential elements of an underlying series. Python signals that the end of an underlying series has been reached by raising a StopIteration exception during a call to __next__.
The Letters class below iterates over an underlying series of letters from a to d. The member variable current stores the current letter in the series, and the __next__ method returns this letter and uses it to compute a new value for current.
>>> class Letters(object): def __init__(self): self.current = 'a' def __next__(self): if self.current > 'd': raise StopIteration result = self.current self.current = chr(ord(result)+1) return result def __iter__(self): return self
The __iter__ message is the second required message of the Python iterator interface. It simply returns the iterator; it is useful for providing a common interface to iterators and sequences, as described in the next section.
Using this class, we can access letters in sequence.
>>> letters = Letters() >>> letters.__next__() 'a' >>> letters.__next__() 'b' >>> letters.__next__() 'c' >>> letters.__next__() 'd' >>> letters.__next__() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 12, in next StopIteration
A Letters instance can only be iterated through once. After its __next__() method raises a StopIteration exception, it continues to do so from then on. There is no way to reset it; one must create a new instance.
Iterators also allow us to represent infinite series by implementing a __next__ method that never raises a StopIteration exception. For example, the Positives class below iterates over the infinite series of positive integers. The built-in next function in Python invokes the __next__ method on its argument.
>>> class Positives(object): def __init__(self): self.current = 1; def __next__(self): result = self.current self.current += 1 return result def __iter__(self): return self >>> p = Positives() >>> next(p) 1 >>> next(p) 2 >>> next(p) 3
The for statement in Python is designed to operate on iterators. Objects are iterable (an interface) if they have an __iter__ method that returns an iterator. Iterable objects can be the value of the <expression> in the header of a for statement:
for <name> in <expression>: <suite>
To execute a for statement, Python evaluates the header <expression>, which must yield an iterable value. Then, the __iter__ method is invoked on that value. Until a StopIteration exception is raised, Python repeatedly invokes the __next__ method on that iterator and binds the result to the <name> in the for statement. Then, it executes the <suite>.
>>> counts = [1, 2, 3] >>> for item in counts: print(item) 1 2 3
In the above example, the counts list returns an iterator from its __iter__() method. The for statement then calls that iterator's __next__() method repeatedly, and assigns the returned value to item each time. This process continues until the iterator raises a StopIteration exception, at which point execution of the for statement concludes.
With our knowledge of iterators, we can implement the execution rule of a for statement in terms of while, assignment, and try statements.
>>> items = counts.__iter__() >>> try: while True: item = items.__next__() print(item) except StopIteration: pass 1 2 3
Above, the iterator returned by invoking the __iter__ method of counts is bound to a name items so that it can be queried for each element in turn. The handling clause for the StopIteration exception does nothing, but handling the exception provides a control mechanism for exiting the while loop.
The Letters and Positives objects above require us to introduce a new field self.current into our object to keep track of progress through the sequence. With simple sequences like those shown above, this can be done easily. With complex sequences, however, it can be quite difficult for the __next__ method to save its place in the calculation. Generators allow us to define more complicated iterations by leveraging the features of the Python interpreter.
A generator is an iterator returned by a special class of function called a generator function. Generator functions are distinguished from regular functions in that rather than containing return statements in their body, they use yield statement to return elements of a series.
Generators do not use attributes of an object to track their progress through a series. Instead, they control the execution of the generator function, which runs until the next yield statement is executed each time the generator's __next__ method is invoked. The Letters iterator can be implemented much more compactly using a generator function.
>>> def letters_generator(): current = 'a' while current <= 'd': yield current current = chr(ord(current)+1)
>>> for letter in letters_generator(): print(letter) a b c d
Even though we never explicitly defined __iter__ or __next__ methods, the yield statement indicates that we are defining a generator function. When called, a generator function doesn't return a particular yielded value, but instead a generator (which is a type of iterator) that itself can return the yielded values. A generator object has __iter__ and __next__ methods, and each call to __next__ continues execution of the generator function from wherever it left off previously until another yield statement is executed.
The first time __next__ is called, the program executes statements from the body of the letters_generator function until it encounters the yield statement. Then, it pauses and returns the value of current. yield statements do not destroy the newly created environment, they preserve it for later. When __next__ is called again, execution resumes where it left off. The values of current and of any other bound names in the scope of letters_generator are preserved across subsequent calls to __next__.
We can walk through the generator by manually calling ____next__():
>>> letters = letters_generator() >>> type(letters) <class 'generator'> >>> letters.__next__() 'a' >>> letters.__next__() 'b' >>> letters.__next__() 'c' >>> letters.__next__() 'd' >>> letters.__next__() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
The generator does not start executing any of the body statements of its generator function until the first time __next__ is invoked. The generator raises a StopIteration exception whenever its generator function returns.
In Python, iterators only make a single pass over the elements of an underlying series. After that pass, the iterator will continue to raise a StopIteration exception when __next__ is invoked. Many applications require iteration over elements multiple times. For example, we have to iterate over a list many times in order to enumerate all pairs of elements.
>>> def all_pairs(s): for item1 in s: for item2 in s: yield (item1, item2)
>>> list(all_pairs([1, 2, 3])) [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
Sequences are not themselves iterators, but instead iterable objects. The iterable interface in Python consists of a single message, __iter__, that returns an iterator. The built-in sequence types in Python return new instances of iterators when their __iter__ methods are invoked. If an iterable object returns a fresh instance of an iterator each time __iter__ is called, then it can be iterated over multiple times.
New iterable classes can be defined by implementing the iterable interface. For example, the iterable LetterIterable class below returns a new iterator over letters each time __iter__ is invoked.
>>> class LetterIterable(object): def __iter__(self): current = 'a' while current <= 'd': yield current current = chr(ord(current)+1)
The __iter__ method is a generator function; it returns a generator object that yields the letters 'a' through 'd'.
A Letters iterator object gets "used up" after a single iteration, whereas the LetterIterable object can be iterated over multiple times. As a result, a LetterIterable instance can serve as an argument to all_pairs.
>>> letters = LetterIterable() >>> all_pairs(letters).__next__() ('a', 'a') >>> all_pairs(letters).__next__() ('a', 'a')
Streams offer another way to represent sequential data implicitly. A stream is a lazily computed recursive list. Like the Rlist class from Chapter 3, a Stream instance responds to requests for its first element and the rest of the stream. Like an Rlist, the rest of a Stream is itself a Stream. Unlike an Rlist, the rest of a stream is only computed when it is looked up, rather than being stored in advance. That is, the rest of a stream is computed lazily.
To achieve this lazy evaluation, a stream stores a function that computes the rest of the stream. Whenever this function is called, its returned value is cached as part of the stream in an attribute called _rest, named with an underscore to indicate that it should not be accessed directly. The accessible attribute rest is a property method that returns the rest of the stream, computing it if necessary. With this design, a stream stores how to compute the rest of the stream, rather than always storing it explicitly.
>>> class Stream(object): """A lazily computed recursive list.""" class empty(object): def __repr__(self): return 'Stream.empty' empty = empty() def __init__(self, first, compute_rest=lambda: empty): assert callable(compute_rest), 'compute_rest must be callable.' self.first = first self._compute_rest = compute_rest self._rest = None @property def rest(self): """Return the rest of the stream, computing it if necessary.""" if self._compute_rest is not None: self._rest = self._compute_rest() self._compute_rest = None return self._rest def __repr__(self): return 'Stream({0}, <...>)'.format(repr(self.first))
A recursive list is defined using a nested expression. For example, we can create an Rlist that represents the elements 1 then 5 as follows:
>>> r = Rlist(1, Rlist(2+3, Rlist(9)))
Likewise, we can create a Stream representing the same series. The Stream does not actually compute the second element 5 until the rest of the stream is requested.
>>> s = Stream(1, lambda: Stream(2+3, lambda: Stream(9)))
Here, 1 is the first element of the stream, and the lambda expression that follows returns a function for computing the rest of the stream.
Accessing the elements of recursive list r and stream s proceed similarly. However, while 5 is stored within r, it is computed on demand for s via addition the first time that it is requested.
>>> r.first 1 >>> s.first 1 >>> r.rest.first 5 >>> s.rest.first 5 >>> r.rest Rlist(5, Rlist(9)) >>> s.rest Stream(5, <...>)
While the rest of r is a two-element recursive list, the rest of s includes a function to compute the rest; the fact that it will return the empty stream may not yet have been discovered.
When a Stream instance is constructed, the field self._computed is False, signifying that the _rest of the Stream has not yet been computed. When the rest attribute is requested via a dot expression, the rest method is invoked, which triggers computation with self._rest = self.compute_rest(). Because of the caching mechanism within a Stream, the compute_rest function is only ever called once, then discarded.
The essential properties of a compute_rest function are that it takes no arguments, and it returns a Stream or Stream.empty.
Lazy evaluation gives us the ability to represent infinite sequential datasets using streams. For example, we can represent increasing integers, starting at any first value.
>>> def make_integer_stream(first=1): def compute_rest(): return make_integer_stream(first+1) return Stream(first, compute_rest)
>>> ints = make_integer_stream() >>> ints Stream(1, <...>) >>> ints.first 1
When make_integer_stream is called for the first time, it returns a stream whose first is the first integer in the sequence (1 by default). However, make_integer_stream is actually recursive because this stream's compute_rest calls make_integer_stream again, with an incremented argument. This makes make_integer_stream recursive, but also lazy.
>>> ints.first 1 >>> ints.rest.first 2 >>> ints.rest.rest Stream(3, <...>)
Recursive calls are only made to make_integer_stream whenever the rest of an integer stream is requested.
The same higher-order functions that manipulate sequences -- map and filter -- also apply to streams, although their implementations must change to apply their argument functions lazily. The function map_stream maps a function over a stream, which produces a new stream. The locally defined compute_rest function ensures that the function will be mapped onto the rest of the stream whenever the rest is computed.
>>> def map_stream(fn, s): if s is Stream.empty: return s def compute_rest(): return map_stream(fn, s.rest) return Stream(fn(s.first), compute_rest)
A stream can be filtered by defining a compute_rest function that applies the filter function to the rest of the stream. If the filter function rejects the first element of the stream, the rest is computed immediately. Because filter_stream is recursive, the rest may be computed multiple times until a valid first element is found.
>>> def filter_stream(fn, s): if s is Stream.empty: return s def compute_rest(): return filter_stream(fn, s.rest) if fn(s.first): return Stream(s.first, compute_rest) else: return compute_rest()
The map_stream and filter_stream functions exhibit a common pattern in stream processing: a locally defined compute_rest function recursively applies a processing function to the rest of the stream whenever the rest is computed.
To inspect the contents of a stream, we can coerce up to the first k elements to a Python list.
>>> def first_k_as_list(s, k): first_k = [] while s is not Stream.empty and k > 0: first_k.append(s.first) s, k = s.rest, k-1 return first_k
These convenience functions allow us to verify our map_stream implementation with a simple example that squares the integers from 3 to 7.
>>> s = make_integer_stream(3) >>> s Stream(3, <...>) >>> m = map_stream(lambda x: x*x, s) >>> m Stream(9, <...>) >>> first_k_as_list(m, 5) [9, 16, 25, 36, 49]
We can use our filter_stream function to define a stream of prime numbers using the sieve of Eratosthenes, which filters a stream of integers to remove all numbers that are multiples of its first element. By successively filtering with each prime, all composite numbers are removed from the stream.
>>> def primes(pos_stream): def not_divible(x): return x % pos_stream.first != 0 def compute_rest(): return primes(filter_stream(not_divible, pos_stream.rest)) return Stream(pos_stream.first, compute_rest)
By truncating the primes stream, we can enumerate any prefix of the prime numbers.
>>> prime_numbers = primes(make_integer_stream(2)) >>> first_k_as_list(prime_numbers, 7) [2, 3, 5, 7, 11, 13, 17]
Streams contrast with iterators in that they can be passed to pure functions multiple times and yield the same result each time. The primes stream is not "used up" by converting it to a list. That is, the first element of prime_numbers is still 2 after converting the prefix of the stream to a list.
>>> prime_numbers.first 2
Just as recursive lists provide a simple implementation of the sequence abstraction, streams provide a simple, functional, recursive data structure that implements lazy evaluation through the use of higher-order functions.
In addition to streams, data values are often stored in large repositories called databases. A database consists of a data store containing structured data values and an interface for retrieving subsets of the data based on their characteristics. Each value stored in a database is called a record. Records are typically retrieved via a query, which is an expression in a query programming language. By far the most ubiquitous query language in use today is called Structured Query Language or SQL (pronounced "sequel").
SQL is an example of a declarative programming language. Expressions do not describe computations directly, but instead state the form of the specifies the form of the result, but abstracts away procedural details.
In this section, we introduce a declarative query language called logic, designed specifically for this text. It is based upon Prolog and the declarative language in Structure and Interpretation of Computer Programs. Data records are expressed as Scheme lists, and queries are expressed as Scheme values. The logic is a complete implementation that depends upon the Scheme project of the previous chapter.
Databases store records that represent facts in the system. The purpose of the query interpreter is to retrieve collections of facts drawn directly from database records, as well as to deduce new facts from the database using logical inference. A fact statement in the logic language consists of one or more lists following the keyword fact. A simple fact is a single list. A dog breeder with an interest in U.S. Presidents might record the genealogy of her collection of dogs using the logic language as follows:
logic> (fact (parent abraham barack)) logic> (fact (parent abraham clinton)) logic> (fact (parent delano herbert)) logic> (fact (parent fillmore abraham)) logic> (fact (parent fillmore delano)) logic> (fact (parent fillmore grover)) logic> (fact (parent eisenhower fillmore))
Each fact is not a procedure application, as in a Scheme expression, but instead a relation that is declared. "The dog Abraham is the parent of Barack," declares the first fact. Relation types do not need to be defined in advance. Relations are not applied, but instead matched to queries.
A query also consists of one or more lists, but begins with the keyword query. A query may contain variables, which are symbols that begin with a question mark. Variables are matched to facts by the query interpreter:
logic> (query (parent abraham ?child)) Success! child: barack child: clinton
The query interpreter responds with Success! to indicate that the query matches some fact. The following lines show substitutions of the variable ?child that match the query to the facts in the database.
Compound facts. Facts may also contain variables as well as multiple sub-expressions. A multi-expression fact begins with a conclusion, followed by hypotheses. For the conclusion to be true, all of the hypotheses must be satisfied:
(fact <conclusion> <hypothesis0> <hypothesis1> ... <hypothesisN>)
For example, facts about children can be declared based on the facts about parents already in the database:
logic> (fact (child ?c ?p) (parent ?p ?c))
The fact above can be read as: "?c is the child of ?p, provided that ?p is the parent of ?c." A query can now refer to this fact:
logic> (query (child ?child fillmore)) Success! child: abraham child: delano child: grover
The query above requires the query interpreter to combine the fact that defines child with the various parent facts about fillmore. The user of the language does not need to know how this information is combined, but only that the result has a particular form. It is up to the query interpreter to prove that (child abraham fillmore) is true, given the available facts.
A query is not required to include variables; it may simply verify a fact:
logic> (query (child herbert delano)) Success!
A query that does not match any facts will return failure:
logic> (query (child eisenhower ?parent)) Failure.
The logic language also allows recursive facts. That is, the conclusion of a fact may depend upon a hypothesis that contains the same symbols. For instance, the ancestor relation is defined with two facts. Some ?a is an ancestor of ?y if it is a parent of ?y or if it is the parent of an ancestor of ?y:
logic> (fact (ancestor ?a ?y) (parent ?a ?y)) logic> (fact (ancestor ?a ?y) (parent ?a ?z) (ancestor ?z ?y))
A single query can then list all ancestors of herbert:
logic> (query (ancestor ?a herbert)) Success! a: delano a: fillmore a: eisenhower
Compound queries. A query may have multiple subexpressions, in which case all must be satisfied simultaneously by an assignment of symbols to variables. If a variable appears more than once in a query, then it must take the same value in each context. The following query finds ancestors of both herbert and barack:
logic> (query (ancestor ?a barack) (ancestor ?a herbert)) Success! a: fillmore a: eisenhower
Recursive facts may require long chains of inference to match queries to existing facts in a database. For instance, to prove the fact (ancestor fillmore herbert), we must prove each of the following facts in succession:
(parent delano herbert) ; (1), a simple fact (ancestor delano herbert) ; (2), from (1) and the 1st ancestor fact (parent fillmore delano) ; (3), a simple fact (ancestor fillmore herbert) ; (4), from (2), (3), & the 2nd ancestor fact
In this way, a single fact can imply a large number of additional facts, or even infinitely many, as long as the query interpreter is able to discover them.
Hierarchical facts. Thus far, each fact and query expression has been a list of symbols. In addition, fact and query lists can contain lists, providing a way to represent hierarchical data. The color of each dog may be stored along with the name an additional record:
logic> (fact (dog (name abraham) (color white))) logic> (fact (dog (name barack) (color tan))) logic> (fact (dog (name clinton) (color white))) logic> (fact (dog (name delano) (color white))) logic> (fact (dog (name eisenhower) (color tan))) logic> (fact (dog (name fillmore) (color brown))) logic> (fact (dog (name grover) (color tan))) logic> (fact (dog (name herbert) (color brown)))
Queries can articulate the full structure of hierarchical facts, or they can match variables to whole lists:
logic> (query (dog (name clinton) (color ?color))) Success! color: white logic> (query (dog (name clinton) ?info)) Success! info: (color white)
Much of the power of a database lies in the ability of the query interpreter to join together multiple kinds of facts in a single query. The following query finds all pairs of dogs for which one is the ancestor of the other and they share a color:
logic> (query (dog (name ?name) (color ?color)) (ancestor ?ancestor ?name) (dog (name ?ancestor) (color ?color))) Success! name: barack color: tan ancestor: eisenhower name: clinton color: white ancestor: abraham name: grover color: tan ancestor: eisenhower name: herbert color: brown ancestor: fillmore
Variables can refer to lists in hierarchical records, but also using dot notation. A variable following a dot matches the rest of the list of a fact. Dotted lists can appear in either facts or queries. The following example constructs pedigrees of dogs by listing their chain of ancestry. Young barack follows a venerable line of presidential pups:
logic> (fact (pedigree ?name) (dog (name ?name) . ?details)) logic> (fact (pedigree ?child ?parent . ?rest) (parent ?parent ?child) (pedigree ?parent . ?rest)) logic> (query (pedigree barack . ?lineage)) Success! lineage: () lineage: (abraham) lineage: (abraham fillmore) lineage: (abraham fillmore eisenhower)
Declarative or logical programming can express relationships among facts with remarkable efficiency. For example, if we wish to express that two lists can append to form a longer list with the elements of the first, followed by the elements of the second, we state two rules. First, a base case declares that appending an empty list to any list gives that list:
logic> (fact (append-to-form () ?x ?x))
Second, a recursive fact declares that a list with first element ?a and rest ?r appends to a list ?y to form a list with first element ?a and some appended rest ?z. For this relation to hold, it must be the case that ?r and ?y append to form ?z:
logic> (fact (append-to-form (?a . ?r) ?y (?a . ?z)) (append-to-form ?r ?y ?z))
Using these two facts, the query interpreter can compute the result of appending any two lists together:
logic> (query (append-to-form (a b c) (d e) ?result)) Success! result: (a b c d e)
In addition, it can compute all possible pairs of lists ?left and ?right that can append to form the list (a b c d e):
logic> (query (append-to-form ?left ?right (a b c d e))) Success! left: () right: (a b c d e) left: (a) right: (b c d e) left: (a b) right: (c d e) left: (a b c) right: (d e) left: (a b c d) right: (e) left: (a b c d e) right: ()
Although it may appear that our query interpreter is quite intelligent, we will see that it finds these combinations through one simple operation repeated many times: that of matching two lists that contain variables in an environment.
This:
logic> (query (ancestor ?a clinton) (ancestor ?a ?brown-dog) (dog (name ?brown-dog) (color brown))) Success! a: fillmore brown-dog: herbert a: eisenhower brown-dog: fillmore a: eisenhower brown-dog: herbert.
Large-scale data processing applications often coordinate effort among multiple computers. A distributed computing application is one in which multiple interconnected but independent computers coordinate to perform a joint computation.
Different computers are independent in the sense that they do not directly share memory. Instead, they communicate with each other using messages, information transferred from one computer to another over a network.
Messages sent between computers are sequences of bytes. The purpose of a message varies; messages can request data, send data, or instruct another computer to evaluate a procedure call. In all cases, the sending computer must encode information in a way that the receiving computer can decode and correctly interpret. To do so, computers adopt a message protocol that endows meaning to sequences of bytes.
A message protocol is a set of rules for encoding and interpreting messages. Both the sending and receiving computers must agree on the semantics of a message to enable successful communication. Many message protocols specify that a message conform to a particular format in which certain bits at fixed positions indicate fixed conditions. Others use special bytes or byte sequences to delimit parts of the message, much as punctuation delimits sub-expressions in the syntax of a programming language..
The TCP/IP Protocols. On the Internet, messages are transferred from one machine to another using the Internet Protocol (IP), which specifies how to transfer packets of data among different networks to allow global Internet communication. IP was designed under the assumption that networks are inherently unreliable at any point and dynamic in structure. Moreover, it does not assume that any central tracking or monitoring of communication exists. Each packet contains a header containing the destination IP address, along with other information. All packets are forwarded throughout the network toward the destination using simple routing rules on a best-effort basis.
This design imposes constraints on communication. Packets transferred using modern IP implementations (IPv4 and IPv6) have a maximum size of 65,535 bytes. Larger data values must be split among multiple packets. The IP does not guarantee that packets will be received in the same order that they were sent. Some packets may be lost, and some packets may be transmitted multiple times.
The Transmission Control Protocol is an abstraction defined in terms of the IP that provides reliable, ordered transmission of arbitrarily large byte streams. The protocol provides this guarantee by correctly ordering packets transferred by the IP, removing duplicates, and requesting retransmission of lost packets. This improved reliability comes at the expense of latency, the time required to send a message from one point to another.
The TCP breaks a stream of data into TCP segments, each of which includes a portion of the data preceded by a header that contains sequence and state information to support reliable, ordered transmission of data. Some TCP segments do not include data at all, but instead establish or terminate a connection between two computers.
Establishing a connection between two computers A and B proceeds in three steps:
After this three-step "handshake", the TCP connection is established, and A and B can send data to each other. Terminating a TCP connection proceeds as a sequence of steps in which both the client and server request and acknowledge the end of the connection.
The client/server architecture is a way to dispense a service from a central source. A server provides a service and multiple clients communicate with the server to consume that service. In this architecture, clients and servers have different roles. The server's role is to respond to service requests from clients, while a client's role is to issue requests and make use of the server's response in order to perform some task. The diagram below illustrates the architecture.
The most influential use of the model is the modern World Wide Web. When a web browser displays the contents of a web page, several programs running on independent computers interact using the client/server architecture. This section describes the process of requesting a web page in order to illustrate central ideas in client/server distributed systems.
Roles. The web browser application on a Web user's computer has the role of the client when requesting a web page. When requesting the content from a domain name on the Internet, such as, it must communicate with at least two different servers.
The client first requests the Internet Protocol (IP) address of the computer located at that name from a Domain Name Server (DNS). A DNS provides the service of mapping domain names to IP addresses, which are numerical identifiers of machines on the Internet. Python can make such a request directly using the socket module.
>>> from socket import gethostbyname >>> gethostbyname('') '170.149.172.130'
The client then requests the contents of the web page from the web server located at that IP address. The response in this case is an HTML document that contains headlines and article excerpts of the day's news, as well as expressions that indicate how the web browser client should lay out that contents on the user's screen. Python can make the two requests required to retrieve this content using the urllib.request module.
>>> from urllib.request import urlopen >>> response = urlopen('').read() >>> response[:15] b'<!DOCTYPE html>'
Upon receiving this response, the browser issues additional requests for images, videos, and other auxiliary components of the page. These requests are initiated because the original HTML document contains addresses of additional content and a description of how they embed into the page.
An HTTP Request. The Hypertext Transfer Protocol (HTTP) is a protocol implemented using TCP that governs communication for the World Wide Web (WWW). It assumes a client/server architecture between a web browser and a web server. HTTP specifies the format of messages exchanged between browsers and servers. All web browsers use the HTTP format to request pages from a web server, and all web servers use the HTTP format to send back their responses.
HTTP requests have several types, the most common of which is a GET request for a specific web page. A GET request specifies a location. For instance, typing the address into a web browser issues an HTTP GET request to port 80 of the web server at en.wikipedia.org for the contents at location /wiki/UC_Berkeley.
The server sends back an HTTP response: text 200 OK indicates that there were no errors in responding to the request. The subsequent lines of the header give information about the server, the date, and the type of content being sent back.
If you have typed in a wrong web address, or clicked on a broken link, you may have seen a message such as this error:
404 Error File Not Found
It means that the server sent back an HTTP header that started:
HTTP/1.1 404 Not Found
The numbers 200 and 404 are HTTP response codes..
Modularity. The concepts of client and server are powerful abstractions. A server provides a service, possibly to multiple clients simultaneously, and a client consumes that service. The clients do not need to know the details of how the service is provided, or how the data they are receiving is stored or calculated, and the server does not need to know how its responses. In addition, the central processing unit (CPU) and the specialized graphical processing unit (GPU) often participate in a client/server architecture with the CPU as the client and the GPU as a server of images.
A drawback of client/server systems is that the server is a single point of failure. It is the only component with the ability to dispense the service. There can be any number of clients, which are interchangeable and can come and go as necessary.
Another drawback of client-server systems is that computing resources become scarce if there are too many clients. Clients increase the demand on the system without contributing any computing resources. transmitted through a peer-to-peer network. This network is composed of other computers running the Skype application. when users enter and exit.
Distributed mapreduce mapreduce import group_values_by_key, emit for key, value_iterator in group_values_by_key(sys.stdin): emit(key, sum(value_iterator))
The mapreduce mapreduce.py run count_vowels_mapper.py sum_reducer.py [input] [output]
where [input] and [output] are directories in the Hadoop file system.
For more information on the Hadoop streaming interface and use of the system, consult the Hadoop Streaming Documentation.
From the 1970s through the mid-2000s, the speed of individual processor cores grew at an exponential rate. Much of this increase in speed was accomplished by increasing the clock frequency, the rate at which a processor performs basic operations. In the mid-2000s, however, this exponential increase came to an abrupt end, due to power and thermal constraints, and the speed of individual processor cores has increased much more slowly since then. Instead, CPU manufacturers began to place multiple cores in a single processor, enabling more operations to be performed concurrently.
Parallelism is not a new concept. Large-scale parallel machines have been used for decades, primarily for scientific computing and data analysis. Even in personal computers with a single processor core, operating systems and interpreters have provided the abstraction of concurrency. This is done through context switching, or rapidly switching between different tasks without waiting for them to complete. Thus, multiple programs can run on the same machine concurrently, even if it only has a single processing core.
Given the current trend of increasing the number of processor cores, individual applications must now take advantage of parallelism in order to run faster. Within a single program, computation must be arranged so that as much work can be done in parallel as possible. However, parallelism introduces new challenges in writing correct code, particularly in the presence of shared, mutable state.
For problems that can be solved efficiently in the functional model, with no shared mutable state, parallelism poses few problems. Pure functions provide referential transparency, meaning that expressions can be replaced with their values, and vice versa, without affecting the behavior of a program. This enables expressions that do not depend on each other to be evaluated in parallel. As discussed in the previous section, the MapReduce framework allows functional programs to be specified and run in parallel with minimal programmer effort.
Unfortunately, not all problems can be solved efficiently using functional programming. The Berkeley View project has identified thirteen common computational patterns in science and engineering, only one of which is MapReduce. The remaining patterns require shared state.
In the remainder of this section, we will see how mutable shared state can introduce bugs into parallel programs and a number of approaches to prevent such bugs. We will examine these techniques in the context of two applications, a web crawler and a particle simulator.
Before we dive deeper into the details of parallelism, let us first explore Python's support for parallel computation. Python provides two means of parallel execution: threading and multiprocessing.
Threading. In threading, multiple "threads" of execution exist within a single interpreter. Each thread executes code independently from the others, though they share the same data. However, the CPython interpreter, the main implementation of Python, only interprets code in one thread at a time, switching between them in order to provide the illusion of parallelism. On the other hand, operations external to the interpreter, such as writing to a file or accessing the network, may run in parallel.
The threading module contains classes that enable threads to be created and synchronized. The following is a simple example of a multithreaded program:
>>> import threading >>> def thread_hello(): other = threading.Thread(target=thread_say_hello, args=()) other.start() thread_say_hello()
>>> def thread_say_hello(): print('hello from', threading.current_thread().name)
>>> thread_hello() hello from Thread-1 hello from MainThread
The Thread constructor creates a new thread. It requires a target function that the new thread should run, as well as the arguments to that function. Calling start on a Thread object marks it ready to run. The current_thread function returns the Thread object associated with the current thread of execution.
In this example, the prints can happen in any order, since we haven't synchronized them in any way.
Multiprocessing. Python also supports multiprocessing, which allows a program to spawn multiple interpreters, or processes, each of which can run code independently. These processes do not generally share data, so any shared state must be communicated between processes. On the other hand, processes execute in parallel according to the level of parallelism provided by the underlying operating system and hardware. Thus, if the CPU has multiple processor cores, Python processes can truly run concurrently.
The multiprocessing module contains classes for creating and synchronizing processes. The following is the hello example using processes:
>>> import multiprocessing >>> def process_hello(): other = multiprocessing.Process(target=process_say_hello, args=()) other.start() process_say_hello()
>>> def process_say_hello(): print('hello from', multiprocessing.current_process().name)
>>> process_hello() hello from MainProcess >>> hello from Process-1
As this example demonstrates, many of the classes and functions in multiprocessing are analogous to those in threading. This example also demonstrates how lack of synchronization affects shared state, as the display can be considered shared state. Here, the interpreter prompt from the interactive process appears before the print output from the other process.
In some cases, access to shared data need not be synchronized, if concurrent access cannot result in incorrect behavior. The simplest example is read-only data. Since such data is never mutated, all threads will always read the same values regardless when they access the data.
In rare cases, shared data that is mutated may not require synchronization. However, understanding when this is the case requires a deep knowledge of how the interpreter and underlying software and hardware work. Consider the following example:
items = [] flag = [] def consume(): while not flag: pass print('items is', items) def produce(): consumer = threading.Thread(target=consume, args=()) consumer.start() for i in range(10): items.append(i) flag.append('go') produce()
Here, the producer thread adds items to items, while the consumer waits until flag is non-empty. When the producer finishes adding items, it adds an element to flag, allowing the consumer to proceed.
In most Python implementations, this example will work correctly. However, a common optimization in other compilers and interpreters, and even the hardware itself, is to reorder operations within a single thread that do not depend on each other for data. In such a system, the statement flag.append('go') may be moved before the loop, since neither depends on the other for data. In general, you should avoid code like this unless you are certain that the underlying system won't reorder the relevant operations.
The simplest means of synchronizing shared data is to use a data structure that provides synchronized operations. The queue module contains a Queue class that provides synchronized first in, first out access to data. The put method adds an item to the Queue, and the get method retrieves an item. The class itself ensures that these methods are synchronized, so items are not lost no matter how thread operations are interleaved. Here is a producer/consumer example that uses a Queue:
from queue import Queue queue = Queue() def synchronized_consume(): while True: print('got an item:', queue.get()) queue.task_done() def synchronized_produce(): consumer = threading.Thread(target=synchronized_consume, args=()) consumer.daemon = True consumer.start() for i in range(10): queue.put(i) queue.join() synchronized_produce()
There are a few changes to this code, in addition to the Queue and get and put calls. We have marked the consumer thread as a daemon, which means that the program will not wait for that thread to complete before exiting. This allows us to use an infinite loop in the consumer. However, we do need to ensure that the main thread exits, but only after all items have been consumed from the Queue. The consumer calls the task_done method to inform the Queue that it is done processing an item, and the main thread calls the join method, which waits until all items have been processed, ensuring that the program exits only after that is the case.
A more complex example that makes use of a Queue is a parallel web crawler that searches for dead links on a website. This crawler follows all links that are hosted by the same site, so it must process a number of URLs, continually adding new ones to a Queue and removing URLs for processing. By using a synchronized Queue, multiple threads can safely add to and remove from the data structure concurrently.
When a synchronized version of a particular data structure is not available, we have to provide our own synchronization. A lock is a basic mechanism to do so. It can be acquired by at most one thread, after which no other thread may acquire it until it is released by the thread that previously acquired it.
In Python, the threading module contains a Lock class to provide locking. A Lock has acquire and release methods to acquire and release the lock, and the class guarantees that only one thread at a time can acquire it. All other threads that attempt to acquire a lock while it is already being held are forced to wait until it is released.
For a lock to protect a particular set of data, all the threads need to be programmed to follow a rule: no thread will access any of the shared data unless it owns that particular lock. In effect, all the threads need to "wrap" their manipulation of the shared data in acquire and release calls for that lock.
In the parallel web crawler, a set is used to keep track of all URLs that have been encountered by any thread, so as to avoid processing a particular URL more than once (and potentially getting stuck in a cycle). However, Python does not provide a synchronized set, so we must use a lock to protect access to a normal set:
seen = set() seen_lock = threading.Lock() def already_seen(item): seen_lock.acquire() result = True if item not in seen: seen.add(item) result = False seen_lock.release() return result
A lock is necessary here, in order to prevent another thread from adding the URL to the set between this thread checking if it is in the set and adding it to the set. Furthermore, adding to a set is not atomic, so concurrent attempts to add to a set may corrupt its internal data.
In this code, we had to be careful not to return until after we released the lock. In general, we have to ensure that we release a lock when we no longer need it. This can be very error-prone, particularly in the presence of exceptions, so Python provides a with compound statement that handles acquiring and releasing a lock for us:
def already_seen(item): with seen_lock: if item not in seen: seen.add(item) return False return True
The with statement ensures that seen_lock is acquired before its suite is executed and that it is released when the suite is exited for any reason. (The with statement can actually be used for operations other than locking, though we won't cover alternative uses here.)
Operations that must be synchronized with each other must use the same lock. However, two disjoint sets of operations that must be synchronized only with operations in the same set should use two different lock objects to avoid over-synchronization.
Another way to avoid conflicting access to shared data is to divide a program into phases, ensuring that shared data is mutated in a phase in which no other thread accesses it. A barrier divides a program into phases by requiring all threads to reach it before any of them can proceed. Code that is executed after a barrier cannot be concurrent with code executed before the barrier.
In Python, the threading module provides a barrier in the form of the the wait method of a Barrier instance:
counters = [0, 0] barrier = threading.Barrier(2) def count(thread_num, steps): for i in range(steps): other = counters[1 - thread_num] barrier.wait() # wait for reads to complete counters[thread_num] = other + 1 barrier.wait() # wait for writes to complete def threaded_count(steps): other = threading.Thread(target=count, args=(1, steps)) other.start() count(0, steps) print('counters:', counters) threaded_count(10)
In this example, reading and writing to shared data take place in different phases, separated by barriers. The writes occur in the same phase, but they are disjoint; this disjointness is necessary to avoid concurrent writes to the same data in the same phase. Since this code is properly synchronized, both counters will always be 10 at the end.
The multithreaded particle simulator uses a barrier in a similar fashion to synchronize access to shared data. In the simulation, each thread owns a number of particles, all of which interact with each other over the course of many discrete timesteps. A particle has a position, velocity, and acceleration, and a new acceleration is computed in each timestep based on the positions of the other particles. The velocity of the particle must be updated accordingly, and its position according to its velocity.
As with the simple example above, there is a read phase, in which all particles' positions are read by all threads. Each thread updates its own particles' acceleration in this phase, but since these are disjoint writes, they need not be synchronized. In the write phase, each thread updates its own particles' velocities and positions. Again, these are disjoint writes, and they are protected from the read phase by barriers.
A final mechanism to avoid improper mutation of shared data is to entirely avoid concurrent access to the same data. In Python, using multiprocessing rather than threading naturally results in this, since processes run in separate interpreters with their own data. Any state required by multiple processes can be communicated by passing messages between processes.
The Pipe class in the multiprocessing module provides a communication channel between processes. By default, it is duplex, meaning a two-way channel, though passing in the argument False results in a one-way channel. The send method sends an object over the channel, while the recv method receives an object. The latter is blocking, meaning that a process that calls recv will wait until an object is received.
The following is a producer/consumer example using processes and pipes:
def process_consume(in_pipe): while True: item = in_pipe.recv() if item is None: return print('got an item:', item) def process_produce(): pipe = multiprocessing.Pipe(False) consumer = multiprocessing.Process(target=process_consume, args=(pipe[0],)) consumer.start() for i in range(10): pipe[1].send(i) pipe[1].send(None) # done signal process_produce()
In this example, we use a None message to signal the end of communication. We also passed in one end of the pipe as an argument to the target function when creating the consumer process. This is necessary, since state must be explicitly shared between processes.
The multiprocess version of the particle simulator uses pipes to communicate particle positions between processes in each timestep. In fact, it uses pipes to set up an entire circular pipeline between processes, in order to minimize communication. Each process injects its own particles' positions into its pipeline stage, which eventually go through a full rotation of the pipeline. At each step of the rotation, a process applies forces from the positions that are currently in its own pipeline stage on to its own particles, so that after a full rotation, all forces have been applied to its particles.
The multiprocessing module provides other synchronization mechanisms for processes, including synchronized queues, locks, and as of Python 3.3, barriers. For example, a lock or a barrier can be used to synchronize printing to the screen, avoiding the improper display output we saw previously.
While synchronization methods are effective for protecting shared state, they can also be used incorrectly, failing to accomplish the proper synchronization, over-synchronizing, or causing the program to hang as a result of deadlock.
Under-synchronization. A common pitfall in parallel computing is to neglect to properly synchronize shared accesses. In the set example, we need to synchronize the membership check and insertion together, so that another thread cannot perform an insertion in between these two operations. Failing to synchronize the two operations together is erroneous, even if they are separately synchronized.
Over-synchronization. Another common error is to over-synchronize a program, so that non-conflicting operations cannot occur concurrently. As a trivial example, we can avoid all conflicting access to shared data by acquiring a master lock when a thread starts and only releasing it when a thread completes. This serializes our entire code, so that nothing runs in parallel. In some cases, this can even cause our program to hang indefinitely. For example, consider a consumer/producer program in which the consumer obtains the lock and never releases it. This prevents the producer from producing any items, which in turn prevents the consumer from doing anything since it has nothing to consume.
While this example is trivial, in practice, programmers often over-synchronize their code to some degree, preventing their code from taking complete advantage of the available parallelism.
Deadlock. Because they cause threads or processes to wait on each other, synchronization mechanisms are vulnerable to deadlock, a situation in which two or more threads or processes are stuck, waiting for each other to finish. We have just seen how neglecting to release a lock can cause a thread to get stuck indefinitely. But even if threads or processes do properly release locks, programs can still reach deadlock.
The source of deadlock is a circular wait, illustrated below with processes. No process can continue because it is waiting for other processes that are waiting for it to complete.
As an example, we will set up a deadlock with two processes. Suppose they share a duplex pipe and attempt to communicate with each other as follows:
def deadlock(in_pipe, out_pipe): item = in_pipe.recv() print('got an item:', item) out_pipe.send(item + 1) def create_deadlock(): pipe = multiprocessing.Pipe() other = multiprocessing.Process(target=deadlock, args=(pipe[0], pipe[1])) other.start() deadlock(pipe[1], pipe[0]) create_deadlock()
Both processes attempt to receive data first. Recall that the recv method blocks until an item is available. Since neither process has sent anything, both will wait indefinitely for the other to send it data, resulting in deadlock.
Synchronization operations must be properly aligned to avoid deadlock. This may require sending over a pipe before receiving, acquiring multiple locks in the same order, and ensuring that all threads reach the right barrier at the right time.
As we have seen, parallelism presents new challenges in writing correct and efficient code. As the trend of increasing parallelism at the hardware level will continue for the foreseeable future, parallel computation will become more and more important in application programming. There is a very active body of research on making parallelism easier and less error-prone for programmers. Our discussion here serves only as a basic introduction to this crucial area of computer science. | http://inst.eecs.berkeley.edu/~cs61a/book/chapters/streams.html | CC-MAIN-2015-40 | refinedweb | 9,362 | 54.63 |
[Solved]Python Relay Expansion help
This post is deleted!
- SYLVAIN MAILHIOT
Is your expansion working if you use the console ?
- Lazar Demin administrators
@Rudy-Trujillo
To install everything required:
opkg update opkg install python-light pyRelayExp
And here is a short script that just tests the functionality:
from OmegaExpansion import relayExp import time import sys # check the arguments if len(sys.argv) != 2: print 'ERROR: expected addr offset:' print sys.argv[0], '<addr offset>' exit() addr = int(sys.argv[1]) print 'Starting to use relay-exp functions on addr offset', addr relayExp.setVerbosity(0) # check initialization ret = relayExp.checkInit(addr) print "checking if initialized: ", ret # initialize the relay-exp ret = relayExp.driverInit(addr) print "Result from relayDriverInit: ", ret if (ret != 0): exit() # check initialization ret = relayExp.checkInit(addr) print "checking if initialized: ", ret time.sleep(1) # set channel 0 to on ret = relayExp.setChannel(addr, 0, 1) print "Result from relaySetChannel: ", ret if (ret != 0): exit() time.sleep(2) # set both channels to on ret = relayExp.setAllChannels(addr, 1) print "Result from relaySetAllChannels: ", ret if (ret != 0): exit() time.sleep(2) # set channel 0 to off ret = relayExp.setChannel(addr, 0, 0) print "Result from relaySetChannel: ", ret if (ret != 0): exit() time.sleep(2) print "Done"
I'll post examples for all three modules later this week!
EDIT: Note that the address argument that specifies the offset to add to the base address of 0x20. Follow the address table on the Wiki.
This post is deleted!
- Lazar Demin administrators
@Rudy-Trujillo
Once the Relay Expansion hardware is initialized once, it will remain initialized. I'm guessing the screenshot above was not from the first time the script was ran? If that's the case, everything seems to be running correctly.
(You can make the
driverInitcall dependant on the
checkInitreturn value to avoid unnecessary initialization in your real program)
Here's my output when I run it right after plugging in the Relay Expansion:
root@Omega-18C2:~# python relay-test.py 7 Starting to use relay-exp functions on addr offset 7 checking if initialized: 0 > Initializing Relay Expansion chip Result from relayDriverInit: 0 checking if initialized: 1 > Setting RELAY0 to ON Result from relaySetChannel: 0 > Setting both RELAYS to ON Result from relaySetAllChannels: 0 > Setting RELAY0 to OFF Result from relaySetChannel: 0 Done
In general, the functions return 0 to indicate success and 1 to indicate failure. The
checkInitfunction is special, take a look at this section from the Relay Expansion Library wiki for more info.
This post is deleted!
- Lazar Demin administrators
Small Update:
Example python code has been added to the i2c-exp-driver repo.
The examples are also linked in the wiki articles for the Relay, PWM, and OLED Libraries.
Edit: Updated the links
- Stephen Tunney
@Lazar-Demin
Your link to the address table on the Wiki is a dead link. Can you update it please?
- Kit Bishop
@Stephen-Tunney I may be wrong, but I think the link(s) you are looking for in relation to Relay, PWM and OLED python libraries are:
- Stephen Tunney
Awesomesauce!!! :) Thank you, @Kit-Bishop. | http://community.onion.io/topic/450/solved-python-relay-expansion-help | CC-MAIN-2018-26 | refinedweb | 514 | 50.33 |
Related to: 2L2T: DjangoCon Feedback, Deploying Python Applications with Docker – A Suggestion, Deploying With Docker, Software You Can Use
I have tried to make an example of some of the ways to avoid mistakes with BoredBot. Hopefully the README explains the problem domain and motivation, but here is the tl;dr:
Deploying applications is a place where it is possible to do things badly, amazingly badly and “oh God!”. I hope to slightly improve on this consensus with the current state of 2015 technology and get to “well, ok, this does not suck too much”. BoredBot is basically my attempt to show how combining NaCl, NColony, Pex and Docker can get you to a simple image which can be deployed to Amazon ECS, Google Container Engine or your own Docker servers without too much trouble.
There is still a lot BoredBot doesn’t do that I think any good deployment infrastructure should support — staging vs. production, dry-run mode, etc. Pull requests and issues are happily accepted!
I have decided it is time to make a new personal calling card for myself. Please let me know what you think! I am reasonably sure that I’m not the only person, but one of a small number of people, who actually unit-tested their card: yep, the code is valid Python and will actually print the right details (if you “pip install attrs”, of course).
Back:
Front:
Below spoilers for the Kushiel’s Legacy books (first trilogy). If you have not read them, I highly recommend reading before looking below — they are pretty awesome. Technically, there are also spoilers for Lord of the Rings, though if you have not read it by now, I don’t know what else to do.
I want to start by talking about Lord of the Rings. As everyone knows, it tells the story of the failed attempt of the dwarves to restore their ancient homeland in a retrospective. I think they had a side-plot about a couple of short guys throwing a ring into a mountain or something? Anyway, back to the main point of LotR: the dwarves. The story of a people who everyone thinks of as just being greedy, master of goldsmithing and gem cutting, but with the desire to return to a homeland — but who wake an ancient evil upon returning there. Though Tolkien maintained he was not into allegories, this one is a pretty thin facade for talking about the struggles of the Jewish people. The reason for this long introduction to LotR is to explain how I read books: parochially, maybe, if they have Jews in them, the Jewish plot lines stir my heart much more than the story the author tried to write.
Well, I have to say, Jacqueline Carey knows how to write Jews. Admittedly, it took me until the end of Kushiel’s Dart to figure out that the Yeshuites were not supposed to be Jesuits. They are really an interesting take on Jews for Jesus. In a world that lacked Christianity, since Elua and his followers took on the role of taking down the Roman (“Tiberian”) empire, there are no evangelical religions. The Jews end up accepting Jesus as the “Mashiach” (not “Christ”, since the Romans aren’t there to take over the terms), and keep being…pretty Jewish. They are discriminated against in a heart-touching manner in Venice (ok, “La Serenissima”) and, like every good Jews, have fierce arguments about restoring their homeland. Near as I can tell, judging from estimated geography, they decide to make their homeland in Switzerland? Or maybe Lichtenstein? Belgium? Netherlands? In any case, the more devout, as always, pray for salvation while the younger and more practically minded take up the sword, and head up north to make a place where they will be free from discrimination.
All the while, the Jews in the Kushielverse keep studying the Talmud, and the more mystical minded of them take up something suspiciously like Qabbalah and seek the true name of God. They speak “Habiru” among each other, and have stories of the lost tribes. That’s, of course, the most awesome parts — the ten tribes have a “Judaism without Jesus” (what we would call, well, Judaism) since they have not heard of him having been sequestered in…Uganda. I, well, I certainly appreciate the subtle humor there.
[Please note that as far as I know, the author really intended the Yeshuites to add color to the religions in the Kushielverse, and actually fairly little of the plotline involves them — it is really the story of a masochist prostitute in a country where not being polyamorous is a blasphemy…]
Fixed:
Mostly internal cleanup release: running scripts is now nicer (all through “python -m ncolony <command>”), added Code of Conduct, releasing based on versioneer, cleaned up tox.ini, added HTTP healthchecker.
Available via PyPI and GitHub!
I don’t like console-scripts. Among what I dislike is their magicality and the actual code produced. I mean, the autogenerated Python looks like:
#!/home/moshez/src/mainland/build/toxenv/bin/python2 # -*- coding: utf-8 -*- import re import sys from tox import cmdline if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(cmdline())
Notice the encoding header for an ASCII only file, and the weird windows compatibility maybe generated along with a unix-style header that also contains the name of the path? Truly, a file that only its generator could love.
Then again, I don’t much like what we have in Twisted, with the preamble:
#!/home/moshez/src/ncolony/build/env/bin/python2 # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. import os, sys try: import _preamble except ImportError: sys.exc_clear() sys.path.insert(0, os.path.abspath(os.getcwd())) from twisted.scripts.twistd import run run()
This time, it’s not auto-generated, it is artisanal. What it lacks in codegen ugliness it makes up in importing an under-module at top-level, and who doesn’t like a little bit of sys.path games?
I will note that furthermore, neither of these options would play nice with something like pex. Worst of all, all of these options, regardless of their internal beauty (or horrible lack thereof), must be named veeeeery caaaaarefully to avoid collision with existing UNIX, Mac or Windows command. Think this is easy? My Ubuntu has two commands called “chromium-browser” and “chromium-bsu” because Google didn’t check what popular games there are on Ubuntu before naming their browser.
Enter the best thing about Python, “-m” which allows executing modules. What “-m” gains in awesomeness, it loses in the horribleness of the two-named-module, where a module is executed twice, once resulting in sys.modules[‘__main__’] and once in sys.modules[real_name], with hilarious consequences for class hierarchies, exceptions and other things relying on identity of defined things.
Luckily, packages will automatically execute “package.__main__” if “python -m package” is called. Ideally, nobody would try to import __main__, but this means packages can contain only one command. Enter ‘mainland‘, which defines a main which will, carefully and accurately, dispatch to the right module’s main without any code generation. It has not been released yet, but is available from GitHub. Pull requests and issues are happily accepted!
Edit: Released! 0.0.1 is up on PyPI and on GitHub
Related: In Favor of Niceness, Community, and Civilization
I’ve seen elsewhere (thankfully, not my project, and no, I won’t link to it) that people want the code of conduct to “protect contributors from 3rd parties as well as 3rd parties from contributors. I would like to first suggest the idea that this is…I don’t even know. The US government has literal nuclear bombs, as well as aircraft carriers, and it cannot enforce its law everywhere. The idea that an underfunded OSS project can do literally anything to 3rd parties is ludicrous. The only enforcement mechanism any project can have is “you can’t contribute here” (which, by necessity, only applies to those who wanted to contribute in the first place.)
So why would a bunch of people take on a code of conduct that will only limit them?
Because, to quote the related article above, “the death cry of liberalism is not ‘death to the unbelievers’, it is ‘if you’re nice, you can join our cuddle pile.” Perhaps describing open source projects as “cuddle piles” is somewhat of an exaggeration, but the point remains. A code of conduct defines what “nice enough is”. The cuddle piles? Those conquer the world. WebKit is powering both Android and iPhone browsers, for example, making open source be, literally, the way people see the online world.
Adopting a code of conduct that says that we do not harass, we do not retaliate and we accept all people is a powerful statement. This is how we keep our own garden clear of the pests of prejudice, of hatred. Untended gardens end up wilderness. Well-tended gardens grow until we need to keep a fence around the wild and call it a “preserve”.
When I first saw the Rust code of conduct I thought “cool, but why does an open source project need a code of conduct”? Now I wonder how any open source project will survive without one. It will have to survive without me — in three years, I commit to not contribute to any project without a code of conduct, and I hope others will follow. Any project that does not have a CoC, in the interim, better behave as though it has one.
Twisted is working hard on adopting a code of conduct, and I will check one into NColony soon (a simpler one, appropriate to what is, so far, a one-person show).
(Or, “So you want to build a new open-source Python project”)
This is not going to be a “here is a list of options, but you do what is right for you” pandering post. This is going to be a “this is 2015, there are right ways to do things, and here they are” post. This is going to be an opinionated, in-your-face, THIS IS BEST post. That said, if you think that anything here does not represent the best practices in 2015, please do leave a comment. Also, if you have specific opinions on most of these, you’re already ahead of the curve — the main target audience are people new to creating open-source Python projects, who could use a clear guide.
This post will also emphasize the new project. It is not worth it, necessarily, to switch to these things in an existing project — certainly not as a “whole-sale, stop the world and let’s change” thing. But when starting a new project with zero legacy, there is no reason to do things wrong.
tl:dr; Use GitHub, put MIT license in “LICENSE”, README.rst with badges, use py.test and coverage, flake8 for static checking, tox to run tests, package with setuptools, document with sphinx on RTD, Travis CI/Coveralls for continuous integration, SemVer and versioneer for versioning, support Py2+Py3+PyPy, avoid C extensions, avoid requirements.txt.
Where
When publishing kids’ photos, you do it on Facebook, because that’s where everybody is. LinkedIn is where you connect with colleagues and lead your professional life. When publishing projects, put them on GitHub, for exactly the same reason. Have GitHub pull requests be the way contributors propose changes. (There is no need to use the “merge” button on GitHub — it is fine to merge changes via git and push. But the official “how do I submit a change” should be “pull request”, because that’s what people know).
License
Put the license in a file called “LICENSE” at the root. If you do not have a specific reason to choose otherwise, MIT is reasonably permissive and compatible. Otherwise, use something like the license chooser and remember the three most important rules:
At the end of the license file, you can have a list of the contributors. This is an easy place to credit them. It is a good idea to ask people who send in pull requests to add themselves to the contributor list in their first one (this allows them to spell their name and e-mail exactly the way they want to).
Note that if you use the GPL or LGPL, they will recommend putting it in a file called “COPYING”. Put it in “LICENSE” (the licenses explicitly allow it as an option, and it makes it easier for people to find the license if it always has the same name).
README
The GitHub default is README.md, but README.rst (restructured text) is perfectly supported via Sphinx, and is a better place to put Python-related documentation, because ReST plays better with Pythonic toolchains. It is highly encouraged to put badges on top of the document to link to CI status (usually Travis), ReadTheDocs and PyPI.
Testing
There are several reasonably good test runners. If there is no clear reason to choose one, py.test is a good default. “Using Twisted” is a good reason to choose trial. Using the built-in unittest runner is not a good option — there is a reason the cottage industry of “test runner” evolved. Using coverage is a no-brainer. It is good to run some functional tests too. Test runners should be able to help with this too, but even writing a Python program that fails if things are not working can be useful.
Distribute your tests alongside your code, by putting them under a subpackage called “tests” of the main package. This allows people who “pip install …” to run the tests, which means sending you bug reports is a lot easier.
Static checking
There are a lot of tools for static checking of Python programs — pylint, flake8 and more. Use at least one. Using more is not completely free (more ways to have to say “ignore this, this is ok”) but can be useful to catch more style static issue. At worst, if there are local conventions that are not easily plugged into these checkers, write a Python program that will check for them and fail if those are violated.
Meta testing
Use tox. Put tox.ini at the root of your project, and make sure that “tox” (with no arguments) works and runs your entire test-suite. All unit tests, functional tests and static checks should be run using tox. It is not a bad idea to write a tox clause that builds and tests an installed wheel. This will require including all test code in the deployed package, which is a good idea.
Set tox to put all build artifacts in a build/ top-level directory.
Packaging
Have a setup.py file that uses setuptools. Tox will need it anyway to work correctly.
Structure
It is unlikely that you have a good reason to take more than one top-level name in the package namespace. Barring completely unavoidable name conflicts, your PyPI package name should be the same as your Python package name should be the same as your GitHub project. Your Python package should live at the top-level, not under “src/” or “py/”.
Documentation
Use sphinx for prose documentation. Put it in doc/ with a relevant conf.py. Use either pydoctor or sphinx autodoc for API docs. “Pydoctor” has the potential for nicer docs, sphinx is well integrated with ReadTheDocs. Configure ReadTheDocs to auto-build the documentation every check-in.
Continuous Integration
If you enjoy owning your own machines, or platform diversity in testing really matters, use buildbot. Otherwise, take advantage for free Travis CI and configure your project with a .travis.yml that breaks your tox tests into one test per Travis clause. Integrate with coveralls to have coverage monitored.
Version management
Use SemVer. Take advantage of versioneer to help you manage it.
Release
A full run of “tox” should leave in its wake tested .zip and .whl files. A successful, post-tag run of tox, combined with versioneer, should leave behind tested .zip and .whl. The release script could be as simple as “tox && git tag $1 && (tox || (git tag -d $1;exit 1) && cp …whl and zip locations… dist/”
GPG sign dist/ files, and then use “twine” to upload them to PyPI. Make sure to upload to TestPyPI first, and verify the upload, before uploading to PyPI. Twine is a great tool, but badly documented — among other things, it is hard to find information about .pypirc. “.pypirc” is an ini file, which needs to have the following sections:
.gitignore
Python versions
If all your dependencies support Python 2 and 3, support Python 2 and 3. That will almost certainly require using “six” (or one of its competitors, like “future”). Run your unit tests under both Python 2 and 3. Make sure to run your unit tests under PyPy, as well.
C extensions
Avoid, if possible. Certainly do not use C extensions for performance improvements before (1) making sure they’re needed (2) making sure they’re helpful (3) trying other performance improvements. Ideally structure your C extensions to be optional, and fall back to a slow(er) Python implementation if they are unavailable. If they speed up something more general than your specific needs, consider breaking them out into a C-only project which your Python will depend on.
If using C extensions, regardless of whether to improve performance or integrate with 3rd party libraries, use CFFI.
If C extensions have successfully been avoided, and Python 3 compatibility kept, build universal wheels.
requirements.txt
The only good “requirements.txt” file is a non-existing one. The “setup.py” file should have the dependencies (ideally as weak-versioned as possible, usually just a “>=” for a library that tends not to break backwards compatibility a lot). Tox will maintain the virtualenv needed based on the things in the tox file, and if needing to test against specific versions, this is where specific versions belong. The “requirements.txt” file belongs in Salt-style (Chef, Fab, …) configurations, Docker-style (Vagrant-, etc.) configurations or Pants-style (Buck-, etc.) build scripts when building a Pex. This is the “deployment configuration”, and needs to be decided by a deployer.
If your package has dependencies, they belong in a setup.py. Use extended_dependencies for test-only dependencies. Lists of test dependencies, and reproducible tests, can be configured in tox.ini. Tox will take care of pip-installing relevant packages in a virtualenv when running the tests.
Thanks
Thanks to John A. Booth, Dan Callahan, Robert Collins, Jack Diedrich, Steve Holden for their reviews and insightful comments. Any mistakes that remain are mine!
There are a few interesting new languages that would be fun to play with: Rust, Julia, LFE, Go and D all have interesting takes on some domain. But ultimately, a language is only as interesting as the things it can do. It used to be that “things it can do” referred to the standard library. I am old enough to remember when “batteries included” was one of the most interesting benefits Python had — the language had dared doing such avant-garde things in ’99 as having a *built-in* url fetching library. That behaved, pretty much, the same on all platform. Out of the box. (It’s hard to convey how amazing this was in ’99.)
This is no longer the case. Now what distinguishes Python as “can do lots of things” is its built-in package management. Python, pip and virtualenv together give the ability to work on multiple Python projects, that need different versions of libraries, without any interference. They are, to a first approximation, 100% reliable. With pip 7.0 supporting caching wheels, virtualenvs are even more disposable (I am starting to think pip uninstall is completely unnecessary). In fact, except for virtualenv itself, it is rare nowadays to install any Python module globally. There are some rusty corners, of course:
I’ll note npm, for example, clearly does better on these three (while doing worse on some things that Python does better). Of the languages mentioned above, it is nice to see that most have out-of-the-box built-in tools for ecosystem creation. Julia’s hilariously piggybacks on GitHub’s. Go’s…well…uses URLs as the equivalent PyPI-level-names. Rust has a pretty decent system in cargo and crates.io (the .toml file is kind of weird, but I’ve seen worse). While there is justifiable excitement about Rust’s approach to memory and thread-safety, it might be that it will win in the end based on having a better internal package management system than the low-level alternatives.
Note: OS package mgmt (yum, apt-get, brew and whatever Windows uses nowadays) is not a good fit for what developers need from a language-level package manager. Locality, quick package refreshes — these matter more to developers than to OS end-users.
Unicode is not a panacea. Some people’s names can’t even be written in unicode. However, as far as universal encodings go, it is the best we have got — warts and all. It is the only reasonable way to represent text inside programs, except for very very specialized needs (no, you don’t qualify).
Now, programs are made of libraries, and often there are several layers of abstraction between the library and the program. Sometimes, some weird abstraction layer in the middle will make it hard to convey user configuration into the library’s guts. Code should figure things out itself, most of the time.
So, there are several ways to make dealing with unicode not-horrible.
Unicode internally
I’ve already mentioned it, but it bears repeating. Internal representation should use the language’s built-in type (str in Python 3, String in Java, unicode in Python 2). All formatting, templating, etc. should be, internally, represented as taking unicode parameters and returning unicode results.
Standards
Obviously, when interacting with an external protocol that allows the other side to specify encoding, follow the encoding it specifies. Your program should support, at least, UTF-8, UTF-16, UTF-32 and Latin-1 through Latin-9. When choosing output encoding, choose UTF-8 by default. If there is some way for the user to specify an encoding, allow choosing between that and UTF-16. Anything else should be under “Advanced…” or, possibly, not at all.
Non-standards
When reading input that is not marked with an encoding, attempt to decode as UTF-8, then as UTF-16 (most UTF-16 decoders will auto-detect endianity, but it is pretty easy to hand-hack if people put in the BOM. UTF-8/16 are unlikely to have false positives, so if either succeeds, it’s likely correct. Otherwise, as-ASCII-and-ignore-high-order is often the best that can be done. If it is reasonable, allow user-intervention in specifying the encoding.
When writing output, the default should be UTF-8. If it is non-trivial to allow user specification of the encoding, that is fine. If it is possible, UTF-16 should be offered (and BOM should be prepended to start-of-output). Other encodings are not recommended if there is no way to specify them: the reader will have to guess correctly. At the least, giving the user such options should be hidden behind an “Advanced…” option.
The most popular I/O that does not have explicit encoding, or any way to specify one, is file names on UNIX systems. UTF-8 should be assumed, and reasonably recovered from when it proves false. No other encoding is reasonable (UTF-16 is uniquely unsuitable since UNIX filenames cannot have NULs, and other encodings cannot encode some characters).
I’m running the ncolony tests with pypy so I can add PyPy support. I expected it to be a no-op — but turned out I have ingrained expectations that are no longer true: moreover, PyPy is right, and I’m wrong.
That was it! It was actually a pleasant experience :) | https://moshez.wordpress.com/feed/atom/ | CC-MAIN-2015-48 | refinedweb | 4,025 | 63.49 |
The project is implemented in Python using Tensorflow.
It is a word-based Recurrent neural network (RNN) inspired by this Tensorflow tutorial.
The model is trained in a corpus containing the song titles and the lyrics of many famous songs of Beatles.
So, given a sequence of words from Beatles' lyrics, it can predict the next words.
We could say that it is a model generating Beatle-like lyrics.
The corpus (aka training dataset)
As we said the corpus (beatles_lyrics.txt) contains the song titles and the lyrics of many Beatles songs in the following format:
Song title 1 ----------------- Lyric line 1 Lyric line 2 Lyric line 3 Lyric line 4 etc... Song title 2 ----------------- Lyric line 1 Lyric line 2 Lyric line 3 Lyric line 4 etc... etc...
I have manually created the corpus with the lyrics I found in this amazing site
Data preprocessing
As almost every machine learning model, training data need a bit of preprocessing before they are ready to be used as a training input for our RNN.
We preprocess the initial corpus by doing the following tasks:
- Convert all letters to lowercase
- Remove blank lines
- Remove special characters (such as ',' , '(' , ')' , '[' , ']' etc)
The following function performs the preprocessing:
stopChars = [',','(',')','.','-','[',']','"'] # preprocessing the corpus by converting all letters to lowercase, # replacing blank lines with blank string and removing special characters def preprocessText(text): text = text.replace('\n', ' ').replace('\t','') processedText = text.lower() for char in stopChars: processedText = processedText.replace(char,'') return processedText
After the text preprocessing step, we need to convert it to a list of words.
This procedure is also known as "Tokenization".
The following function performs the tokenization:
def corpusToList(corpus): corpusList = [w for w in corpus.split(' ')] corpusList = [i for i in corpusList if i] #removing empty strings from list return corpusList
Then, we trim each word for leading or trailing spaces / tabs.
map(str.strip, corpus_words) # trim words
Now, it is time to find the unique words (aka vocabulary) from which our dataset is composed of.
vocab = sorted(set(corpus_words))
In order to train our model, we need to represent words with numbers. So we map a specific number to each unique word of our corpus and vice versa by creating the following lookup tables. Then we represent the whole corpus as a list of numbers (
word_as_int).
print('Corpus length (in words):', len(corpus_words)) print('Unique words in corpus: {}'.format(len(vocab))) word2idx = {u: i for i, u in enumerate(vocab)} idx2words = np.array(vocab) word_as_int = np.array([word2idx[c] for c in corpus_words])
The prediction process
Our goal is to predict the next words that will follow in a sequence, given some starting words (a start sequence).
In layman's terms, RNNs are able to maintain an internal state that depends on the elements (in our case elements = sequences of words) that the RNN has previously "seen".
So, we train the RNN to take as an input a sequence of words and predict the output, which is the following word at each time step. As you can easily understand, if we run the model for many time steps we generate sequences of words!
In order to train it, we have to split our train dataset (aka corpus) in "batches" of sequences of words (as this is what we also want to predict). Then, we need to shuffle them, because we want to make the order with which the songs have been placed in the dataset indifferent for the RNN (and thus for the prediction it will do). If we do not shuffle them, RNN may learn the order of the songs in the corpus to and that may lead it to overfitting
Creating training batches
Now it is time to slice the corpus into training batches. Each batch should contain
seqLength words from the corpus.
For each split sequence of words, there is also a target sequence which has the same length as the training one and it is the same but one word shifted to the right. So, we slice the text into
seqLength+1 words slices and we use the first
seqLength words as training sequence and we extract the target sequence as mentioned.
Example:
Let's say our corpus contains the following verse:
I read the news today oh boy About a lucky man who made the grade
Now, if the seqLength is 14, the training sequence will be :
I read the news today oh boy About a lucky man who made the
and the target sequence will be:
read the news today oh boy About a lucky man who made the grade.
We do so with the following lines:
# The maximum length sentence we want for a single input in words seqLength = 10 examples_per_epoch = len(corpus_words)//(seqLength + 1) # number of seqLength+1 sequences in the corpus # Create training / targets batches wordDataset = tf.data.Dataset.from_tensor_slices(word_as_int) sequencesOfWords = wordDataset.batch(seqLength + 1, drop_remainder=True) # generating batches of 10 words each, typically converting list of words (sequence) to string def split_input_target(chunk): # This is where right shift happens input_text = chunk[:-1] target_text = chunk[1:] return input_text, target_text # returns training and target sequence for each batch dataset = sequencesOfWords.map(split_input_target) # dataset now contains a training and a target sequence for each 10 word slice of the corpus
Shuffling the batches
As we mentioned earlier, before we feed our training batches in our RNN, we have to shuffle them to prevent the RNN from learning the order of the songs in the corpus which may lead it to overfitting.
BATCH_SIZE = 64 # each batch contains 64 sequences. Each sequence contains 10 words (seqLength) BUFFER_SIZE = 100 # Number of batches that will be processed concurrently dataset = dataset.shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True)
dataset now contains batches of 64 word sequence each, each sequence is filled in the previous step with 10 words.
The model
Our RNN is composed of 3 layers:
- Input layer. It maps the number representing each word to a vector with known dimensions (that are explicitly set)
- GRU (middle) layer: GRU stands for Gated Recurrent Units. The number of units that this layer contains is also explicitly set. This layer could also be replaced by a Long Short-Term Memory (LSTM) layer. More on LSTMs and GRUs in this useful link
- Output layer: It has as many units as the size of the vocabulary
The model definition code:
# Length of the vocabulary in words vocab_size = len(vocab) # The embedding dimension embedding_dim = 256 # Number of GRU units rnn_units = 1024 def createModel(vocab_size, embedding_dim, rnn_units, batch_size): model = tf.keras.Sequential([ tf.keras.layers.Embedding(vocab_size, embedding_dim, batch_input_shape=[batch_size, None]), tf.keras.layers.GRU(rnn_units, return_sequences=True, stateful=True, recurrent_initializer='glorot_uniform'), tf.keras.layers.Dense(vocab_size) ]) return model model = createModel(vocab_size = len(vocab), embedding_dim=embedding_dim, rnn_units=rnn_units, batch_size=BATCH_SIZE)
How the RNN works
For each word in the input layer, the model passes its embedding to the GRU layer for one step of time.
The output of the GRU is then passed to the dense layer which predicts the log-likelihood of the next word.
The schematic below is a bit more descriptive.
Training the model
From now on, we can consider the problem as a simple classification problem.
If you think about it, our model predicts the "class" of the next word based on its current state and the input words during a time step.
So, as in every classification model, in order to train it we need to calculate the loss in each time step.
We do so by defining the following function:
def loss(labels, logits): return tf.keras.losses.sparse_categorical_crossentropy(labels, logits, from_logits=True)
Then we compile the model using 'adam' oprimizer.
model.compile(optimizer='adam', loss=loss)
During the training process, we should save checkpoints of the training in a directory that we have manually created
checkpoint_dir = './training_checkpoints' checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt_{epoch}") checkpoint_callback=tf.keras.callbacks.ModelCheckpoint( filepath=checkpoint_prefix, save_weights_only=True)
Now it is time to execute training.
We explicitly set the number of epochs.
At this point I would like to remind you that an epoch is one forward pass and one backward pass of all the training examples.
We choose to train for 20 epochs. Note that as you increase number of epochs, the training time will increase too.
You should experiment with this number in order to fine tune the model.
But be careful, training for too many epochs may lead to overfitting.
EPOCHS = 20 history = model.fit(dataset, epochs=EPOCHS, callbacks=[checkpoint_callback])
After the training process is over, we restore the trained model form the latest checkpoint.
It is time to generate the lyrics!
tf.train.latest_checkpoint(checkpoint_dir) model = createModel(len(vocab), embedding_dim, rnn_units, batch_size=1) model.load_weights(tf.train.latest_checkpoint(checkpoint_dir)) model.build(tf.TensorShape([1, None])) model.summary()
Generating the lyrics
RNNs (as most of Neural network types in general) need an initial state to start predicting.
In our case, this initialization is represented by a starting string with which we want the generated lyrics to start.
The model generates the probability distribution of the next word using the start string and the RNN state.
Then, with the help of categorical distribution, the index of the predicted word is calculated and the predicted word is used as the input for the next time step of the model
The state that the RNN returns is then fed back to the input of the RNN, in order to help it by providing more context (not just one word). This process continues as it generates predictions and this is why it learns better while it gets more context from the predicted words.
The following function performs the task mentioned above:
def generateLyrics(model, startString, temp): print("---- Generating lyrics starting with '" + startString + "' ----") # Number of words to generate num_generate = 30 # Converting our start string to numbers (vectorizing) start_string_list = [w for w in startString.split(' ')] input_eval = [word2idx[s] for s in start_string_list] input_eval = tf.expand_dims(input_eval, 0) text_generated = [] model.reset_states() for i in range(num_generate): predictions = model(input_eval) # remove the batch dimension predictions = tf.squeeze(predictions, 0) # temp represent how 'conservative' the predictions are. # Lower temp leads to more predictable (or correct) lyrics predictions = predictions / temp predicted_id = tf.random.categorical(predictions, num_samples=1)[-1,0].numpy() # We pass the predicted word as the next input to the model # along with the previous hidden state input_eval = tf.expand_dims([predicted_id], 0) text_generated.append(' ' + idx2words[predicted_id]) return (startString + ''.join(text_generated))
As you can see, many factors may influence the accuracy of the predictions.
temp parameter for example represents how 'conservative' the predictions are.
This means that lower temp values lead to more predictable (or correct) lyrics.
Running the model
model.py also contains a "demo part".
After the training process is finished, it saves the model in a binary file (you can then restore it in one line of code and use it instantly to predict values) for future use so we do not have to train it every time we want to generate lyrics.
#save trained model for future use (so we do not have to train it every time we want to generate text) model.save('saved_model.h5')
Then it calls the
generateLyrics function with the start string "love" (We all know how much Beatles used) this word in their songs.
Then it prompts the user to enter a start string and a temp value to generate lyrics.
Some examples that the model gave me:
Start string: "love" Generated lyrics: "love youyouyouyou as i write this letter send my love to give you all my loving i will send to you all my loving i will send to you don't bother" Start string: "boys and girls" temp: 0.4 Generated lyrics: "boys and girls make me sing and shout that georgia's always be blind love is here to stay and that's enough to make you my girl be the only one love me hold" Start string: "day" temp: 0.8 Generated lyrics: "day tripper night at my own it will take a walk on home loretta get back get back get back get back get back get back get back get back get"
`
Hm... Not that bad.
Optimizing the model
You can easily fine-tune the model by changing the variables that influence the accuracy of the predictions. Using a stopwords set with the very common words in the corpus and removing them from the training data may help the predictions as it will eliminate the noise and the features that do not offer a significant info gain.
BATCH_SIZE,
temp, embedding dimensions, sequence length can all influence the prediction and thus the generated lyrics.
You can also try to use LSTM units in the middle layer.
So you can experiment yourself and comment with the results.
Project is available on this Github Repo
Discussion (0) | https://dev.to/demetrakopetros/generating-beatles-like-lyrics-with-rnns-48ki | CC-MAIN-2021-10 | refinedweb | 2,131 | 52.29 |
What's new in Matplotlib 1.4 (Aug 25, 2014)#
Thomas A. Caswell served as the release manager for the 1.4 release.
Table of Contents
Note
matplotlib 1.4 supports Python 2.6, 2.7, 3.3, and 3.4
New colormap#
In heatmaps, a green-to-red spectrum is often used to indicate intensity of
activity, but this can be problematic for the red/green colorblind. A new,
colorblind-friendly colormap is now available at
matplotlib.cm.Wistia.
This colormap maintains the red/green symbolism while achieving deuteranopic
legibility through brightness variations. See
here
for more information.
The nbagg backend#
Phil Elson added a new backend, named "nbagg", which enables interactive figures in a live IPython notebook session. The backend makes use of the infrastructure developed for the webagg backend, which itself gives standalone server backed interactive figures in the browser, however nbagg does not require a dedicated matplotlib server as all communications are handled through the IPython Comm machinery.
As with other backends nbagg can be enabled inside the IPython notebook with:
import matplotlib matplotlib.use('nbagg')
Once figures are created and then subsequently shown, they will placed in an interactive widget inside the notebook allowing panning and zooming in the same way as any other matplotlib backend. Because figures require a connection to the IPython notebook server for their interactivity, once the notebook is saved, each figure will be rendered as a static image - thus allowing non-interactive viewing of figures on services such as nbviewer.
New plotting features#
Power-law normalization#
Ben Gamari added a power-law normalization method,
PowerNorm. This class maps a range of
values to the interval [0,1] with power-law scaling with the exponent
provided by the constructor's gamma argument. Power law normalization
can be useful for, e.g., emphasizing small populations in a histogram.
Fully customizable boxplots#
Paul Hobson overhauled the
boxplot() method such
that it is now completely customizable in terms of the styles and positions
of the individual artists. Under the hood,
boxplot()
relies on a new function (
boxplot_stats()), which
accepts any data structure currently compatible with
boxplot(), and returns a list of dictionaries
containing the positions for each element of the boxplots. Then
a second method,
bxp is called to draw the boxplots
based on the stats.
The
boxplot() function can be used as before to
generate boxplots from data in one step. But now the user has the
flexibility to generate the statistics independently, or to modify the
output of
boxplot_stats() prior to plotting
with
bxp.
Lastly, each artist (e.g., the box, outliers, cap, notches) can now be toggled on or off and their styles can be passed in through individual kwargs. See the examples: Artist customization in box plots and Boxplot drawer function
Added a bool kwarg,
manage_xticks, which if False disables the management
of the ticks and limits on the x-axis by
bxp().
Support for datetime axes in 2d plots#
Andrew Dawson added support for datetime axes to
contour(),
contourf(),
pcolormesh() and
pcolor().
Support for additional spectrum types#
Todd Jennings added support for new types of frequency spectrum plots:
magnitude_spectrum(),
phase_spectrum(), and
angle_spectrum(), as well as corresponding functions
in mlab.
He also added these spectrum types to
specgram(),
as well as adding support for linear scaling there (in addition to the
existing dB scaling). Support for additional spectrum types was also added to
specgram().
He also increased the performance for all of these functions and plot types.
Support for detrending and windowing 2D arrays in mlab#
Todd Jennings added support for 2D arrays in the
detrend_mean(),
detrend_none(),
and
detrend(), as well as adding
matplotlib.mlab.apply_window which support windowing 2D arrays.
Support for strides in mlab#
Todd Jennings added some functions to mlab to make it easier to use NumPy
strides to create memory-efficient 2D arrays. This includes
matplotlib.mlab.stride_repeat, which repeats an array to create a 2D
array, and
stride_windows(), which uses a moving window
to create a 2D array from a 1D array.
Formatter for new-style formatting strings#
Added
StrMethodFormatter which does the same job as
FormatStrFormatter, but accepts new-style formatting strings
instead of printf-style formatting strings
Consistent grid sizes in streamplots#
streamplot() uses a base grid size of 30x30 for both
density=1 and
density=(1, 1). Previously a grid size of 30x30 was used for
density=1, but a grid size of 25x25 was used for
density=(1, 1).
Get a list of all tick labels (major and minor)#
Added the kwarg 'which' to
Axes.get_xticklabels,
Axes.get_yticklabels and
Axis.get_ticklabels. 'which' can be 'major', 'minor', or
'both' select which ticks to return, like
set_ticks_position. If 'which' is
None then the old
behaviour (controlled by the bool minor).
Separate horizontal/vertical axes padding support in ImageGrid#
The kwarg 'axes_pad' to
mpl_toolkits.axes_grid1.axes_grid.ImageGrid can now
be a tuple if separate horizontal/vertical padding is needed.
This is supposed to be very helpful when you have a labelled legend next to
every subplot and you need to make some space for legend's labels.
Support for skewed transformations#
The
Affine2D gained additional methods
skew and
skew_deg to create skewed transformations. Additionally,
matplotlib internals were cleaned up to support using such transforms in
Axes. This transform is important for some plot types,
specifically the Skew-T used in meteorology.
Support for specifying properties of wedge and text in pie charts.#
Added the kwargs 'wedgeprops' and 'textprops' to
pie
to accept properties for wedge and text objects in a pie. For example, one can
specify wedgeprops = {'linewidth':3} to specify the width of the borders of
the wedges in the pie. For more properties that the user can specify, look at
the docs for the wedge and text objects.
Fixed the direction of errorbar upper/lower limits#
Larry Bradley fixed the
errorbar() method such
that the upper and lower limits (lolims, uplims, xlolims,
xuplims) now point in the correct direction.
More consistent add-object API for Axes#
Added the Axes method
add_image to put image
handling on a par with artists, collections, containers, lines, patches,
and tables.
Violin Plots#
Per Parker, Gregory Kelsie, Adam Ortiz, Kevin Chan, Geoffrey Lee, Deokjae Donald Seo, and Taesu Terry Lim added a basic implementation for violin plots. Violin plots can be used to represent the distribution of sample data. They are similar to box plots, but use a kernel density estimation function to present a smooth approximation of the data sample used. The added features are:
violin - Renders a violin plot from a collection of
statistics.
violin_stats() - Produces a collection of statistics
suitable for rendering a violin plot.
violinplot() - Creates a violin plot from a set of
sample data. This method makes use of
violin_stats()
to process the input data, and
violin_stats() to
do the actual rendering. Users are also free to modify or replace the output of
violin_stats() in order to customize the violin plots
to their liking.
This feature was implemented for a software engineering course at the University of Toronto, Scarborough, run in Winter 2014 by Anya Tafliovich.
More markevery options to show only a subset of markers#
Rohan Walker extended the markevery property in
Line2D. You can now specify a subset of markers to
show with an int, slice object, numpy fancy indexing, or float. Using a float
shows markers at approximately equal display-coordinate-distances along the
line.
Fixed the mouse coordinates giving the wrong theta value in Polar graph#
Added code to
transform_non_affine
to ensure that the calculated theta value was between the range of 0 and 2 * pi
since the problem was that the value can become negative after applying the
direction and rotation to the theta calculation.
Simple quiver plot for mplot3d toolkit#
A team of students in an Engineering Large Software Systems course, taught
by Prof. Anya Tafliovich at the University of Toronto, implemented a simple
version of a quiver plot in 3D space for the mplot3d toolkit as one of their
term project. This feature is documented in
quiver().
The team members are: Ryan Steve D'Souza, Victor B, xbtsw, Yang Wang, David,
Caradec Bisesar and Vlad Vassilovski.
polar-plot r-tick locations#
Added the ability to control the angular position of the r-tick labels
on a polar plot via
set_rlabel_position.
Date handling#
n-d array support for date conversion#
Andrew Dawson added support for n-d array handling to
matplotlib.dates.num2date(),
matplotlib.dates.date2num()
and
matplotlib.dates.datestr2num(). Support is also added to the unit
conversion interfaces
matplotlib.dates.DateConverter and
matplotlib.units.Registry.
Configuration (rcParams)#
savefig.transparent added#
Controls whether figures are saved with a transparent
background by default. Previously
savefig always defaulted
to a non-transparent background.
axes.titleweight#
Added rcParam to control the weight of the title
axes.formatter.useoffset added#
Controls the default value of useOffset in
ScalarFormatter. If
True and the data range is much smaller than the data average, then
an offset will be determined such that the tick labels are
meaningful. If
False then the full number will be formatted in all
conditions.
nbagg.transparent added#
Controls whether nbagg figures have a transparent
background.
nbagg.transparent is
True by default.
XDG compliance#
Matplotlib now looks for configuration files (both rcparams and style) in XDG compliant locations.
style package added#
You can now easily switch between different styles using the new
style
package:
>>> from matplotlib import style >>> style.use('dark_background')
Subsequent plots will use updated colors, sizes, etc. To list all available styles, use:
>>> print style.available
You can add your own custom
<style name>.mplstyle files to
~/.matplotlib/stylelib or call
use with a URL pointing to a file with
matplotlibrc settings.
Note that this is an experimental feature, and the interface may change as users test out this new feature.
Backends#
Qt5 backend#
Martin Fitzpatrick and Tom Badran implemented a Qt5 backend. The differences in namespace locations between Qt4 and Qt5 was dealt with by shimming Qt4 to look like Qt5, thus the Qt5 implementation is the primary implementation. Backwards compatibility for Qt4 is maintained by wrapping the Qt5 implementation.
The Qt5Agg backend currently does not work with IPython's %matplotlib magic.
The 1.4.0 release has a known bug where the toolbar is broken. This can be fixed by:
cd path/to/installed/matplotlib wget # unix2dos 3322.diff (if on windows to fix line endings) patch -p2 < 3322.diff
Qt4 backend#
Rudolf Höfler changed the appearance of the subplottool. All sliders are vertically arranged now, buttons for tight layout and reset were added. Furthermore, the subplottool is now implemented as a modal dialog. It was previously a QMainWindow, leaving the SPT open if one closed the plot window.
In the figure options dialog one can now choose to (re-)generate a simple automatic legend. Any explicitly set legend entries will be lost, but changes to the curves' label, linestyle, et cetera will now be updated in the legend.
Interactive performance of the Qt4 backend has been dramatically improved under windows.
The mapping of key-signals from Qt to values matplotlib understands was greatly improved (For both Qt4 and Qt5).
Cairo backends#
The Cairo backends are now able to use the cairocffi bindings which are more actively maintained than the pycairo bindings.
Gtk3Agg backend#
The Gtk3Agg backend now works on Python 3.x, if the cairocffi bindings are installed.
PDF backend#
Added context manager for saving to multi-page PDFs.
Text#
Text URLs supported by SVG backend#
The SVG backend will now render
Text objects'
url as a link in output SVGs. This allows one to make clickable text in
saved figures using the url kwarg of the
Text
class.
Anchored sizebar font#
Added the
fontproperties kwarg to
AnchoredSizeBar to
control the font properties.
Sphinx extensions#
The
:context: directive in the
plot_directive
Sphinx extension can now accept an optional
reset setting, which will
cause the context to be reset. This allows more than one distinct context to
be present in documentation. To enable this option, use
:context: reset
instead of
:context: any time you want to reset the context.
Legend and PathEffects documentation#
The Legend guide and Path effects guide have both been updated to better reflect the full potential of each of these powerful features.
Widgets#
Span Selector#
Added an option
span_stays to the
SpanSelector which makes the selector
rectangle stay on the axes after you release the mouse.
GAE integration#
Matplotlib will now run on google app engine. | https://matplotlib.org/stable/users/prev_whats_new/whats_new_1.4.html | CC-MAIN-2022-27 | refinedweb | 2,065 | 55.03 |
My app's buildbot went all red last night, because its config wants the latest zope.testing (for our developers' convenience), and the latest zope.testing release no longer ships its own copy of doctest.py, I guess:
Advertising
from zope.testing.doctestunit import DocTestSuite ImportError: cannot import name DocTestSuite Does anybody have any objections for a BBB import, making DocTestSuite available from the old location? I don't think breaking API is appropriate in a point-release (3.8.4), so I'd like to release 3.8.5 with that fixed. Marius Gedminas -- -- Zope 3 consulting and development
signature.asc
Description: Digital signature
_______________________________________________ Zope-Dev maillist - Zope-Dev@zope.org ** No cross posts or HTML encoding! ** (Related lists - ) | https://www.mail-archive.com/zope-dev@zope.org/msg31932.html | CC-MAIN-2016-44 | refinedweb | 121 | 53.47 |
We do provide a
downloadable archived version of cppreference.com. If you're
interested in getting archived versions of websites in general, you
might want to check out utilities like GNU's wget
(Windows version here).
In addition, James Heany has compiled a PDF version of the site
(as of October 2007) that is available for download. There is a C++ Reference PDF and a STL Reference PDF available
for download.
Also, James Brown has generously shared a set of Perl scripts that convert the
content on this site to compiled help (CHM) format. His archive
includes a CHM of the site (as of March 2008), Perl scripts, and
instructions.
#include <vector>
#include <Vector>
#include <vector.h>
#include <cstdio>
#include <stdio.h>
cout << "hello world!";
std::cout << "hello world!"; | http://www.cppreference.com/faq.html | crawl-001 | refinedweb | 129 | 67.45 |
Tiny Handy Prompting Lib
Project description
tinyprompt
A tiny lib for nice, handy prompts, primarily for Ops scripts.
This README contains all documentation.
Usage
pip install tinyprompt
Use tinyprompt.skippable to wrap script steps with a Yes / Skip / Quit prompt. This is very useful for simple scripted operations where - yes is the normal case - skip can be used to resume after a failure or abort - quit is used to abort when issues are encountered
import tinyprompt # note: tinyprompt.skippable passes arguments through verbatim, but it's # not guaranteed to return a meaningful result # `quit` does a sys.exit(1) and `skip` makes it return `None` @tinyprompt.skippable('skippable script step') def my_func(): """ Do some things, this docstring will show up as a command description when the script is run. The "skippable script step" arg will be uppercased and used as the step name. """ print('this skippable step') @tinyprompt.skippable('other skippable script step', color=False) def my_func2(): """another func""" print('hi') def otherfunc(): # yes, it's on purpose tinyprompt.color_print('red string', tinyprompt.RED) tinyprompt.color_print('yellow string', tinyprompt.BLUE) tinyprompt.color_print('green string', tinyprompt.GRAY) tinyprompt.color_print('blue string', tinyprompt.GREEN) tinyprompt.color_print('gray string', tinyprompt.YELLOW) def main(): my_func() # skippable my_func2() # skippable otherfunc() # not skippable, but not reached on quit if __name__ == '__main__': main()
Contributing
- All code must pass make test
- All code is autoformatted with black and isort
- Try to write a test whenever you find a bug
- Make your PRs clean. Rebase to avoid merge conflicts and squash fixup commits
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/tinyprompt/ | CC-MAIN-2021-04 | refinedweb | 283 | 66.33 |
#include <gromacs/mdrun/mdmodules.h>
Manages the collection of all modules used for mdrun.
This class acts as a central place for constructing modules for mdrun and wiring up dependencies between them. This class should be the only place that contains the full list of modules, although in the future, some code (e.g., in tools) may benefit from the ability to only create one or a few modules and use them.
The general idea is that each module takes care of its own data rather than mdrun having to know about all the details of each type of force calculation. Initially this is applied for simple things like electric field calculations but later more complex forces will be supported too.
Currently, where the set of modules needs to be accessed, either a pointer to MDModules is passed around, or an instance of IMDOutputProvider or ForceProviders returned from MDModules. These objects returned from MDModules call the corresponding methods in the relevant modules. In the future, some additional logic may need to be introduced at the call sites that can also influence the signature of the methods, similar to what ForceProviders already does for force computation.
The assignOptionsToModules() and adjustInputrecBasedOnModules() methods of this class also take responsibility for wiring up the options (and their defaults) for each module.
Add a module to the container.
An object may be added by a client to the bound MD Modules at run time. Both the client and the MDModules object may need to extend the life of the provided object. However, the MDModules container guarantees to extend the life of a provided object for as long as its consumers may attempt to use its the interfaces accessible through IMDModule methods.
Normalizes inputrec parameters to match current code version.
This orders the parameters in
ir->param to match the current code and adds any missing defaults. It also throws an error if the inputrec contains parameters that are not recognized by any module.
Sets input parameters from
params for each module.
Initializes a builder of flat mdp-style key-value pairs suitable for output.
If used as input to initMdpTransform(), the key-value pairs resulting from this function would leave the module settings unchanged.
Once the transition from mdp to key-value input is complete, this method will probably not exist.
Initializes a transform from mdp values to sectioned options.
Initializes the combined transform from all modules.
Subscribe MdModules to notifications during pre-processing.
Allows MdModules to subscribe to notifications that are called back during pre processing an MD simulation, after the options were assigned to the modules.
Subscribe MdModules to simulation setup notifications.
Allows MdModules to subscribe to notifications that are called back during the set up of an MD simulation, after the options were assigned to the modules. | https://manual.gromacs.org/current/doxygen/html-lib/classgmx_1_1MDModules.xhtml | CC-MAIN-2021-17 | refinedweb | 465 | 54.32 |
afGetMarkIDs(3dm) afGetMarkIDs(3dm)
afGetMarkIDs - get the number and list of marker ID's for an audio track
#include <dmedia/audiofile.h>
int afGetMarkIDs(AFfilehandle file, int trackid, int markids[])
file is an AFfilehandle structure, created when an audio file was
opened by a call to afOpenFile(3dm).
trackid is an integer which identifies an audio track contained in
file. All currently supported file formats contain exactly one
track, so always use the constant value AF_DEFAULT_TRACK for
now.
markids is an array of integer locations used to return a list of
unique positive marker id's which can be used to reference the
marker structures for track.
afGetMarkIDs() returns a nonnegative integer count of the number of
marker structures in the specified audio track, or -1 in case of error.
For AIFF/AIFF-C files, the number of marker structures in the
AF_DEFAULT_TRACK may be from 0 to 65535.
afGetMarkIDs() returns the number of marker structures contained in the
audio track given by trackid, as well as a list of integer id's which can
be used to reference the markers individually.
In the current version of the AF, markers are used to store the locations
of loop endpoints in AIFF-C (AIFF) files only.
Typically, you call afGetMarkIDs() twice. The first time, you pass it a
null markids pointer and just check the return value.
The return value tells you how many locations to allocate in the
markids[] array, which you pass back to afGetMarkIDs() to obtain a list
of mark ID's.
You can then use these id's to reference the individual markers and
obtain information about them such as marker position and associated name
string.
This function may return any configuration or number of marks just as it
may with an AIFF/AIFF-C file. Apps should be written to expect and
ignore marks they do not understand.
Page 1
afGetMarkIDs(3dm) afGetMarkIDs(3dm)
afOpenFile(3dm), afGetMarkPosition(3dm), afGetMarkName(3dm),
afInitMarkIDs(3dm)
afGetMarkIDs(3dm) afGetMarkIDs(3dm)
afOpenFile(3dm), afGetMarkPosition(3dm), afGetMarkName(3dm),
afInitMarkIDs(3dm)
PPPPaaaaggggeeee 2222 | https://nixdoc.net/man-pages/IRIX/man3d/AFgetmarkids.3d.html | CC-MAIN-2020-34 | refinedweb | 340 | 51.68 |
My first reaction is that this is a bad idea, it means that your modules are relying on certain functions to exist in the 'main' namespace. It would seem to me to be clearer to simply have a use Foo::Utility qw/:common/; at the top of each of these modules, that means your modules are only relying on things they have control over. That also has the benefit of meaning you can now say
That alone will probably save you typing, which seems to be what you were worried about in the first place. If you were worried about actually loading the module multiple times, don't, perl only loads it once.
Exporter will give you everything you need to do in Foo::Utility with very little effort (if you weren't already aware of it).
In reply to Re: Exporting functions into main namespace for the benefit of other use'd modules
by tedrek
in thread Exporting functions into main namespace for the benefit of other use'd modules
by tunaboy
. | https://www.perlmonks.org/?node_id=3333;parent=273117 | CC-MAIN-2021-43 | refinedweb | 173 | 60.28 |
Hello I am using youtube-dl to download a video and I am using the silent option not to print the information in the terminal as follows:
import youtube-dl import os ydl_opts = {'outtmpl': os.path.join('caminho-para-salvar'), 'quiet': True} video = 'minha-url' with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download((video))
However, I want the download progress bar to appear, which is not the case in quiet mode:
(download) 100% of 532.63MiB
The following list of options is available in the YoutubeDl class. I couldn't find one that met this requirement:
Available options: username: Username for authentication purposes. password: Password for authentication purposes. videopassword: Password for accessing a video. ap_mso: Adobe Pass multiple-system operator identifier. ap_username: Multiple-system operator account username. ap_password: Multiple-system operator account password. usenetrc: Use netrc for authentication instead. verbose: Print additional info to stdout. quiet: Do not print messages to stdout. no_warnings: Do not print out anything for warnings. forceurl: Force printing final URL. forcetitle: Force printing title. forceid: Force printing ID. forcethumbnail: Force printing thumbnail URL. forcedescription: Force printing description. forcefilename: Force printing final filename. forceduration: Force printing duration. forcejson: Force printing info_dict as JSON. dump_single_json: Force printing the info_dict of the whole playlist (or video) as a single JSON line. simulate: Do not download the video files. format: Video format code. See options.py for more information. outtmpl: Template for output names. restrictfilenames: Do not allow "&" and spaces in file names ignoreerrors: Do not stop on download errors. force_generic_extractor: Force downloader to use the generic extractor nooverwrites: Prevent overwriting files. playliststart: Playlist item to start at. playlistend: Playlist item to end at. playlist_items: Specific indices of playlist to download. playlistreverse: Download playlist items in reverse order. playlistrandom: Download playlist items in random order. matchtitle: Download only matching titles. rejecttitle: Reject downloads for matching titles. logger: Log messages to a logging.Logger instance. logtostderr: Log messages to stderr instead of stdout. writedescription: Write the video description to a .description file writeinfojson: Write the video description to a .info.json file writeannotations: Write the video annotations to a .annotations.xml file writethumbnail: Write the thumbnail image to a file write_all_thumbnails: Write all thumbnail formats to files writesubtitles: Write the video subtitles to a file writeautomaticsub: Write the automatically generated subtitles to a file allsubtitles: Downloads all the subtitles of the video (requires writesubtitles or writeautomaticsub) listsubtitles: Lists all available subtitles for the video subtitlesformat: The format code for subtitles subtitleslangs: List of languages of the subtitles to download keepvideo: Keep the video file after post-processing daterange: A DateRange object, download only if the upload_date is in the range. skip_download: Skip the actual download of the video file cachedir: Location of the cache files in the filesystem. False to disable filesystem cache. noplaylist: Download single video instead of a playlist if in doubt. age_limit: An integer representing the user's age in years. Unsuitable videos for the given age are skipped. min_views: An integer representing the minimum view count the video must have in order to not be skipped. Videos without view count information are always downloaded. None for no limit. max_views: An integer representing the maximum view count. Videos that are more popular than that are not downloaded. Videos without view count information are always downloaded. None for no limit. download_archive: File name of a file where all downloads are recorded. Videos already present in the file are not downloaded again. cookiefile: File name where cookies should be read from and dumped to. nocheckcertificate:Do not verify SSL certificates prefer_insecure: Use HTTP instead of HTTPS to retrieve information. At the moment, this is only supported by YouTube. proxy: URL of the proxy server to use geo_verification_proxy: URL of the proxy to use for IP address verification on geo-restricted sites. socket_timeout: Time to wait for unresponsive hosts, in seconds bidi_workaround: Work around buggy terminals without bidirectional text support, using fridibi debug_printtraffic:Print out sent and received HTTP traffic include_ads: Download ads as well default_search: Prepend this string if an input url is not valid. 'auto' for elaborate guessing encoding: Use this encoding instead of the system-specified. extract_flat: Do not resolve URLs, return the immediate result. Pass in 'in_playlist' to only show this behavior for playlist items. postprocessors: A list of dictionaries, each with an entry * key: The name of the postprocessor. See youtube_dl/postprocessor/__init__.py for a list. as well as any further keyword arguments for the postprocessor. progress_hooks: A list of functions that get called on download progress, with a dictionary with the entries * status: One of "downloading", "error", or "finished". Check this first and ignore unknown values. If status is one of "downloading", or "finished", the following properties may also be present: * filename: The final filename (always present) * tmpfilename: The filename we're currently writing to * downloaded_bytes: Bytes on disk * total_bytes: Size of the whole file, None if unknown * total_bytes_estimate: Guess of the eventual file size, None if unavailable. * elapsed: The number of seconds since download started. * eta: The estimated time in seconds, None if unknown * speed: The download speed in bytes/second, None if unknown * fragment_index: The counter of the currently downloaded video fragment. * fragment_count: The number of fragments (= individual files that will be merged) Progress hooks are guaranteed to be called at least once (with status "finished") if the download is successful. merge_output_format: Extension to use when merging formats. fixup: Automatically correct known faults of the file. One of: - "never": do nothing - "warn": only emit a warning - "detect_or_warn": check whether we can do anything about it, warn otherwise (default) source_address: Client-side IP address to bind to. call_home: Boolean, true iff we are allowed to contact the youtube-dl servers for debugging. sleep_interval: Number of seconds to sleep before each download when used alone or a lower bound of a range for randomized sleep before each download (minimum possible number of seconds to sleep) when used along with max_sleep_interval. max_sleep_interval:Upper bound of a range for randomized sleep before each download (maximum possible number of seconds to sleep). Must only be used along with sleep_interval. Actual sleep time will be a random float from range (sleep_interval; max_sleep_interval). listformats: Print an overview of available video formats and exit. list_thumbnails: Print a table of all thumbnails and exit. match_filter: A function that gets called with the info_dict of every video. If it returns a message, the video is ignored. If it returns None, the video is downloaded. match_filter_func in utils.py is one example for this. no_color: Do not emit color codes in output. geo_bypass: Bypass geographic restriction via faking X-Forwarded-For HTTP header geo_bypass_country: Two-letter ISO 3166-2 country code that will be used for explicit geographic restriction bypassing via faking X-Forwarded-For HTTP header geo_bypass_ip_block: IP range in CIDR notation that will be used similarly to geo_bypass_country The following options determine which downloader is picked: external_downloader: Executable of the external downloader to call. None or unset for standard (built-in) downloader. hls_prefer_native: Use the native HLS downloader instead of ffmpeg/avconv if True, otherwise use ffmpeg/avconv if False, otherwise use downloader suggested by extractor if None. The following parameters are not used by YoutubeDL itself, they are used by the downloader (see youtube_dl/downloader/common.py): nopart, updatetime, buffersize, ratelimit, min_filesize, max_filesize, test, noresizebuffer, retries, continuedl, noprogress, consoletitle, xattr_set_filesize, external_downloader_args, hls_use_mpegts, http_chunk_size. The following options are used by the post processors: prefer_ffmpeg: If False, use avconv instead of ffmpeg if both are available, otherwise prefer ffmpeg. ffmpeg_location: Location of the ffmpeg/avconv binary; either the path to the binary or its containing directory. postprocessor_args: A list of additional command-line arguments for the postprocessor. The following options are used by the Youtube extractor: youtube_include_dash_manifest: If True (default), DASH manifests and related data will be downloaded and processed by extractor. You can reduce network I/O by disabling it if you don't care about DASH.
Is there a way to do this by passing parameters?
Thank you! | https://proxies-free.com/python-youtube-dl-print-download-progress-in-quiet-mode/ | CC-MAIN-2021-10 | refinedweb | 1,329 | 50.23 |
Tetris (NES) for OpenAI Gym
Project description
gym-tetris
An OpenAI Gym environment for Tetris on The Nintendo Entertainment System (NES) based on the nes-py emulator.
Installation
The preferred installation of
gym-tetris is from
pip:
pip install gym-tetris
Usage
Python
You must import
gym_tetris before trying to make an environment.
This is because gym environments are registered at runtime. By default,
gym_tetris environments use the full NES action space of 256
discrete actions. To constrain this,
gym_tetris.actions provides
an action list called
MOVEMENT (20 discrete actions) for the
nes_py.wrappers.JoypadSpace wrapper. There is also
SIMPLE_MOVEMENT with a reduced action space (6 actions). For exact details,
see gym_tetris/actions.py.
from nes_py.wrappers import JoypadSpace import gym_tetris from gym_tetris.actions import MOVEMENT env = gym_tetris.make('Tetris-v0') env = JoypadSpace(env, MOVEMENT) done = True for step in range(5000): if done: state = env.reset() state, reward, done, info = env.step(env.action_space.sample()) env.render() env.close()
NOTE:
gym_tetris.make is just an alias to
gym.make for
convenience.
NOTE: remove calls to
render in training code for a nontrivial
speedup.
Command Line
gym_tetris features a command line interface for playing
environments using either the keyboard, or uniform random movement.
gym_tetris -e <environment ID> -m <`human` or `random`>
Environments
There are two game modes define in NES Tetris, namely, A-type and B-type. A-type is the standard endurance Tetris game and B-type is an arcade style mode where the agent must clear a certain number of lines to win. There are three potential reward streams: (1) the change in score, (2) the change in number of lines cleared, and (3) a penalty for an increase in board height. The table below defines the available environments in terms of the game mode (i.e., A-type or B-type) and the rewards applied.
info dictionary
The
info dictionary returned by the
step method contains the following
keys:
Citation
Please cite
gym-tetris if you use it in your research.
@misc{gym-tetris, author = {Christian Kauten}, title = {{Tetris (NES)} for {OpenAI Gym}}, year = {2019}, publisher = {GitHub}, howpublished = {\url{}}, }
References
The following references contributed to the construction of this project.
- Tetris (NES): RAM Map. Data Crystal ROM Hacking.
- Tetris: Memory Addresses. NES Hacker.
- Applying Artificial Intelligence to Nintendo Tetris. MeatFighter.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/gym-tetris/3.0.2/ | CC-MAIN-2022-27 | refinedweb | 412 | 58.79 |
ALICIA WEENUM51 Points
It's giving me an error message once I complie it.
import java.io.Console;
public class Introductions {
public static void main(String[] args) { Console console = System.console(); // Welcome to the Introductions program! Your code goes below here console,printf("Hello, my name is Alicia\n"); console.printf("Alicia is learning how to write Java\n");
} }
This is what I have and then it sends me this
Picked up _JAVA_OPTIONS: -Xmx128m
Introductions.java:8: error: not a statement
console,printf("Hello, my name is Alicia\n");
^
Introductions.java:8: error: ';' expected
console,printf("Hello, my name is Alicia\n");
^
2 errors
2 Answers
Ryan Groom17,042 Points
ALICIA WEENUM I believe your issue is that you have a comma instead of a period in your first console.printf() statement... let me know if this fixes your issue. | https://teamtreehouse.com/community/its-giving-me-an-error-message-once-i-complie-it | CC-MAIN-2020-34 | refinedweb | 140 | 56.66 |
holger krekel wrote: > [Rocco Moretti Fri, Jul 02, 2004 at 11:29:29AM -0500] > >. > > > yes, i think this technique makes sense. But did you look into doctests, btw? > The thought was that running doctests/unittests at applevel involves a large amount of code that might not run on pypy. If most of the testing apparatus is at interpreter level, there is less chance the test framework is what is failing, as opposed to the test itself. I guess this is moot now that Seo has shown that the CPython regrtest framework is working now. Add to that the fact that I can't seem to find a good way to create an extensible way of adding tests (currently adding new test scripts requires a substantial amount of cut-and-paste), and its probably best just to delete the whole deal, and get rid of the concomitant namespace pollution. -- If someone thinks it'll be worthwhile later, they can either resurrect it from svn, or recreate it from scratch. Sorry about the dead-end-wild-goose-chase -Rocco | https://mail.python.org/pipermail/pypy-dev/2004-July/001475.html | CC-MAIN-2016-40 | refinedweb | 177 | 78.18 |
This is part 3 of the introduction to handling JSON with Python. This post covers a real world example that accesses data from public API from the New York City Open Data. For fun we are going to look at the most popular baby names by sex and ethnicity.
The key idea is that JSON structures vary, and the first step in dealing with JSON is understanding the structure. Once we understand the structure, we select the appropriate techniques to handle the JSON data. Most of these techniques were covered in part 1 and part 2 of this series.
Browsing the data
You can browse the data from the API URL endpoint. The displayed format is not really going to help us understand the data. Copy the text over to an online JSON formatter such as jsonformatter. Here we see the pretty JSON format on the left:
Click on the JSON Viewer button to see a tree view of the JSON data on the right:
The very first thing you notice right at the top of the tree view is that there are 2 objects at the top level and the JSON consists of nested dictionaries. By collapsing the tree structure to only the top level, we see the following:
Here we see the meta dictionary has 1 sub-dictionary and the data dictionary is a list of 11345 items. Further exploration shows that the data dictionary items are also lists i.e. the data dictionary is a list of 11345 lists (rows). Each of these lists are a list of 14 items. Each item represents a value (column).
The data we have only shows a list index and a list value. We don’t know what those values represent … yet.
It is reasonably easy to get to the data by referencing the data dictionary directly as shown in the script below:
import requests, pandas url = '' req = requests.get(url) mydict = req.json() df = pandas.DataFrame.from_dict(mydict['data'])
The results show that the only problem is the column names are the index values.
We revisit our JSON tree view and find that the meta dictionary contains a view sub-dictionary, which in turn contains a list of dictionaries called columns. Each item in the columns list is a dictionary with 8 column properties.
To access the column names is not that tricky. We will use the same techniques from the previous posts. Perhaps the only “trick” is to reference the nested columns dictionary. The rest of the code accesses the key: value pairs nested inside the list, and adds the column name value to our columns list. The final step replaces the column headers with the newly acquired column headers.
cols_lst = [] for obj in mydict['meta']['view']['columns']: for key, value in obj.items(): if key == 'name': cols_lst.append(value) df.columns = cols_lst
You can clean up by removing the columns you don’t need (see previous blog posts using the drop method for dataframes).
When the problem is understood …
… the solution is (hopefully) obvious. While this post barely introduced anything new from a Python perspective (except referencing sub-dictionaries), the focus was on understanding the problem and cementing techniques for handling JSON.
In the next blog post I want to conclude this JSON series with another real world example. | https://dataideas.blog/2018/10/23/loading-json-it-looks-simple-part-3/?share=google-plus-1 | CC-MAIN-2020-34 | refinedweb | 551 | 64.1 |
*
A friendly place for programming greenhorns!
Big Moose Saloon
Search
|
Java FAQ
|
Recent Topics
|
Flagged Topics
|
Hot Topics
|
Zero Replies
Register / Login
JavaRanch
»
Java Forums
»
Java
»
JSF
Author
Hit Counter
Christopher Sharp
Ranch Hand
Joined: Dec 12, 2007
Posts: 152
posted
Dec 13, 2007 07:06:00
0
This is my first posting on this board, and I'm new to
JSF
and Glassfish, as well as server-side programming in Java in general.
I am using Java Server Faces with Glassfish, and I would be very
grateful to know how to implement hit counters..
Rather than having three separate beans for each counter, it would
make sense to have one bean that reads and updates one of three very
small files that store the counter for the particular page. When the
page loads, how do I tell the counter which file to read and update?
Once I have the value from the counter, then it is just a matter of
using the h
utputText tag, but of course that tag has to be
rendered after it has the value?
After the "submit" button is clicked, a quite separate counter can be
updated, which should be much easier. In the web page I have a JavaScript function that on page load passes a
string
to:
h:inputHidden id="update" value="#{user.counter}"
in a form using the DOM, then immediately I have the line:
h
utputText id="newvalue" value="#{user.counter}"
that is supposed to return the count from the counter file.
The code for the bean is:
public class FormBean { // Other private variables and constants. private String counterfile; // Holds the name of the file with the counter private String numberstring; // The value of the count as a string public FormBean() {} // Other getters and setters // This sets the filename holding the count. public void setCounter(String s) { counterfile=s; } // This gets the count from the filename and increments it. // A negative value is returned if there is an error. public String getCounter() { try { // Open file for reading and get count. BufferedReader fin = new BufferedReader(new FileReader(counterfile)); if ((numberstring = fin.readLine()) == null) { fin.close(); return "-1"; } fin.close(); } catch (IOException ein) { return "-2"; } int count; try { // Increment count. count = Integer.parseInt(numberstring); count++; numberstring = "" + count; } catch (NumberFormatException e) { return "-3"; } try { // Store new count in the file. BufferedWriter fout = new BufferedWriter(new FileWriter(counterfile)); fout.write(numberstring); fout.close(); return numberstring; } catch (IOException eout) { return "-4"; } } }
Depending on which of the three (or in general more) pages I have
placed the counter in, I want to call up the file that holds the count for
that page and update it. What happens at the moment is that the bean tries to display a number before it has got the file, so it fails.
It's a bad idea to pass the filename directly to the bean, and I could instead have the filenames stored in the bean, but I would still need
to specify which file I want to access for a particular page. I could of
course write separate logic for each page that are identical, except for
filename, but there must be a better way. Incidentally, I tried to post the HTML code, but that wasn't possible.
I would be most grateful for some help on this, which may involve configuring the faces-config.xml and/or the web.xml files in a special way, for which I'm having problems finding documentation.
Christopher Sharp
I agree. Here's the link:
subject: Hit Counter
Similar Threads
Editable Data table in request scop JSF2.0
JSF v1.2: Pass total figure into bean for generation of pages
Upload more than 1 MB
Using properties file in source file
How to get the no.of website hits?
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/213496/JSF/java/Hit-Counter | CC-MAIN-2014-35 | refinedweb | 645 | 70.84 |
So I ran into an interesting dilemma regarding object/receiver cases (upper/lower). Convention states lowercase but something seems to go awry. But, it my case, my code only works when the instance begins with a cap? It's driving me nuts!
I'm am using Start Command Prompt with Ruby. IRB 2.3, and also C9 (problem persisted in the IDE as well)
An example:
#rex.rb
class Dog
def wants(something)
puts "Rex wants to #{something}."
end
end
#rex instance is lowercase, per convention and the book's fidelity
rex = Dog.new
rex.wants("play")
rex.wants("x") yields a NameError basically saying rex object is undefined.
#rex.rb
class Dog
def wants(something)
puts "Rex wants to #{something}."
end
end
#Rex starts with an uppercase R now, not lowercase r - which it should be
Rex = Dog.new
Rex.wants("play")
Rex.wants("x")
Your trouble here is that any local variable defined in an included file will be out of scope within
IRB. By defining a constant, you were able to get around this. Declaring an explicit global variable
$rex or instance variable
@rex are alternatives:
@rex = Dog.new @rex.wants("play")
@rex will now be accessible through IRB...
@rex.wants "x" # Rex wants to x. # => nil
@John Hyland has a suggestion for declaring a constant within a module which you might also look into.
@mudasobwa's accusation of heresy for using an instance variable globally is not without merit. Declaring
@rex outside of the context of a class and importing the containing file into IRB will add that instance variable to the main object. This violates Object Oriented design principles, may be confusing, and global variables should generally be avoided.
That said, a globally scoped instance variable may be appropriate if viewed as a "fish out of water" for experimentation purposes. I prefer it to declaring a constant we intend to mutate. Instance variables may also more closely resemble resemble code you'll eventually deploy; often in
rails or
sinatra applications, instance variables are declared within the scope of a route handler (e.g.
#get) that a
view can access.
Classically, instance variables should pertain to the class they live within. Here's how that looks:
# dog.rb class Dog @legs # instance variable (for each Dog) @@population = 0 # class variable (shared across all Dogs) def initialize legs=4 self.legs = legs @@population += 1 end def amputate @legs-=1 if @legs > 0 @legs end # setters and getters (we could DRY this up with attr_accessor...) def legs= x @legs = x end def legs @legs end def self.count @@population end end
Our class describes a model of what a Dog looks like in our program. Every dog we create will have its own instance variable
@legs and share a class variable
@@population with all Dogs. Calling
Dog.new will invoke
#initialize, which sets @legs to 4, by default, and adds 1 to the total population. From irb, we could test this out:
# irb terminal rex = Dog.new.amputate fido = Dog.new puts "rex has %i legs, fido has %i legs" % [rex.legs, fido.legs] # => rex has 3 legs, fido has 4 legs puts "We have %i total dog(s)" % Dog.count # => We have 2 total dog(s) | https://codedump.io/share/ZrBxhJeX9LDl/1/ruby-object-case-sensitive-in-irb | CC-MAIN-2017-43 | refinedweb | 539 | 66.33 |
. . . . ,`,`,`,`, . . . . `\`\`\`\; `\`\`\`\`, ~|;!;!;\! ~\;\;\;\|\ (--,!!!~`! . (--,\\\===~\ (--,|||~`! ./ (--,\\\===~\ `,-,~,=,:. _,// (--,\\\==~`\ ~-=~-.---|\;/J, Welcome to the Unicorn Database (--,\\\((```==. ~'`~/ a | BigTable, Document and Graph (-,.\\('('(`\\. ~'=~| \_. \ Full Text Search (,--(,(,(,'\\. ~'=| \\_;> (,-( ,(,(,;\\ ~=/ \ Haifeng Li (,-/ (.(.(,;\\,/ ) ADP Innovation Lab (,--/,;,;,;,\\ ./------. (==,-;-'`;' /_,----`. \ ,.--_,__.-' `--. ` \ (='~-_,--/ , ,!,___--. \ \_) (-/~( | \ ,_- | ) /_| (~/((\ )\._, |-' _,/ / \\)))) / ./~. | \_\; ,__///// / / ) / '===~' | | (, <. / / \. \ _/ / \_\ /_!/ >_\ Welcome to Unicorn Shell; enter ':help<RETURN>' for the list of commands. Type ":quit<RETURN>" to leave the Unicorn Shell Version 2.1.0, Scala 2.11.7, SBT 0.13.8, Built at 2016-07-04 03:42:14.238 =============================================================================== unicorn>
UNICORNUNICORN
Unicorn is a simple and flexible abstraction of BigTable-like database such as Cassandra, HBase, Accumulo, and RocksDB. Beyond a unified interface to various database systems, Unicorn provides easy-to-use document data model and MongoDB-like API. Moreover, Unicorn supports directed property multigraphs and documents can just be vertices in a graph.
Agility, flexibility and easy to use are our key design goals. With different storage engine, we can achieve different strategies on consistency, replication, etc.
With the built-in document and graph data models, developers can focus on the business logic rather than work with tedious key-value pair manipulations. Of course, developers are still free to use key-value pairs for flexibility in some special cases.
Unicorn is implemented in Scala and can be used as a client-side library without overhead. Unicorn also provides a shell for quick access of database. The code snippets in this document can be directly run in the Shell. A HTTP API, in the module
Rhino, is also provided to non-Scala users.
For analytics, Unicorn data can be exported as RDDs in Spark. These RDDs can also be converted to DataFrames or Datasets, which support SQL queries. Unicorn graphs can be analyzed by Spark GraphX too.
To use Unicorn as a library, add the following to SBT build file.
libraryDependencies += "com.github.haifengl" % "unicorn-unibase_2.11" % "2.1.1"
If you need additional HBase-only features, please link to the module
Narwhal.
libraryDependencies += "com.github.haifengl" % "unicorn-narwhal_2.11" % "2.1.1"
With the module
Narwhal that is specialized for HBase, advanced features such as time travel, rollback, counters, server side filter, Spark integration, etc. are available.
To support the document model, Unicorn has a very rich and advanced JSON library. With it, the users can operate JSON data just like in JavaScript. Moreover, it supports JSONPath for flexibly analyse, transform and selectively extract data out of JSON objects. Meanwhile, it is type safe and may capture many errors during the compile time. To use only the JSON library,
libraryDependencies += "com.github.haifengl" % "unicorn-json_2.11" % "2.1.1"
DownloadDownload
Get pre-packaged Unicorn in universal tarball from the releases page.
If you would like to build Unicorn from source, please first install Java, Scala and SBT. Then clone the repo and build the package:
git clone cd unicorn ./unicorn.sh
which also starts the Shell.
Unicorn runs on both Windows and UNIX-like systems (e.g. Linux, Mac OS). All you need is to have Java installed on your system
PATH, or the
JAVA_HOME environment variable pointing to a Java installation.
If you want to work on the Unicorn code with IntelliJ, please first install SBT plugin. To import the project, on the main menu select File | New | Project from Existing Sources.
ShellShell
Unicorn comes with an interactive shell. In the home directory of Unicorn, type
./bin/unicorn
to enter the shell, which is based on Scala interpreter. So you can run any valid Scala expressions in the shell. In the simplest case, you can use it as a calculator. Besides, all high-level Unicorn operators are predefined in the shell. Be default, the shell uses up to 4GB memory. If you need more memory to handle large data, use the option
-J-Xmx. For example,
./bin/unicorn -J-Xmx8192M
You can also modify the configuration file
./conf/unicorn.ini for the memory and other JVM settings.
In the shell, type :help to print Scala interpreter help information. To exit the shell, type :quit.
Connecting to DatabaseConnecting to Database
Suppose that
hbase-site.xml and
hbase-default.xml can be found on the
CLASSPATH, one can connect to HBase as simple as
val db = HBase()
The user may also pass a Configuration object to
HBase() if HBase configuration files are not in the
CLASSPATH.
To connect to Cassandra, please enable the Thrift API by configuring
start_rpc to
true in the
cassandra.yaml file, which is
false by default after Cassandra 2.0.
val db = Cassandra("127.0.0.1", 9160)
To connect to Accumulo,
val db = Accumulo("instance", "zookeeper", "user", "password")
where the first parameter is the Accumulo instance name and the second is the ZooKeeper connection string.
An interesting feature of Accumulo is to create a mock instance that holds all data in memory, and will not retain any data or settings between runs. It presently does not enforce users, logins, permissions, etc. This is very convenient for test. This doesn't even require an installation of Accumulo. To create a mock instance, simply do
val db = Accumulo()
RocksDB is an embeddable persistent key-value store for fast storage. RocksDB builds on LevelDB to be scalable to run on servers with many CPU cores, to efficiently use fast storage, to support IO-bound, in-memory and write-once workloads.
If your data can be fit in one machine and low latency (in microseconds) is important to your applications, RocksDB is a great choice. Especially for graph database use cases, a graph traversal may touch thousands or event millions vertices, the cost of IPC to a distributed database will be too high. In this case, RocksDB will easily outperformance other distributed storage engine.
There is no concept of tables in RocksDB. In fact, a RocksDB is like a table in HBase. Therefore, we create a higher level concept of database that contains multiple RocksDB databases in a directory. Each RocksDB is actually a subdirectory, which is encapsulated in RocksTable. To create RocksDB, simply provides a directory path.
val db = Unibase(RocksDB.create("/tmp/unicorn-twitter"))
To use an existing database,
val db = Unibase(RocksDB("/tmp/unicorn-twitter"))
With a database instance, we can create, drop, truncate, and compact a table. We can also test if a table exists.
db.createTable("test_table", "cf1", "cf2") val table = db("test_table") table("row1", "cf1", "c1") = "data" db.dropTable("test_table")
Here we first create a table with two column families. We can also pass a
Properties object for additional table configuration, which usually depends on the backend system. For example, sharding and replication strategies, compression, time-to-live (TTL), etc. Then we get the table object, put some data, and finally drop the table. In what follows, we will go through the data manipulation APIs.
BigTable-like APIBigTable-like API
In BigTable-like databases, Cassandra and HBase, column families must be declared up front at schema definition time whereas new columns can be added to any column family without pre-announcing them. In contrast, column family are not static in Accumulo and can be created on the fly. The only way to get a complete set of columns that exist for a column family is to process all the rows.
A cell’s content is an uninterpreted array of bytes. And table cells are versioned. A
(row, column, version) tuple exactly specifies a cell. The version is specified using a
long integer. Typically this
long contains timestamps.
The trait
unicorn.bigtable.BigTable defines basic operations on a table such as
Get,
Put, and
Delete. The corresponding implementations are in
unicorn.bigtable.cassandra.CassandraTable,
unicorn.bigtable.hbase.HBaseTable, and
unicorn.bigtable.accumulo.AccumuloTable.
/** Get one or more columns of a column family. If columns is empty, get all columns in the column family. */ def get(row: ByteArray, family: String, columns: ByteArray*): Seq[Column] /** Get all columns in one or more column families. If families is empty, get all column families. */ def get(row: ByteArray, families: Seq[(String, Seq[ByteArray])] = Seq.empty): Seq[ColumnFamily] /** Upsert a value. */ def put(row: ByteArray, family: String, column: ByteArray, value: ByteArray, timestamp: Long): Unit /** Upsert values. */ def put(row: ByteArray, family: String, columns: Column*): Unit /** Upsert values. */ def put(row: ByteArray, families: Seq[ColumnFamily] = Seq.empty): Unit /** Delete the columns of a row. If columns is empty, delete all columns in the family. */ def delete(row: ByteArray, family: String, columns: ByteArray*): Unit /** Delete the columns of a row. If families is empty, delete the whole row. */ def delete(row: ByteArray, families: Seq[(String, Seq[ByteArray])] = Seq.empty): Unit
Setting
timestamp as
0L,
Put creates a new version of a cell with the server’s currentTimeMillis (for Cassandra, it is caller's machine time). But the user may specify the version on a per-column level. The user-provided version may be a time in the past or the future, or a non-time purpose long value.
def update(row: ByteArray, family: String, column: ByteArray, value: ByteArray): Unit
The helper function
update is provided as a syntactic sugar so that the user can put a value in the way
table(row, family, column) = value
In this case, timestamp is always set as the current machine time.
Delete can happen on a specific version of a cell or all versions. Deletes work by creating tombstone markers. Once a tombstone marker is set, the "deleted" cells become effectively invisible for
Get operations but are not immediately removed from store files. Note that.
For these APIs, there are also corresponding batch mode operations that work on multiple rows. However, the implementation may or may not optimize the batch operations. In particular, Accumulo does optimize it in parallel.
Besides the basic operations, advanced features that are not available on all backend systems are organized into various traits.
Time TravelTime Travel
By default, when doing a
Get, the cell whose version has the largest value is returned. It is possible to return more than one version or to return versions other than the latest. These special methods are defined in trait
TimeTravel, which is supported by HBase.
ScanScan
HBase and Accumulo support the
Scan operation that fetches zero or more rows of a table. In fact, A
Get is simply a
Scan limited by the API to one row in these systems. The trait
RowScan provides operations to scan the whole table, or a range specified by the start and stop row key, or rows with a given prefix.
Filter ScanFilter Scan
HBase provides advanced filtering functionality when reading data using
Get or
Scan operations, which return a subset of results to the client. While this does not reduce server-side IO, it does reduce network bandwidth and reduces the amount of data the client needs to process.
The filter operators (
Equal,
NotEqual,
Greater,
GreaterOrEqual,
Less,
LessOrEqual) and logic operators (
And,
Or) are defined in trait
ScanFilter. The enhanced
Get and
Scan operators with filter parameter are defined in
FilterScan.
Intra Row ScanIntra Row Scan
In BigTable, a row could have millions columns. Cassandra actually supports up to 2 billions columns. In such a wide columnar environment, intra row scan is an useful operation in some use cases. Both HBase and Cassandra support
IntraRowScan trait that can scan columns of given range in a row (inside a column family).
RollbackRollback
HBaseTable implements the
Rollback trait that defines the methods to rollback cell(s) to previous version.
CounterCounter
A counter is a special column used to store a 64 bit integer that is changed in increments. Both HBase and Cassandra support counters.
To use counters in Cassandra, the user has to define a column family whose columns will act as counters.
AppendAppend
HBase support the
Append operation that appends data to a cell. Note that this operation does not appear atomic to readers. Appends are done under a single row lock, so write operations to a row are synchronized, but readers do not take row locks so get and scan operations can see this operation partially completed.
Cell Level SecurityCell Level Security
Accumulo and HBase support cell level security that provides fine grained access control. Cells can have visibility labels, which is used to determine whether a given user meets the security requirements to read the value. This enables data of various security levels to be stored within the same row, and users of varying degrees of access to query the same table, while preserving data confidentiality.
Security labels consist of a set of user-defined tokens that are required to read the value the label is associated with. The set of tokens required can be specified using syntax that supports logical
AND and
OR combinations of tokens, as well as nesting groups of tokens together.
JSONJSON
Although Unicorn provides a modular and unified interface to various BigTable-like systems, it is still a very low level API to manipulate data. A more productive way to use Unicorn is through the rich, flexible, and easy-to-use document data model. A document is essentially a JSON object with a unique key (corresponding to the row key). With document data model, the application developers will focus on the business logic while Unicorn efficiently maps documents to key-value pairs in BigTable. In this section, we first introduce Unicorn's JSON data types and APIs. In the next section, we will discuss the document API, which is compatible with MongoDB.,
JSON has only types of
string,
number,
boolean,
object,
array, and
null. Unicorn includes additional types such as
date,
int,
long,
double,
counter,
binary,
UUID,
ObjectId (as in BSON), etc.
In Unicorn, it is very easy to parse a JSON object:
val doc = json""" { interpolator
json parse a string to
JsObject. It is also okay to embed variable references directly in processed string literals.
val x = 1 json""" { "x": $x } """
If the string is not a JSON object but any other valid JSON expression, one may use
parseJson method to convert the string to a
JsValue.
"1".parseJson
The
json interpolator can only be applied to string literals. If you want to parse a string variable, the
parseJson method can always be employed. If you know the string contains a JSON object, you may also use the method
parseJsObject.
val s = """{"x":1}""" s.parseJsObject
To serialize a JSON value (of type
JsValue) in compact mode, you can just use
toString. To pretty print, use the method
prettyPrint.
doc.toString doc.prettyPrint
With a
JsObject or
JsArray, you can refer to the individual elements with a variation of array syntax, like this:
doc("store")("bicycle")("color") // Use symbol instead of string doc('store)('bicycle)('color)
Note that we follow Scala's array access convention by
() rather than
[] in JavaScript.
Besides, you can use the dot notation to access its fields/elements just like in JavaScript:
doc.store.bicycle.color doc.store.book(0).author
It is worth noting that we didn't define the type/schema of the document while Scala is a strong type language. In other words, we have both the type safe features of strong type language and the flexibility of dynamic language in Unicorn's JSON library.
If you try to access a non-exist field,
JsUndefined is returned.
unicorn> doc.book res11: unicorn.json.JsValue = undefined
Although there are already several nice JSON libraries for Scala, the JSON objects are immutable by design, which is a natural choice for a functional language. However, Unicorn is designed for database, where data mutation is necessary. Therefore,
JsObject and
JsArray are mutable data structures in Unicorn. You can set/add a field just like in JavaScript:
json.store.bicycle.color = "green"
To delete a field from
JsObject, use
remove method:
doc.store.book(0) remove "price"
It is same as setting it
JsUndefined:
doc.store.book(0).price = JsUndefined
To delete an element from
JsArray, the
remove method will effectively remove it from the array. However, setting an element to
undefined doesn't reduce the array size.
// delete the first element and array size is smaller doc.store.book.remove(0) // set the first element to undefined but array size keeps same doc.store.book(0) = JsUndefined
It is also possible to append an element or another array to
JsArray:
val a = JsArray(1, 2, 3, 4) a += 5 a ++= JsArray(5, 6)
Common iterative operations such as
foreach,
map,
reduce can be applied to
JsArray too.
doc.store.book.asInstanceOf[JsArray].foreach { book => println(book.price) }
Because Scala is a static language, it is impossible to know
doc.store.book is an array at compile time. So it is typed as generic
JsValue, which is the parent type of specific JSON data types. Therefore, we use
asInstanceOf[JsArray] to convert it to
JsArray in order to use
foreach.
With Unicorn, we can also look up field in the current object and all descendants:
unicorn> doc \\ "price" res29: unicorn.json.JsArray = [8.95,12.99,8.99,22.99,19.95]
For more advanced query operations, JSONPath can be employed.
JSONPathJSONPath
JSONPath is a means of using XPath-like syntax to query JSON structures. JSONPath expressions always refer to a JSON structure in the same way as XPath expression are used in combination with an XML document.
val jspath = JsonPath(doc)
Since a JSON structure is usually anonymous and doesn't necessarily have a "root member object" JSONPath assumes the abstract name
$ assigned to the outer level object. Besides,
@ refers to the current object/element.
// the authors of all books in the store jspath("$.store.book[*].author") // all authors jspath("$..author") // all things in store jspath("$.store.*") // the price of everything in the store jspath("$.store..price") // the third book jspath("$..book[2]") // the last book in order jspath("$..book[-1:]") // the first two books jspath("$..book[0,1]") jspath("$..book[:2]") // filter all books with isbn number jspath("$..book[?(@.isbn)]") //filter all books cheaper than 10 jspath("$..book[?(@.price<10)]") // all members of JSON structure jspath("$..*")
Our JSONPath parser supports all queries except for queries that rely on expressions of the underlying language like
$..book[(@.length-1)]. However, there’s usually a ready workaround as you can execute the same query using
$..book[-1:].
Another deviation Unicorn, we always flatten the result of recursive queries regardless of the context.
It is also possible to update fields with JSONPath. Currently, we support only child and array slice operators for update.
jspath("$['store']['book'][1:3]['price']") = 30.0
Document APIDocument API
Unicorn's document APIs are defined in package
unicorn.unibase, which is independent of backend storage engine. Simply pass a reference to storage engine to
Unibase(), which provides the interface of document model.
In relational database, a table is a set of tuples that have the same attributes. In Unibase, a table contains documents, which are JSON objects and may have nested objects and/or arrays. Besides, the tables in Unibase do not enforce a schema. Documents in a table may have different fields. Typically, all documents in a collection are of similar or related purpose. Moreover, documents in a table must have unique IDs/keys, which is not necessary in relational databases.
In MongoDB, such a group of documents is called collection. In order to avoid the confusion with Java/Scala's collection data structures, Unibase simply calls it table.
val db = Unibase(Accumulo()) db.createTable("worker") val workers = db("worker")
In above, we create a table
worker in Unibase. Then we create a JSON object and insert it into the worker table as following. Note that we explicitly create the
JsObject by specifying the fields and values instead of parsing from a JSON string. This way provides fine controls on the data types of fields.)
Each document should have a field
_id as the primary key. If it is missing, the
upsert operation will generate a random UUID as
_id, which is returned and also added into the input JSON object:
unicorn> joe.prettyPrint res input object includes
_id and the table already contains a document with same key, the document will be overwritten by
upsert. If this is not the preferred behavior, one may use
insert, which checks if the document already exists and throws an exception if so.
To make the code future proof, it is recommended to use the constant value
$id, defined in
Unibase package object, instead of
_id in the code.
Besides UUID, one may also
Int,
Long,
Date,
String, and BSON'
ObjectId (12 bytes including 4 bytes timestamp, 3 bytes machine id, 2 bytes process id, and 3 bytes incrementer) as the primary key. One may even use a complex JSON data type such as object or array as the primary key. However, this is NOT recommended because primary keys cannot be updated once a document inserted. To achieve similar effects, the old document has to be delete and inserted again with new key. However, the old document will be permanently deleted after the major compaction, which may not be desired. Even before the document be permanently deleted, the time travel functionality is broken for this document.
To get the document back, simply treat the table as a map and use
_id as the key:
unicorn> workers(key).get.prettyPrint res document doesn't exist,
None is returned.
To update a document, we use a MongoDB-like API:
val update = JsObject( "$id" -> key, "$set" -> JsObject( "salary" -> 100000.0, "address.street" -> "5 ADP Blvd" ), "$unset" -> JsObject( "gender" -> JsTrue ) ) workers.update(update)
The
$set operator replaces the value of a field with the specified value, provided that the new field does not violate a type constraint (and the document key
_id should not be set). If the field does not exist,
$set will add a new field with the specified value. To specify a field in an embedded object or in an array, use dot notation. To be compatible to MongoDB, we concatenate the array name with the dot (.) and zero-based index position to specify an element of an array by the zero-based index position, which is different from the
[] convention in JavaScript and JSONPath.
In MongoDB,
$set will create the embedded objects as needed to fulfill the dotted path to the field. For example, for a
$set {"a.b.c" : "abc"}, MongoDB will create the embedded object "a.b" if it doesn't exist. However, we don't support this behavior because of the performance considerations. We suggest the the alternative syntax
{"a.b" : {"c" : "abc"}}, which has the equivalent effect.
If you want to use
json string interpolation to create a JSON object for
update, remember to escape
$set and
$unset by double dollar sign, e.g.
$$set and
$$unset.
To delete a document, use the method
delete with the document key:
workers.delete(key)
Append OnlyAppend Only
When creating a table, we may declare it append only. Such a table is write-once (i.e. the same document is never updated). Any updates to existing documents will throw exceptions. Deletes are not allowed either.
db.createTable("stock", appendOnly = true) val prices = db("stock") val trade = json""" { "ticker": "GOOG", "price": 700.0, "timestamp": ${System.currentTimeMillis} } """ val key = prices.upsert(trade) prices.update(JsObject( "_id" -> key, "$set" -> JsObject( "price" -> JsDouble(800.0) ) )) java.lang.UnsupportedOperationException at unicorn.unibase.Table.update(Table.scala:320) ... 52 elided
Multi-TenancyMulti-Tenancy
Multi-tenant tables are regular tables that enables views to be created over the table across different tenants. This option is useful to share the same physical BigTable table across many different tenants.
To use a multi-tenant table, the user must firstly set the tenant id, which cannot be
undefined,
null,
boolean,
counter,
date, or
double. The tenats only see their data in such tables.
val workers = db("worker") workers.tenant = "IBM" val ibmer = workers.upsert(json""" { "name": "Tom", "age": 40 } """) workers.tenant = "Google" val googler = workers.upsert(json""" { "name": "Tom", "age": 30 } """)
Because the tenant is "Google" now, the data of tenant "IBM" are not visible.
unicorn> workers(ibmer) res5: Option[unicorn.json.JsObject] = None unicorn> workers(googler) res6: Option[unicorn.json.JsObject] = Some({"name":"Tom","age":30,"_id":"545ed4d1-280c-4b6a-a3cc-e0a3c5fc5b43"})
Switch back to "IBM", the view is different:
unicorn> workers.tenant = "IBM" workers.tenant: Option[unicorn.json.JsValue] = Some(IBM) unicorn> workers(ibmer) res8: Option[unicorn.json.JsObject] = Some({"name":"Tom","age":40,"_id":"2b7fb69f-810f-4ca7-a70f-5db767bc8e49"}) unicorn> workers(googler) res9: Option[unicorn.json.JsObject] = None
As a client-side solution, Unicorn does not enforce security on multi-tenant tables. In fact, there are no concepts of user and/or role. It is the application's responsibility to ensure the authorization and the authentication on the access of multi-tenant tables.
LocalityLocality
When Unicorn creates a document table, it creates only one column family by default.
db.createTable("worker", families = Seq(Unibase.DocumentColumnFamily), locality = Map().withDefaultValue(Unibase.DocumentColumnFamily))
where the parameter
families is the list of column families, and the parameter
locality, a map, tells Unicorn how to map the data to different column families. Because we have only one column families here, we simply set the default value of map is the only column family.
This schema can be customized. When documents in a table have a lot of fields and only a few fields are needed in many situations, it is a good idea to organize them into different column families based on business logic and access patterns. Such a design is more efficient because the storage engine needs scan only the necessary column family. It also limits the network data transmission.
db.createTable("worker", families = Seq( "id", "person", "address", "project"), locality = Map( $id -> "id", "address" -> "address", "project" -> "project" ).withDefaultValue("person"))
For simplicity, Unicorn uses only the top level fields of documents to determine the locality mapping.)
We can retrieve partial documents as following, which is known as "projection" in relational database and MongoDB.
unicorn> workers(key) res17: Option[unicorn.json.JsObject] = Some({"address":{"city":"Roseland","state":"NJ","zip":"07068","street":"1 ADP Blvd"},"project":["HCM","NoSQL","Analytics"],"_id":"6df63cf3-e4dd-4381-8276-ac0c0626dc78"}) unicorn> workers(key, "address") res19: Option[unicorn.json.JsObject] = Some({"address":{"city":"Roseland","state":"NJ","zip":"07068","street":"1 ADP Blvd"},"_id":"6df63cf3-e4dd-4381-8276-ac0c0626dc78"}) unicorn> workers(key, "project") res20: Option[unicorn.json.JsObject] = Some({"project":["HCM","NoSQL","Analytics"],"_id":"6df63cf3-e4dd-4381-8276-ac0c0626dc78"})
You can retrieve data from multiple column families too.
unicorn> workers(key, "name", "address") res21: Option[unicorn.json.JsObject] = Some({"address":{"city":"Roseland","state":"NJ","zip":"07068","street":"1 ADP Blvd"},"name":"Joe","gender":"Male","salary":50000.0,"_id":"6df63cf3-e4dd-4381-8276-ac0c0626dc78"})
However, there is a semantic difference from regular projection as you may notice in the above. Even though the user asks for only
name, all other fields in the same column family are returned. This is due to the design of BigTable and the mapping from document fields to columns. For example, if a specified field is a nested object, there is no easy way to read only the specified object in BigTable. Intra-row scan may help but not all BigTable implementations support it. And if there are multiple nested objects in request, we have to send multiple
Get requests, which is not efficient. Instead, we return the whole object of a column family if some of its fields are in request. This is usually good enough for hot-cold data scenario. For instance of a table of events, each event has a header in a column family and event body in another column family. In many reads, we only need to access the header (the hot data). When only user is interested in the event details, we go to read the event body (the cold data). Such a design is simple and efficient. Another difference from MongoDB is that we do not support the
excluded fields.
ScriptScript
We may also run Unicorn code as a shell script or batch command. The following bash script can be run directly from the command shell:
#!/bin/bash exec unicorn -nc "$0" "$@" !# import unicorn.json._ import unicorn.bigtable._ import unicorn.bigtable.accumulo._ import unicorn.bigtable.hbase._ import unicorn.unibase._ val db = Unibase(Accumulo()) db.createTable("worker") val workers = db("worker") val joe = JsObject( "name" -> "Joe", "gender" -> "Male", "salary" -> 50000.0, "address" -> JsObject( "street" -> "1 ADP Blvd", "city" -> "Roseland", "state" -> "NJ", "zip" -> "07068" ), "project" -> JsArray("HCM", "NoSQL", "Analytics") ) workers.upsert(joe)
NarwhalNarwhal
Advanced document API with HBase is available in the package
unicorn.narwhal. To use these features, the user should use the class
Narwhal and
HTable, which are subclasses of
Unibase and
Table, respectively.
val db = new Narwhal(HBase()) db.createTable("narwhal") val rich = json""" { "owner": "Rich", "phone": "123-456-7890", "address": { "street": "1 ADP Blvd.", "city": "Roseland", "state": "NJ" }, "children": 2C } """ val bucket = db("narwhal") val key = bucket.upsert(rich)
CounterCounter
The usage of
Narwhal and
HTable are similar to their parent classes. Besides, additional operators are available by taking advantage of HBase's features. Note that in the above the field
children takes the value of
2C. The suffix
C indicates it is a counter. You may use
JsCounter to create a counter directly too. With counters, we may update them in an atomic operation. For a regular integer, we instead have to read, update, and write back, which may cause consistency problems.
val increment = json""" { "$$inc": { "children": 1 } } """ increment("_id") = key bucket.update(increment) val doc = bucket(key).get println(doc.children)
This example will print out the new value, i.e. 3, of
children. It is also possible to use a negative value in
$inc operations, which effectively decreases the counter.
RollbackRollback
Another interesting feature is that we can rollback document fields back to previous values. If a user accidentally changes a value, don't worry. The old values are still in HBase and we can easily rollback.
val update = json""" { "$$set": { "phone": "212-456-7890", "gender": "M", "address.street": "5 ADP Blvd." } } """ update("_id") = key bucket.update(update)
In the above example, we update three fields
phone,
gender, and
address.street. Note that
gender is actually a new filed. Let's verify these fields be updated.
unicorn> bucket(key).get res11: unicorn.json.JsObject = {"children":2,"address":{"city":"Roseland","state":"NJ","street":"5 ADP Blvd."},"owner":"Rich","gender":"M","_id":"0c354c07-6e25-4b30-9cf3-9a508b6868fd","phone":"212-456-7890"}
Now we rollback
phone and
gender.
val rollback = json""" { "$$rollback": { "phone": 1, "gender": 1 } } """ rollback("_id") = key bucket.update(rollback)
Printing out the document, we can find that
phone has the previous value and
gender disappears now. Of course,
address.street still keeps the latest values.
unicorn> bucket(key).get res15: unicorn.json.JsObject = {"children":4,"address":{"city":"Roseland","state":"NJ","street":"5 ADP Blvd."},"owner":"Rich","_id":"0c354c07-6e25-4b30-9cf3-9a508b6868fd","phone":"123-456-7890"}
This example shows how we can rollback
$set operations. We actually can also rollback
$unset operations.
val update = json""" { "$$unset": { "owner": 1, "address": 1 } } """ update("_id") = key bucket.update(update) val rollback = json""" { "$$rollback": { "owner": 1, "address": 1 } } """ rollback("_id") = key bucket.update(rollback)
Time TravelTime Travel
Another cool feature of Narwhal is time travel. Because HBase stores multiple timestamped values, we can query the snapshot of a document at a given time point.
val asOfDate = new Date val update = json""" { "$$set": { "phone": "212-456-7890", "gender": "M", "address.street": "5 ADP Blvd." }, "$$inc": { "children": 1 } } """ update("_id") = key bucket.update(update) bucket(asOfDate, key)
Besides the plain
Get, we can supply an as-of-date parameter in a time travel
Get, which will retrieval document's value at that time point.
FilterFilter
So far, we get documents by their keys. With HBase, we can also query documents with method
find by filtering field values. The
find method returns an iterator to the documents that match the query criteria.
bucket.upsert(json"""{"name":"Tom","age":30,"state":"NY"}""") bucket.upsert(json"""{"name":"Mike","age":40,"state":"NJ"}""") bucket.upsert(json"""{"name":"Chris","age":30,"state":"NJ"}""") val it = bucket.find(json"""{"name": "Tom"}""") it.foreach(println(_))
Optionally, the
find method takes the second parameter for projection, which is an object that specifies the fields to return.
The
find method with no parameters returns all documents from a table and returns all fields for the documents.
The syntax of filter object is similar to MongoDB. Supported operators include
$and,
$or,
$eq,
$ne,
$gt,
$gte (or
$ge),
$lt,
$lte (or
$le).
bucket.find(json""" { "$$or": [ { "age": {"$$gt": 30} }, { "state": "NY" } ] } """)
If you prefer SQL-like query, just do it as follows:
bucket.find("""age > 30 OR stage = "NY"""")
Note that the query operation is based on server side filters. Although it minimizes the network transmission, it is still a costly full table scan. If the table is multi-tenanted and each tenant does not have too much data (e.g. SaaS solutions for small business), however, the scan will be usually localized to one or a few nodes and often quite fast. Compared to secondary index, this approach does not have penalty on the write performance and still provides fairly good performance on queries in such a situation.
For general purpose queries, secondary index should be built to accelerate frequent queries. We will discuss our secondary index design in the below.
SQLSQL
In fact, you can do a SQL-like query in the code or shell, which returns a
DataFrame.
db.sql("""SELECT address.state, COUNT(address.state), MAX(age), AVG(salary) as avg_salary FROM worker GROUP BY address.state ORDER By avg_salary""")
Although filtering is done on the server side, all other heavy computation such as
SUM,
GROUP BY,
ORDER BY, etc. are done on the client side. So this is only useful for small operational queries that involves a handful rows. For large scale analytics queries, we should use Spark as discussed below.
SparkSpark
For large scale analytics, Narwhal supports Spark. A table can be exported to Spark as
RDD[JsObject].
import org.apache.spark._ import org.apache.spark.rdd.RDD val conf = new SparkConf().setAppName("unicorn").setMaster("local[4]") val sc = new SparkContext(conf) val db = new Narwhal(HBase()) val table = db("worker") table.tenant = "IBM" val rdd = table.rdd(sc) rdd.count()
In the above example, we first create a
SparkContext. To export a table to spark, simply pass the
SparkContext object to the
rdd method of a table object. In this example, we only export the data of tenant
IBM.
Although Spark has filter functions on
RDDs, it is better to use HBase's server side filter at beginning to reduce network transmission. The
rdd method can take the second optional parameter for filtering, same syntax as in
find.
val table = db("narwhal") val rdd = table.rdd(sc, json""" { "$$or": [ { "age": {"$$gt": 30} }, { "state": "NJ" } ] } """) rdd.count()
For analytics,
SQL is still the best language. We can easily convert
RDD[JsObject] to a strong-typed
DataFrame to be analyzed in
SparkSQL.
val sqlContext = new org.apache.spark.sql.SQLContext(sc) import sqlContext.implicits._ case class Worker(name: String, age: Int) val workers = rdd.map { js => Worker(js.name, js.age) } val df = sqlContext.createDataFrame(workers) df.cache df.show df.registerTempTable("worker") sqlContext.sql("SELECT * FROM worker WHERE age > 30").show
In the above example, we create a
SQLContext on top of
SparkContext to use SparkSQL features. Then we create a
DataFrame of case class
Worker with type information. Since we will use this
DataFrame many times in analysis, we also
cache it with an in-memory columnar format. To do SQL queries, we also register this
DataFrame as a temporary table.
GraphGraph
Graphs are mathematical structures used to model pairwise relations between objects. A graph is made up of vertices (nodes) which are connected by edges (lines). A graph may be undirected, meaning that there is no distinction between the two vertices associated with each edge, or its edges may be directed from one vertex to another. Directed graphs are also called digraphs and directed edges are also called arcs or arrows.
A multigraph is a graph which is permitted to have multiple edges (also called parallel edges), that is, edges that have the same end nodes. The ability to support parallel edges simplifies modeling scenarios where there can be multiple relationships (e.g., co-worker and friend) between the same vertices.
In a property graph, the generic mathematical graph is often extended to support user defined objects attached to each vertex and edge. The edges also have associated labels denoting the relationships, which are important in a multigraph.
Unicorn supports directed property multigraphs. Documents from different tables can be added as vertices to a multigraph. It is also okay to add vertices without corresponding to documents. Each relationship/edge has a label and optional data (any valid JsValue, default value JsInt(1)).
Unicorn stores graphs in adjacency lists. That is, a graph is stored as a BigTable whose rows are vertices with their adjacency list. The adjacency list of a vertex contains all of the vertex’s incident edges (incoming and outgoing edges are in different column families).
Because large graphs are usually very sparse, an adjacency list is significantly more space-efficient than an adjacency matrix. Besides, the neighbors of each vertex may be listed efficiently with an adjacency list, which is important in graph traversals. With our design, it is also possible to test whether two vertices are adjacent to each other for a given relationship in constant time.
In what follows, we create a graph of gods, an example from Titan graph database.
val db = Unibase(Accumulo()) db.createGraph("gods") val gods = db.graph("gods", new Snowflake(0))
Because each vertex in the graph must have a unique 64-bit ID, we should provide a (distributed) ID generator when we go to mutate a graph. We currently provide the Snowflake ID generator, designed by Twitter. Each Snowflake worker should have a unique worker ID so that multiple worker won't generate duplicate IDs in parallel. In a small system, these worker IDs may be hand picked. For a large system, it is better coordinated by ZooKeeper. In this demo, we simply use
0 as the worker ID in the shell. For production, you may do things like
db.graph("gods", "zookeeper connection string")
If no ID generator is provided,
db.graph("gods") returns a read only instance for graph traversal or analytics.
In the next, we will add several vertices with properties stored in a
JsObject. The function
addVertex returns the ID of type
Long of new vertex.
val saturn = gods.addVertex(json"""{"label": "titan", "name": "saturn", "age": 10000}""") val sky = gods.addVertex(json"""{"label": "location", "name": "sky"}""") val sea = gods.addVertex(json"""{"label": "location", "name": "sea"}""") val jupiter = gods.addVertex(json"""{"label": "god", "name": "jupiter", "age": 5000}""") val neptune = gods.addVertex(json"""{"label": "god", "name": "neptune", "age": 4500}""") val hercules = gods.addVertex(json"""{"label": "demigod", "name": "hercules", "age": 30}""") val alcmene = gods.addVertex(json"""{"label": "human", "name": "alcmene", "age": 45}""") val pluto = gods.addVertex(json"""{"label": "god", "name": "pluto", "age": 4000}""") val nemean = gods.addVertex(json"""{"label": "monster", "name": "nemean"}""") val hydra = gods.addVertex(json"""{"label": "monster", "name": "hydra"}""") val cerberus = gods.addVertex(json"""{"label": "monster", "name": "cerberus"}""") val tartarus = gods.addVertex(json"""{"label": "location", "name": "tartarus"}""")
Of course, we will also add edges between vertices. It is important that edges have direction. With
addEdge(jupiter, "father", saturn), we add an edge from
jupiter to
saturn with label
father. For this edge,
jupiter is called out vertex while
saturn is in vertex. From the point view of vertex, this edge is an outgoing edge of
jupiter while the incoming edge of
saturn.
Besides, we may also associate any
JsValue to an edge. If no value is provided, the default value is
1.
gods.addEdge(jupiter, "father", saturn) gods.addEdge(jupiter, "lives", sky, json"""{"reason": "loves fresh breezes"}""") gods.addEdge(jupiter, "brother", neptune) gods.addEdge(jupiter, "brother", pluto) gods.addEdge(neptune, "lives", sea, json"""{"reason": "loves waves"}""") gods.addEdge(neptune, "brother", jupiter) gods.addEdge(neptune, "brother", pluto) gods.addEdge(hercules, "father", jupiter) gods.addEdge(hercules, "mother", alcmene) gods.addEdge(hercules, "battled", nemean, json"""{"time": 1, "place": {"latitude": 38.1, "longitude": 23.7}}""") gods.addEdge(hercules, "battled", hydra, json"""{"time": 2, "place": {"latitude": 37.7, "longitude": 23.9}}""") gods.addEdge(hercules, "battled", cerberus, json"""{"time": 12, "place": {"latitude": 39.0, "longitude": 22.0}}""") gods.addEdge(pluto, "brother", jupiter) gods.addEdge(pluto, "brother", neptune) gods.addEdge(pluto, "lives", tartarus, json"""{"reason": "no fear of death"}""") gods.addEdge(pluto, "pet", cerberus) gods.addEdge(cerberus, "lives", tartarus)
Correspondingly,
deleteEdge removes an edge and
deleteVertex removes the vertex and all associated edges.
To retrieve a vertex and its edge,
gods(jupiter) will return a
Vertex object containing its ID, properties, and associated edges. One can also directly access the data of an edge by
gods(pluto, "brother", jupiter). If the edge doesn't exist,
None is returned.
Although some graphs (e.g. Twitter graph) natively use
Long integer as vertex IDS, many graphs use Strings as vertex IDs. In RDF (Resource Description Framework), for example, vertices are encoded as URI. In Unicorn, we can use strings as vertex keys too. Internally, Unicorn translates them to the corresponding
Long vertex IDs. However, it is recommended to use
Long vertex ID directly if possible because it provides better performance.
It is also possible to add a document (in another table) as a vertex to a graph.
// key is the document key in the table "person" val id = gods.addVertex("person", key)
If the
person table is multi-tenanted, remember to use tenant id as the third argument. To access the vertex, it is simply as
gods("person", key).
Gremlin-like APIGremlin-like API
For graph traversal, we support a Gremlin-like API. To start a traversal,
val g = gods.traversal
Then we can start with one or more vertex by the method
v,
g.v(saturn)
A Traversal is essentially an Iterator of vertices or edges. On a vertex, we can call
outE() and
inE() to access its outgoing edges or incoming edges, respectively. On an edge,
inV() and
outV() returns its in vertex and out vertex, respectively. For vertex,
out() is a shortcut to
outE().inV() and similarly
in() is shortcut to
inE().outV(). All these functions may take a set of labels to filter relationships.
The following example shows how to get saturn's grandchildren's name.
g.v(saturn).in("father").in("father").name
For detailed information on Gremlin, please refer its website.
Graph SearchGraph Search
Beyond simple graph traversal, Unicorn supports DFS, BFS, A* search, Dijkstra algorithm, etc.
The below example searches for the shortest path between jupiter and cerberus with Dijkstra algorithm.
val path = GraphOps.dijkstra(jupiter, cerberus, new SimpleTraveler(gods)).map { edge => (edge.from, edge.label, edge.to) } path.foreach(println(_))
Note that this search is performed by a single machine. For very large graph, it is better to use some distributed graph computing engine such as Spark GraphX.
Spark GraphXSpark GraphX
With HBase/Narwhal, we can export a graph to Spark GraphX for advanced analytics such as PageRank, triangle count, SVD++, etc.
import org.apache.spark._ val conf = new SparkConf().setAppName("unicorn").setMaster("local[4]") val sc = new SparkContext(conf) val graph = db.graph("gods") val graphx = graph.graphx(sc) // Run PageRank val ranks = graphx.pageRank(0.0001).vertices
HTTP APIHTTP API
So far we access Unicorn through its Scala APIs. For other programming language users, we can manipulate documents with the HTTP API, which is provided by the Rhino module.
In the configuration file
conf/rhino.conf, the underlying BigTable database engine should be configured in the section
uncorn.rhino. The configuration file is in the format of Typesafe Config. For example,
unicorn.rhino { bigtable = "hbase" accumulo { instance = "local-poc" zookeeper = "127.0.0.1:2181" user = "root" password = "secret" } cassandra { host = "127.0.0.1" port = 9160 } }
In this example, we use HBase as the BigTable engine. Note that the configuration of HBase is in its own configuration files, which should be in the
CLASSPATH of Rhino. Sample configurations of Accumulo and Cassandra are provided in the example for demonstration.
Currently, Rhino provides only data manipulation operations. Other operations such as table creation/drop should be done in the Unicorn Shell.
The API is simple and easy to use. To insert a document, use the
PUT method with the JSON object as entity-body.
curl -X PUT -H "Content-Type: application/json" -d '{"_id":"dude","username":"xyz","password":"xyz"}'
To read it back, simply use
GET method. If the key is a string, the key can be part of the URI. Otherwise, the key should be set in the entity-body. The same rule applies to the
DELETE method.
curl -X GET
To update a document, use the
PATCH method.
curl -X PATCH -H "Content-Type: application/json" -d '{"_id":"dude","$set":{"password":"abc"}}'
In case of multi-tenancy, the tenant id should be set in the header.
curl -X PUT -H "Content-Type: application/json" --header 'tenant: "IBM"' -d '{"_id":"dude","username":"xyz","password":"xyz"}' curl -X GET --header 'tenant: "IBM"' curl -X GET --header 'tenant: "MSFT"' curl -X DELETE --header 'tenant: "IBM"' | https://index.scala-lang.org/haifengl/unicorn/unicorn-util/2.1.1?target=_2.11 | CC-MAIN-2021-10 | refinedweb | 7,520 | 50.63 |
Makefileand source code build a simple line drawing application and runs on Linux, Mac OS X, and Windows platforms. You can also try out some examples with buffer objects and shaders. If you're interested in using GLFW instead of GLUT, please refer to the course note Building OpenGL/GLFW Apps. Please let me know if you have any correction or addition. Thanks. To find out how to specify command line options, add to header file search path, and link with libraries such as GLEW, Expat, JPEG, and PNG, see the course note on these topics.
/usr/lib/libGL*on Ubuntu 14.04.1:
/usr/lib/x86_64-linux-gnu/libGL*
/usr/include/GL/{gl,glu}.h
/usr/lib/libglut*on Ubuntu 14.04.1:
/usr/lib/x86_64-linux-gnu/libglut*
/usr/include/GL/glut.h
Ubuntu# sudo apt-get install freeglut3-dev
Fedora/RedHat# sudo yum install freeglut-develwhich should install all the dependent packages, including OpenGL itself. You must have sudo/administrator privileges.
#include <GL/glut.h>You don't need to include
gl.hand
glu.h, as they are already included in
glut.h.
-lGL -lGLU -lgl,GLUT}.framework[The installed GLUT is the original GLUT not
freeglut.]
#include <GLUT/glut.h>Despite Apple's documentation, you don't need to include
gl.hand
glu.h, as they are already included in
glut.h. For an example, see the provided sample source code.
-framework OpenGL -framework GLUT
C:\Program Files (x86)\Windows Kits\8.1\Include\um\gl\{GL,GLU}.h
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Include\gl\{GL,GLU}.h
[without the " (x86)" for 32-bit Windows; VS2010: v7.0A, VS2008: v6.0A]
C:\Program Files (x86)\Windows Kits\8.1\Lib\winv6.3\um\x86\{OpenGL32,GlU32}.Lib
C:\Program Files (x86)\Windows Kits\8.1\Lib\winv6.3\um\x64\{OpenGL32,GlU32}.Lib
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Lib\{OpenGL32,GlU32}.Lib
C:\Windows\SysWOW64\{opengl,glu}32.dll
C:\Windows\System32\{opengl,glu}32.dll
C:\Program Files (x86)\NVIDIA Corporation\Cgfolder. You can then distribute the GLUT files as follows:
C:\Program Files (x86)\Microsoft Visual Studio *\VC\include\GL\glut.h
includefolder.
C:\Program Files\Microsoft SDKs\Windows\v7.0A\Include\GL\glut.h
C:\Program Files (x86)\Microsoft Visual Studio *\VC\lib\glut32.lib
C:\Program Files\Microsoft SDKs\Windows\v7.0A\Lib\glut32.lib
C:\Program Files (x86)\Microsoft Visual Studio *\VC\lib\amd64\glut32.lib
C:\Program Files (x86)\Microsoft Visual Studio *\VC\bin\glut32.dll
C:\Windows\system\glut32.dll
C:\Program Files (x86)\Microsoft Visual Studio *\VC\bin\amd64\glut32.dll
stdlibheader file that comes with Visual Studio 2013 has compatibility issue with the header file that comes with the 32-bit glut-3.7.6.zip (web site), in particular with the redefinition of
exit(). So you may want to avoid using this library. There is also the freeglut library. However, freeglut on Windows makes duplicate calls to the display callback handler. This means your display handler must be safe to be run multiple times, which could require extra memory copying to save and restore states. It also is a performance hit as each display redrawn must be done twice. I suggest you don't use freeglut on Windows in EECS 487.
#include <GL/glut.h>You don't need to include
gl.hand
glu.h, as they are already included in
glut.h.
opengl32.lib;glu32.lib;glut32.lib;
/SUBSYSTEM:WINDOWS /ENTRY:mainCRTStartupthen click "Apply" (Fig. 37). You may not want to disable the console window if you print out messages to the console (see next step).
glut32.dllwith your distribution. Unfortunately there doesn't seem to be any precompiled statically linked GLUT library for Windows.
glBindBuffer()and those that use shaders segfault on the call to
glCreateProgram(). So we'll build WGL apps instead. The compiler toolchain that comes with Cygwin can build WGL apps (see Building OpenGL/GLFW Apps), but unfortunately there is no GLUT library that works with it. The available freeglut binaries for MinGW makes duplicate calls to the display callback hanlder as noted above. The Nvidia's GLUT binaries were evidently not compiled to support large memory model, resulting in "relocation truncated to fit" error messages from the linker. Fortunately, the MinGW x86_64 compiler toolchain can work with the Nvidia's GLUT libraries, so we'll use this toolchain instead of the native Cygwin toolchain.
Devel→mingw64-x86_64-gcc-g++The setup program will figure out, download, and install all necessary dependencies. To use WGL instead of GLX under Cygwin, you need to link your program against native Win32 graphics libraries. Let YOUR_TOOLCHAIN be
x86_64-w64-mingw32and replace every occurrences of YOUR_TOOLCHAIN below with x86_64-w64-mingw32 (we'll see the use of other toolchains later). Verify that you have the Win32 version of OpenGL and GLU installed:
/usr/YOUR_TOOLCHAIN/sys-root/mingw/lib/libopengl32.awith the OpenGL include files in:
/usr/YOUR_TOOLCHAIN/sys-root/mingw/lib/libglu32.a
/usr/YOUR_TOOLCHAIN/sys-root/mingw/include/GLYou would then need to add the path /usr/YOUR_TOOLCHAIN/sys_root/mingw/bin and /usr/YOUR_TOOLCHAIN/bin to your search path, i.e., your environment PATH variable, for binaries and dynamically linked libraries (dll). (As such, you can only have one toolchain in use for a given PATH environment variable.)
/cygdrive/c/Program\ Files\ (x86)/NVIDIA\ Corporation/Cgas follows:
/usr/YOUR_TOOLCHAIN/include/GL/You'd have to create the include and GL directories.
/usr/YOUR_TOOLCHAIN/lib/libglut32.aWhen linking against a library, unlike Visual Studio, the MinGW/Cygwin linker looks for either lib<pkg>.a or <pkg>.lib, not lib<pkg>.lib.
/usr/YOUR_TOOLCHAIN/bin/glut32.dllRemember to add /usr/YOUR_TOOLCHAIN/bin to your environment PATH variable prior to launching your app, as noted above.
-lglut32 -lglu32 -lopengl32[Some antivirus software such as Avast! may automatically move the binary you build into its virus quarantine folder. You may want to exclude your working folder from automatic virus quarantine.]
Devel→cygwin32-gcc-g++use the following labels, respectively, in place of YOUR_TOOLCHAIN above:
Devel→mingw64-i686-gcc-g++
Devel→mingw-gcc-g++
i686-pc-cygwin,
i686-pc-mingw32, or
i686-w64-mingw32. For
i686-pc-cygwin, the subdirectory under
sys-rootis called usr instead of mingw. | http://web.eecs.umich.edu/~sugih/courses/eecs487/glut-howto/ | CC-MAIN-2017-30 | refinedweb | 1,048 | 52.15 |
On Mon, 2007-07-09 at 22:06 +0200, Cedric Le Goater wrote:> Badari Pulavarty wrote:> > On Fri, 2007-07-06 at 12:01 +0400, Pavel Emelianov wrote:> >> This is "submition for inclusion" of hierarchical, not kconfig> >> configurable, zero overheaded ;) pid namespaces.> > > > Not able to boot my ppc64 machine with the patchset :(> > I can't boot either on a x86_64 but I don't even have logs to send :(Yes. It blew up way early in the boot on my x86_64, so nothing cameup on the console to capture (blank screen) :(Thanks,Badari-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at | http://lkml.org/lkml/2007/7/9/418 | CC-MAIN-2013-48 | refinedweb | 121 | 61.19 |
Solving problem is about exposing yourself to as many situations as possible like Iterating over every two elements in a list Iterating over every two elements in a list, which can be followed any time. Take easy to follow this discuss.
How do I make a
for loop or a list comprehension so that every iteration gives me two elements?
l = [1,2,3,4,5,6] for i,k in ???: print str(i), '+', str(k), '=', str(i+k)
Output:
1+2=3 3+4=7 5+6=11
Answer #1:
You need a
pairwise() (or
grouped()) implementation.
For Python 2:
from itertools import izip def pairwise(iterable): "s -> (s0, s1), (s2, s3), (s4, s5), ..." a = iter(iterable) return izip(a, a) for x, y in pairwise(l): print "%d + %d = %d" % (x, y, x + y)
Or, more generally:
from itertools import izip def grouped(iterable, n): "s -> (s0,s1,s2,...sn-1), (sn,sn+1,sn+2,...s2n-1), (s2n,s2n+1,s2n+2,...s3n-1), ..." return izip(*[iter(iterable)]*n) for x, y in grouped(l, 2): print "%d + %d = %d" % (x, y, x + y)
In Python 3, you can replace
izip with the built-in
zip() function, and drop the
import.
All credit to martineau for his answer to my question, I have found this to be very efficient as it only iterates once over the list and does not create any unnecessary lists in the process.
N.B: This should not be confused with the
pairwise recipe in Python’s own
itertools documentation, which yields
s -> (s0, s1), (s1, s2), (s2, s3), ..., as pointed out by @lazyr in the comments.
Little addition for those who would like to do type checking with mypy on Python 3:
from typing import Iterable, Tuple, TypeVar T = TypeVar("T") def grouped(iterable: Iterable[T], n=2) -> Iterable[Tuple[T, ...]]: """s -> (s0,s1,s2,...sn-1), (sn,sn+1,sn+2,...s2n-1), ...""" return zip(*[iter(iterable)] * n)
Answer #2:
Well you need tuple of 2 elements, so
data = [1,2,3,4,5,6] for i,k in zip(data[0::2], data[1::2]): print str(i), '+', str(k), '=', str(i+k)
Where:
data[0::2]means create subset collection of elements that
(index % 2 == 0)
zip(x,y)creates a tuple collection from x and y collections same index elements.
Answer #3:
1,2,3,4,5,6] zip(l,l[1:]) [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)] zip(l,l[1:])[::2] [(1, 2), (3, 4), (5, 6)] [a+b for a,b in zip(l,l[1:])[::2]] [3, 7, 11] ["%d + %d = %d" % (a,b,a+b) for a,b in zip(l,l[1:])[::2]] ['1 + 2 = 3', '3 + 4 = 7', '5 + 6 = 11']l = [
Answer #4:
A simple solution.
l = [1, 2, 3, 4, 5, 6] for i in range(0, len(l), 2): print str(l[i]), '+', str(l[i + 1]), '=', str(l[i] + l[i + 1])
Answer #5:
While all the answers using
zip are correct, I find that implementing the functionality yourself leads to more readable code:
def pairwise(it): it = iter(it) while True: try: yield next(it), next(it) except StopIteration: # no more elements in the iterator return
The
it = iter(it) part ensures that
it is actually an iterator, not just an iterable. If
it already is an iterator, this line is a no-op.
Usage:
for a, b in pairwise([0, 1, 2, 3, 4, 5]): print(a + b)
Answer #6:
I hope this will be even more elegant way of doing it.
a = [1,2,3,4,5,6] zip(a[::2], a[1::2]) [(1, 2), (3, 4), (5, 6)]
Answer #7:
In case you’re interested in the performance, I did a small benchmark (using my library
simple_benchmark) to compare the performance of the solutions and I included a function from one of my packages:
iteration_utilities.grouper
from iteration_utilities import grouper import matplotlib as mpl from simple_benchmark import BenchmarkBuilder bench = BenchmarkBuilder() def Johnsyweb(l): def pairwise(iterable): "s -> (s0, s1), (s2, s3), (s4, s5), ..." a = iter(iterable) return zip(a, a) for x, y in pairwise(l): pass def Margus(data): for i, k in zip(data[0::2], data[1::2]): pass def pyanon(l): list(zip(l,l[1:]))[::2] def taskinoor(l): for i in range(0, len(l), 2): l[i], l[i+1] def mic_e(it): def pairwise(it): it = iter(it) while True: try: yield next(it), next(it) except StopIteration: return for a, b in pairwise(it): pass def MSeifert(it): for item1, item2 in grouper(it, 2): pass bench.use_random_lists_as_arguments(sizes=[2**i for i in range(1, 20)]) benchmark_result = bench.run() mpl.rcParams['figure.figsize'] = (8, 10) benchmark_result.plot_both(relative_to=MSeifert)
So if you want the fastest solution without external dependencies you probably should just use the approach given by Johnysweb (at the time of writing it’s the most upvoted and accepted answer).
If you don’t mind the additional dependency then the
grouper from
iteration_utilities will probably be a bit faster.
Additional thoughts
Some of the approaches have some restrictions, that haven’t been discussed here.
For example a few solutions only work for sequences (that is lists, strings, etc.), for example Margus/pyanon/taskinoor solutions which uses indexing while other solutions work on any iterable (that is sequences and generators, iterators) like Johnysweb/mic_e/my solutions.
Then Johnysweb also provided a solution that works for other sizes than 2 while the other answers don’t (okay, the
iteration_utilities.grouper also allows setting the number of elements to “group”).
Then there is also the question about what should happen if there is an odd number of elements in the list. Should the remaining item be dismissed? Should the list be padded to make it even sized? Should the remaining item be returned as single? The other answer don’t address this point directly, however if I haven’t overlooked anything they all follow the approach that the remaining item should be dismissed (except for taskinoors answer – that will actually raise an Exception).
With
grouper you can decide what you want to do:
from iteration_utilities import grouper list(grouper([1, 2, 3], 2)) # as single [(1, 2), (3,)] list(grouper([1, 2, 3], 2, truncate=True)) # ignored [(1, 2)] list(grouper([1, 2, 3], 2, fillvalue=None)) # padded [(1, 2), (3, None)]
Answer #8:
Use the
zip and
iter commands together:
I find this solution using
iter to be quite elegant:
it = iter(l) list(zip(it, it)) # [(1, 2), (3, 4), (5, 6)]
Which I found in the Python 3 zip documentation.
it = iter(l) print(*(f'{u} + {v} = {u+v}' for u, v in zip(it, it)), sep='n') # 1 + 2 = 3 # 3 + 4 = 7 # 5 + 6 = 11
To generalise to
N elements at a time:
N = 2 list(zip(*([iter(l)] * N))) # [(1, 2), (3, 4), (5, 6)] | https://discuss.dizzycoding.com/iterating-over-every-two-elements-in-a-list/ | CC-MAIN-2022-33 | refinedweb | 1,162 | 53.14 |
$108.00.
Premium members get this course for $122.40.
Premium members get this course for $159.20.
Premium members get this course for $389.00.
Premium members get this course for $259.00.
Premium members get this course for $167.20.
I must say I don't quite follow you with your dir's on c: (Why so many win95?? one is the installed c:\win95 or?)well anyway a workararound (It's not the best one but....) If you check the box with inf-installer that you always want to select your own NIC then you shuld be able to use the 'have disk' option and point it to some shared place on your network where you have a copy of your NIC's diskette and go from there. Thus making it semi automatic. You have to tell the installation to install the specific NIC but everyting else will be automatic.
By the way Are you using w95 or w95b (release 2)??? if not w95b maby you should try. It might have support for your NICs and then maby it can atodetect them (Or at least you can set them manualy whithout to much trouble)
If you feel this was enough help for you you can close this qestion or send me a comment (Or even reject it if you are not satisfied at all)
I wish you Good Luck
//Yin
//Yin
1. Batch.inf
2. Building batch.inf using the setup program
I have also had a bit of a surf and found an article which explained how to stop the oem product id dialog box comming up. (I'm using SR2). This article () also has information on auto logon during startup, hoever this is not auto logon to a domain server but just autologon to the PC.
I did find some information in technet about forcing the network card hardware selection. I have created the line s (in my batch.inf)
[Setup]
DevicePath=1
[Network]
netcards=*PCI\VEN_8086&DEV
IgnoreDetectedNetCards=1
I have also copyed my network card driver disk into the win95 install directory. so in this directory I have a file Netj3171.inf and a whole lot of subdirectories like on the driver disk.
When I run the win95 setup It is almost automat (I have to press enter to start the disk test, and select yes for the licence agreement screen) but when I get to the network driver section, it aks me to pick a driver. I then point to the win95 directory and a dialog box comes up to verify the driver and I hit ok. I then get an error message "This directory does not include any information about your hardware".
Daniel.
Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.
One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.
An exampel of a win95 install command.
p:\win95\install.exe /IW p:\win95\msbatch2.inf <a:\enter.txt
The undocumented swich /IW takes care of the agreeing to the licence. (Note: It must be with capital letters)
'inserting' enter.txt takes care of the enter part.... You will have to create a text file, preferrably with Edit.com where you just save a carrige return (Enter).
If I remember correctly your Netj3171.inf olso has to be in the \\server\share\win95\inf subdir and that you are not to keep the subfolders for the files on your network card driver disk. We skipped to automat the NIC identification since we used different NICs and this is our only input to install w95 together with User/Computername.
Tell me how it goes.
//Yin
The latest thing that I have tried is xcopy the network card driver disk to c:\win95 and also c:\win95\inf. So I have a directory tree that looks a bit like....
c:\win95
c:\win95\dos
c:\win95\info
....
c:\win95\win95
c:\win95\inf\dos
c:\win95\inf\info
.....
c:\win95\inf\win95
I also have copies of netj3171.inf in both c:\win95 and c:\win95\inf.
In my batch.inf I have the following lines....
[setup]
DevicePath=0
[Network]
IgnoreDetectedNetCards=0
ValidateNetCardResources=1
;netcards=PCI82557B,PCI825
;We are relying on plug and play here
When I run the setup with these options I get the error message..
Error SU0335
Setup could not determine your hardware settings. There may be a missing or damaged Setup file or there may not be enough memory to continue. Free some memory and then run Setup again.
I press OK and get
Error SU995019
Control Data corrupt (0x139b)
I was wondering, do I need to tell some part of the setup to scan netj3171.inf for the driver information, or does the mere fact that it is in the win95 directory enough ?
The other question Yin is how do I close this question so you get your rating etc... | https://www.experts-exchange.com/questions/10025723/Automated-installs-of-Windows-95-application.html | CC-MAIN-2018-09 | refinedweb | 840 | 73.58 |
Foreign.Storable.Record
Description
Here we show an example of how to define a Storable instance with this module.
import Foreign.Storable.Record as Store import Foreign.Storable (Storable (..), ) import Control.Applicative (liftA2, ) data Stereo a = Stereo {left, right :: a} store :: Storable a => Store.Dictionary (Stereo a) store = Store.run $ liftA2 Stereo (Store.element left) (Store.element right) instance (Storable a) => Storable (Stereo a) where sizeOf = Store.sizeOf store alignment = Store.alignment store peek = Store.peek store poke = Store.poke store
The
Stereo constructor is exclusively used
for constructing the
peek function,
whereas the accessors in the
element calls
are used for assembling the
poke function.
It is required that the order of arguments of
Stereo
matches the record accessors in the
element calls.
If you want that the stored data correctly and fully represents
your Haskell data, it must hold:
Stereo (left x) (right x) = x .
Unfortunately this cannot be checked automatically.
However, mismatching types that are caused by swapped arguments
are detected by the type system.
Our system performs for you:
Size and alignment computation, poking and peeking.
Thus several inconsistency bugs can be prevented using this package,
like size mismatching the space required by
poke actions.
There is no more restriction,
thus smart constructors and accessors
and nested records work, too.
For nested records however,
I recommend individual Storable instances for the sub-records.
You see it would simplify class instantiation if we could tell the class dictionary at once instead of defining each method separately.
poke :: Dictionary r -> Ptr r -> r -> IO ()Source | http://hackage.haskell.org/package/storable-record-0.0.3/docs/Foreign-Storable-Record.html | CC-MAIN-2015-14 | refinedweb | 257 | 59.8 |
Ed Bundy5,407 Points
Could you just as easily have used var name instead of const name and made sure that name was local to the function?
I thought variable names are local to functions and therefore you can declare and use the same names within different functions without affecting each other. In that case, it would seem that the error is simply forgetting to use a declaration of a new variable. So the mistake of forgetting to do so would just as easily happen whether you use var or const.
In that case, it seems like a better example of the use of const would be in creating the global variable. Or am I misunderstanding?
Ed Bundy5,407 Points
Actually, I notice in one of the quiz questions a scenario like I was talkng about.
"What happens when this code runs: const taxRate = 8.5; function calculateTax(cost, tax) { taxRate = tax; return (cost * taxRate) / 100; } console.log(calculateTax(100, 10);
"An Uncaught TypeError. is logged to the console" "You can't reassign the value of a constant."
The above code protects taxRate when it is declared outside the function. So there is no concern about using const within the function.
Anyway, I decided to find a workspace and plug in some code.
taxRate = 'mike'; function calculateTax(cost, tax) { var taxRate = 'joe'; return ((cost * tax) / 100); } document.write(calculateTax(100, 10)) document.write( "<br>" + taxRate);
I just changed taxRate to hold strings to put aside the calculations and just zero in on what happens to its value. Whether const or var is used to declare taxRate in the function, the global variable named taxRate is unchanged and prints as mike after the function has been run. So the video seems to be citing the advantage ES2015's const brings to the table by using it within the function, when really it was just his mistake in not forgetting to declare the variable within the function, and whether he used const or var really has no bearing.
I'm new to JavaScript, which is why I'm taking the course. So maybe I'm missing something here, but it seems like a poor example of what const brings to the table with ES2015 (though, I understand const is valuable. I'm surprised that this was something new with EC2015 ).
1 Answer
gregory gordonFull Stack JavaScript Techdegree Student 14,652 Points
as far as i see you are telling it taxRate = 'mike'; so you will always get mike. But once you set a var inside you are creating a different object.
Dave StSomeWhere19,786 Points
Dave StSomeWhere19,786 Points
Not really, that's the whole purpose of const - it doesn't implicitly get defined in the global scope, so you can't make the same error with const.
From MDN Const
"Constants are block-scoped, much like variables defined using the let statement. The value of a constant cannot change through reassignment, and it can't be redeclared." | https://teamtreehouse.com/community/could-you-just-as-easily-have-used-var-name-instead-of-const-name-and-made-sure-that-name-was-local-to-the-function | CC-MAIN-2019-51 | refinedweb | 496 | 70.73 |
In December, we announced the beta of Cloudflare Pages: a fast, secure, and free way for frontend developers to build, host, and collaborate on Jamstack sites.
It’s been incredible to see what happens when you put a powerful tool in developers’ hands. In just a few months of beta, thousands of developers have deployed over ten thousand projects, reaching millions of people around the world.
Today, we’re excited to announce that Cloudflare Pages is now available for anyone and ready for your production needs. We’re also excited to show off some of the new features we’ve been working on over the course of the beta, including: web analytics, built in redirects, protected previews, live previews, and optimized images (oh, my!). Lastly, we’ll give you a sneak peek into what we'll be working on next to make Cloudflare Pages your go-to platform for deploying not just static sites, but full-stack applications.
What is Cloudflare Pages?
Cloudflare Pages radically simplifies the process of developing and deploying sites by taking care of all the tedious parts of web development. Now, developers can focus on the fun and creative parts instead.
Seamless builds for developers
Getting started with Cloudflare Pages is as easy as connecting your repository and selecting your framework and build commands.
Once you’re set up, the only magic words you’ll need are `git commit` and `git push`. We’ll take care of building and deploying your sites for you, so you won’t ever have to leave your current workflow.
Instant feedback for teams
With every change, Cloudflare Pages generates a new preview link and posts it to the associated pull request. The preview link makes sharing your work with others easy, whether they’re reviewing the code or the content for each change.
Bullet-proof security and scale for enterprises
Every site developed with Cloudflare Pages is deployed to Cloudflare’s network of data centers in over 100 countries — the same network we’ve been building out for the past 10 years with the best performance and security for our customers in mind.
But wait, that’s not all
Over the past few months, our developers have been busy too, hardening our offering from beta to general availability, fixing bugs, and working on new features to make building powerful websites even easier.
Here are some of the new and improved features you may have missed.
Integrated experience, every step of the way
With Cloudflare Pages, we set out to make developing and deploying sites easy at every step, and that doesn’t stop at production. Launch day is usually when the real work begins.
Built-in, free web analytics
Speaking of launch days, if there’s one question that’s on my mind on a launch day, it’s: how are things going?
As soon as the go-live button is pressed, I want to know: how many views are we getting? Was the effort worth it? Are users running into errors?
The weeks, or months after the launch, I still want to know: is our growth steady? Where is the traffic coming from? Is there anything we can do to improve the user’s experience?
With Pages, Cloudflare’s privacy-first Web Analytics are available to answer all of these essential questions for successfully running your website at scale. Later this week, you will be able to enable analytics with a single click and start tracking your site’s progress and performance, including metrics about your traffic and web core vitals.
_redirects file support
Websites are living projects. As you make updates to your product names, blog post titles, and site layouts, your URLs are bound to change as well. The challenge is not letting those changes leave dead URLs behind for your users to stumble over.
To avoid leaving behind a trail of dead URLs, you should create redirects that automatically lead the user to your content’s new home. The challenge with creating redirects is coordinating the code change that changes the URL in tandem with the creation of the redirect.
You can now do both with one swift commit.
By adding a
_redirects file to the build output directory for your project, you can easily redirect users to the right URL. Just add the redirects into the file in the following format:
[source] [destination] [http code]
Example:
/home / 301 /contact-me /contact 301 /blog 301
Cloudflare Pages makes it easy to create new redirects and import existing redirects using our new support for
_redirects files.
Jam harder
When we started Cloudflare, people believed performance and security were at odds with each other, and tradeoffs had to be made between the two. We set out to show that that was wrong.
Today, we similarly believe that working collaboratively and moving fast are at odds with each other. As the saying goes, “If you want to go fast, go alone. If you want to go far, go together.”
We previously discussed the ways in which Cloudflare Pages allows developers and their stakeholders to move fast together, and we’ve built two additional improvements to make it even easier!
Protected previews with Cloudflare Access integration
One of the ways Cloudflare Pages simplifies collaboration is by generating unique preview URLs for each commit. The preview URLs make it easy for anyone on your team to check out your work in progress, take it for a spin, and provide feedback before the changes go live.
While it’s great to shop ideas with your coworkers and stakeholders ahead of the big day, the surprise element is what makes the big day, The Big Day.
With our new Cloudflare Access integration, restricting access to your preview deployments is as easy as clicking a button.
Cloudflare Access is a Zero Trust solution — think of it like a bouncer checking each request to your site at the door. By default, we add the members of your Cloudflare organization, so when you send them a new preview link, they’re prompted with a one-time PIN that is sent to their email for authentication. However, you can modify the policy to integrate with your preferred SSO provider.
Cloudflare Access comes with 50 seats included in the free tier — enough to make sure no one leaks your new “dark mode” feature before you want them to.
Live previews with Cloudflare Tunnel
While preview deployments make it easy to share progress when you’re working asynchronously, sometimes a live collaboration session is the best way to crank out those finishing touches and last minute copy changes.
With Cloudflare Tunnel, you can expose your localhost through a secure tunnel to an easily shareable URL, so you can get live feedback from your teammates before you commit (pun intended).
Speed, security & scalability — no really, we got you
Assets, optimized
It’s easy to get excited about all the new features you can play with, one of the real killer features of Pages is the performance and reliability.
We got a bit of a head start on performance because we built Pages on the same network we’ve been optimizing for performance for the past ten years. As a result, we learned a thing or two about accelerating web performance along the way.
One of the best tools for improving your site performance is by serving smaller content, which takes less time to transfer. One way to make your content smaller is via compression. We’ve recently introduced two types of compression to Pages:
Image compression: Since images represent some of the largest types of content we serve, serving them efficiently can have great impact on performance. To improve efficiency, we now use Polish to compress your images, and serve fewer bytes over the wire. When possible, we’ll also serve a WebP version of your image (and AVIF too, coming soon).
Gzip and Brotli: Even smaller assets, such as HTML or JavaScript can benefit from compression. Pages will now serve content compressed with gzip or Brotli, based on the type of compression the client can support.
While we’ve been offering compression for a long time now (dating all the way back to 2012), this is the first time we’re able to pre-process the assets, at the time of the build step, rather than on the fly, resulting in even better compression.
Another way to make content smaller is by literally shrinking it.
Device-based resizing: To make users’ experiences even smoother, especially on less reliable mobile devices, we want to make sure we’re not sending large images that will only get previewed on a small screen. Our new optimization will appropriately resize the image based on whether the device is mobile or desktop.
If you’re interested in more image optimization features, we have some announcements planned for later in the week, so stay tuned.
What’s next?
While today’s milestone marks Cloudflare Pages as a production-ready product, like I said, that’s where our true work begins, not ends.
There are so many features we’re excited to support in the future, and we wanted to give you a small glimpse into what it holds:
GitLab / Bitbucket support
We started out by offering direct integration with GitHub to reach as many developers as we possibly could, but we want to continuously grow out the ecosystem we interact with.
Webhooks
If you’re managing all of your code and content through source control, it’s sufficient to rely on committing your code as a way to trigger a new preview. However, if you’re managing your code in one place, but the content in another, such as a CMS, you may still want to preview your content changes before they go live.
To enable you to do so, we’ll be providing an endpoint you’ll be able to call in order to trigger a brand new deployment via a webhook.
A/B testing
No matter how much local testing you’ve done, or how many co-workers you’ve received feedback from, some unexpected behavior (whether a bug or a typo) is eventually bound to slip, only to get caught in production. Your reviewers are human too, after all.
When the inevitable happens, however, you don’t want it impacting all of your users at once.
To give you better control of rolling out changes into production, we’re looking forward to offering you the ability to roll out your changes to a percentage of your traffic to gain confidence in your changes before you go to 100%.
The future: full stack applications with Cloudflare Workers and Durable Objects
Supporting static sites is just the beginning of the journey for Cloudflare Pages. With redirects support, we’re starting to introduce the first bit of dynamic functionality to Pages, but our ambitions extend far beyond.
Our long term goal with Pages is to make full-stack application development as breezy an experience as static site development is today. We want to make Pages the deployment target for your static assets, and the APIs that make them dynamic. With Workers and Durable Objects, we believe we have just the toolset to build upon.
We’ll be starting by allowing you to deploy a Worker function by including it in your /api or /functions directory. Over time, we’ll be introducing new ways for you to deploy Durable Objects or utilize the KV namespaces in the same way.
Imagine, your entire application — frontend, APIs, storage, data — all deployed with a single commit, easily testable in staging, and a single merge to deploy to production.
The best part about this is getting to see what you build, so if you’re building something cool, make sure to pop into our Discord and tell us all about it. | https://blog.cloudflare.com/cloudflare-pages-ga/ | CC-MAIN-2021-21 | refinedweb | 1,971 | 57.2 |
Wikiversity:Colloquium
Contents
- 1 Extension request
- 2 Involvement in the Wikipedia Eduction Program
- 3 Hive Learning Networks
- 4 Wikiversity policy/guideline change process
- 5 Wikiversity at Wikipedia Science Conference
- 6 Introducing the Wikimedia public policy site
- 7 Templates to keep your user talk page clean
- 8 Topic specific discussion forum
- 9 Open call for Individual Engagement Grants
- 10 Programming Resource in scope?
- 11 Undeletion of user page of SolVelasco09265
- 12 Technological singularity
- 13 Extension:Variables
- 14 PlanetPhysics functions
- 15 Wikipedia copies
- 16 Tell about Wikiversity in mentorship program
- 17 Major changes to Fundamentals of Probability, Statistics, Experiments and Data
- 18 Grant submission
- 19 Speedy deletion of templates
- 20 Deletion of Sport/Volleyball
- 21 Reimagining WMF grants report
- 22 Are you concerned about Colloquium discussions getting so long they are hard to follow?
- 23 Assistant custodians group
Extension request[edit]
mw:Extension:Education Program has been requested via the Mailing list. Thoughts? - CQ (discuss • contribs) 15:56, 17 July 2015 (UTC)
Support - It looks like an extension that could help Wikiversity. I think it's worth a try. --I8086 (discuss • contribs) 16:03, 17 July 2015 (UTC)
Support - Yes, this extension should be enabled. -- Dave Braunschweig (discuss • contribs) 17:15, 17 July 2015 (UTC)
Support - see comment below. --Guy vandegrift (discuss • contribs) 23:39, 18 July 2015 (UTC)
Support I have used it in Wikipedia: it's good. Leutha (discuss • contribs) 20:41, 1 September 2015 (UTC)
I looked at the description for Wikipedia and must confess it makes no sense to me. Having said that, as long as it is voluntary and does not conflict with our usual openness, I'm in favor of it. I've been spending a lot of time on Wikipedia lately and have seen no signs of any Wikipedia Education Program, other than the usual. Is it for off-site use to bring in more editors? --Marshallsumter (discuss • contribs) 23:45, 17 July 2015 (UTC)
- I think what gets added by the extension can be seen at Wikipedia:Special:SpecialPages#Education. -- Dave Braunschweig (discuss • contribs) 00:11, 18 July 2015 (UTC)
- w:Special:Institutions shows the top level. The extension creates a number of Special pages. - CQ (discuss • contribs) 00:48, 18 July 2015 (UTC)
- I found it by searching for "Wikipedia Education Program" on Wikipedia. Generally, it seems to be a program usually from off-site educational centers to help potential editors to learn about Wikipedia, use Wikipedia, and with guidance editing designated entries to improve them. It can and does include research focused on Wikipedia projects like medicine. The number of such programs and off-site courses is large. It's an interesting idea perhaps motivated by the steady decline in new, successful editors for Wikipedia. Ultimately, it may turn out to be far more successful with the Wikiversities. Let's do it! --Marshallsumter (discuss • contribs) 02:47, 18 July 2015 (UTC)
┌─────────────────────────────────┘
This looks really exciting. Colleges and universities moving towards the w:Flipped classroom, and the wiki sisters should get involved, even though Wikipedia seems to be tripping over the jargon used to describe this trend (see LMS). At the moment the successful ventures seem to be commercial (see w:Category:Learning_management_systems, but this might change someday: The wikis never go bankrupt or get sold and have only improved (albeit at a slow rate). I am concerned that I can't seem to search into the middle of the alphabet in the long list of w:Special:Institutions, but that will eventually be fixed I'm sure. One advantage the wikisisters have over the commercial ventures is that we can so easily link in and out of Wikipedia.--Guy vandegrift (discuss • contribs) 23:38, 18 July 2015 (UTC)
Support - I think this extension, although there would be a lot of UI design to do, may get us forward to have "collaborative learning communities", such as free and open online courses (compare to MOOCS). --Teemu (discuss • contribs) 16:05, 21 July 2015 (UTC)
┌─────────────────────────────────┘
Dear All,
I just noticed this topic in the TOC when I saved my last edit. How fortuitous. I am the Education Program Extension's defacto spokesperson on the education program team at the Wikimedia Foundation. This page might be useful to your discussion: Outreach:Education/Extension. I hope you don't mind that I've added English Wikiversity under Possible Installations. :) If there is consensus to enable the extension on your project, please follow the steps listed here to request installation on Phabricator and please CC me in the task so that I can follow its progress and help out if needed. If I can answer any questions about the extension or be of further assistance to you in this discussion, please don't hesitate to ping me.
All the best, AKoval (WMF) (discuss • contribs) 22:54, 1 September 2015 (UTC)
I have requested the extension and started Wikiversity:Education extension. This discussion has been added to the talk page. Leutha (discuss • contribs) 10:15, 6 September 2015 (UTC)
Involvement in the Wikipedia Eduction Program[edit]
Is Wikiversity involved in the Wikipedia Eduction program ()? If not, should we be involved? According to me, the Wikiversity is a more logical platform to support education than Wikipedia. Timboliu (discuss • contribs) 09:50, 11 August 2015 (UTC)
- I added a question on the discuss-page of Wikipedia Education Program: Timboliu (discuss • contribs) 10:16, 11 August 2015 (UTC)
┌─────────────────────────────────┘
Dear Timboliu,
Thank you for initiating this conversation in the Wikiversity:Colloquium and at Outreach:Talk:Education. And thanks to Koavf and Grind24 for noting this on the Outreach:Village pump and for pinging me there. I'll reply here first and then note that in those other threads. It'd be helpful to centralize the discussion.
These are great questions that you ask. Thank you for asking them.
1) Should the Wikiversity Community be involved with the Wikipedia Education Program? The answer is YES! It is officially called the *Wikipedia* Education Program, but in reality, it is the *Wikimedia* Education Program. All 12 of the sister projects are being utilized in one or more WEPs worldwide.
2) Is Wikiversity already involved in the Wikipedia Education Program? The answer is also YES! There are a number of examples of Wikiversitarians and educators who have been involved with the Wikipedia Education Program through Wikiversity. For example:
"The Department of Computer and Systems Science at Stockholm University is running an advanced international training program,." More information at: Outreach:Education/Newsletter/May 2014/Wikimedia Sverige: Meeting the educators
." More information at: Outreach:Education/Newsletter/April 2014/Wikimedia Sverige: New resource for Swedish teachers on Wikiversity
"Some students at secondary school Katedralskolan in Skara, Sweden, have been nominated for a national prize celebrating the use of web publication in education, called "the Web star". They have produced an MOOC, Massive open online course, on Swedish Wikiversity including articles, podcasts, quizes, badges and resources they have authored and collected as part of their coursework." More information at: Outreach:Education/Newsletter/April 2015/Students nominated for their MOOC on Swedish Wikiversity
In 2007, User:Teemu created a course on English Wikiversity called "Composing free and open online educational resources." More information at: Outreach:Education/Countries/Finland#Wikiversity Course
ICT course curriculum on French Wikiversity (in French). More information at: fr.wikiversity:Projet:Atelier « Enrichir Wikipédia M1 CRDM Nanterre 2014»
La Trobe University piloted open education practices using Wikiversity. And Wikiversity was discussed at the 2013 Wikimedia in Higher Education Symposium at the University of Sydney. More information at: Outreach:Education/Countries/Australia
At the Vorarlberg University of Applied Sciences, has taught courses on German Wikipedia since 2011. More information at: Outreach:Education/Countries/Austria
@Guy vandegrift: and @Marshallsumter: seem to be veteran educators on this project. I wanted to include them in this conversation.
If there are other examples, I do hope that you will point them out to me. Very soon (this month approximately) I will begin systematically collecting historical data about Wikimedia Education Programs worldwide. And I want to be certain that Wikiversity is accurately counted.
There are so many teaching resources available to educators here on Wikiversity, for example, Portal:Learning Materials. There is also a smaller collection of materials at Outreach:Other_Wikimedia_Projects#Wikiversity. I'm sure that these pages are only the tip of the iceberg. It'd ben helpful to have a map of Wikiversity and a tour guide! :)
Lastly, Tim, I am very glad to know that you have been talking with Floor Koudijs about this as well. Her advice about education programs partnering with the existing Wikiversity community in their language is crucial to an education program’s success. We're looking forward to following your progress and supporting you along the way. All the best, AKoval (WMF) (discuss • contribs) 22:32, 1 September 2015 (UTC)
- Hi AKoval, it is great to read your message. Sometimes I feel like a voice in the wilderness when I'm talking about Wikiversity. The Dutch Wikiversity is still in beta and in the last four years I only convinced a few people to join me in learning projects :-) But, I'm still a believer. I will keep you posted on the developments. Cheers, Tim Timboliu (discuss • contribs) 09:46, 2 September 2015 (UTC)
Hive Learning Networks[edit]
Hi,
Is anyone familiar with Mozilla's Hive Learning Networks ()? I think these networks could be very interesting for Wikiversity? Does anyone know how these learning networks share learning material? I think the wikiversity could be the perfect platform for these learning networks.
Regards,
Tim, Timboliu (discuss • contribs) 08:42, 25 August 2015 (UTC)
- This is a very nice programs --103.1.92.93 (discuss) 03:18, 1 September 2015 (UTC)
- In my namespace I started to collect some information. See. Suggestions are welcome. Timboliu (discuss • contribs) 10:07, 1 September 2015 (UTC)
Wikiversity policy/guideline change process[edit]
Wikiversity at Wikipedia Science Conference[edit]
Thanks to Andy for his introduction to Wikiversity to the 80 odd people attending the Wikipedia Science Conference today. Leutha (discuss • contribs) 16:10, 2)
Templates to keep your user talk page clean[edit]
If you want your user talk page to be as clean as mine, use Template:Moveon top and Template:Moveon bottom to help you "move on" after the topic no longer interests you. To play with it, copy/paste this wikitext into your sandbox:
{{Moveon top|write a statement or summary here}} First statement :Second statement ::Third statement {{Moveon bottom}}
(The preceding unsigned comment was added by Guy vandegrift (talk • contribs) .)
- Just to note: it is not common to quickly archive or collapse discussions until there is plenty of time for responses to appear. "Clean" is not as valuable as "Complete." On the other hand, fast closing of discussions can be done when the discussion is considered harmful. We used to have a discussion archive bot running. (the bot was controlled by a page parameter that would set the archiving period, usually so many days after the last signed edit to a section.) That could be done again. I have been doing manual archiving of various process pages. Bot archiving is often less transparent, it depends on details. --Abd (discuss • contribs) 01:29, 5 September 2015 (UTC)
- I didn't know about archiving bots, but they sound interesting. My intent was to use the Moveon templates on user talk pages, not resource talk pages. Having said that, at Template_talk:Moveon_top I illustrated how the reopening of a closed discussion could be proposed/requested.--Guy vandegrift (discuss • contribs) 04:56, 5 September 2015 (UTC)
Topic specific discussion forum[edit]
Is there a way to create a discussion forum for a specific content? Me and several other educators are collaboratively creating content for Localization. It'd be great to have a discussion forum specific to this topic. --Jangrode (discuss • contribs) 19:14, 4 September 2015 (UTC)
I just realized, there's a discussion tab to every topic. This will probably fit the purpose. (The preceding unsigned comment was added by Jangrode (talk • contribs) .)
- Right. You may also create seminar subpages, with discussion, then, being in mainspace. (With talk being about the page process.) On discussion pages, such as seminars, comments should be signed. It is also possible to later refactor discussions, in ways that can summarize them. This can be a powerful technique for creating deep content that, I've seen, can have real-world impact. --Abd (discuss • contribs) 01:32,) (discuss • contribs) 15:30, 24 September 2015 (UTC)
Programming Resource in scope?[edit]
Id like to mirror some of the content here :
on Wikiversity as a resource.
I'd like to know if it's OK to do that ( the license on the source site is CC-Attribution).
Sfan00 IMG (discuss • contribs) 12:46, 9 September 2015 (UTC)
- Assuming details are handled properly, yes, this can be done. Since that site is on a single topic, it should be all subpages of a single page. Programming/BB4W could be the top-level page. I've noticed before that we have scattered programming pages, and that Programming is redirected to a topic. Moving the specific language pages to subpages of Programming will give fully descriptive page names. This classification of resources by page hierarchy has been going on for some years, with little opposition. But some may have different opinions. I do not suggest Programming languages/BB4W, Programming/Languages/BB4W or the usage of the full name of the language, "BBC BASIC for Windows." However, since there are many BASIC implementations, I'd prefer Programming/BASIC/BB4W. See w:BASIC and w:BBC BASIC.
- It should be possible to export all the pages from that wiki. A custodian may then import them. The import should show sufficient information to allow identification of the pages as imported from that wiki, as of a certain time, which, as long as that wiki is up, will then allow author attributions. The export and import could be full, i.e., with edit history, which can create some problems with user names. Those could be resolved by using a User name prefix. If that is done, attribution is full, stand-alone. User:Dave Braunschweig has done these imports, I think he's used a bot. --Abd (discuss • contribs) 16:18, 9 September 2015 (UTC)
- There isn't a direct export option available to normal users on Wikispace as far as I can tell (it's using it's own software not Mediawiki) The site is also "conveniently" excluded from Wayback. I don't think wikiversity has mirroring specilaists.
The concern I had was scope, given that the underlying language tool it's not exactly 'free' software, even though the wiki content is nominally CC-BY-SA 2.5. Is there someone that can give a definitive answer?
Sfan00 IMG (discuss • contribs) 16:34, 9 September 2015 (UTC)
- How to use non-free software is in scope here. See Windows. There is nobody that can give a definitive answer, but I'll assert that my answer is as likely to be representative of consensus here as any. There is no copyright issue, because of that license, if it attributed. It's not NC restricted, for example. Export is not going to work, perhaps. I attempted to Join. It's broken. Long story. I did manage to create a new account, and then the wiki asked me for information so the management of the wiki could approve the account. So, maybe I'll get a response. I've watched many wikis die because of overcontrol, or undercontrol.... It's an active wiki, though.
- Don't start until there is a response from, at least, a custodian, and I hope Dave will respond, that's why I pinged him with his user name. Definitely don't start creating random pages based only on the source wiki pagenames, but if you create a master page, then all pages can be copied with their original wiki pagenames. I cannot see a way to display the original wikitext with my unapproved account. This is all SNAFU. Wikipedia allows any user (including IP) to copy the wikitext, and to export the page as XML, with or without full history. The BB4w wiki does allow export of history as a .csv file, but it's only useful as a list of contributors, it does not include content information or links to revisions.
- There will be specific issues to be addressed, and they should be addressed before there are many pages to deal with. --Abd (discuss • contribs) 17:58, 9 September 2015 (UTC)
Wikispaces wikitext is not 100% compatible with MediaWiki wikitext. There will be either conversion or reformatting required to transfer content. Also, Wikispaces does not support exporting as far as I know, and I have management rights on a Wikispaces wiki. It may be just as effective to copy formatted text using a browser window and then paste the text into the VisualEditor, but I haven't tried that yet. It will be a page-by-page effort either way.
Wikispaces doesn't seem to be going away. My recommendation would be to develop resources here that link to the existing content rather than trying to mirror it at this point, unless everyone maintaining the Wikispace wiki is ready to move on for some reason. Otherwise, you'll end up with two different sources to maintain and ultimately a lack of consistency between them.
Regarding naming pages here, there is no advantage to putting this project under Programming, and no consensus that such a naming approach is appropriate. My suggestion would be to create a main project page for either BBC BASIC or BBC BASIC for Windows, and then create subpages below that. But, again, I would use the pages here to link to Wikispaces, unless everyone is ready to abandon the Wikispaces project and move the content here.
Let us know what additional assistance you need. -- Dave Braunschweig (discuss • contribs) 21:02, 9 September 2015 (UTC)
- It's not my wiki, I just thought the content might be useful here. ShakespeareFan00 (discuss • contribs) 22:27, 9 September 2015 (UTC)
- My comment about pagenames is part of a long-term organizational strategy, which has been going on for a long time, supported by many users and only recently questioned. It has never been formally established as consaensus. It is also never urgent.
- It is not crucial -- at all -- that a particular pagename be chosen for the highest level resource used for such a set of pages. It could easily be BB4W, which is unique, and the entire structure can later be moved with a single command. What would be a problem would be many different pagenames, not subpages of BB4W.
- I agree with Dave that there may not be much necessity, at least not immediately, to copy that content here. I was able to join, and look at the wikitext. Major project, moving it here, unless a translator is written. Creating an index to that wiki, here, could be useful, and far simpler. Later, if desired, the index could be turned into a fork or copy.
- I looked into w:wikispaces. Ugh. According to one source, wikispaces supports "raw export." Not XML export. Not sure what "raw export" means. However, "Organizers" appear to have the export option.
- Looks to me like any previous wiki that was hosted by wikispaces, other than wikis used for "Pre-K, K-12, or Higher Education," is in danger of disappearing. See the bestsoftware wiki. The owner of that wiki bailed when fees were set up (she wrote about it elsewhere). Sometimes a wiki under conditions like this will struggle on for a time. Wikispaces requires an "organizer" to handle payments, etc. Some wiki organizers, as seen on the comments on the Wikispaces announcement, are "no longer with us." I've seen a vibrant mailing list go south when the owner died or just disappeared, and had never designated co-owners. Can't even get the subscription list. Sometimes one can reconstruct at least those who sent email to the list.... If a MediaWiki installation is up, anyone can, anonymously, export the content as XML, with or without history. I used to use other wiki software. It all became unmanageable. So, "free license," but, in practice, restricted access. And then they shut that down. Users will not necessarily know it's coming, until they see that screen that shows on the bestsoftware wiki. Only the organizer will know, if the organizer is still active. The content is on archive.org, at this point, will likely stay there, but sometimes site owners request it be taken down. Archive.org stopped archiving the bestsoftware wiki in 2013.
- Wikispaces appear to have actively excluded their site from Wayback ( in effect ransoming some sites). Sfan00 IMG (discuss • contribs) 08:13, 10 September 2015 (UTC)
- It occurred to me that we could copy content here, then protect the pages, to avoid forking as long as the wikispaces wiki is functioning. One command, cascaded protection, of the top level page. Removable at any time by an admin if someone wants to update the pages. So if an importer is written, the importer could overwrite the existing content, but all of it would be in page history. --Abd (discuss • contribs) 01:46, 10 September 2015 (UTC)
- @Sfan00 IMG: I'd like to echo the above that reproducing the pages would possibly have the issue of having content that is not synchronized but that may not be a big deal. Maybe you want to have some basic documentation and you just want to reproduce it here to organize some contests or experiments, so you don't need every bleeding-edge edit to every page. It could definitely be useful. —Justin (koavf)❤T☮C☺M☯ 04:25, 10 September 2015 (UTC)
- What I was wanting to mirror was more to do with some of the techniques (and the assmbler routines menntioned) then specifcally BB4W.Sfan00 IMG (discuss • contribs) 08:12, 10 September 2015 (UTC)
Undeletion of user page of SolVelasco09265[edit]
I deleted this user page because it fit the following profile: a new user creates a user page and then creates an apparent resource that is actually solicitation for their business. Usually the user puts apparently harmless information on their user page such as "I'm Cristine and I live in London.
I'm interested in Continuing Education and Summer Sessions, Disc golf and Russian art. I like to travel and reading fantasy." This is from this former visible user page. The page the user created "Straightforward Solutions In Toe Pain In The UK" contains good information on foot health wrapped into a solicitation. The user is apparently female. I believe her account is globally locked so that she cannot receive email. But, WMF is seriously concerned about the low numbers of female contributors to WMF projects primarily Wikipedia. Should we undelete the user page and attempt email to ask the user to contribute learning resources here on foot health, without soliciting for her business, or leave the user page deleted. --Marshallsumter (discuss • contribs) 03:02, 11 September 2015 (UTC)
- The presumption that the user is female is not supported by the evidence. Bots don't have gender, and there's nothing about the edit to suggest that there is a person behind it. The deletion is appropriate, and no additional contact should be pursued. This is another example where we should accept that stewards have more information than we do, and a global lock as a spam-only account should be recognized as such. -- Dave Braunschweig (discuss • contribs) 03:22, 11 September 2015 (UTC)
- I agree--Guy vandegrift (discuss • contribs) 09:34, 11 September 2015 (UTC)
- I have occasionally considered attempting to engage with a user like this. Then, when I realized that the user information was almost certainly false (inconsistencies in it), I abandoned that idea. Once in a while I've attempted to engage a spammer. It has never worked. But it might work if someone merely looks like a spammer. And, definitely, stewards make mistakes. Just not many. When I see a global lock, I often look at account contributions. It's rare to see even a possibility of an error. However, I've come across errors from other means. There are about 20,000 accounts locked per year, last I looked it's a huge flow. There are stewards of whom I would have said they never make a mistake. Then I found one, a usage of the lock tool well outside of original intention (give a man a hammer, he finds nails to hit).
- Marshall, consider leaving the user page be for a bit, when you see one of these that has a remote possibility of being sincere. Realize that the user page does not help the user get away with creating spam. I do not welcome users from these user page creations, I welcome from any edit that looks like it might be sincere. So I look at discussion page red links, not the user page redlink. Then I look at new page creations. Then at resource edits.
- Dave is correct. It is unlikely that the user is "female," Consider a female user named "Cristine" who creates a user name like SolVelasco09265, an apparently male name. It makes no sense. Again, that page follows a formula, I saw it many times doing Recent Changes patrol here. "I am [A], I live in [B], I'm interested in [C], [D], and [E]. I like [F] and [G]." That this was followed quickly by a spam page creation, has gone beyond a reasonable doubt: Spammer. Was the edit related to "Continuing Education and Summer Sessions, Disc golf and Russian art"? No.
- Was the solicitation related to podiatry? If a podiatrist wanted to announce their practice here, in good faith, they could actually do it. But they would not start with this BS user page. They would start with something like, "Hi, I'm Donald Gregory, and I'm a podiatrist in private practice in the U.K. I'd like to help create educational resources on podiatry here." Maybe they would put a link to their web site on their user page. We might remove that link and tell them that if they do create some podiatry resources, we may consider allowing a relevant personal link. And we do allow that.
- No, this was a spammer, perhaps an illegitimate SEO optimizer, possibly paid by incoming traffic driven by placed links. I found a page, googling the same name on a Korean web site. (UK on a Korean web site? hello?). However, that page did not seem to have any link. Did the page here mention bathing in the Dead Sea? The page is a dead link, or the site is down, but I could read it with google translate. The page was weird. Paragraphs put together as good English, more or less, but the presentation very choppy, as if pieces were put together by a bot. Hmm... !!!
- In this case, the steward locked a series of accounts at the same time. Stewards identify these accounts with checkuser, typically (and at least one steward uses checkuser on log-in wiki, and they block suspected spammer sock accounts with no edits, based on registration data. Here is the lock log showing that series of account locks: [7]. The first locked account was the one that only edited here, 2 edits, as you reported. No other edits globally. The pattern of what might seem to be a possibly decent article with an embedded spam link is common. They can get through many recent changes patrollers with that. If the user appeared to be good faith, I'd just remove the link. The resource, however, was inappropriate for here anyway, at least under that name! I looked at some of the other accounts. All were 2 edits on one wiki, different wikis, one of the pair to the user page. I could look at account creation times and see more of the story, but I didn't.
- Then, bottom line: the users behind these accounts have very little invested in them. If they did happen to be good faith, they would simply register another account, and if they show a good contribution, certainly if they do that here, we could protect them. Global locks are not global bans. These accounts were almost certainly detected because of many registrations in a short period from the same IP, or similar. (A steward once globally locked maybe twenty accounts, they were students signing up to do a school project, all from the same IP. The steward quickly recognized his error and unlocked.) --Abd (discuss • contribs) 02:13, 12 September 2015 (UTC)
- The steward actions, I'm quite sure, significantly reduce the flow of spam from spambots. When I see what looks like spam here, I will look at global contributions. If I see a spam pattern, I then go to m:Steward requests/global and request global block (for IP) or global lock (for registered accounts). Should this happen to hit a rare sincere user, the damage is small. In this case, if it were worthwhile, I could probably verify the spamminess beyond a reasonable doubt, even without being able to see the pages. This particular spammer seems to have been using many accounts each making two edits to a local wiki, thus making it more difficult to detect. I would not be able to tell that the account was part of a puppet network. But for a steward with checkuser, it would be fairly easy.
- Dave is right, in general. There can be exceptions. They are rare, and this is not one. --Abd (discuss • contribs) 02:13, 12 September 2015 (UTC)
Technological singularity[edit]
A user uploaded several self-created logos and abstract images to Commons, and they were then nominated for deletion because they were thoroughly out of the project's scope. Taking advantage of the Commons provision that all images in good-faith use by other WMF projects, someone created Technological singularity here and added all of this user's images to it. Is this a reasonable page hhere, something that is accepted as a proper page here? Nyttend (discuss • contribs) 00:17, 15 September 2015 (UTC)
- Thanks for the heads up. I've looked at one of the logo images. It's copyright is "Creative Commons Attribution-Share Alike 3.0 Unported license." so that's not a problem, if they are all that way. The one peculiarity so far is the request for a link to url= to use the image with the words "please include the words: "Singularity Utopia".". It's a .org rather than a .com which may mean it's not monetary solicitation. The logo artist is talking about an ideal gift economy which could make any resource the artist makes with these images fall under the School:Economics. The further comment "Unhappiness and discontent will be vanquished." is disturbing if a militaristic demand, that might put it under the School:Philosophy depending on intent, but not if a simple prediction. Many gift economies are contented. If the images have been uploaded here I believe they will remain if deleted at commons. Let me know if this is not the case and I'll change their names so they can remain. They do have educational value here immediately as another gift economy and could be put as a subpage to Gift economy if the artist does not begin to create a resource. The same can be said of Technological singularity itself. As a resource it can stay as is to see if the artist wants to develop it further. If not right away it can also become a subpage to Gift economy or to the artist's user page if there is one. I would say at first glance Technological singularity is a reasonable page here and as such is acceptable as a proper page. We often organize these under the user's page or another as I mentioned such as Gift economy. I hope this information is helpful. --Marshallsumter (discuss • contribs) 02:41, 15 September 2015 (UTC)
I would add that the page itself could be reasonable as an example of an artist's work, but at this point shows no connection to technological singularity. It could be an artist's vision of the concept, but to me would be better created as a subpage of something, either examples of art related to technological singularity, or simply as examples of art of the creator, or examples of art of the given style.
But what User:Nyttend is really asking is related to Commons:Deletion_requests/Files_uploaded_by_Ps2045. The observation that a page was created here simply to block the deletion request without any other educational value is a valid assessment at this point. If the artist had created a page and explained and exemplified the concept, this would absolutely be a valid project of educational value. If someone else had likewise created a page and explained and exemplified the artistic concept, that would absolutely be a valid project of educational value. As it stands right now, it appears to be just an attempt to block deletion. More work needs to be done on this project to make the educational value apparent.
It does not appear that the images have been uploaded to Wikiversity. They are on Commons only. I wouldn't have any problem with the artist uploading them here and creating a learning project about this art if Commons doesn't want the files. I am concerned about others jumping in here just to prevent the deletion of these images at Commons. Let's teach others how to create valid educational content rather than just rescuing the content from other WikiMedia projects, which otherwise has no educational value.
Dave Braunschweig (discuss • contribs) 12:52, 15 September 2015 (UTC)
- I did a quick concept search on Google Advanced Scholar and came up with about 1,480 references. From this I could develop the resource enough to remove the prod but I was hoping user Ps2045 would be interested in doing that. Unfortunately, this user appears to have given up and left because of an inability to upload files. There may be a time delay before new users are autoconfirmed to upload files. I left a message how to use "Upload file" but no response has occurred. In using our search engine I noticed we do not even have a resource entitled Futurism. This I can also create. But regarding the user, I was unaware of the problems until 15 September. So what would the community like? Although Abd apparently has email exchanges with this user I've received no word of response on file uploads. I uploaded one of the user's files here that might make a good image either for Futurism or Technological singularity which the references I've found describe well. --Marshallsumter (discuss • contribs) 20:00, 16 September 2015 (UTC)
- If I receive no negative responses I'll go ahead and create or expand both Futurism and Technological singularity. I don't know why the user was having trouble uploading files other than perhaps a lack of familiarity. --Marshallsumter (discuss • contribs) 22:21, 16 September 2015 (UTC)
- Brand new users can't upload files. They have to wait until they are auto-confirmed. It's a combination of days and/or edits. I don't have a problem with anyone working on this resource if it interests them. But I am concerned about doing more work for a resource than the user whose content we're trying to assist with. I'd much rather see the user engaged in that process. -- Dave Braunschweig (discuss • contribs) 02:09, 17 September 2015 (UTC)
- I agree on the participation of the user whose artwork I am using. The curious thing about Technological singularity is what I've been presenting so far in the lecture/article. This idea has been around since the sixties and now the prediction is 2045. That may become another 18 more years from a full century. I'm not saying it won't happen. But having lived through this entire period, I am adding notes in the text I've written so far that may serve a far greater educational purpose than originally intended. That is "the future isn't written yet. So make it a good one." a paraphrase of Doc Brown in Back to the Future, part III.
- Thanks for the info on the autoconfirmation. This is proving to be more fun (as a learning experience) than expected. I'll create Post scarcity and Futurism using the artwork. If the artist is still out there, we'll be reading from it. If not, we'll have some educationally good, hopefully, resources on futurism, gift economy, and realism. Comments, criticisms, questions, suggestions, and insightful additions are most welcome and can be presented for discussion on the Discuss pages. I'm tentatively uploading the artwork as Fair Use since the outcome on Commons is up in the air but moving in a positive direction. If they decide to keep all of it, or some of it, someone can change the licensing if they want. Alternate versions of each of these resources, and there are lots of alternate titles, are also most welcome. I'm just presenting one or two points of view at the moment. --Marshallsumter (discuss • contribs) 03:39, 17 September 2015 (UTC)
Extension:Variables[edit]
This is a proposal to add the mw:Extension:Variables extension to Wikiversity. Having variables available on the page would allow us to set up more complex numbering and counting sequences, such as being able to pass item numbers to templates and modules. If there is support, I will create a phabricator request to have the extension added. -- Dave Braunschweig (discuss • contribs) 17:27, 19 September 2015 (UTC)
Discussion[edit]
@Marshallsumter: There's a template I use frequently in my lessons that requires a unique number for each instance that it is called. It sets up the review questions I use and allows the user to toggle each one individually and see the answer. So far I've been numbering them manually, but always wanted to find a way to automate that. I tried today using Lua to solve the problem, but found that each #invoke generates a new environment. But in the process of searching for MediaWiki variables, I came across this extension. I thought it would already be turned on, since we have Parser Functions turned on, but that's not the case. So, I thought I'd see if we can enable it. My understanding is that we have to have a conversation we can point to that shows the community supports the extension, and then we can get it added. As for additional extensions, start with mw:Manual:Extensions. -- Dave Braunschweig (discuss • contribs) 00:35, 20 September 2015 (UTC)
Vote[edit]
Support - Dave Braunschweig (discuss • contribs) 17:27, 19 September 2015 (UTC)
Support - with the caveat that I have no immediate need for this extension and won't object if it is not installed (too many pots on the stove already) --Guy vandegrift (discuss • contribs) 19:59, 19 September 2015 (UTC)
Support - having as much flexibility as possible is great even if I don't know how to use it yet. But, I was wondering how you learned about it. Perhaps there are more such mediawiki features that would help us. My request at phabricator to have the PlanetPhysics additional variables turned on only received a curiously vague response. Is there some sort of catalogue of special features at mw that we can peruse? --Marshallsumter (discuss • contribs) 23:05, 19 September 2015 (UTC)
Support --SB_Johnny talk 08:35, 20 September 2015 (UTC)
Support - this looks like a useful extension. If it proves to be un-useful, it can always be deactivated. Green Giant (talk) 11:36, 20 September 2015 (UTC)
Support - Leutha (discuss • contribs) 10:18, 21 September 2015 (UTC)
Status[edit]
The request has been created as T113859. The quick response is that the Variables extension conflicts with VisualEditor and is unlikely to be added. -- Dave Braunschweig (discuss • contribs) 19:31, 26 September 2015 (UTC)
PlanetPhysics functions[edit]
Apparently there is a custom I was not aware of that to, for example, turn on variables in our math, wikimath, or LaTex, we need to show a Colloquium consensus. I already have a request at phabricator number T104698 to turn on variables or functions so that PlanetPhysics resources are fully functional. Please indicate your support or not for turning these on, or perhaps all that are available on, so we can use them and PlanetPhysics is fully operational. I will start to list them as I find them just in case we have to ask for each one. As soon as we have say at least three supports I'll add a comment to T104698 with a link here.
- \vcenter{}
- \begin{definition}
- \newcommand{}
- \documentclass{}
Discussion[edit]
@Marshallsumter: Have we confirmed that these are legitimate Latex Math commands, and not just PlanetPhysics extensions? I know the PlanetPhysics editors defined a number of things themselves. I never researched whether they were legitimate extensions or their own creations. -- Dave Braunschweig (discuss • contribs) 00:11, 21 September 2015 (UTC)
- I tried searching for number one above on the full web with Google and found this "For fancy math stuff with LaTeX see the AMS documentation." at [homepages.inf.ed.ac.uk/imurray2/compnotes/latex.html Latex Notes]. If WMF has available to it the AMS documentation and thereby all LaTex functions then as many as possible should turn on. We can also add this to the request, just in case.--Marshallsumter (discuss • contribs) 00:29, 21 September 2015 (UTC)
- I checked (\med) and this is a function that can be defined using the new number three above. Depending on what WMF has they may have to load amsmath and amssymb packages of LaTex. --Marshallsumter (discuss • contribs) 00:35, 21 September 2015 (UTC)
- On Wikibooks there is url=. --Marshallsumter (discuss • contribs) 00:42, 21 September 2015 (UTC)
- I never understood why our Latex needs to be different from Wikipedia's. I say this not because I advocate importing/exporting between these wikis, but because it seems like it would be easier to simply mirror Wikipedia and let them make the decisions. The decision to differ from Wikipedia was made long before I arrived, and perhaps there were considerations I don't know about. --Guy vandegrift (discuss • contribs) 00:52, 21 September 2015 (UTC)
- This is interesting because PlanetPhysics has 72 resources for which
is not working. It may mean that the math brackets are missing for these. --Marshallsumter (discuss • contribs) 01:32, 21 September 2015 (UTC)
- Here's another problem, \mathbf is supposed to bold what's in between but instead does this:
. Apparently the expressional form is different. --Marshallsumter (discuss • contribs) 01:40, 21 September 2015 (UTC)
- The new number four doesn't work here or on Wikipedia. Whether math brackets are present or not. --Marshallsumter (discuss • contribs) 01:56, 21 September 2015 (UTC)
- <:math>\left\{
\vcenter{\advance\hsize-1em \abovedisplayskip0pt \belowdisplayskip0pt \begin{align} a^{b+1}b^2&=a,\\ b^2-1&=b. \end{align}} \right</math>. This is another example of LaTex not working. If you remove the second : from after the < before math, these equations do not parse nor are they numbered. --Marshallsumter (discuss • contribs) 02:38, 21 September 2015 (UTC)
Vote[edit]
Support as proposer --Marshallsumter (discuss • contribs) 00:00, 21 September 2015 (UTC)
Support If these are missing math library items. Otherwise, it may be that we need a different <latex> tag and corresponding library.-- Dave Braunschweig (discuss • contribs) 00:11, 21 September 2015 (UTC)
Support with reservations noted above. Also, we currently have the
item installed.
Wikipedia copies[edit]
Dave Braunschweig has apparently suggested that we put a soft redirect such as the soft redirect on Sport/Volleyball/2015 U20 FIVB World Championships on Wikipedia copies as we find them. The category Wikipedia copies currently has 38 such resources. There was an ongoing effort sometime back to convert these to usable educational resources. What would the community like to do, or has a consensus been reached on this matter that I'm forgetting? I can start tagging each in the category with a soft redirect, including any more I find, unless there is a consensus against the soft redirects. Comments, questions, criticisms, suggestions are most welcome. --Marshallsumter (discuss • contribs) 18:17, 24 September 2015 (UTC)
- One additional point: putting a soft redirect on these resources changes their status from a content page to a non-content page and reduces our total number of content pages that are shown on the Main Page.
- Rocks/Glaciers is currently included in the category even though I have converted more than 95% to a Wikiversity resource. If the consensus is to replace these content pages with soft redirects I will remove any from the category that are more than 50% converted or are spoken for. --Marshallsumter (discuss • contribs) 19:04, 24 September 2015 (UTC)
- I have removed Rocks/Glaciers from the category. --Marshallsumter (discuss • contribs) 19:45, 24 September 2015 (UTC)
- Sport/Volleyball/2015 U20 FIVB World Championships, just FYI: I reinserted this page to see "What links here" but no other resource does even though subpages here are included in templates. So the page is being developed at least in this way. There are also links to Japan and Brazil that trigger the page being counted as a content page. The easiest thing to do is to insert references to the Wikipedia page for text copied from Wikipedia as I have done on quite a few resources and see what happens with the rest. I've temporarily put the page back to the soft redirect. --Marshallsumter (discuss • contribs) 20:23, 24 September 2015 (UTC)
- I've inserted references to the Wikipedia page and restored the page that was being developed. Please, let me know if there are disagreements with my actions. Unfortunately, the developer does not seem to communicate readily so for me it's a wait and see. --Marshallsumter (discuss • contribs) 20:39, 24 September 2015 (UTC)
- Sport/Volleyball/2015 U20 FIVB World Championships needs to be imported properly if it is to be kept with original content. Use Special:Import if this project is something you wish to support and encourage. -- Dave Braunschweig (discuss • contribs) 21:47, 24 September 2015 (UTC)
- Sport/Volleyball/2015 U20 FIVB World Championships was being converted to non-Wikipedia text before my involvement and with my additions and replacements is now about 10-15% converted. As such I am speaking for this resource. There is no need for additional blanking, import, or use of soft redirects. --Marshallsumter (discuss • contribs) 12:26, 25 September 2015 (UTC)
- Sport/Volleyball/2015 U20 FIVB World Championships is currently a violation of CC-BY-SA license. The original Wikipedia article must be imported so that the original authors receive credit for their work before derivatives are created and shared alike. As a custodian, you have the ability to import the source page and merge histories so that proper licensing is maintained. If more work is to be done on the volleyball project, the other subpages also need to be reviewed and perhaps imported to ensure that their edit histories properly credit the original authors. -- Dave Braunschweig (discuss • contribs) 12:40, 25 September 2015 (UTC)
- Plant physiology is a good example. It was C&P'd 07:33, 12 October 2008 by Emesee, added to by Jade Knight 21:49, 2 September 2009 with more C&P, then abandoned. There is way too much text here for an easy conversion to a Wikiversity resource. To me this is a prime candidate for a soft redirect. --Marshallsumter (discuss • contribs) 21:31, 24 September 2015 (UTC)
- Perhaps importing wasn't an option back in 2008. But Plant physiology is certainly a resource that should be redirected for now, and imported correctly if someone wants to extend it later. -- Dave Braunschweig (discuss • contribs) 21:47, 24 September 2015 (UTC)
- Plant physiology has now been blanked and soft redirected. --Marshallsumter (discuss • contribs) 00:52, 26 September 2015 (UTC)
Discussion[edit]
From my perspective, it goes back to Wikiversity:What is Wikiversity? and Wikiversity:What Wikiversity is not. Content copies that don't extend learning beyond what is already available elsewhere aren't adding value, and aren't as well maintained here as they are at the original source. To me, the choice is whether to delete and remove from search, or to use softredirect to point back to the original source. Users who are convinced Wikiversity needs this content seem to be more accepting of the softredirect than having no page at all.
If a user wants to correctly Wikiversity:Import content and develop it into a learning project, either for themselves or others, that's a different situation entirely than just straight copies without modification or learning value added. Perhaps a notice regarding Wikiversity Copy or a link back to the original source could go on the talk page of pages that have been kept and further developed.
Dave Braunschweig (discuss • contribs) 19:47, 24 September 2015 (UTC)
- All proposals are acceptable to me, but I vote for the soft redirect after blanking the page with a comment identifying this as a copy from Wikipedia. I see one disadvantage and the following three advantages to the soft redirect:
- Many Wikipedia articles suffer from too much irrelevant content and could be improved by making drastic cuts (see w:Timeline of quantum mechanics and it's derivative v:How_things_work_college_course/Quantum_mechanics_timeline)
- Blanking with a soft redirect decentralizes power because it is reversible by any editor. Undeletions can only be reversed by Custodians/Bureaucrats.
- I personally find it less tedious and less stressful to automatically blank with a redirect than to read through the page and its history and try to make a judgement of a page.
- The disadvantage against which we must weigh the advantages is that the redirect page will be a "Google-trap" for people searching for useful pages (this currently occurs with Google and the key words Wikiversity and Undelete.) Perhaps we could establish a category for soft-redirects so that some bot of the future could clean up the mess if this becomes a problem? Also, there might be other unforeseen consequences to these soft redirects. Does anybody know of any?--Guy vandegrift (discuss • contribs) 21:42, 24 September 2015 (UTC)
- I mentioned one in the upper section: a soft redirect removes the page from the list of content pages and lowers the total on Main Page. We are still missing about 8,000 such pages. --Marshallsumter (discuss • contribs) 01:33, 25 September 2015 (UTC)
- A softredirect category is unnecessary. A bot can look at the
{{softredirect}}template itself to see what pages use the template. I'm not too concerned about page counts. I'd rather have 10,000 high quality pages than 25,000 pages that are 60% stubs and other low-value offerings. -- Dave Braunschweig (discuss • contribs) 01:45, 25 September 2015 (UTC)
- A second disadvantage can be seen by comparing the history of Plant physiology with Sport/Volleyball/2015 U20 FIVB World Championships. Plant physiology was abandoned over six years ago and contained only C&P content. The latter was actively being converted away from Wikipedia content within the last 24 hours by the resource creator before blanking. A soft redirect was then applied. Does the community want me to be blanking actively edited Wikipedia copies, that are being converted away from the original Wikipedia content, followed by applying a soft redirect? --Marshallsumter (discuss • contribs) 11:56, 25 September 2015 (UTC)
- Content should not be blanked if it is being developed in good faith, but we must ensure that licensed content is being used for the development. If you find content copied from Wikipedia, you must import the underlying source to preserve edit history, or delete or blank the page as a license violation. Sport/Volleyball/2015 U20 FIVB World Championships was blanked and replaced with a softedirect because it was a license violation. The Volleyball user has been informed on multiple occasions on multiple accounts that content from Wikipedia must be imported rather than copied in order to maintain CC-BY-SA licensing. Their work no longer constitutes a good-faith effort. -- Dave Braunschweig (discuss • contribs) 12:58, 25 September 2015 (UTC)
I agree with Dave that we should be looking at things in terms of how "we" want WV to develop. So, taking Marshall's example, w:Timeline of quantum mechanics is no problem because it is inclusive, that is the role of an encyclopedia, but when creating an online learning environment we require more focus, thus works as a derivative, and in other circumatnces another derivative list may be produced to serve a different pedagogical purpose. I also agree that having a smaller number of effective pages is better than gaining a false sense of importance by counting substandard pages. Leutha (discuss • contribs) 14:12, 25 September 2015 (UTC)
- I just noticed that Dave provided me with a solid reason to delete pages that are nearly empty of content. If someone wants to import a Wikipedia article to Wikiversity, and the original page Wikiversity is not deleted, the process is very complicated.--Guy vandegrift (discuss • contribs) 21:53, 25 September 2015 (UTC)
- Here's a good example of a properly imported resource from Wikipedia Ancient Innovations. It has the imported tag Imported. The problem is that it has apparently had little or nothing done to it since it was imported in 2008. It was even prodded for deletion. With the exception of some small edits it is essentially unchanged. Should this be soft redirected? Wikipedia content isn't Wikiversity. It turns out this resource was moved here from Wikipedia before being deleted there. It is counted as a content page, but almost all the material has no citations. It would take a lot of work to bring this up to Wikiversity level as a learning resource. I'm tempted to prod it again. --Marshallsumter (discuss • contribs) 23:33, 25 September 2015 (UTC)
- Nothing but vandalism that is corrected and minor copy edits since 2008. I say "delete".--Guy vandegrift (discuss • contribs) 00:19, 26 September 2015 (UTC)
- Also, whatever edit history may have been with Ancient Innovations, it was not imported when the resource was imported here. The only edits in its history here are those made here. Perhaps when they began this importing process it did not include the edit history while the entry was still in Wikipedia.
- I have applied the usual prod to Ancient Innovations. It's really unfortunate that no citations to the contained statements were added to verify the claims made. --Marshallsumter (discuss • contribs) 14:44, 26 September 2015 (UTC)
- Applied ethics would normally get a soft redirect, but one of our bureaucrats (now perhaps considered inactive) left the following comment after removing a copyright violation tag, "00:23, 27 January 2008 Mu301 (discuss | contribs | block) . . (2,869 bytes) (-183) . . (copying from WP is not copyright violation)". This is odd. I've been using citations for text taken directly from WP, but Mu301 may be right. If so or something has changed since he became inactive it may not be a license violation to copy text with or without proper import. Referring to "If you find content copied from Wikipedia, you must import the underlying source to preserve edit history, or delete or blank the page as a license violation." Can you cite for me where you read this? For example, on each edit page we have hyperlink or URL back to Wikipedia is the only bit missing. While a soft redirect to the Wikipedia can be added to the resource once we realize where it's from, simply putting each in the Category:Wikipedia copies meets this requirement. Ironically, those copies we have not yet found wouldn't require deletion or blanking but just adding the category link is sufficient from a copyright violation point of view. What do you think? --Marshallsumter (discuss • contribs) 00:47, 26 September 2015 (UTC)
- The agreement to accept a link as sufficient attribution seems to be a decision of practicality by WikiMedia rather than a true application of CC-BY-SA licensing. According to Creative Commons, the author is to be credited if that information is available. Since we have the ability to import the article and credit the original authors, we should do so. -- Dave Braunschweig (discuss • contribs) 13:22, 26 September 2015 (UTC)
- I agree with the practicality of the WMF as practicality in this instance is the essence of the licensing you've cited. When I can find one or more authors for specific text from any of the WMF projects as well as outside such as NASA, I include them in the "author" line for the citation. For the article about the World Cup for women's volleyball as an example, the original text has been changed many times from the creator's work so that the citation I'm using is the practical and reasonable answer but unfortunately contains no "author" line. --Marshallsumter (discuss • contribs) 14:12, 26 September 2015 (UTC)
- If you import and then merge history, all authors are credited and the current content remains. I see import and merge as a benefit to all, so I'm not understanding the dilemma here. -- Dave Braunschweig (discuss • contribs) 14:36, 26 September 2015 (UTC)
- I've attempted to use Special:MergeHistory to merge the histories each of four ways:
- stating the source page as w:2015 FIVB Volleyball Women's World Cup,
-,
- 2015 FIVB Volleyball Women's World Cup, or
- 2015 FIVB Volleyball Women's World Cup,
but the feature does not allow merge to occur or even a presentation of possible merging to occur. Suggestions? --Marshallsumter (discuss • contribs) 15:03, 26 September 2015 (UTC)
- It won't allow a merge across projects. Import the source page to Wikiversity. Then merge histories from the imported page to the page you want to merge history into. Finally, view the history and make sure the edit version you want displayed is the current version. You can try it on a sandbox page first if you want, then delete as test when you're done. -- Dave Braunschweig (discuss • contribs) 16:04, 26 September 2015 (UTC)
- I tried using Special:Import with and without templates and received the message: "Import failed: Could not open import file". I was attempting "Import as subpages of the following page: Volleyball." Maybe it doesn't allow the sub page option. --Marshallsumter (discuss • contribs) 18:02, 26 September 2015 (UTC)
- Importing with templates probably won't work, particularly pages with as many templates as these use. I was able to import the page to a subpage of the Wikiversity:Sandbox with history, so it's not an issue of history or subpages. -- Dave Braunschweig (discuss • contribs) 18:13, 26 September 2015 (UTC)
- Thanks! The resource 2015 FIVB Volleyball Women's World Cup actually ended up in Mainspace instead of a sandbox subpage. No problem. I've merged the histories and put the import up for speedy deletion. This process is quite tedious yet I'm reluctant to put Special:Import under tools outside special pages. What do you think? --Marshallsumter (discuss • contribs) 18:42, 26 September 2015 (UTC)
- I'm not sure I understand the question. Special:Import is a restricted tool. It's only available to custodians. -- Dave Braunschweig (discuss • contribs) 19:13, 26 September 2015 (UTC)
- Now that's interesting! The write up on the page for the tool mentions that any user can import with this tool, not just custodians. I'll check the page history. --Marshallsumter (discuss • contribs) 00:23, 27 September 2015 (UTC)
- Found it on the page Wikiversity:Import, "Most of the work related to migrating imported pages does not require that you be a custodian." This suggests but does not confirm that only custodians can import. --Marshallsumter (discuss • contribs) 00:29, 27 September 2015 (UTC)
The softredirects that I have been applying to Wikipedia copies are showing up in Category:Wikiversity soft redirects. --Marshallsumter (discuss • contribs) 01:20, 27 September 2015 (UTC)
Tell about Wikiversity in mentorship program[edit]
Hi all,
I posted a suggestion on the co-op page about Wikiversity.
Cheers,
Tim, Timboliu (discuss • contribs) 07:46, 25 September 2015 (UTC)
- My understanding is that our mentoring program is informal. Perhaps we could improve in two ways:
- Work with Wikipedia to encourage qualified editor/authors to create parallel content pages on Wikiversity. As Leutha just pointed out, we want pages with more focus. And, we can tolerate many parallel pages on one subject. Up to this point, every would-be editor I met on Wikipedia turned out to be neither qualified nor motivated (or of course, not interested).
- Encourage newbies to post someplace, for now it could be the Colloquium. I hope we someday grow to the point where a special page for such posts becomes necessary, but for now the Colloquium seems as good a place as any.--Guy vandegrift (discuss • contribs) 21:46, 25 September 2015 (UTC)
- In order to increase trans-wiki activity I offered to become a mentor at w:Wikipedia:Co-op/Guy_vandegrift, a decision I hope I don't regret.--Guy vandegrift (discuss • contribs) 19:36, 26 September 2015 (UTC)
Major changes to Fundamentals of Probability, Statistics, Experiments and Data[edit]
I think both the name and the scope of Fundamentals of Probability, Statistics, Experiments and Data are too broad, and would like to rename the page and place its contents into various subpages. I also want to rewrite at least one section. In-depth discussion of this belongs at Talk:Fundamentals of Probability, Statistics, Experiments and Data, but brief comments concerning the process of rewriting pages, creating subpages, and selecting namespace titles do belong here because others might find it helpful--Guy vandegrift (discuss • contribs) 19:30, 26 September 2015 (UTC)
- I don't see any immediate problems. User Aravind V R has contributed in the past and is active so there may be some comments. --Marshallsumter (discuss • contribs) 19:41, 26 September 2015 (UTC)
Grant submission[edit]
Hi, here is a message to inform the Wikiversity community about my grant submission on Meta-Wiki. You are welcome to correct mistake, give opinion or endorse it. A nice end of the day for every one. Lionel Scheepmans ✉ Contact (French native speaker) 22:52, 26 September 2015 (UTC)
Speedy deletion of templates[edit]
Three or four templates appeared recently in the Category:Candidates_for_speedy_deletion on the basis of license violations. At least one of these was copied from Wikipedia and an import request apparently was not made. I suspect almost all templates used here on Wikiversity were copied at one time from Wikipedia or one of the other WMF projects such as Wikibooks and probably lack a category or merged history with its origin. One of our perhaps no longer active bureaucrats has pointed out that copying from Wikipedia is not a copyright violation and he may be right. In any case, if anyone believes that a template is a copy from Wikipedia they can always add the category Category:Wikipedia copies to it. Further, they can always make a request for import of the template to preserve author history if they wish to for custodial import of the template. But what would the community like to do about all our templates that have been copied from Wikipedia? Personally, while we are free to add any of these to the category mentioned or to a similar one for say wikibooks, I do not believe it serves the community to delete almost all of our templates that are not in one of these category types or lacks a merged history with its origin. What do you think? --Marshallsumter (discuss • contribs) 01:27, 28 September 2015 (UTC)
- If a template was imported for no reason, I see no reason to keep it. Templates get updated, and we risk having out-of-date templates. Do we have a reliable method for determining whether a template is being used? --Guy vandegrift (discuss • contribs) 01:53, 28 September 2015 (UTC)
- Some of the templates are linked to resources. This is available using Special:Whatlinkshere. There is a template "Template:Dontblockusername" the purpose of which may not be in the communities best interest, but I'm not sure about this. It links to no resource and is the only contribution of blocked User:Agahama. As always any user can put any resource here up for speedy deletion or use a prod. --Marshallsumter (discuss • contribs) 02:51, 28 September 2015 (UTC)
Adding a category identifies the problem, but does not address the underlying issue. Copied resources would either need to be imported to credit the original authors, or somehow linked to the original source to support the license agreement. -- Dave Braunschweig (discuss • contribs) 03:26, 28 September 2015 (UTC)
Deletion of Sport/Volleyball[edit]
On Wikiversity:Requests for deletion there is a request that all of the content and project it is under Sport/Volleyball or Volleyball be deleted for license violations. License violations as discussed above in the Section on Wikipedia copies consists of two parts:
- failure to cite authors such as those on Wikipedia.
At the bottom of each page we are about to save is "You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license." This applies to our resources and those copied from Wikipedia; hence, MikeU in the Wikipedia copies section above is correct that copying from Wikipedia is not a copyright violation. Further adding any resource we believe is copied from Wikipedia to the Category:Wikipedia copies complies with the quote included so that anyone wishing to check author history need only type in the resource title or some portion thereof, check the article history to view and if needed attribute authorship. Wikipedia recommends that anyone citing a Wikipedia article cite the author as "Wikipedia". So what would the community like to do? If MikeU is correct and the quote at the bottom of the page is appropriate and authorship per Wikipedia is only supposed to be "Wikipedia", then none of these resources have violated our license. What do you think? --Marshallsumter (discuss • contribs) 02:21, 28 September 2015 (UTC)
The special page for citing any Wikipedia page is Special:CiteThisPage. Type in any page title and the authors are suggested as "Wikipedia contributors" or depending on style chosen "Wikipedia". --Marshallsumter (discuss • contribs) 02:39, 28 September 2015 (UTC)
- I agree that copyvio is not a valid reason for deleting these pages (although I am no expert!). But they seem to be empty of content. If they are mere copies of Wikipedia articles, copy-pasting them was a good activity for the students. But that doesn't mean the articles should be saved. Have any of the individuals who pasted the articles requested that the articles been kept? --Guy vandegrift (discuss • contribs) 02:47, 28 September 2015 (UTC)
- Usually a C&P say from Wikipedia undergoes development here as some of the resources under Sport/Volleyball have, others like Plant physiology underwent none, so after say three years of nothing can be soft redirected or prodded, which I did. Those resources that refer to the ongoing World Cup for volleyball were actively being updated as events indicated until recently. All of the remaining articles in the Wikipedia copies category do not have requests that the articles be kept. I updated Glaciers and Ice cores out of the Wikipedia copies category. Others have done the same with some of the remaining ones. User Erkan Yilmaz was conducting a course or class on how to convert a Wikipedia copy to a Wikiversity resource in the past but I don't know the status of this now. --Marshallsumter (discuss • contribs) 03:03, 28 September 2015 (UTC)
There seems to be some confusion between copyright violation and license violation. Copying content from Wikipedia would not be a copyright violation. Copying it without either referencing the original authors (CC-BY-SA requirement) or proving a hyperlink or URL (WikiMedia alternative) is violating the license under which the original content was published. The only legitimate choices I see are to reference the original source or delete the content.
In the case of the Volleyball resources, we have a user (or multiple users who appear to edit as the same user using multiple accounts) who refuses to either import or reference sources, despite repeated attempts to encourage them to do so. The quantity of resources the user has created and continues to create makes custodial assistance in proper licensing of these resources untenable.
Note that continued development after the fact isn't relevant to the discussion. CC-BY-SA allows derivative works through the Share-Alike part of the license. But sharing alike would require a reference to the original source first.
I'm sorry, but I really don't see any way we can simply ignore the issue. CC-BY-SA is the basis for everything we do.
Dave Braunschweig (discuss • contribs) 03:23, 28 September 2015 (UTC)
Consider FIVB World U21 Women's Championships for the moment. It has no resource on Wikipedia from which it has been directly copied. The information being inputted is actually more accurate regarding its topic than the closest Wikipedia article. I estimate about 50-60% of the content may be from one or more Wikipedia sources formerly without attribution. If the resource creator continues this will drop below 50%. When it does by preponderance it can no longer be claimed to be attributable to Wikipedia.
While Sidelight12, for example, did import Ice cores and properly attribute it to Wikipedia, had I not stumbled across it. It probably would have been prodded for deletion just as Ancient Innovations has been.
I agree that these resource creators may not properly attributing Wikipedia as their source but some are linked to the Wikipedia source. I found 38 such resources here not properly attributed to Wikipedia. The number that actually are is unknown but probably much larger.
As I wrote above, anyone can put either speedy deletion tags or prods on any resource here they want to. But, a custodian must decide if deletion is the proper course. Almost none of our templates here attribute their source but deleting them definitely is not in the best interests of the community and would probably constitute serious disruption.
I'm not interested in ignoring the issue. I'm interested in handling the issues involved while resources are being developed. Each resource must be considered individually. Mass deletions are seriously frowned upon without consensus, large consensus, not just three or four of us.
Singling these World Cup oriented resource creations out for special attention while ignoring all the others here that are already here may be inappropriate. All of these unattributed pages here can best and only be handled individually. Regarding proper licensing these too can be easily handled on an individual basis. As I've demonstrated above importing isn't necessary to conform to our license. All that really is, involves testing the title on Wikipedia. If it's not there and nothing more than 50% similar is, it's not attributable to Wikipedia. Checking the time of likely C&P can demonstrate that the resource was copied in the past and from what. It takes a few minutes per resource. --Marshallsumter (discuss • contribs) 04:33, 28 September 2015 (UTC)
- I'm sure that Wikiversity has something resembling a charter, and somewhere is a rule stating that we must follow the licensing policy. We can't enforce it every time, and I'm sure I myself have forgotten to attribute material copied from Wikipedia. I think we could ignore this violation if the people who are downloading the files agreed to "work on the problem". But their silence on this is deafening. We don't have to go after every violation, but we can't ignore flagrant violations when they are brought to our attention. Am I right in saying that Abd tried hard to contact them? If so, I don't think we have time to fuss with this problem.--Guy vandegrift (discuss • contribs) 04:53, 28 September 2015 (UTC)
- I definitely agree with "I don't think we have time to fuss with this problem." I'm tired of it and it's disrupting my resource development and my research. The answer is simple. If anyone wants to put either a prod or a speedy delete individually on any of these resources I'll be happy to check them out, delete where appropriate, add a category where appropriate, etc. A large number as a mass deletion may constitute disruption so please one or two at a time. I'll do my best. The Russians for example seem to have read and understood. Their actions speak well of them. --Marshallsumter (discuss • contribs) 05:06, 28 September 2015 (UTC)
- We also need to seriously warn and/or block repeat offenders. The collection of subpages is so large I don't know where to begin. @Marshallsumter, Dave Braunschweig: You seem to be the "experts" on this problem. Is there a portion of it you can identify and hand over for me to handle? Also, is there a way to mass delete subpages? If so, we should encourage novices to do complex projects as subpages of a single page.--Guy vandegrift (discuss • contribs) 12:09, 28 September 2015 (UTC)
Marshallsumter asked at what point a derivative work no longer requires a reference. There is no such point. No matter what content remains, someone else's ideas led to the result. The only way attribution wouldn't be appropriate is if the entire page was blanked first, rather than building on what was provided.
The Volleyball resources have been singled out because they are an active work in progress. For more than a year now, we have been able to prevent new works from violating licensing requirements. Wikipedia copies were deleted. There are some who opposed that practice, so recently the pages were replaced with soft redirects. But the original content did not remain unlicensed. The primary exception is the Volleyball content. This is not only ongoing, but multiplying, and therefore needs to be resolved.
If we don't have time to fuss with the problem, we need to stop it. It is disruptive, and that, alone, is reason enough to block the users involved and eliminate the content. We also need to revert the whitelisting of the IP address that has led to the recurrence of this problem.
User:Guy vandegrift asked where to start on cleanup. I recommend using Special:NewPages and look first at the Template namespace. There are almost 100 templates created in the last week that need to be addressed.
Dave Braunschweig (discuss • contribs) 12:36, 28 September 2015 (UTC)
- I'm missing something here. Using Special:NewPages, there are no new templates and four new infoboxes, nine resources total by one user, since 17 September. That's about as many as I created. How do we find these remaining templates? --Marshallsumter (discuss • contribs) 13:55, 28 September 2015 (UTC)
- At the top of Special:NewPages, change the Namespace to Template. -- Dave Braunschweig (discuss • contribs) 14:13, 28 September 2015 (UTC)
- Thanks! That worked. I checked "Template:Country IOC alias GRE" which was at the bottom of the automated return. This template on Wikipedia was generated by a bot to fill in one of these Infoboxes apparently. It may be the case that the user here is doing the same. I don't know how to check for this. I'll check some more. These templates would not need a citation to Wikipedia if a bot here is generating them here based solely on IOC information. The only cite to IOC here is the same as on Wikipedia. --Marshallsumter (discuss • contribs) 14:50, 28 September 2015 (UTC)
- I checked another "Template:Vrt" to see if it was being generated on Wikipedia by a bot but this one appears to be unique to Wikiversity. This suggests but does not confirm that 50% of these new templates are unique to Wikiversity and the other 50% are bot generated on Wikipedia and maybe here. But these are only two data. --Marshallsumter (discuss • contribs) 14:59, 28 September 2015 (UTC)
- Here's a third "Template:Round4-with third". This is a Wikipedia copy generated initially by Wikipedia user Palffy in 2006 and links to two resources here and more than 500 on Wikipedia since created for a variety of sports. If we decide what to do with these as well as any others from Wikipedia, the easiest thing is to put all of them not bot generated into the category Wikipedia copies that are such. This third one suggests but does not confirm that 33% are Wikipedia copies generated by users, etc. --Marshallsumter (discuss • contribs) 15:14, 28 September 2015 (UTC)
- Great work Marshalsumter. Am I correct in surmising that the big question here is the appropriateness of posting soccer (football) statistics on Wikiversity?--(15:25, 28 September 2015) Or is it the need to get users to properly attribute what they are doing? --Guy vandegrift (discuss • contribs) 15:32, 28 September 2015 (UTC)
- Good question! Obviously user JESAAS11 is learning about how to make templates and generating resources here, some of which are unique to here, as part of a learning project, at least about the Volleyball World Cup competition and some other apparently unrelated topics. I don't understand the interlinking of these templates to create an apparently progressive series to follow the World Cup. If it is to get users to properly attribute what they are doing, this user is getting some of the message. We use to be able to use HotCat I believe it was to put categories automatically at the page bottom, but this seems to have disappeared. I was using it a lot. What happened? This appears to be the only remaining license confirming act. Suggestions? --Marshallsumter (discuss • contribs) 15:43, 28 September 2015 (UTC)
- I just spent a few minutes searching in vain for any effort by these people to communicate with us. That alone is justification for blocking. We need to give the blocked users clear instructions on how to appeal the block (or at least say something) on their user page after they are blocked.--Guy vandegrift (discuss • contribs) 15:54, 28 September 2015 (UTC)
- This is perhaps a common problem. We have or had a course hosted here on the history of North Carolina during World War I, I believe it was. I and others tried communicating with the course instructor about unlicensed images that were uploaded by students. She never responded to anyone as far as I know. Uncommunicativeness, per se, is not a reason for blocking anyone. The disruption of having to try to get communication and having to delete all or most of those images was, but it's part of the custodial responsibility. --Marshallsumter (discuss • contribs) 16:08, 28 September 2015 (UTC)
- I also tried communicating with one of her students. Same problem, nada. --Marshallsumter (discuss • contribs) 16:11, 28 September 2015 (UTC)
@Marshallsumter: You've mentioned several times that adding a category to these resources would resolve the problem. Can you help me understand how adding a category meets either the CC-BY-SA requirement to credit the creator or the Wikimedia alternative of providing a hyperlink or URL to the original source? -- Dave Braunschweig (discuss • contribs) 16:28, 28 September 2015 (UTC)
- See "Wikipedia copies" above and "The special page for citing any Wikipedia page is Special:CiteThisPage." These two facts indicate that adding the category is sufficient. Importing is not necessary. With respect to "necessary", the templates alone by precedence do not need to be added to the category, nor do the Wikipedia copies we have or haven't found yet, but I've started doing this for the non-template resources. --Marshallsumter (discuss • contribs) 16:49, 28 September 2015 (UTC)
- Just FYI, but Wiktionary defines hyperlink as "Some text or a graphic in an electronic document that can be activated to display another document or trigger an action." As I read this, putting these in the category succeeds. --Marshallsumter (discuss • contribs) 17:01, 28 September 2015 (UTC)
- Special:CiteThisPage does show how to properly cite a page with a link. Putting pages in a category does not do that. And unfortunately, precedence is not a justification for ignoring licensing requirements. Those of us who write code expect to be credited for our work, just as everyone else does. -- Dave Braunschweig (discuss • contribs) 17:20, 28 September 2015 (UTC)
- An obvious answer though perhaps not so easy to do is have an embedded link so that if someone wishes to see the Wikipedia entry, they click on the category and it takes them to the category or to a comparably titled wikipedia page if it exists. It's what I've been doing manually. Another way to do this is to use the Sisterprojectsearch template at the bottom. The latter may be faster. I'll try it on a couple. --Marshallsumter (discuss • contribs) 17:32, 28 September 2015 (UTC)
- I tried sisterprojectsearch and the search does not include "Template:" so the template was not found. The title "20th Asian Women's Volleyball Championship" in the template "sisterlinks|20th Asian Women's Volleyball Championship" produced no exact match on Wikipedia suggesting that the resource is partially already unique to Wikiversity. I'll try linking the templates directly. --Marshallsumter (discuss • contribs) 17:46, 28 September 2015 (UTC)
- I tried Template:Round4-with third. This provides an exact link to the template copied from Wikipedia. This may be the only way to provide a hyperlink to any other WMF project from which a template is copied. The solution to the templates is easy. --Marshallsumter (discuss • contribs) 17:54, 28 September 2015 (UTC)
- I tried Template:Vrt, which I already know is unique to Wikiversity, and the link takes me to Wikipedia, but there is no such Template there. Using this would have to be tested with each otherwise we'd be wasting our contributors' time. --Marshallsumter (discuss • contribs) 18:16, 28 September 2015 (UTC)
- Using Glaciers as a member of a control group: the template "sisterlinks|Glaciers" takes anyone to the Wikipedia page Glacier from which the Wikipedia copy was imported about a couple years ago. This type of hyperlink works for close-enough matches in titles and may be both necessary and sufficient here. --Marshallsumter (discuss • contribs) 18:28, 28 September 2015 (UTC)
@Guy vandegrift: My primary concern is one of attribution, followed by one of disruptive editing. Pages in a project can be managed. Pages not in a project can be moved, but it's more work. The Template namespace applies to all projects, and the creation of hundreds of templates without any coordination makes later cleanup much more difficult. Practically speaking, our only choices will be to delete the templates and start over, or write a bot to manage all of the templates and transclusions. Neither is possible while the problem grows exponentially with unlicensed content and unresponsive users (who are blocked from all other WikiMedia wikis because of their approach). -- Dave Braunschweig (discuss • contribs) 16:28, 28 September 2015 (UTC)
- The unresponsive behavior of the users is quite a puzzle. Now I understand why they were site blocked. I suggest that we site block again, for a specific period of time. Then leave clear instructions on what to do when they are unblocked. Give them one last chance. Then we delete everything ... unless this was their N-th last chance already, in which case we block and delete everything. You can argue that posting sporting even scores is an educational experience for the users and within the scope of Wikiversity. But, having to repost them due to procedural violations is also a learning experience.--Guy vandegrift (discuss • contribs) 18:32, 28 September 2015 (UTC)
- Mississippi28 was/is an unresponsive instructor for the course North Carolina World War I. Blocking was not done even once nor was any warning issued about such a block. These current users are generating content some of which is Wikiversity unique. Some is in Sport/Volleyball. Any mass deletion may result in desysop by a watching steward. My original suggestion still stands: anyone can apply either a speedy delete or prod to any of these and a custodian must decide what to do. The direct link mentioned above works for any template specifically copied from Wikipedia and the sisterlinks templates accomplish the rest. The good part about this is I no longer need to put any resource in the category Wikipedia copies, unless the conversion course is still in operation and wants to use the ones in the category. --Marshallsumter (discuss • contribs) 19:03, 28 September)
Are you concerned about Colloquium discussions getting so long they are hard to follow?[edit]
If so, visit user:Guy vandegrift/B and put in your two-cents.--Guy vandegrift (discuss • contribs) 01:21, 1 October 2015 (UTC)
Assistant custodians group[edit]
Here's an update of comments received for T113109 at the phabricator.
"It looks like the WMF will still be happy with this request if (a) assistants go through a community selection process, or (b) they don't have access to deleted content. We'll see what the Wikiversity community has to say." TTO
This is based on these comments from Jrogers-WMF:
- It’s extremely important for the health and protection of the projects to limit access to deleted material that may include sensitive content. For this reason, we can’t support a proposal to create an assistant admin class that has access to deleted content before going through any kind of community selection process. We would not have the same concerns with a class of probationary administrators (or custodians) who have undergone a community selection process, even if other “full” administrators were given the right to add and remove their advanced user rights. We applaud the idea of having experienced administrators (or custodians) mentor new users with advanced rights; what is important is that users who receive access to deleted content have gone through a community selection process first.
- Our request is that you create a community review process to select all custodians who would have access to deleted content prior to giving them that access. We are fine with this proposal to create different levels of admin rights as long as that community review process is completed.
--Marshallsumter (discuss • contribs) 02:30, 1 October 2015 (UTC)
- It would appear from this response that the idea of having a probationary custodian (at any level) approved only by obtaining a mentor is not an accepted approach. I agree. In light of this clarification, do we still want or need multiple levels of administration?
- I think there is still a possibility for this. Perhaps we could have an instructor level. Someone who would be able to do content clean-up (delete pages, etc.), but who would not be able to block users or view deleted content. This would allow instructors to better support their students, and distribute some of that custodial work. This role could be assigned directly by custodians, and would not seem to violate the guidelines provided by the phabricator response. -- Dave Braunschweig (discuss • contribs) 13:59, 1 October 2015 (UTC)
- More instructor involvement with Wikiversity is essential. Perhaps the instructor also could do rollback? I would suggest adding page protection, but we seem to have little need for that at the moment. We also need to verify that the instructors are indeed instructors. --Guy vandegrift (discuss • contribs) 18:52, 1 October 2015 (UTC)
I've created a proposal page for Wikiversity:User access levels. There's no detail yet, but a placeholder for both policy and discussion. The name was chosen based on corresponding Wikipedia page title. -- Dave Braunschweig (discuss • contribs) 19:12, 1 October 2015 (UTC)
- Just to clarify (as I was the user who originally brought up the issues on the bug) there would be no issue with any of the bits apart from viewdelete (and restore deleted pages). I would happily create a group without this in, if consensus existed. Mdann52 (discuss • contribs) 19:18, 2 October 2015 (UTC)
- I appreciate you mentioning the issues. Let us think through this a bit further before we proceed. The initial request was a response to a specific situation that no longer exists. We now have an opportunity for more prudent consideration. -- Dave Braunschweig (discuss • contribs) 19:29, 2 October 2015 (UTC) | https://en.wikiversity.org/wiki/Colloquium | CC-MAIN-2015-40 | refinedweb | 14,843 | 62.27 |
fennec:also, shouldn't that be website.renameTo() instead of Website.RenameTo()?
Publius:I think the real WTF here is that I'll never have to hear what the real WTF here is again.
Censoring FAILS!:Yet another website falls for the censoring way of life. In every country (especially USA) you see this shit happening :S stop bloody censoring things just cos some ppl can't handle vulgare names!
Up yours!
Jackal von ÖRF:What happened to the "show full articles" checkbox on the front page? Today when I came to the site, there were 3 new articles, which meant that I had to (1) click "Full Article" link on the oldest article and read it, (2) click "Back" button, (3) click "Full Article" link on the second oldest article and read it, (4) click "Back" button, (5) click "Full Article" link on the latest article and read it. So a total of 5 clicks compared to 0 clicks if the full articles had been visible on the front page.
Censoring FAILS!:Basically, I am completly against censoring, and as this is censoring I am against this website, and as I am against this website I will stop reading this website as regulary as I did before.
fennec:-- also, shouldn't that be website.renameTo() instead of Website.RenameTo()?
GeneWitch:I don't care what the site is named, that's so petty.
WORSE and FAILURE: GeneWitch:I don't care what the site is named, that's so petty.
Then why change it, changing it is petty and truly a bad marketing decision. I know programmers dont' do marketing but branding works. The whole site was spawned from one thread titled the Daily WTF, why be petty and change it.
Jochen Ritzel:"IBM stands for Industrial Buisness Machines". :/
swapo:I recently had an similar situation about what WTF stands for. I like the new Backronym, keep up the good work (and I should send in some WTFs myself...).
fennec:also, shouldn't that be website.renameTo() instead of Website.RenameTo()?
Not if you're from the .NET-World as Alex obviously is, they use some really WTFish naming conventions over there ;-)
But a lot of people in the “real world” don’t quite share that sentiment. Especially my relatives:
Soro:
Admit it, having "fuck" in the name was not business friendly. So when you sold out you had to change it.
Otto:
I will also continue to give thedailywtf.com out as the domain to people when it comes up (and it has, many times).
10 read from $s.mag = 8*"TheDailyWTF" print; next i;
john q public:Stupid to change the name. dumb move.
That said, there were a few reasons that I wanted to rename the site, perhaps the biggest being that “Daily” and “What The F*” don’t quite describe it anymore.
PetPeeve:Isn't it easier just to keep everything the same and just change only the official name to "The Daily "Worse Than Failure".
<script type="text/javascript">
function setDisp(disp)
{
var exp = new Date();
exp.setDate(exp.getDate()+365);
document.cookie =
"HPDISPALL=" + (disp?"Y":"N") +
";expires=" + exp.toGMTString();
window.location = '/';
}
</script>
...
<script type="text/javascript">
if (document.cookie)
{
document.write('Display: ');
if (true)
{
document.write('<b>Full Article</b> | <a href="JavaScript:setDisp(false)">Summary</a>');
}
else
{
document.write('<a href="JavaScript:setDisp(true)">Full Article</a> | <b>Summary</b>');
}
}
else
{
document.write("Tip: Enable Cookies to toggle full article text");
}
</script>
<noscript>
Tip: Enable JavaScript & Cookies to toggle full article text
</noscript>
EnterUserNameHere:The REAL WTF is that the intent of renaming the site has had the opposite effect and actually resulted in MORE of the F-word!
wgh:Man, this is a sad day. I _really_ like the old name so much better.
J:First, this is not censorship. Censorship is when an official body such as the government comes in and declares that you aren't allowed to say or write certain things. This is a voluntary move away from what the site owner considers to be a vulgarity.
whiny wee bastard:I also wanted to add that BOFH would be ashamed.
unlimitedbullshit:as the owner of the unlimitedbullshit domain
thedailywtfisanawesomenameandbrand:Ads - OK
Occasional self promotion - OK
Bean bag girl - Totally hot
Name change - Fucking lame
Nik:I've been following these for about a year now, and I've recruited a readers..
DaveE1:Changing the name is a weak move.
oooooo oooooo oooo oooo .
`888. `888. .8' `888 .o8
`888. .8888. .8' 888 .oo. .oooo. .o888oo
`888 .8'`888. .8' 888P"Y88b `P )88b 888
`888.8' `888.8' 888 888 .oP"888 888
`888' `888' 888 888 d8( 888 888 .
`8' `8' o888o o888o `Y888""8o "888"
. oooo
.o8 `888
.o888oo 888 .oo. .ooooo.
888 888P"Y88b d88' `88b
888 888 888 888ooo888
888 . 888 888 888 .o
"888" o888o o888o `Y8bod8P'
oooooooooooo oooo .oooooo. .o.
`888' `8 `888 dP' `Y8b 888
888 oooo oooo .ooooo. 888 oooo 88o .d8P 888
888oooo8 `888 `888 d88' `"Y8 888 .8P' `"' .d8P' Y8P
888 " 888 888 888 888888. `88' `8'
888 888 888 888 .o8 888 `88b. .o. .o.
o888o `V88V"V8P' `Y8bod8P' o888o o888o Y8P Y8P
Quicksilver:oh please please name it back...
whats so bad about wtf? your granny has brought some cildren to the world in her life ... she knows what fuck means ...
pinkduck:Don't underestimate the power of TheDailyWTF brand, and remember who your core audience is (or were).
wtf:When I used to tell a friend about this site, they'd get a kick out of the name and that alone would make them want to check it out. "Worse Than Failure" sounds like a shitty local emo band or something. Very disappointing.
Granny/Boss/Priest: The Daily WTF? What does WTF stand for?
You + Balls: "Worse Than Failure"..
Ahnfelt: J:First, this is not censorship. Censorship is when an official body such as the government comes in and declares that you aren't allowed to say or write certain things. This is a voluntary move away from what the site owner considers to be a vulgarity..
bullseye:I miss the days when the average IQ of posters here was higher.
At any rate, I suspect the complaining was to be expected. You should have posted the article on a school night...
michael:Is it just me but is this a bike shed argument to rival the fbsd sleep discussion. We have 4 pages of replies, and really in the grand scheme of things, who cares? do people really come here to read the url? how about the banner? personally i come to read the stories and they will still be here.
Ryan:I think "The Daily WTF" was part of this site's success and an excellent brand. We'll see if Worse Than Failure captures new audience as well, I doubt it.
Ryan:When do people make business plans based on how their Grandma likes the name? I thought that the target market determined the name.
Martin:
... Or maybe you think the name hurts you in your professional life as too many people judge it negatively before you have a chance to explain why the name is excellent to address a specfic demography of technical people.
David Cameron:
...Most people seemed to grow out of that by the age of 12.
<snip>
I'll give it a week or so to see if the name changes back. If not I'll be deleting this from my bookmarks and I won't be visiting again.
Icarium:YOU RE A SISSY!
D:Can't you just change it back?
*Sob*
I like considerate people:.
fennec:
-- also, shouldn't that be website.renameTo() instead of Website.RenameTo()?
baddognotbarking:The new name is a crude reinterpretation of the WTF acronym. It may be politically correct but it reflects just a fraction of the site's content.!
Anonymous:I like the new one too, only shortening it to just WTF could cause some confusion... WoTF perhaps? Any better ideas?
fennec:I've done basic updates to the Wikipedia article.
bstorer:Jeez, people, fear change much? You all complain about the site's name while simultaniously searching the web on Google, and doing your online shopping on websites called eBay and Amazon. The name doesn't matter, the content does.
meh:Yeah I love the renaming.
Its like renaming Terminator II to The Robot from The Future.
The name is lame.
yeah, but i bet none of them would dilute their brand by renaming.
bstorer:yeah, but i bet none of them would dilute their brand by renaming.
Dilute the brand? Are you completely insane? It's a blog!
Oh, and tell that to Verizon, Mandriva, Wireshark, Ask.com, CBS Radio, and USAirways... I could keep going.
I like considerate people: Censoring FAILS!:Basically, I am completly against censoring, and as this is censoring I am against this website, and as I am against this website I will stop reading this website as regulary as I did before..
Someone peeved at the twats:Jeeze, it's like a little bunch of children arguing over which pokemon is better.
public class Website
{
public static void RenameTo(string name)
{
if (name.Equals("Worse Than Failure"))
{
Website.Flush();
Website.Close();
}
}
}
JTK:The Daily SNAFU (can use Situation Normal - All Fouled Up as the tag, while the script kiddies snicker in the back of the room)
The Daily FOOBAR (as above, dates back to K&R C)
yoz:well it's not the name but the content which matters
way to go alex
doof:It's really sad how folks can't comprehend the difference between "censorship" and "tact / discretion / decorum".
Edowyth:
void clear(int* x, int* y)
{
x = 0;
y = 0;
}
???
Cthulhu:[this] reminds me of the BFG (10K) in quake2. ID software could have gone all PC or worried about 'inherent meaning' and called it the "What's going on gun" instead. They didn't.
Paul:WHAT THE FUCK
Your grandma can handle the FUCK word. Seriously. To think otherwise is rather condescending.
Raina:While I have nothing against the 'wtf' in the original name, I know what you mean about explaining to grandma .. I had the same problem with my multimedia programming class last year.
me> you should check out this site to know what not to do... [writes url on board]
fairly clueless female student > what does wtf stand for ?
me> err ... err ... 'what the fudge' :)
class> *laughs*
Cthulhu:The real WTF are comments like this:.
CAPTCHA: Quake - this relevant captcha reminds me of the BFG (10K) in quake2. ID software could have gone all PC or worried about 'inherent meaning' and called it the "What's going on gun" instead. They didn't. It's better this way.
Thiago Berti:you culd stick with "Daily WTF" and just say that WTF stands for Worse than failure to your relatives.
kettch:50 years in the future, what will our grandkids be doing that we now find unspeakably foul? I'm not saying that certain things should be banned, but they should probably not become a common part of "polite society".
Thiago Berti:Well, in my humble opinion (sorry if someone had already said that, i didn't read all the comments) you culd stick with "Daily WTF" and just say that WTF stands for Worse than failure to your relatives.
This way you'd have both names and people could choose between the one they liked more.
Plasmab:Just change it back. As soon as the urls stops working i stop reading.
Roy:How about "WTF Technology Folklore"?
Bot2:10 "Worse Than Failure is a lame name".
gc:
<sn
<snip>
Sell out!:Another person bows to public pressure. I say fuck at least 60 times a day if not more. Just because it makes people uncomfortable.
JS:I for one welcome the name change. Mostly because it has fewer syllables. I hate saying "doubleyou".
Name:This is censorship at its finest. F in WTF means "fuck" not fudge, failure, fridge or fool. This web site is not dedicated to our granmas, we can say "fuck" here and that's why I liked it here. I don't know if I'll stay any longer, the new name is really so stupid.
Ned Flanders:You could always just say it stands for "what the fiddilydangdiggily"
<b style="color:black;background-color:#ffff66">John Robo</b>:FUCK YOU!
You didn't mention the tweaked looked -- I like it!!
I like the new one too, only shortening it to just WTF could cause some confusion... WoTF perhaps? Any better ideas?
Addendum (2007-02-24 16:21):
-- also, shouldn't that be website.renameTo() instead of Website.RenameTo()?
wtf
Not if you're from the .NET-World as Alex obviously is, they use some really WTFish naming conventions over there ;-)
The Real WTF? RSS link!(“Worse_Than_Failure”).aspx
clicked in RSS newsreader opens up url:
...
Bad Request (Invalid URL)
Up yours!
Addendum (2007-02-25 04:09):
mario, the hyperlink was not visible when I wrote that message (using Firefox + NoScript). Now it at least says "Tip: Enable JavaScript & Cookies to toggle full article text" so I will know to enable JavaScript to get the link visible. So the WTF is only that the site requires JavaScript enabled.
Uh, I think you need to look at the new name a little more carefully guys...
Capcha: Darwin
Or, you could have cliked on hyperlink right where the checkbox used to be that says "Display: Full Article.
Sure, it would have required 1 click more than 0 clicks, but you would have saved at least 500 keystrokes, and an additional 2 clicks to post the comment.
Heck, you would have even saved me a bunch of keystrokes and clicks as well.
Just here to defend my statement, and wanna see people defending the renaming :).
How is this change at all censorship? Censorship would be deleting your comment because you're whining.
Censoring would be not printing the real names of WTF companies involved in the stories. Oh wait. That's already done ... so ... wait, how are you reading the WTF still if Alex already does that?
unfuckingbelievable.
- daily was in the name (it just sounds more frequent, visit daily)
- wtf is the real wtf (and an internet lingo - worse than failure is just a cop out to keep WTF acronym but changes the meaning)
- mentally seeing FAILURE at the top of your page in red is bad for the irrational marketing side.
- longer URL (new name)
- dailywtf was a name that caught attention, new name does not have the same ring
- your relatives disliked the name, usually means you are onto something good.
At least grandma is happy.
come on saying fuck to your grandma can't be worth it :)
let's hope this site doesn't turn into something that sounds similar eh :)
I'm shocked that anyone who would have used the original name in the first place would later cave to this sort of pressure. Definitely a sad day and I will close by saying that if you stick with the neutered name, then the terrorists have truly won.
Looking forward to the programming contests though!
Fuck-fuckity-fuck-fuck-fuck. Jesus Christ - it doens't hurt anybody!
Captcha: smile
(I wrote to them suggesting that 'eWeak' might be a better monicker given their submission to industry peer pressure, but I guess they didn't think it was funny.)
CAPTCHA: Xevious. Back in the day.
No, it should be:
:1,$s/The Daily WTF/Worse Than Failure/
The REAL WTF is that apparently, according to the title, no one at the site's end bothered to edit the configuration files or templates or update the database table or whatever the heck this monstrous piece of software uses. Instead they just dived in the CMS logic, added a line of code to change the site title, and recompiled.
So, um, the title is obviously in line with the contents of the site.
I'll still visit and be an asshole sometimes and be nice othertimes and appreciate all the help you guys give me. and advice!
One thing though Alex... Obfuscate the real reason next time... say that the TLD .com people made you change your domain name because they were scared they'd be featured on your main page or something.
And don't sell off the old domain, forever forward it here!
Weeeeee!
EDIT:
Do you guys write letters when vivendi buys companies and makes them change their names? How about Time? Warner? Bell labs/ Ma Bell?
The lot of you that are being cantankerous about this really should look at what you are doing... you get this site for FREE... it's funny and entertaining... and you guys are giving the webmaster shit because he changed something. Get a grip.
Would it be possible:
* For the old domain not to redirect to "worsethanfailure.com"
* For the old domain to keep the old DWTF branding
?
It's pretty trivial to do so the tech part shouldn't be much of an issue
That way, those who really prefer their WTF with more dailys and more fucks would get to keep it, and those who prefer failures could fail as hard as they can?
TenToTheTenToTheTen.com - World's fastest search engine.
I'm sorry about you talking to your grandma but so what? Just tell her it's an acronym that means something doesn't make sense. Changing the whole site because the F stands for a swear is silly.
Changing the format of the site is up to you, Want to have a "worse than failure" section that's fine, but changing the name is going to lose you readers.
And when I say WTF I'm being polite here, I mean the What the **** not the letters.
Then why change it, changing it is petty and truly a bad marketing decision. I know programmers dont' do marketing but branding works. The whole site was spawned from one thread titled the Daily WTF, why be petty and change it.
Yeah shut up! that's more like it bitches
(captcha: slashbot, pwn3d)
Makes me think of Monthy Python: The Usage Of Fuck.
captcha: fuck (just kidding, it's kungfu)
New name = shit.
Bring back tdwtf!
The name just does not fit. If you want to go all PC, pick a name that really reflects what the site contains. The new name is now the site's "Curious Perversion". Sheesh.
CAPTCHA: stinky (my thoughts exactly)
That makes me curious. Where and when was this thread posted and can it still be found somewhere?
The name really set the tone for this website. I too think differently of WTF and the F-word - WTF seems so much more innocuous for us web users.
I have to agree that the best solution would be keeping both domains and trying to set it up so the header and all references to the acronym are replaced with family-friendly versions.
Also, I agree with whoever said that the word "daily" isn't a problem - check the site daily! Not having daily in the name tempts less frequent updating and traffic.
If I ever have to explain to people WTF, I just tell them straight up that it's an acronym that stems from a vulgar expression, but its meaning and seriousness have changed throughout frequent usage on the internet.
If anything, tell people that it stands for "Worse than Failure," which I have to admit is a pretty good reinterpretation of the acronym.
WTF? Actually, it's "INTERNATIONAL Business Machines".
;)
CAPTCHA: scooter.
Captha: what the fook!
As far as I'm aware, though, the curly quotes will still probably cause compilation problems. :P
Hope it works..
Alex, if your grandma' is really the reason for changing the name of one of TheDailyWTF...I don't exactly know what to say. The new name is a WTF as per both the old and new definitions.
I also had an urgent need to bring out my feelings about this new name thing. The daily WTF really is a brand and a concept. People who find wtf vulgar should maybe loose it up a bit. The new name is literally worse than failure. Sorry, it just is...
I don't know what the real reason for the change was, but the grandma story sounds extremely lame -- even too lame to be true?
One more vote for restoring the old name!
It's not?
Well...then fuck. I don't actually dislike the new name, but I think the old name was better for what this site is about, and the branding is well worth keeping, and, honestly, you can just tell your grandmother it stands for "worse than failure" if "fuck" is not a word you can say in her presence.
Tell you what: I'm going to keep going to thedailywtf.com. I'm going to keep calling it the daily wtf. The day that url quits working is the day I quit reading. You don't care about my readership, since I'm only one random person, but that's the only vote I've got.
Cheers!
...
}
What the fuck is "worse than failure" about a stupid piece of code? Fuck nothing, that's what. The new name is totally idiotic. What a heap of shit.
This software sucks the sweat from my taint too.
Sad.
I'll still continue to read the site, but I'll continue thinking of it as the dailyWTF and it's definitely moved down a notch or two in my list of must read sites.
Don't let the perpetually juvenile whiners get you down. I think you are on the right track re; vulgarity, but I would suggest that there are better expansions of the acronym that do not require profanity. I actually had already thought a few up since I started reading about a week ago.
They all fit the pattern What T* Folly.
T*:
Terrible
Tremendous
Ticklesome
Total
...
The advantage I see is that Folly is just more lyrical than failure. It has classical roots, and is relatively non-judgemental.
As to the ranting and cursing about the word "fuck", the best I can do is quote my late father:
"Profanity is the sound of an inarticualte person seekng to express himself forcefully."
The truly creative, and articulate, person can almost always find a better, more expressive word to use than the guttueral and troglodytic expression to which so many posters on this thread seem so attached.
One practical issue that I do have is that I have had some trouble replying on pre-existing threads. Nothing whatsoever happens when I click the 'Submit" button. I am now wondering if there is a relationship between this problem and the change in domain name. I'd appreciate it if you could look into this.
But if its a _must_ to change the name. At least come up with something better. I understand that you want to keep the 'wtf' acronym but it doesn't make sense and has a confusing meaning.
..and I'm sure that we can all agree that RTFM abbreviates the word "Fine" as well.
Seriously though... four letter words and "vulgarities" are part of our language. I've always insisted those who would excise them from my speech or those who are unwilling to hear them are, at some fundamental level, immature and hypocritical. All you have to do is look at the comments on any code over 10,000 lines in size and you *WILL* find this type of language in use. I'm particularly curious about how honest people are in their assessment of Open Source code through the use of four (and more) letter words. I suspect that there's maybe 10x more usage when your audience accepts the language without judgement and when there's an absence of "fear" (personally, I'm not sure which is more vulgar: using fear to limit another person's speech or being intellectually dishonest enough to deny the distinct possibility that a four letter word just might be the most apropos lexicon to describe what is happening in a particular piece of code)
...but anyway, congratulations on finding your new crutch and caving to mediocre (yes, every person of excellence I have ever known in my life uses "vulgar" language... some even in their public writing).
Watch out SNAFU and FUBAR, you're next.
i guess you'd have issue when steven colbert talks about "balls" because of the inappropriateness?
part of the appeal was that this was slightly risqué. i dont know- you still have "Submit Your WTF" so are you trying to make that stand for worse than failure? thats a wtf in and of itself.
very lame. as if grandma didnt know what fuck was. cmon now. since when have the standards for the site been tailored to grandmothers?!
ps- people voting against the new name arent all whiny kids. some of us actually liked the fact that this was an off color area to share our stories in IT. i suppose its a good name- the change is definitely worse than failure
See ya Daily WTF.
First, this is not censorship. Censorship is when an official body such as the government comes in and declares that you aren't allowed to say or write certain things. This is a voluntary move away from what the site owner considers to be a vulgarity.
Second, why the crap would you quit reading the site? The content is the same, so unless you spent most of your time on the website laughing at the name, it won't make a darn bit of difference. It's like firing an employee because he decided to break his swearing habit.
At the risk of sounding like a "whiney kid," this is why people are up in arms about the name change.
At TheDailyWTF, you have built a wonderful community of people who fight the good fight against every day against clueless managers, stupid users, and both coworker and self-inflicted wounds. The site is not only good for a laugh, it is good for a morale boost for any IT worker who has had to deal with this on a daily basis. Seeing another person's "curious perversion" experience makes our own seem better. Yes, in a sense, you have done a valuable therapy service to the IT community.
And with this name change, much of that therapy will be gone. WTF is a perfect shorthand for the moment we all see every day. It is an expression of the community, for the community, and in use every day by the community. It is ours. "Worse Than Failure" is theirs -- it is for others, an attempt to impose a name from the outside on a decidedly insider phenomenon. Instead of MySpace, it is Walmart's MySpace clone.
At the end of the day, it is about the content, and if Alex continues his outstanding work serving up good "curious perversions" under any name, I will continue to read and to be a fan. But I hope you can at least see why this name change has IT people leery of the future direction.
And "Worse than failure" is *horrible*. It sounds like something dreamt up by a committee.
If you have to drop "WTF" (and I don't see why you do), please, please pick something else.
Perhaps this is to appeal to a wider audience than just coders. It probably has increased readership. Nevertheless it's sad.
This is not to say the new series' (or new writers) are all bad. The quality drop is across the board..
Jesus Fucking Christ you people are whiny fucking children. The dumbfucks around you that didn't get Alex didn't change it because of his grandmother are even dumber, and should really be brought out back and put down.
I hope the majority of you rot in hell.
I am yet another long time reader and first time poster who feels the need to make a comment on this event. But for me, the event is not the so much the change of name (I care only slightly), but something more significant.
Once, this board was a obviously done for the sole purpose of ammusment. There was no intent to capitalize on it, and the aesthetic was based on the aribitray personal choices of one person. This gave it Quality. Quality comes from a clear vision, and bold choices from the right person.
Then the move was made to capitalize on the site. The introduction of the advertising, the non-WTF jobs, etc. Now unlike many people, I don't believe that all attempts to make money are evil. I myself am a capitalist and entrepreneur. I welcomed these changes for the most part. I was slightly concerned that sponsers might begin to impact the content of the site, etc, but things remained mostly as they were. There was some shift in the aesthetic, and it had a hint of "caring too much about other people's opinions", but I tried to write it off as a simple and natural change on Alex's part.
However, this latest change, being significantly incompatiable with the prior aesthetic, seems to strongly indicate that Alex has lost his nerve. He has lost the ability to make bold personal choices, instead, he considers first how others will react to them. He brings up the example of his grandmother, but I think the story is made up, Grandma is just a stand in for 'the other', 'everyman', 'the majority', name them what you will. And Alex has now put them above his personal aesthetic, which really is "worse than failure". It is the descent into mediocrity. It is the end of the "great", and the enshrining of the "not terrible". The way of the committee.
It didn't have to go this way. Many individuals can make the transition from hobby to occupation and keep their faith in the original goals. Take a look at Penny Arcade for a clear example. But it has gone this way. Even if Alex changes the name back, it will most likely be due to the pressure of his readers. Perhaps with great force of will, Alex could regain his nerve, but it's unlikely. So much so that I probably wont bother to check this site again. It's certainly leaving my bookmarks. Not really because the name changed, but because it's been getting more lame for a while now. Until this point, I thought it might be temporary, transitional, just someone trying to find their center. But now I'm pretty sure it's getting lame because Alex is not trying to find his center, but the center of everyone else. And I've seen the middle. It's boring and I hate it.
Someday in a few weeks I'll try the old URL because I'm bored, and the because the name has always been easy to remember. Maybe it'll be good, if so, I might keep coming back. Or maybe it will be lame, in which case I'll engage in some exponential backoff, and try again in a month or two. Eventually, I'll forget.
Thanks for the good times while they lasted.
Occasional self promotion - OK
Bean bag girl - Totally hot
Name change - Fucking lame
At any rate, I suspect the complaining was to be expected. You should have posted the article on a school night...
I will not be changing my bookmarks to the new domain. I will also continue to give thedailywtf.com out as the domain to people when it comes up (and it has, many times).
And if the old URL stops redirecting, I will stop reading. Why? Because there's no way I'm going to remember a crap name like this.
Bad decision with the new name. This site will only ever appeal to software developers. 95% of them will not be offended by 'WTF' or what it really stands for.
DailyWTF is a brand that you've spent time building, destroying that and starting again is madness.
If you really wont go back to the old name, someone posted a good idea... Have a 'clean' site and a 'DailyWTF' site.
I often IM or email my developer friend and say "There's a good daily WTF today". Now I have to say "Look at 'worsethanfailure.com'"
Lame lame lame.
Can't you hear the site caling?
"Don't try to fix me, I'm not broken... Hello?"
WTFs are not business-friendly either and yet...
I'll second that: I can't speak for the future, but for now it seems it will always be TheDailyWTF to me.
I don't like the new name. Does grandma read the site? Than what does it matter?!
If your family doesn't appreciate this site than don't tell them about it in detail. @#$%, lie if you have to! Hell, the Internet porn industry is thriving... Don't you think those developers have grandmothers!? I doubt they have the conversation:
“So do you still write that website ... oh, what did you call it? MILF..?”
“MILF Doggy-Style...”
“Ah yes. I can never remember, what does M-I-L-F stand for again?”
“Well, Grandma,...” [runs away!]
Not all WTFs are worse than failure. Sometimes they work, but incredibly inefficiently, etc... But they >>work<<. What's better: 3 months of work for a bad solution that works or a complete and utter failure with no deliverable? (Even though we all hate maintaining WTF projects and it would be great to just start over and do it right).
I don't know. The name seems less catchy and less witty.
When I first heard "TheDailyWTF" I was immediately interested... Not just in the article, but in the SITE. I'm not sure "Worse Than Failure" will have that same effect.
But again, I don't hate the new name. Maybe it'll grow on me.
Without the name the sites is only half as funny, and grandma won't read it anyway, nor is this a "family" site. Stupid move. Content was lacking anyway, so site removed from bookmarks and good riddance. kthxbye.
Website.RenameTo("The Daily WTF")
Aye!
-The name (sucks as a brand; psychologically bad)
-The forum software (sucks)
-Granny marketing (WFT?!)
-Alex himself in certain regards (myopic and fanatical resistance to open source; opposition to anything non-corporate, non-Windows; and to open the political can of worms, conservative/republican worldview; etc)
Thus, as Zach said, "at least symmetry".
this is incredibly lame. wtf is going on here lately?
Quick, better rename a site that was memorable to its target audience to one that is an expansion of an acronym that ISN'T EVEN THE CORRECT EXPANSION! It's bad enough that we have to contend with so many acronyms, but making up new meanings for old acronyms is a wtf in itself.
Naughty, naughty Alex.
Then again, ironically the name change perfectly encapsulates what this site is all about, as my first reaction the the article was: What the fuck!
Though it has to be said that it was the first genuine WTF in a while as I thought the overall quality of the submissions had been going down.
That's like Microsoft changing their company name to Miniware??!
you get -300 respect from me. keep up the good WTF-posting thou
I can't believe you didn't go with my suggestion of
I can't decide which is the bigger WTF - wilfully destroying a brand which was perfect for your target audience or the absurd self-censoring reasoning behind it.
We'll probably get used to it in no time, like I had to get used to wrestling's WWF now being WWE. MAN I HATE THOSE PANDAS!!
Website.RenameTo("Worse Than Failure").NOT!
It may seem like a trivial move to some, but this is seriously disappointing.
It's like when a raunchy comedian/actor becomes a parent and decides he wants to clean up his act, so he takes on family comedy fare.
At least bring the old domain back up and tweak a bit the code for the site so when you get to the site from thedailywtf.com it shows that in the title.
If you can't afford to pay for that domain too, just say so, and I bet $10 that you will gather enough money to pay that domain for a life. Same applies to the code I was talking about.
I am guessing that you won't care about this but I am going to post it and then that will be that.
I am deleting this website from my bookmarks. I will never look at it again. I am going to outline the reasons to you, you may take this criticism as you see fit.
Since 2005, the site has gotten worse and worse. Here are some of my quarrels.
1) Moderation: for a time, you made available a script to let all users see what moderation was taking place. You stopped that. A moderated forum by secret moderators is not of interest to me. [Not to mention the fact that the moderators are still doing a piss poor job.]
2) Long stories: I don't know why you made this shift but the long stories with no code are terrible. If this is truly the direction you want to take this site in, I would suggest that you either hire a writer or really work on your writing skills. They leave much to be desired.
3) The data-backup blurb: you put this advertisement into one of your posts as though it were part of the story. I am fine with advertisements in the side panel. Placing ads in the text of the article as though it were part of the piece is just terrible. And I question the validity of the post itself. You received an ad for a data backup site. Did you then make up that story about data backup so that the story would fit the ad? Curious.
4) Disregard for forum regulars.
5) Arrogant attitude.
Again, I don't expect you to change from the current road you are travelling down. I would suggest that I and others, who were regular members of this site, have left in numbers. If losing the people that supported your site from the beginning was part of your vision, then congratulations - you are on your way!
Last post from me.
sincerely,
Richard Nixon
The whole WTF hasn't been used in it's original meaning on this site anyway. (More used as another word for "horrible mistake") And
Oh well. Just sorta feels like a bait and switch now. Think I'll dump it from my daily surfing. Was getting a bit boring anyway.
Bottom line is i respect your decision, but i resent it. A friend told me to look it up, because it had stuff worth reading, and the name itself made me curious enough to actually do it. If that same dude had said "go to 'worsethanfailure.com', it's cool", i'd probably think it's something about crash tests gone bad.
End Note: does this mean that 'the daily wtf' is available? Because i'd like to take it - it's a cool name, and my grandma is usually online on ymsg on her laptop anyway, so she's probably used to web acronyms :)
Captcha: bathe. wtf? how did they know? Bastards! :D
I've visited your site daily and this change is absurd.
The mere reason that this is my first comment should mean something - you really dissapointed me!
This site really is an impressive and useful accomplishment. Alex should be proud of it.
But it's hard to flaunt something, or list it on your own résumé, when it has the word "fuck" in its name, even implicitly.
However, I directly disagree with this statement:
That's utterly wrong. Long before I found this site, and many times since having found it, I have been looking at someone else's clearly novice code, in a commercial product, and I have muttered, "What... the... fuck?" And you know what, I even make a face that's very similar to that red circle-guy at the top of the page. And I've seen other people make that face when looking at legacy code.
Exactly what should have been done. No one tried to make a replacement for RTFM; they just found a gentler expansion of it. If you want to describe the site to your grandmother, just say, "Oh, it stands for `Worse Than Failure.'" Heck, that's downright funny.
It should be pointed out that "worse than failure" is not descriptive. Heck, it's utterly obfuscatory. It'd not even a tenth as memorable as "thedailywtf.com" is, which is important if you want to have repeat visitors.
If you really want a less vulgar name, and since you're obviously willing to move to a whole new domain anyway, consider some of these:
The Daily DGI ("don't get it")
The Daily ITI ("IT idiocy" or "IT injustice")
The Daily HTEW ("how'd that ever work")
The Daily PFN ("paid for nothing")
The Daily Unprofessional
(I hereby place all of the above names in the public domain. Go wild with 'em.)
You want to cater to the clue-deprived masses, fine - but the internet's too big to waste time with weak-ass, pussy sell-outs.
Send up a signal when you grow a new pair.
(I wonder if theoccasionalWTF.com is taken?)
All of this should be done server side, so that seeing the full articles on the front page would not require JavaScript nor even cookies.
The solution is to have links such as <a href="CurrentPage.aspx?full=1">Full Article</a> which would set the cookie and show full articles. This way enabling JavaScript would not be required for all NoScript users. Also, this solution would not even require cookies, if the "?full=1" parameter would be kept on the address line after clicking the link (so no redirects for "cleaning up" the URL).
I've removed the site from my RSS feeds - not just because of this - I was starting to get a bit bored with it anyway, this is just the straw that broke the camel's back. I'll probably come back and have a look from time to time, but not daily like before, and I doubt I'll remember the new name, so I hope the old one stays up for a while.
Seeing the current title, if I was a first-time reader, it would tend to make me think that TDWTF *is* the one that is worse than failure... (a WTF in itself)
Yup me too :-|
CAPTCHA: ewww, indeed
bad idea, imho - I predict that you won't draw in nearly as many new readers after this
Alex, you could have told your grandmother it stands for "What the frak/freak/fudge. The old title was *the perfect name* for this blog. The new name, well, let's just say that it describes itself (the name, not the blog) very, very accurately :-(
So it with a bit of sadness that I now unsubscribe from this once-treasured RSS feed. Farewell and goodnight..
WTF? Such self-deprecation!
I'd have written "yeah, I still write 'Worse Than Failure'."
;)
Second that.
If I had other ideas kicking around I would get other domains, not change one that already worked
will you be carrying wtfs?
I'm deleting you from my bookmark list right now.
PS: Wtf, this CAPTCHA software is cool - "slashdot" !!!
I would like to see still load the site, but for it to detect the hostname used and customise the branding accordingly.
Don't underestimate the power of TheDailyWTF brand, and remember who your core audience is (or were).
"When I used to tell a friend about this site, they'd get a kick out of the name and that alone would make them want to check it out."
Sums my experience up perfectly.
Goodbye, TDWTF.
Finn.
Last time poster.
I won't be back.
What next? Are you gonna remove nekkid women as well?
Maybe granny likes bald clams.\
Oh wait,...I was thinking of wtfpeople.com.
No titties here? Never mind.
Agreed! Everyone I've shown this site to immediately had the reaction: "the daily wtf? that's hilarious" and most, just because of that, gave it a shot and still read it.
Also, the acronym "wtf" is perfect for programmers. Especially when you are trying to fix someone else's busted code.
Considering the workplace, I think that profanity is acceptable as long as it is used sparingly and in appropriate situations, ESPECIALLY when used in a acronyms such as NFG ("no f***ing good").
Couldn't you just leave it as thedailyWTF and then on the "about" page note that the acronym stands for "worse than failure?" Then we could all just think of it as sarcasm, kinda like when Naughty by Nature said the OPP stood for "Other people's property" but we all knew what it really stood for.
Changing the name is a weak move.
Couldn't agree more. You'll basically have to decide at some point what the target audience for your site is going to be, and by changing the name, you've just alienated a large part of the "hardcore" regulars, who've come to respect you because of the name, not despite it.
I personally don't care much about the name change, but "recruiting" new ("hardcore") regulars from the industry to read worsethanfailure.com is, as others have already said, going to be a largely futile task, because the name doesn't cater to them anymore. Neither does it cater to me, and as others have said, I'm going to keep calling it The Daily WTF, no matter what happens here.
Anyway, I'll be following whether this is just the latest move in a general downward trend of this blog (which I've noticed from mid of last year already). That'll be the point when I'll decide to drop reading this blog, or not.
whats so bad about wtf? your granny has brought some cildren to the world in her life ... she knows what fuck means ...
where is the problem with it? its not a bad word...
its a bit to early for bad april first jokes...
and if you were a company this renameing announcement would have been presented on thedailywtf.com because it is so hillarious ... imagine Apple renameing itself because Jobs granny always thinks her son goes to the market for selling fruits..
If you really dont like the word "fuck", then replace it with Frack, which I've started to use latelly.
Secondly renaming it to Worst than Failure is along the same lines as spelling FUBAR FOOBAR. It's just wrong.
Thirdly and finally Worse Than Failure is just a lame name, sorry, but it's rubbish.
If he was really following .NET standards, this website should just expose a "Name" property. It should then be: Website.Name = "Worse Than Failure";
Captcha: ewww (that adequately describes this name change)
I agree with those who say that the old name was part of the identity of the site. To the ones who decided to say goodbye: hey, fuck, were you here just because you liked having that name once a day on your screen, or was it for the contents ?
Old-time readers will still be able to say "WTF", while the new ones will be happy to find a new meaning to the acronym made by "worse than failure".
captcha: sanitarium. Still damn context-based !
--
vlekk
Seriously though. Grow a pair of nuts and change it back to What The Fuck.
No, you have to now write "Really, the forum software is still WTF."
Just a simple syntactic change...]
If the core audience "was" dorks who get their panties in a twist over such a trivial detail then, well, I'm sure they'll find asomeone else to satisfy their special needs.
And driving away idiots may raise the average IQ of the eyeballs, and thus improve response to advertisments as they can be targetted at people who can keep a job. ;)
Although the whole "I'll never read this site again! This is my first post, just wanted you guys to know that you have to change so I'll come back even though I'll never find out if you did change so there's no point" thing does have a certain amusement value. It would be itneresting to know how many of those geniuses actually keep their promises - there always seem to be a lot of "that WTF was so bad that I'll never read this site again even though I've been reading since the very start" posts, and there's a finite number of people who can make that claim.
I doubt your pagerank will ever recover.
Everyone who likes the old name start putting up lots of links to it, domain redirects are one of the biggest pagerank killers.
I doubt your advertisers will appreciate that.
(I see you're getting public service google ads now, that should be your first clue that something is badly wrong...)
Why change something that doesn't need to be changed.
I concur..
Putting the subtitle as "What the fark" would have done, for goodness sakes. Who reads this site and doesn't know what wtf means? honestly? Would this ever appear in any other capacity? If it was going to start appearing in Newspapers or on a big news site, then it might warrant a change (but still, isn't the column BoFH still a regular at The Register? that never got its name changed...).
Shame you won't even keep the old domain or name in any capacity. Why it needed to be changed anyway is a big question that you didn't answer either - the other "sections" are still "wtf"'s, and why the name wouldn't fit a coding contest, I've no idea. Kinda loses the point of the name now.
Oh well, you might as well do what you like with it - its all your content of course. At least your grandma can be provided a full "U" grade explaination now.
While your right in a lot of the posts are immature, they do express a valid concern that I'm not sure Alex has thought through. ANY time a company changes a brand, espically a well-loved cherished brand, there is the very real concern that they will alienate a good portion of their customers. If Alex is not able to retrieve his long term base of readers or find a new base of readers (for the WorseThenFailure site), then his blog is going to lanquish in obsurity with minimal readers. Much like a lot of blogs on the internet.
While the profanity was not a "cherished" thing for me, it was what I was able to use to get other programmers to read the site. When I say "Visit the The Daily What The Fuck?, you'll love the code examples they put up", they would actually laugh and go to the site. Now I feel that if I say "Visit the Worse then Failure site. They have lots of code examples of bad code....." that I will get a luke-warm reception, and they may or may not go. I feel like a few posts already have said, I will probably still come, but I almost certainly won't be elicting anymore new readers. And will probably start looking else where for these type of blog entries.
--D
no naturally it doesn't follow (except in transmogrified logic)
also the things you are interpreting in the word are very culture based ... for example in an american background fuck can be used for nearly everything (ie get the fucking bread out of the fridge! )... while in other countrys it may be only used for the sexual, term if ever..
So please accept my view is diffrent than yours on that word..
Also I have learned that a lot of elder people seem to have less problems with talking about sex as younger ones think they have .. often its rather the younger ones that are so inhibited.
But that may also change from culture to culture...
but what we are here is geek culture isn't it...
when I read wtf I don't think about fuck or any other meaning ... the meaning of wtf has nothing to do with fuck
its just the curiosity I see when I come to this place..
more mature or not I don't care... worseThanFailure simply sounds bad ... its not sounding as round as thedailywtf
besides I feel discriminated ... I am treated like a child that is not allowed to read "fuck"...
cowardice or what ever no .. this renameing is imho simply childish and very uptight ...
Movie recommendation for the Mormons: Orgazmo (makes you less uptight)
Catcha: Atari .. works also
also I don't think people will leave this site because of the renaming ... though I think names have power .. I don't wan't to thing of this site as worsethanfailure ... uncool and bad karma
Dont be such a drama queen. Do you honestly visit the site b/c it had the word fuck in it or because you enjoy the content? Had they not made a thread about the name change I wouldnt have even noticed - thedailywtf.com forwards over to this new one.
Seriously who gives a shit what its called?
thedailywtf.com was a perfect name for the site, I remember reading the articles and thinking What The Fuck… not “this is Worse Than Failure”. And if you had an objection to the word Fuck in the name why not rename the site to thedailywhatthe.com and let the user insert the expletive of choice (e.g. heck, hell, fuck, frick, frack)
worse than failure is so wrong on so many levels, the words worse and failure are off-putting to start with but you essentially keep the WTF anachronism which defeats the point of your censorship, that’s just plain daft dude… besides that I cant imagine anything worse than failure, and it doesn’t inspire confidence that there may be a chuckle at the end of it…
I used to come here and was guaranteed a laugh if not at the article then at some of the comments, and I don’t mean a half hearted chuckle I mean a roll about the floor tears streaming down the face kind of laugh.
Over the last year or so the articles have gone down hill and I must confess I don’t visit as much as I used to do, I guess that you have capitulated to the god of commercialism and Grandma…
I do have one suggestion though: keep the “thedailywtf.com” name host it on another server reinstall the old crappy forum software and post articles like you did back in the beginning at least it was funny reading mangled posts bitching about the forum software, the isTrue() jokes and constant references to Paula…. Ah happy days…
V
Go Fuck Yourself
I will terribly miss the Daily WTF.
Way To Funny
I think you missed the point you read the URL first then go to the site, a piss poor URL will put people off before they come for example which site would you go to:
sexywomen.com
Or
fatuglyslags.com
And you know who to show the site to, by whether or not they'd be intimidated by the off-color name. Such filters are a good thing.
Christ on crutches...
Motherfucking signed.
And for the record, for all those self-righteous pricks who think the name-change will change the IQ-level or whatever of the site (good luck on that): I'll still come here. But I don't have to like it.
Fuck you Alex. What the fuck, dude?
I've been enjoying this site since sometime in 2004. It's on the front page of my rss feed page and has consistently been a hilarious take on the programming side of the world.
I have watched as the site has increasing become commercialized, castrated and reborn as a figment of what it once was.
This name change itself (albeit sucky) isn't the reason I will stop reading this site today, it is however truly the straw that broke the camel's back. The transformation into shit is complete, goodbye dailywtf, it was a good run.
Agree.
name a site "Worse than failure" ??? WHAT THE FUCK??????
what was you thinking???? This name sucks, and 200 readers already agree.
Forget this dumb idea, rollback all this thing, and make a mock site to show to your grandmother, (put some bunnies in there too, it makes no sense, but she will love such cute thing)
PS. My CAPTCHA Test says "gygay"
This renaming is just back-assward.
Nevertheless:
Nice heart warming, probably made up story about the grandma. But why don't you keep the original WTF and just tell her it means worse than failure. It is not that she will check. Or maybe you think the name hurts you in your professional life as too many people judge it negatively before you have a chance to explain why the name is excellent to address a specfic demography of technical people.
The old name is still better, IMHO. It condenses the web site perfectly, the political correct version is lame.
My best wishes, nonetheless.
Captcha: ewww. Indeed.
Hell, even my grandma understands what WTF means.
Yes, may be he wants to put it in his curriculum vitae and this name doesn't look professional enough.....!
I also agree with other comments that the new name might not attract the semi-curious web surfer as strongly, but look at us-- we've already found the site! It's Alex's problem if new people don't find the site, and it sounds like he's happy with his decision.
WTF really summarized what this site was all about. Worse than failure just sucks
As the quality of the posts has gone down (I'd much rather have one GOOD post per day than the multiple pieces of mediocre content that have appeared on this site of late.), the WTF name would at least bring a smile to my face. Once the old URL stops working, I'm going to stop reading.
Now, how can I get a good deal on the leftover TheDailyWTF swag?
You win the daily WTF award on this one - and I don't think I've ever posted a comment on this site before, ever - until now.
You couldn't even think to say, "... it stands for 'what the frig'" or something else? There's quite a few replacement slangs that begin with the letter f and would fit quite nicely and wouldn't hurt your virgin grandmothers ears - and she wouldn't hit you with her jesus cross either and tell you that you're going to H E DOUBLE HOCKEY STICKS!
Wow, just wow. Check your pants man, I think your vagina is dry.
long time reader, rarely posting.
The name change is a bad idea for the reason others have pointed out: WTF is the perfect phrase to describe what is posted here. It is appropriate for the industry.
I say this as someone who rarely swears. It is pretty immature of all the people swearing to prove that can. Most people seemed to grow out of that by the age of 12. However the acronym WTF is embedded in the industry.
I'll give it a week or so to see if the name changes back. If not I'll be deleting this from my bookmarks and I won't be visiting again. I'd guess that you are going to lose 75% of your readers.
In the end it is your choice, it is your site. I personally think it is a bad choice.
David Cameron
Funny, I thought the whining mentality was supposed to die off around the age of 12 too...
If you wanted to carry some extra weight to your "I won't read your site any more!!" sobbing, threaten not to digg any of the posts ;P
That is all. Thank you.
fuck fuck fuck fuck
also cocks
captcha: sanitarium; NO U
However it is not my site, and I'll continue reading anyway.
Yours truly,
Lauri
... because you're not adult enough to swear in front of your family?
So you renamed your site to three hastily assembled words that could "explain away" the acronym and sacrificed the entire spirit of the site in the doing?
You tell me, What The Fuck is wrong with this picture?
"Worse Than Failure" doesn't really describe the content and see a bit "made up" to that it fits the original acronym.
However, life moves on...
(Keep up the good work)
This name change is plain silly. Sad that Alex quoted his grandma as the person responsible for this.
OMFG WTF ??1?
About the new name, nice and quite relevant too. It's no about failures but strange survival of monsters than shouldn't even be born. It's about kind of corporate anti-darwinism. Instead of being still-born projects, resources are wasted at them, and like I said before, it's often due to overconfidence but it's more than that ; I think this new name really embraces the website's purpose from its very start. The only grief I have : it's less funny.
I've enjoyed What The Failure for so long, and as you so accurately wrote, it's the only natural reaction to some of the content.
MAN, I'm soooo failured off!!!
To me, I dont care, because is the content. But I will not remeber the new name, so please NEVER remove the old name. I will continue typing thedailywtf.com on the browser address.
- terrible new name
- even worse because you have tried to keep the old acronym
- grandma? seriously?!
- PC = not-cool anymore = are you selling out??
Politically correct my ass - to me this site is called What-the-Fuck!.. Dude... "Worse than Failure"?! You got that right... :-(
Biggest wtf to date, right here.
No, he's a pussy.
Goodbye DailyWTF :)
captcha: darwin (these 250+ comments evolved from apes)
I don't understand why so many people are getting worked up about it either, do you come to this website just to stare at the url and write stupid comments?
New name sucks monkey balls.
WTF were you thinking? *shakes head* :(
Daz
captcha: alarm (bells)
I'm really quite bored by the whole PC-stuff (and I'm not talking about Personal Computers...)
did any of the "correct" phrases ("xyz challenged" etc.) change anything in the way people think about things?
or are these phrases just covering up narrow-minded and chauvinist thinking which does not change the least by using new labelling?
I'm quite convinced that it is the latter - so there's really no sense in giving in to PCness.
I'm disappointed. the new name is sort of "lamely correct"...
thankfully, this whole PCness did not catch on so heavy here in europe. might be it was not as necessary in the first place ;o)
captcha: kungfu - yeah, let's shatter PCness! ;o)
Remember kids, 'Failure' is a very bad word.
I think Richard Pryor said it best: "Fuck censorship, and its moma.."
It's one drop too far... first there was that summary/full article change, then now choice is gone and the name change, as well as the domains.
I'm just removing the old wtf bookmark from my bar, no promise, no menace, just dropping.
I did enjoy Paula, and the others articles, but not enough to bother with a changing spirit.
Do not bother to address me with a reply, i'm just gone.
Bye.
If that isn't the reason, well I'm sorry but that's what I and many people gather from this post, which is just sad. I always find it quite funny when people try to coddle and protect their grandparents and elderly people because they think "ZOMG, SWEAR WORDS, OH NOOOES!", and it turns out that the old person in question doesn't really give two shits.
Come on, dude... changing the name just so you don't have to say "The 'F'? It uh.. stands for.. uh...". Now THAT is a WTF in itself.
What about a Schroedinger's cat solution? It's still TheDailyWTF, but nobody is told what WTF stands for unless they ask you, and depending on your mood, you can answer What The Fuck or Worse Than Failure?
Or even better, you leave it to the reader to decide whether they prefer to think of WTF as What the Fuck, Worse Than Failure or the new weird thing on technorati?
*Sob*
Now there's an idea worth of credence ;)
Daz
You and all the smart persons saying "that's no censorship", have you ever heard the word "Self-censorship"?
Correcting one's own speech for being more political correct is just a form of (Self-)censorship. Being political correct is nice and sometimes just necessary, but being PC just for being PC is siiiillllly!
So yes, I'm another 'new name sucks' whiner, but at least I'm free and mature enough to use swear words when necessary.
Strange: the country that invented the idea of 'free speech' and strangely still stands for liberty in some parts of the world (mostly in your own land I suppose) - but it's inhabitans doesn't even realize that they conduct self-censorship on a broad, daily basis.
Too sad...
The site's written in .NET (check the URL extension - .aspx), which has a convention of naming methods with an initial capital letter.
I think it's to piss off Java programmers that decide to learn C#...
captcha: dreadlocks
WTF?
The Real WTF is that if he'd changed the name to "The Daily WOE" (that's for "What On Earth") then he'd have kept the original sense of the WTF part of the name and had a site name acceptable to prudes. He'd have even been able to avoid having to explain it to lay-people.
Now, if only we could guess the real identity of the prude Alex's worried about. Given his propensity for changing the names involved, I'd guess it must not be a grandmother. Maybe a potential future employer instead?
Captcha: WTF (means What The Fuck, and don't you forget it buddy!)
gone chicken?
push from the advertisers?
WHAT THE FUCK????
Its like renaming Terminator II to The Robot from The Future.
The name is lame.
After at least 265 comments, for whoever might be counting, here's yet another gratuitous occurence of each of the words, with my compliments:
pussy, sell-out, lame, weak, vagina and naturally Fuck.
Pitty. TheDailyRestInPeace.
Nerf undead.
not sure if this has been edited out or not, but it currently ends with the following:
"On February 24, 2007, the site was renamed to Worse Than Failure because Alex was not man enough to say the name in front of his family"
yeah, but i bet none of them would dilute their brand by renaming.
Amazon Exec - hmm, this jungle name just doesnt make sense to our non-core user base....hey, check and see if bookshop.com is registered.....
Pleaaaaaaase
The site's written in .NET (check the URL extension - .aspx), which has a convention of naming methods with an initial capital letter.[/quote]
No I will not say that it's one more thing they copied from Delphi, I will resist
Well as long as it's not The SpamBot from the Future... :-)
-Lars
Oh well. The content is still great, though, keep it up!
Dilute the brand? Are you completely insane? It's a blog!
Oh, and tell that to Verizon, Mandriva, Wireshark, Ask.com, CBS Radio, and USAirways... I could keep going.
Thats the most sensible thing said so far.
haha lots of wtf's in that sentance.
Promote worsethanfailure.com, but leave the old name for all those who can't stand change. I don't think the name change is good or bad, but it's a good thing if it makes Alex happy with his work...
Though I expect our pleas are falling on deaf ears, please change it back.
Though I expect our pleas are falling on deaf ears, please change it back.
Please reconsider. This just doesn't feel right.
In any case, I don't care much about the name itself, although I liked the old one better. I do care about the political correctnes reason, but sure, it's Alex' decision.
Recruiting new readers will be hard because the new name is a turn-off, except maybe for some percentage of the US population who cannot approve of internet slang.
In any case, consider being a bit more mature the next time you feel the need to disagree. Name calling is pretty weak.
The new brand is weak. Please change it back!
I personally don't care what the site is named; I like to read the stories, and I like to read the comments. I'm actually hoping that with the number of people who have threatened to stop reading we might cut down on the number or people putting "frist psot!" comments in.
Perhaps the site's name should remain The Daily WTF, but change the official meaning of WTF to "Worse Than Failure". That way we can tell grandma's aboout the site, but we can also still attract the "cursing is cool" crowd.
Bingo - it is a blog. That is it.
And for all of you who say you are leaving and never coming back you're full of shit. You dont come here b/c it was called WTF (at least I hope not). So I guarantee you will return.
Alex, I think you're a good person and sometimes good people make mistakes. Let's hope that Worse Than Failure ends up on the same junk pile as Microsoft Bob.
It's creative because all these code segments are worse than failure...at least if the person writing it had failed to implement something then someone could have done it correctly the first time.
It explains the site better because, as Alex said, it's more than daily now, there are multiple forums, and not all of the code segments/ stories make you say "WTF", but they are all worse than failure.
It's an improvement because of the above reasons and because those who do have relations who care about that stuff can redirect them to something we think is funny and show them a small part of the headaches we deal with daily without having to obfuscate the website.
To those who are angry about the idea of political correctness: You'll find that Alex actually increases his readership by changing the name because. How can you work with syntax specific languages all the time and not see that using phrases like "What the fuck?" are like writing this:
void c(int* x, int* y){x=y;y=0;(int)x!=0?c(x,y)}
when you could have written this:
void clear(int* x, int* y)
{
x = 0;
y = 0;
}
???
The last time i held back about anything in front of my relatives was when i still depended on them giving me those extra bucks when i visit :P
And a coding contest? And "other things"? Just keep the site like it is dude.
The site is fine as it is. If you're bored with it, make another one. But don't fuck up a site people already love ;)
I shouldn't actually really care, cause, well, it's your site. But the new name really sucks :P
Actually, not all censorship is directly externally imposed, perhaps you should do more studying. For example, at one point in US history there was the "Equal Time Doctrine" which held that when a media outlet provided space and/or time for a political view, it was required to provide an equal amount to the other side(s). This led inevitably to the outlets not allowing any political content because they were then forced to double the amount of time/space available. This was correctly held to be a form of censorship as it effectively prohibited certain speech. This is but one example. If you truly did as you suggested you will find many many cases of this.
Most of us do in fact practice self-censorship at various times - especially those of us who are married.
The "consideration of others" is one of the bricks on the road of good intentions. Are people forced to read thedailywtf.com? Nope. It is a voluntary choice. Thus, there is no need or benefit to the alleged "consideration of others". Further there is no evidence that there exists any consideration of others among a self-selecting audience.
That self-selecting audience made a conscious choice to read the site - many due to the name. It was apropos. It made sense. Now it does not. It is no "immature whining" on the part of readers to disagree and to stop reading or suggest that they might. indeed, if anything is immature it is those of you who call the "whiners" children. That is known as an ad hominem attack and is a good way to show you have nothing of value or merit in your argument. Instead of attacking the argument, you attack the poster. Quite immature.
Indeed some of the arguments made are made from experience. As history and experience shows us when groups or entities start shifting towards more political correctness, it is more often than not a sign that change is coming. And more often than not that change is in watering down the content, intent, or purpose. The stories have slacked off over the last few months IMO. Taken with the PC name change it is not illogical to conclude there is a chance that the essence of what was thedailywtf.com is waning.
Will it go away? At this point it is quite likely. As people who are in the IT world and seeing these WTFs leave the site due to it losing it's essence (it's purity some would say), the submissions of good, genuine WTFs will decrease. This will further decrease the essence that was thedailywtf.com thus perpetuating the fall.
Will it come to pass? Perhaps. It would be neither the first nor last time such an event occurs.
And yeah, Slashdot-style fr1st psot bullshit irritates the fuck out of me. Hopefully this will cut them down, if not I might have to get hold of a chainsaw (and not by the blade).
Jeeze, it's like a little bunch of children arguing over which pokemon is better.
It's pretty simple really ... there is a purpose in life for swearing, but not everyone likes to hear a nonstop string of profanities.
Sure, this name change might upset all of you stuck up twits that seem to think we give a damn if you come here and post your drivel. Sorry if you're so used to being able to cuss a storm and get your own way ... sorry if you feel you've been oppressed by the man ... hell I'm even sorry if you got dropped on your head as a baby ...
BUT WE DON'T GIVE A SHIT!
I mean seriously ... how much credibility do you think any major organization would have if they swore in their names or slogans?
"" ... yeah, sure bet that'd do wonders for their user base...
"Dell gives a damn about you" ... Yeah, so much B2B sales gonna come from that one...
"MicroShit Windows" ... actually that might be kinda appropriate
Are we getting the point yet dumbdumbs? Since Alex appears to wish to expand the readership and activity of the site, the best move for his credibility is to get a name that won't destroy his credibility as site worth viewing.
And for the record, I'm one of these people that consider it highly inappropriate to swear in front of children, your parents/grandparents, or complete strangers ... but I am willing to make some exceptions when dealing with 2 short planks.
Now can we all please get over it and go back to laughing at the crazy code?
*puts his straight jacket back on*
CAPTCHA: Quake - this relevant captcha reminds me of the BFG (10K) in quake2. ID software could have gone all PC or worried about 'inherent meaning' and called it the "What's going on gun" instead. They didn't. It's better this way.
-Harrow.
But now you mention it that Pikachu one is overrated
I know give out free stickers that'll help.
Now all we need is a classic WTF story about rebranding and how it always is a diaster.
New name is Lame. I'll prob still read, but change it back.
The new name is just fine; I had a somewhat similar problem, if only because saying "Double U Tee Ef" out loud sounds weird.
Now I can just tell them to check out Worse Than Failure. :)
way to go alex
1) Wuss Towards Family
2) Wet, Tiny, Flacid
3) Write Terrible. Flee.
4) Win The For
5) Well Timed Fart
Having said that, I have to admit that "Worse Than Failure" does not exactly roll trippingly off the tongue. There have been some much better suggestions in all the above drivel:
The Daily WOE (describes my job to a T)
The Daily SNAFU (can use Situation Normal - All Fouled Up as the tag, while the script kiddies snicker in the back of the room)
The Daily FOOBAR (as above, dates back to K&R C)
Alex -- It's your site, and the rest of us should remember we are but guests. I applaud you for having the guts to stick with your convictions, regardless of what the rest of us freeloaders think.
First, I started reading the site because of the name. I'm not one to swear, so telling others can make me blush, but I think it attracts readers. I'm glad WTF wasn't spelled out or I might not have visited. (I don't think I could visit a site with f*** spelled out in the URL at work!)
But when I viewed the code submitted here I always had "WTF?" running through my head. I thought it was very appropriately named site.
I'm doubtful people will stop visiting just because of the name change. If they do, fine. I know won't stop visiting. (I will still go to thedailywtf.com instead of the new URL however!) But I do have to say, the content seems to have gone downhill lately. (But if the "frist" posters all leave, great!)
I would have rather seen you tell your granny that WTF stood for Worse Than Failure than change the name of the site (I know I could never said f*** to my grandma!), but I understand how a site with WTF in it could turn off potential employers or companies wanting advertise here. It is kind of sad though.
I like the suggestion of keeping thedailywtf.com domain name and having a different header for visitors to that site.
As for the free stickers, I think I'm going to try to score one and then just cut off the bottom.
How is SNAFU or FOOBAR (originally FUBAR) any better that WTF? They all started with the F meaning f*ck. (At least to me! And still do!)
About the meaning of the old name, some have said that 'daily' it's not good now because it's not 'daily' anymore and 'WTF' is because 'cursing is cool' :P I've never thought of it this way I always thought that 'daily' comes from the idea of being a newspaper and 'WTF' not because of the 'fuck' but because 'WTF' is a very very (extremely very) common expression. Anyways, let's hope for the best (=
Tact? Discretion? Decorum? When it comes to WTFs for some of which the perpetrators should be sentenced for life in front of a firing squad?? Get real. We're big boys and we talk here of things where swearing is the least you should do. I'd manhandle some of the WTF'ers had I worked with them.
Tact, my ass. What the WTF perps do is tactless already, so The Daily WTF was simply following that direction, and it made sense to me.
The name change is quite spineless to me.
captcha: waffles -- as in, "thinks of a good website name, but then waffles"
My recommendation would be to -- as others have said -- to keep multiple version of this site, with different branding depending on the url. By the way, I'm the guy that recommended you to register therealwtf.com. Hurry up before some one else does so. This site deserves it since the tradition originated here.
Me, myself, I'll keep on reading this web site, but i promise to use the word FUCK at least once in every comment and commend people to do the same.
Oh by the way, this is in reply to:
"Profanity is the sound of an inarticulate person seeking to express himself forcefully."
Except when you choose so. You miss the point, programmers are incredibly articulate people, yet we still like to express ourselves forcefully. Besides bending your speech to show off your literary prowess for fear of being mistaken as inarticulate is a sign of insecurity and immaturity, unless you do it because you choose so.
Disclaimer: not a native speaker, spare me of reaching a thesaurus.
Worse than Failure doesn't have the same rhythm and flow as DailyWTF.
WTF was a perfect name, because almost all of those that (I believe) this site is aimed at know that expression. And have probably used it.
However WTF itself is simply an acronym, or a collection of letters. Why not leave the name as it is, and just explain to your Grandmother that it means Worse Than Failure?
Or heck, use the Phonetic alphabet: WhiskyTangoFoxtrot.
Of course I'll keep reading; it's the same site. But I really think you've made a bad decision here. I just can't see the point.
Look, bring back the old name. I don't want a sticker. This is like M$ getting rid of the My Pictures toolbar in IE7 (the only good feature ever added to IE6). Complained to someone in India who didn't get it and pointed me to the tech department for installation problems...WTF?!? It's a feature I can't install cause you GOT RID OF IT!
Look, nobody liked New Coke either:
Ironically, the new name describes exactly what it is: worse than [a] failure.
I understand your desire to try something new, but I'm not keen on the new name. I don't think it is at all descriptive of what gets posted here.
"WTF" is what we say when we see the things that happen to us that relate to the stories and code snippets that are on here. It's relevant, topical, and has "brand" value, since we've been reading "theDailyWTF" for as long as we have.
Let me know when you change it back.
AL
Vinny.
let's hear what our good old friend Bill Hicks thinks about the new name:
"Piieeeeecccee ooooooofff sssssshhhhiiiiiitttt !!!"
c'mon change it back! you know it sucks!
Can't we use some Firefox Plugins to replace text and images?
No, they called it Blast Field Gun/Generator, IIRC.
If they use the same database i don't think it should be any problem.
me> you should check out this site to know what not to do... [writes url on board]
fairly clueless female student > what does wtf stand for ?
me> err ... err ... 'what the fudge' :)
class> *laughs*
Your grandma can handle the FUCK word. Seriously. To think otherwise is rather condescending.
So be honest with us, is it really because of Grandma?
Whatever, i'm not going to lose any sleep over it but it's a pretty retarded move IMO. New name sucks, old name rocks.
AWFUL AWFUL AWFUL.
Captcha: atari!!!!!!!
Hell, Grandma had to do it herself, otherwise she wouldn't be a GRANDMA!!!!
I've worked for a lot of small companies, and I see it all the time - as soon as things get going people in charge will start making a truly stupid mistakes (like changing the name) and derail themselves. And then fragile ego's prevent them from acknowledging the mistakes and fixing them. Dont follow that road to failure.
Let me give you a bit of free advice. GO WITH WHAT GOT YOU THERE. There's tons of sites out there that cater to IT people and cubicle monkeys, and their need for sufficiently watered down, office safe humor. But there is and always will be just one TheDailyWTF.com! DONT SCREW THAT UP!!!
STUPID!!
Great site, great stories, great original name, and I'll stop there.
I'm also holding seminars - well, not for students, but for grown-up real-world developers and decision makers, admittedly ;o)
however, there never was any problem spelling out the name of this site for those rare occasions where someone did not know what WTF meant.
mind, that I am in Austria, where "fuck" is seen as a much stronger swear word and not as commonplace as in english (e.g. as intensifier in phrases like "this is fucking great" etc.). interestingly, in german the prevalent swear words tend to be more of an anal than a sexual connotation, i.e. most common ones include "scheisse" (="shit"), "Arsch(loch)" (="ass(hole)") etc.
as an intensifier we are often using something like "verdammt":
"it's fucking cold" = "es ist verdammt kalt" (="it's damned cold") or also "es ist scheisskalt" (=literally: "it is shitty-cold").
also interestingly, "fuck(-ing/-ed)" was sort of incorporated into the german language in the last years as "verfickt" (one wouldn't have said that 20 years ago, and it's still regarded to be stronger than the original german swear words like "scheisse" etc.).
hey, this may become a linguistic discussion, nice ;o)
Anyway, I read the site via RSS, and I would never have known about the name change if it hadn't been for the announcement. This is because the RSS feed has never been branded with the name of the website. The posts are always tagged with the personal name of the poster, and the only mention of the website was in the link to the discussion. So, I don't follow the logic of the people who are unsubscribing their RSS feeds as if they are suddenly being deprived of a vital part of their lives. If you need it that bad, go get a girlfriend, or a calculator.
BTW, is the real WTF still copyright?
Please change it back
Also, sorry if I've repeated something for the nth time - I cbf'ed reading through 8 pages of comments.
CAPTCHA: Completely irrelevant sentence (to the discussion) having to do with my previously overstated and completely unsupported opinion.
<analogy>
<compares>
<problem>
<name>Won't Work</name>
<description>XML won't fix the problem</description>
</problem>
<solution>
<name>Violence</name>
<description>Use more XML</description>
</solution>
</compares>
<compares>
<problem>
<name>Whine</name>
<description>I don't like what he said</description>
</problem>
<solution>
<name>Whine</name>
<description>Give my opinion and imply 'He's dumb!' or 'My Dad's stronger than your dad!'</description>
</solution>
</compares>
</analogy>
Horse
I can sort of understand wanting to distance yourself from the vulgarity. However wose than failure doesn't have the same feeling as wtf. Basically, I'd say call it what you like, but just keep using the wtf label. Also, the daily part, since no one really cares if its more than daily, only if its less. Its cathcy to sayl the daily wtf. Worse than failure sounds like a cheesy comic.
I'll still keep reading whatever is chosen, because I some here for the content, not becuase of the name.
This way you'd have both names and people could choose between the one they liked more.
Please, pretty please with sugar on top, work up some backbone, change the name back and get your act together again.
For now, alas, I'm deleting the shortcut from my 'dailies'.
So the PC crowd has "won" another battle but they can rest assured that they'll never win the WAR.
I know a good proctologist that might help them locating their heads. :)
Somebody posted an interesting suggestion to make the old domain use the same content with the old branding - a brilliant idea.
captcha: ewww. Yeah, 'sabout right.
I completely agree. I feel vaguely let down by this name change - it loses the spirit of the site.
Those turlingdromes will probably be saying belgium to everything ;)
Actually it would be even funnier than the old title as most people would think it's the "what the fuck" at first until they see the subtitle.
it's your loss.
I've read all the comments on this article so far, and it's rather interesting to see where the readership's perspectives lie. The collective intelligence of the WTF readers seem to express a negative opinion of the recent name change.
A few commenters are complaining of Alex "selling out" to political correctness, and some raised an excellent point about the failure of brand renamings in the corporate world. Another person made an excellent observation about WTF's pagerank, which will inevitably decrease due to the site redirect.
The poster "Richard Nixon," who I have a fair amount of respect for, made an excellent argument against the name change. It's a pity that he plans to delete his WTF bookmark and never return to this website again.
I personally prefer this website's prior name, but I do not plan on leaving. The content is still the same, and I expect plenty of excellent articles in the future. In my mind I will always refer to this website as "The Daily WTF" though. That's how rebranding often works: consumers are inherently stubborn, and refuse to recognize an entity by its new name.
I would like to make a comment to those who plan on leaving. The content is still the same. You enjoyed reading the articles, and a mere name change isn't going to change the quality of the writing.
Also, I believe having "thedailywtf.com" retain the old logo is an excellent idea. Though I doubt Alex will approve: it creates a disunity amongst WTF readers.
Sincerely,
Gregory
excellent..
- Look at this WTF!
- What?
- Look at this Weird Tech Finding, here...
There are numerous WTFs (weird terrible features) in the name change, for instance if Alex just said he was messing with us we could have even laugh, instead, he said he was embarrassed in from of his grandma!? fucking lame! And a non sequitor by itself, does your Granny read tech news at all?
CAPTCHA: burned, That's how we feel!
Oh wait, yeah, that never happened.
Boo on you, Alex. DailyWTF forever!
PUT THE FUCKING NAME BACK
THANK YOU
Your ZX81 basic is WTF material on it's own. Line 10 fails with a syntax error.
You need a PRINT before the quoted text you pillock.
p.s. please change the name back. Your new site name sucks.
2)And to all you who are saying "Well I'm still going to keep coming. The content hasn't changed." YOU ARE HIGH! The content of this site HAS changed drastically in the last few months. And THAT is the reason I'm am coming here less and less.
3)You are overreaching, Alex. KISS (keep it simple stupid). There is elegance and and permanance in simplicity. Does the term "Bloatware" mean anything to you.
Capcha: stinky (how apropos)
The new name is terrible, I have unsubscribed from your feed.
Don't get me wrong though, I'm not going on an ultimatum tantrum declaring I'll stop reading, I read this site for the contents, not some ridiculous reason like the title or "coolness". And the contents just keep on getting better and better. Keep that part up! :)
captcha: (i know) kungfu.
"WTF" is a perfect description of the articles on this site and has "mind share" (as the marketing drones call it) with the target audience. When I tell people I saw something on "The Daily WTF", they either get it immediately or will never understand either the name or the site's contents.
"Worse Than Failure" is a completely artifical phrase, has no meaning to anyone, and doesn't convey the true meaning and horror of the articles.
Tell your grandmother to suck it up and deal with the profanity, or just stop telling her what it means. Changing the name to match someone who isn't in the target audience and who therefore doesn't have the background to understand most of the articles (and therefore won't read them anyway) is ridiculous.
Awareness of an alternative to "classic" WTF has been raised; just keep it in the tagline.
The old URL was much better, punchier and to the point.
But this is the best you came up with?
Another cool website jumps the shark.
To keep everyone happy, can I suggest it changes again to WTWTF (Worse than WTF). And can I just add, in the interests of being fair and balanced: "What the FUCK?!!!"
Get real, switch back.
Shame on you...
The site's written in .NET (check the URL extension - .aspx), which has a convention of naming methods with an initial capital letter.[/quote]
No I will not say that it's one more thing they copied from Delphi, I will resist[/quote]
And I will resist pointing out that the guy who made Delphi also made .NET
1. Alex started a fun site to mock his own industry
2. It caught on and grew
3. Alex recognized the opportunity to generate some ad revenue offset some of the investment in costs and
6. Upon announcing the change, the children whined and cried
7. Life went on, with loyal readers and advertisers staying-the-course (sorry - it really does hurt to use this particular phrase)
Of course, changing the title doesn't prevent people from using bad words in their posts. Hmmm....
S*** P*** F*** C*** C***S***** M*****F***** and T*** !!!
--gc
Everyone's dad is a M*****F*****!
--me
This is the point at which a successful business decides whether or not to turn down business because, on one hand, it is income, and who doesn't want that? On the other hand, what the customer (in this case, advertisers) demands distracts the company from it's core offering, ultimately driving away customers.
Personally, I like the old name, and won't stop reading, but I don't have high hopes as to the quality of the site getting much better. It's not the name change, per se, but what the name change is indicative of. Too many times, a decision like this marks a turning point in a company's offerings, usually for the worse. In this case, the site may go on for years to come, but not with the bite that a name like "Daily WTF" connotates. It's precisely the word "Fuck" that causes the contributors to unconsciously feel okay (and possibly go out of their way) in writing their posts in that wonderfully sardonic and irreverent way we love so much.
It's like the difference between a Sunday car ride and a couple laps around the race track. They're both really great for their intended audiences, but don't expect a fan of one to like doing the other. I'm a race car guy who likes taking it easy once in a while, but I fear this wbesite may have just slowed down a bit too much.
I don't feel it was an encounter with Grandma that caused this change, but more likely it was one or more advertisers. However, keep this in mind; this website is an entertainment venue, which goes by different rules than the rest of the business world. Whether you hate him or like him, do you really think Johnny Knoxville's resume has been doomed because he had the word "Jackass" on it?
I wish I was that cool ;-)
By taking that problem away from me, I'm very much grateful for the namechange (especially since that they can claim the acronym is a cunning coincidence than a bowdlerisation).
But anyways, I think this whole thing has convinced me never to use swears in names, because if you try and change it, no matter how much better you might like the new name, people will accuse you of bowdlerising it to suit the Man.
"dailywtf", no that's not it.
"worse than fucked?" no, that's not it either. It's some name that didn't have "fuck" in it. Um...
Oh now google found dailywtf for me. Thanks google!
Yeah, not really marketable.
And just who are you selling out to? There isn't a demographic that
A.) isn't familiar with the expression "WTF" and
B.) understands programming well enough to understand this site.
While neither "The Daily WTF" or "Worse Than Failure" give any indication that it's an IT site, it was a link on TheOldNewThing that drew me here, not the name itself, so that's not a deal breaker for me.
I agree with many previous comments the snigger factor is way down with the new name, and possibly in another direction where it looks like you're trying to pull one over the audience by disguising a well known acronym with a fairly trite title.
However, there's a difference in spirit in the two names -- if you are planning to change the direction of the site then it's possible you'll lose some readers (maybe me, who knows, I'll wait until it happens).
Anyway all up, it's your site dude, good luck to you.
"What" has only one syllable.
... to be 15 again...
Grow a pair and change it back.
new name is much better.
Tal.
- I'm submitting the 450th (or something like that) comment thinking that it will actually be read by anyone.
- (the real real wtf): So many code monkeys are so endeared to a vulgar word.
I for one (and I do mean one) am glad I will no longer say, "I don't like the name, but the stories are great".
this is pathetic.i still can't believe it.
its like google.com change its name to gsearchengine.com. The feature is the same, but it lost some something. Something that make a site so special.
......
I still can't believe it. Fuck! Out of my bookmark dammit!
'Worse than Failure'.. no kidding
If any of the advertisers signed up with "The Daily WTF" (N.B. the "advertise" page still uses that name) then by changing the name there is probably a breech of contract! They probably signed up to this site BECAUSE it has a brand name and url that will continue to attract NEW visitors, which the new name will not at anything like the same rate.
Another problem is that a lack of new visitors should cause a sharply reduced flow in new WTF's to post on the site...the existing people only know so many. Such a lack of new content should cause a second lowering in the eyeballs as the interest level of the site to existing people goes down.
there are only 3 lame articles.
It's not too late to change it back.
ok... everybody was shocked, everybody laughed *g*... now change it back!
Some things you didn't know about grandma:
- she has watched porn
- she has been to a strip club
- she has taken drugs
- she has told very dirty jokes
- she has tried every sex position in the book
- she has done as much fucked up shit that you have (most likely more because she is older)
- she has used the word FUCK thousands of times
- yes she is old, but she is also a human just like you and everybody else you know and people were not any tamer back in her day. She puts on an act for the grand kids just like all grandparents because she sees you as innocent in the same way you see her.
Removing this site from my daily list and I won't be adding it back till the name is back.
fubar
Same concept. They'd understand.
And by the way, the site's new name is fubar. :P
If he changed it for the actual reasons he sited (his grandmother) then it would have been simpler to just tell her that WTF stood for “Worse than failure.” It would have saved the time and money of having to register another domain and create a new logo.
thedailyWTF (btw daily does not necessarily mean once per day, it can also mean every day)
worse than failure SUX0RZ :(
LMFAO i would so love THAT name.
captcha ATARI (would laugh too)
Like many others said before:
- Old name is way better!
- Reason for change is sad, pathetic, hypocrite and what not.
Nothing wrong with the word Fuck. (Listen to 'The F-word')
You could always explain to Grandma that WTF in theDailyWTF stands for 'Worse than Failure'.
That said I will continue reading the site, cause the stories makes me smile everyday.
Hope thedailywtf.com stays forwarding (cause I don't want to update my bookmark), or like mentioned by another reader, maybe you can use both domains with the same content, just a different header.
Captcha: stinky - Yeah, this smells bad!
"The Daily WTF" was hilarious - it alone made people laugh when I mentioned it. This new name feels more like indulging in stories that make us feel superior. Yuck, I'm embarrassed to mention the name now.
A Lange & Sohne watches
Audemars Piguet watches
Ulysse Nardin watches
Vacheron Constantin watches
p.s. the 'f' totally stands for "frack", everyone knows that. Or "frell", that works too. ("I see you drivin' round town, with the girl I love, and I'm like: "Frack you!") | http://thedailywtf.com/articles/comments/Announcement_0x3a__Website_0x2e_RenameTo(_0x201c_Worse_Than_Failure_0x201d_) | CC-MAIN-2015-32 | refinedweb | 17,281 | 73.58 |
I am using Visual Studio 6.0 and code is in C/C++. Commercial software with over 2000 source files scattered all over. Trying to get a handle on doing some estimates on various tasks.
Is there a way in VS6.0 that allows one to do "Find In Files..." with some complex search criteria?
For example, I would like to search for lines in files that contains the string "alloc" or "malloc" or "calloc" or "realloc" which does NOT contain the string "sizeof". Is there a way to do this?
I also would like to have a line count (how many lines are there in all these files when the search pattern matches), and a file count (how many files do these lines occured in).
If they can be configures to ignore lines that preceeds with "//" or in the middle of a /*...*/ block or even inside of a #if 0 ... #endif even better.
This is just one example, I need to do dozens of different searches to make an assessment on how bad the code is and decide whether we hack/patch or refactor or whatever.
Also we use CVS source code control which creates a admin directory with duplicate code that will double the count, is there a way to "include subfolder" but not to include subfolders of a specific name?
Thanks,
MC | http://cboard.cprogramming.com/brief-history-cprogramming-com/71293-search-patterns-source-code-printable-thread.html | CC-MAIN-2015-22 | refinedweb | 225 | 81.93 |
Taking a break from diving into further details of Classes and Objects, I have detoured into taking a closer look at some of the naming conventions that are used in the Ruby programming language. In particular we are going to look at Constants and local, global, instance, and class variables.
Constants
In Ruby you define a constant by having it start with an uppercase character. Yes, it is that simple if you want a constant whether at the class level or on the procedural level simply start your naming with an upper case character and it is defined as a constant.
SecretNum = 13987 class ConstantClass Pass = "PASS" Fail = "FAIL" end
To access the constants of a class you would simply type {ClassName::ConstantName} while non class constants are simply called like a variable.
puts SecretNum puts ConstantClass::Pass
However as it turns out Ruby let’s you reassign the value of defined constants at any time, yes they say that you should only assign a value to it once but they let you change it. Why would you use these “constants” if they can be changed at any time? The second strange thing is that if you have a Constant defined Ruby still lets you define a method with the same name.
def SecretNum() puts 666 end
Now you have both a constant and a method with the same name. Where if you leave out the parenthesis the Constant is used by if you add them the method is called.
puts SecretNum // outputs 13987 puts SecretNum() // outputs 666
Again why? Needless to say it is good practice to name your methods starting with a lower case, but if you are defining your language so that Capitals are reserved for defining constants you should enforce that either methods all start with a lowercase character or that a constant with the same name doesn’t exist.
Variables
Variables are identified by their first and or second character, in which they define the scope of where it can be utilized.
Global Variables
Global Variables are identified by starting with the $ character. These variables can be set or read from anywhere within your program even in classes and methods.
$globVar = 8 puts $globVar // outputs 8
Local Variables
A local variable is simply a named variable. It can be accessed anywhere in the current scope it was defined. If it is defined in a method it can only be used in that method.
def testMethod( var = "testing 1 2 3" ) puts var end
Instance Variables
An instance Variable has it’s scope confined to the object it belongs to and begins with the @ character. These can be accessed by methods belonging to the object or set and read by their name if they are defined as accessible.
class MyClass def doSomething( var ) @something = var end def doSomethingElse( ) puts @something end end
Class Variables
Perhaps the most confusing of all variables is the Class Variable. These variables are recognized by their names starting with @@. These variables can be accessed by a class and its inheriting sub classes. So if you change the variables value in a sub class the base class’s value is also changed. I’m not going to go into any further detail on this as of this moment I do not see any reason why you would ever use a Class Variable as if you needed to I don’t see why you wouldn’t just use a constant.
Those are the basics on the Naming Convention used by Ruby to identify the scope of variables and constants. Pretty basic with a few strange twists added in, once again I find myself thinking that Ruby is popular simply because it lets you do pretty much whatever you want no matter how bad design and code wise it is. However i am trying very hard to keep an open mind and will reserve judgment until my crash course is finished. | http://mdbitz.com/2010/03/24/ruby-naming-conventions-lesson-3-of-my-self-inflicted-crash-course-into-ruby/ | CC-MAIN-2018-30 | refinedweb | 657 | 64.95 |
Opened 8 years ago
Closed 3 years ago
#7467 closed New feature (fixed)
[Improvement] Easier way to overwite the admin welcome message
Description
To change the prominent visual welcome in admin/base.html div user-tools, one must copy the entire admin/base.html template and modify just one line. A block containing this welcome i.e.
block userwelcome would be useful for customization.
Attachments (1)
Change History (14)
comment:1 Changed 8 years ago by
comment:2 Changed 8 years ago by
comment:3 Changed 8 years ago by
Milestone post-1.0 deleted
comment:4 Changed 7 years ago by
I second this. There are languages that use different form for vocative, thus "Welcome, Vlada" is incorrect. I think this form could fit to the majority:
{% trans 'User: ' %} {% if user.first_name %}<strong>{{ user.first_name }} {{ user.last_name }}</strong> {% else %}{{ user.username }}{% endif %}.
It does not matter how to reach it, but currently AFAIK the only way is to override entire admin/base.html, which is complex.
If this applies to your language to, please vote for this.
comment:5 Changed 7 years ago by
comment:6 Changed 7 years ago by
I'll attach a patch to make it possible to override the default welcome message.
Thus, one could do:
{% extends '/path/to/default/admin/templates/admin/base.html' %} {% block welcome-msg %} <strong>{% firstof user.first_name user.username %}</strong>, {% trans 'welcome!' %} {% endblock %} That said, I'm not against the "re-phrasing" of the message.
Changed 7 years ago by
See comment 6.
comment:7 Changed 7 years ago by
comment:8 Changed 6 years ago by
comment:9 Changed 5 years ago by
comment:10 Changed 3 years ago by
comment:11 Changed 3 years ago by
Changing to unreviewed as there seems to be no comments by others [in a while, and based on the new version].
comment:12 Changed 3 years ago by
@kamu - Unreviewed means that nobody has looked at the ticket. Several people *have* looked at this ticket, so it has been accepted.
If you want to know more about the Trac ticket states, see the documentation on contributing.
I agree on that, but according to 1.0 policy I think that it will be postponed after Django 1.0 is released.
Changing summary to clarify that this is an improvement. | https://code.djangoproject.com/ticket/7467 | CC-MAIN-2016-44 | refinedweb | 386 | 67.45 |
Hello. I used to script several years ago, and I would typically use 'goto' to jump to a different function. The script would basically have a large set of functions, with a starting function that would then call a different function based on what was done or typed, and then continue jumping from there.
I am having a bit of trouble now that I am trying out Python (and rusty on top of that) with being able to hop like that. Basically, I am currently trying to make something like this:
def start_game():
Welcome! Please type a command. For a list of commands, please type 'command'.
if input=command
-------goto list_commands
elif input=start
-------goto game_init
start_game()
def list_commands()
Here is the list of command:
Start
Blah
Blah
Blah
goto start_game
list_commands()
def game_init():
game_init()
Obviously this is not the syntax used, but it was just to quickly demonstrate what I mean. It asks for input, you give input, and then it calls a function based on that. In the "list_commands" function, you would get the list, and then it would return you back to the "start_game" function, so that you could then enter the commands.
I am curious how to get this to work, as various places that I have read about calling functions dont seem to make sense, or they dont work in the way I expect them to. Thanks! | http://forums.devshed.com/python-programming-11/question-calling-functions-939699.html | CC-MAIN-2017-30 | refinedweb | 232 | 73.51 |
I have made an array of objects. I've started by defining a class and making an array containing pointers to that class type. Then I initialized each pointer to NULL.
What I would like to do from here is pass the array to a function that will tell me how many classes are stored in the array. How would I go about doing this? Is it possible to pass an array to a function? Thanks.
Here is my code:
Code:
#include <iostream>
#include <cstring>
using namespace std;
class customer{
public:
customer( string );
private:
string name;
};
customer::customer( string x ){
name = x;
}
int main(){
customer * array[50]; //create array of pointers to customer objects
customer fry ( "fry" );
customer bender ( "bender" );
for( int c = 0; c < 50; c++ ){ //initialize to NULL
array[c] = NULL;
}
array[23] = &fry;
return 0;
} | https://cboard.cprogramming.com/cplusplus-programming/83250-how-do-i-make-function-accepts-array-objects-its-argument-printable-thread.html | CC-MAIN-2017-22 | refinedweb | 138 | 69.11 |
I'm trying to create a "disable this spawn point" script using both RegisterStartPosition() and UnRegisterStartPosition():
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
public class SpawnDisable : NetworkBehaviour {
private NetworkManager net;
[Server]
void Start ()
{
net = GameObject.FindGameObjectWithTag ("NetworkManager").GetComponent<NetworkManager> ();
}
[Server]
void OnTriggerEnter(Collider col)
{
net.UnRegisterStartPosition (gameObject.transform);
}
[Server]
void OnTriggerExit (Collider col)
{
net.RegisterStartPosition (gameObject.transform);
}
}
but I'm getting errors from Unity:
Static member 'UnityEngine.Networking.NetworkManager. RegisterStartPosition(UnityEngine.Transform)' cannot be accessed with an instance reference, qualify it with a type name instead
And the exact same error for UnRegisterStartPosition(). This is the code I'm using:
I've been Googling around trying to find a solution to the "Static Member" problem but I've only found solutions for variables, not a function. I've had a look at the source of NetworkStartPosition.cs that uses RegisterStartPosition() but I'm none the wiser.
Does anyone know how to use these functions correctly?
Answer by Naphier
·
Oct 20, 2016 at 03:41 AM
Both of the methods are STATIC that means you access them via the class name like so:
NetworkManager.RegisterStartPosition(transform);
Wow, I didn't realize it was the wrong "instance", I thought it was the transform being put into the function that was the problem, thank you so much!
Could you explain why this works? I'm a bit lost.
With my logic I'm thinking that you can't just say "use a network manager" because it needs to be the specific network manager that we're using in-game, otherwise how would everyone else be able to know which spawn points to use and not
You're not using the "wrong" instance, you're using AN instance. Static methods and variables apply themselves to all instances of the class. An instance is accessed by declaring a variable (Network$$anonymous$$anager net$$anonymous$$an) and that variable is set with an instance of the class via the inspector, Get/AddComponent, or instantiating the class with the "new" operator.
Static members (methods and variables) do not allow access to them via an instance of the class so that you don't think you're only affecting a single instance, you're affecting ALL instances when using static members. They are globally acting on the class.
So with these static methods you're applying those spawn points to all Network$$anonymous$$anagers in your game (why you'd ever have more than 1 Network$$anonymous$$anager, I'm not sure...).
I've not used Unity Networking, only PUN so I'm not overly familiar with it, but I'm not sure if what you're doing is what you really want to do. You're saying when a player exits a trigger you want all other players who join to spawn at that location (or one of the other spawn points that you've registered). These are likely set globally/statically just for convenience, but there may be other reasons.
Hmm, interesting. So STATIC is just an easy way of telling all of the instances with that class to do something.
You're correct, however, I'm using [Server] which means the functions are only run on the server that's keeping track of all of the spawn.
Distribute terrain in zones
3
Answers
Multiple Cars not working
1
Answer
This is giving an error for the other client and cannot hit other client.
1
Answer
UnityWebRequest - login page returns a "not found"
0
Answers
Can I use Rpc Calls and Commands on the same object?
0
Answers
EnterpriseSocial Q&A | https://answers.unity.com/questions/1259115/using-registerstartposition-and-unregisterstartpos.html | CC-MAIN-2022-40 | refinedweb | 596 | 52.7 |
This problem is really easy, but I do not get AC for one implementation, the bug I meet is that the loop in the while(left<right),
I just use like this
while(!check(s[left])) left++;
But as we can expect if we think carefully, the left might cause RE, because we do not check the left is a valid index.
So to fix this bug, we should write like this:
while(left<len && !check(s[left])) left++;
Besides, we can use
isalnum(c) to check whether c is a valid char. to_lower to change the 'A' to 'a' OR to_upper similarly.
Here is the final code implementation.
class Solution { public: bool isPalindrome(string s) { int len=s.size(); if(len<=1) return true; int left=0, right=len-1; while(left<right){ while(left<=len-1 && !check(s[left])) left++; while(right>=0 && !check(s[right])) right--; if(left==len || right==-1) return true; if(toupper(s[left])!=toupper(s[right])) return false; left++; right--; } return true; } bool check(char c){ return (c>='a' && c<='z') || (c>='A' && c<='Z') || (c>='0' && c<='9'); } };
You don't need the first two line in the function, since if the length is 0 or 1, left will be greater than or equal to right, it will still return true.
Also, if you change the condition of the 2 while loops inside the inner loop to while (left < right && ...) and while (left < right && ...), then you don't need the check for the left and right bound. This won't gain improvement to the runtime but it might look better. Also, when you call the toupper() function, you can first check if left < right, if left is equal to right, then you don't need 2 extra function calls. | https://discuss.leetcode.com/topic/37674/one-ac-c-implementation | CC-MAIN-2018-05 | refinedweb | 297 | 81.12 |
#include <jevois/Debug/Watchdog.H>
Simple watchdog class.
This class will kill the current process if reset() is not called at least every timeout seconds. If timeout <= 0.0 then the watchdog is inactive (will never time out and kill the process). Note that to be as lightweight as possible, this class runs a background thread with a loop that iterates every timeout seconds, so the exact kill time is approximate.
Definition at line 29 of file Watchdog.H.
Constructor.
Definition at line 27 of file Watchdog.C.
References jevois::async_little(), itsRunFut, itsRunning, and run().
Virtual destructor for safe inheritance.
Definition at line 37 of file Watchdog.C.
References JEVOIS_WAIT_GET_FUTURE.
Reset our internal timer. If this does not happen at least every timeout seconds, process is killed.
Definition at line 47 of file Watchdog.C.
Definition at line 51 of file Watchdog.C.
References LERROR, jevois::system(), and jevois::to_string().
Referenced by Watchdog().
Definition at line 44 of file Watchdog.H.
Definition at line 43 of file Watchdog.H.
Referenced by Watchdog().
Definition at line 45 of file Watchdog.H.
Referenced by Watchdog(). | http://jevois.org/doc/classjevois_1_1Watchdog.html | CC-MAIN-2022-27 | refinedweb | 183 | 63.36 |
20 January 2012 08:55 [Source: ICIS news]
SINGAPORE (ICIS)--?xml:namespace>
The complex, located at Duolun in northern
The company could sell around 300 tonnes of propylene in the spot market each day as its downstream 460,000 tonnes/year polypropylene unit was taken off line, a source close to the company said.
The MTP unit mainly produces propylene with gasoline and LPG as co-products, according to the company source. It can produce 182,200 tonne/year of gasoline and 42,000 tonne/year of LPG.
Datang Duolun Coal Chemical is a joint venture between China Datang and Datang International Power | http://www.icis.com/Articles/2012/01/20/9525552/chinas-datang-duolun-starts-selling-propylene-from-mid-january.html | CC-MAIN-2014-15 | refinedweb | 103 | 61.06 |
As usual while waiting for the next release - don't forget to check the nightly builds in the forum.
Pre-build and post-build steps are part of the build process ! Important consequence : if you want to debug something, the debugger will only kick off after Code::Blocks was able to carry out a successful build (including the pre/post builds steps). Therefor it is not wise to have the unit test executable being carried out as a post-bild step of the 'Debug' target. But as a post-build step of the Release target, our goal is met.
That is quite wrong. You 1000% want to have the tests as post-build step in the Debug target, because this is the primary target a developer is using. And C::B should be fixed to allow this king of usage. The fix is quite simple in the debugger if the build fails show an Annoying dialog with "Build failed, do you still want to debug the application?" (or something like that).(I've started to do it but left it over )
Great job on the article. I have three questions.In LeapYear-Step2 you said "it is good to put the tests in a nameless namespace (will be explained later on)". But you never explained it. Why is this a good idea?
What if you have a console program that has a main() function. This will conflict with the main() function in the test program used to call the unit tests. What are some ways to resolve this? (The ideal solution would be one that doesn't require modifying the original source.)
Do you plan on automating the UnitTest++ program in CodeBlocks? For instance a template that will generate the "main" test source and possibly a test source for each source or class in a project file. It could also link to the UnitTest++ library and compile the library file if needed. UnitTest++ also has the capability of GUI output. The test run can be activated from a toolbar, displayed in a GUI, and clicking on an error line can then display the source and indicate the line with the error (the CodeLite IDE has this capability). It would be a useful addition to CodeBocks.
I use googletest (), another great framework for unit testing. The latest version of googletest, from the head of the repository, can be easily built with MinGW and Code::Blocks. It would be nice if you could "generify" your article by separating out the UnitTest++ specific bits, and possibly indicating which parts of the project files would need to change if you want to use a different unit test framework.
Dear All,As a long lived promise I finally finished my first article on unit testing and Code::Blocks.It can be found at :'s much more to come, but for the moment it already provides a first introduction. It even contains a Test Driven Development example, extremely simple but the easier to grasp. I am sure the text currently contains a lot of typos, just PM them to me, and I will fix them.FYI : the unit test framework used is UnitTest++ :.
||=== UnitTest++, Debug ===|||warning: command line option "-Wmissing-declarations" is valid for C/ObjC but not for C++|||warning: command line option "-Wmain" is valid for C/ObjC but not for C++|||=== Build finished: 0 errors, 2 warnings ===| | https://forums.codeblocks.org/index.php/topic,11155.0/all.html?PHPSESSID=34d9bcc7b014d224d15b7ba243cd05de | CC-MAIN-2021-31 | refinedweb | 564 | 72.26 |
.
Prior to C++11, a trailing comma after the last enumerator (e.g. after COLOR_MAGENTA) is not allowed (though many compilers accepted it anyway). However, starting with C++11, a trailing comma is allowed. Now that C++11 compilers are more prevalent, use of a trailing comma after the last element is generally considered acceptable.
Naming enums
Enum identifiers are often named starting with a capital letter, and the enumerators are often named using all caps.: Don’t assign the same value to two enumerators in the same enumeration unless there’s a very good reason. statement:
Once you’ve learned to use switch statements, you’ll probably want to use those instead of a bunch of if/else statements, as it’s a little more readable. cannot forward declare enum types. However, there is an easy workaround., functions often
1) Define an enumerated type to choose between the following monster races: orcs, goblins, trolls, ogres, and skeletons.
2) Define a variable of the enumerated type you defined in question 1 and assign it the troll enumerator.
3) True or false. Enumerators can be:
3a) given an integer value
3b) not assigned a value
3c) given a floating point value
3d) negative
3e) non-unique
3f) initialized with the value of prior enumerators (e.g. COLOR_MAGENTA = COLOR_RED)
Quiz answers
1) Show Solution
2) Show Solution
3) Show Solution
Alex,
Making your own data type using enum Color and auto. assigning COLOR_BLACK a value 0 all seems pretty simple for just 7 color.
What's going to be hard is defining all the colors to make up a pallet (2^8)256 or more and how and what you need to do to use them.
So can I assume some of this has already been done for us in C++? Or maybe we can find this in some library out there?
Enums are useful when you have well defined set of things that have discrete names.
For something like a palette of 256 colors, I probably wouldn't use an enum. Creating names for all 256 colors and setting up huge switches to handle them doesn't seem efficient or readable. At that point, you're probably better of just passing an RGB color value.
#include<iostream>
using namespace std;
enum Monster{
BOCKY,
KING,
FIREBALL,
BULL,
SCOOBY
};
function(Monster monster){
switch(monster){
case(BOCKY):
cout<<"you choose a RAT!";
break;
case(KING):
cout<<"you choose a LORD!";
case(FIREBALL):
cout<<"you choose a DRAGON!";
break;
case(BULL):
cout<<"you choose a BULL!";
break;
case(SCOOBY):
cout<<"you choose a DOG!";
}
}
main(){
cout<<function(FIREBALL);
}
why i am getting extra valur after my enum type.
Hello Alex,
On the quiz part of this section, what do you mean by " enumerators can be non-unique"?
I know many people have said this, but thanks for all you hard work on the lessons and this website.
I updated the wording to be more clear:
"These integer values can be positive or negative and can share the same value as other enumerators"
Basically, two different enumerators can resolve to the same value.
I think there are ; missing from the game(sword,torch etc) example given above after the return statements defined under "string getItemName(.....)" .
Please correct me if I am wrong. 🙂
You are correct. I've fixed it. Thanks!
Typo,
In the first answer of quiz I think the last enumeration shouldn't have a ','.
Good catch. Fixed.
Oh!! got it I was putting a small 'c' for 'color' instead of 'Color'.
got it, thanks!
techsavvy....aye
How can I output in the above program I tried many things but couldn't. It must be some small mistake could you tell me how to do it.
I don't understand what problem you are having. Did you try this?
How to use switch statements for the program
Switch statements for enums are covered in lesson 5.3 -- Switch statements.
In the line number
11.std::string getItemName(ItemType itemType)..."getItemName is a keyword or anything can be written with get??
getItemName is a function name that I arbitrarily picked for the example. It's not a keyword.
Typos.
"An enumerated type (also called an enumeration is a data type..." (insert an end parentheses after "enumeration")
Updated as you correctly note! Thanks for all the wording and grammar fixes, they've been great.
I'm reading your tutorial as a precursor to a C++ video game development tutorial, so obviously this example intrigued me. But I don't understand how it is useful. So you've a got string ("torch"), you have an enum called itemType with value (ITEMTYPE_CARRYABLE), but how are those in anyway related? How could you use those in context? I mean, if you were trying to "use" the torch and decide what to do with it, how would your function know that "torch" was a "ITEMTYPE_CARRYABLE"? I'm really frustrated because I feel like this example went right over my head, but it seems extremely useful. Would really love some clarification!
The short answer is that the example I provided wasn't very good. I've updated the example to one that I think is more straightforward. Check it out and let me know if that answers your question.
It is common to use enums to define "categories" of things (like I did in the original example you quoted). These can be used in many different ways. For example, if you had an array of all the items in your game, it might be useful to assign a type to each item so that you'd know how to handle them (e.g. weapons get held, armor gets worn, consumables get used).
Alternatively, each of your items could have a type (as defined in the example you quoted) and a subtype (that specifies whether the weapon is a sword or a dagger or a bow, or the carryable is a torch or a shield), and use them in pairs.
Hi Alex,
In your last comment, line 12 of the code: Color color = BLUE; What do 'Color' and 'color' refer to?
I expect that 'Color' is the enum identifier, but not sure about the other one.
Also, why do you sometimes use eColor (e.g. in Enum type evaluation and input/output)?
Thanks a lot.
Jana
This declares a variable named color of type Color (which is an enumeration defined previously), and then sets the value of color to BLUE.
When this lesson was first written, I used the prefix "e" on all enumerator variables. Since then, I've moved away from that naming convention, but I missed one instance. It's updated now.
in the example:
what if there are two enumerators with assigned value 5?
It still works. Enumerators aren't guaranteed to be distinct, so two enumerators with the same value are essentially interchangeable.
Although it doesn't make any sense:
This prints "Color is equal to GREEN" because we assigned the same value to the enumerators BLUE and GREEN.
In short, the takeaway is that generally you shouldn't assign the same value to two enumerators in the same enumeration.
What if:
It works for me! Althought Color enumeration has only 8 Colors!
Great Tuts!
P.S: You should add a union section after this one. 😉
Yup, you can cast an integer to an enumeration value that doesn't have an associated enumerator.
I'll think about adding a lesson on unions. They're not used very often, but they can be interesting in some cases.
I think that unions are worth mentioning. It's not a big topic but a useful knowledge. Like a struct with a number of any type.
Agreed. They're on my to-do list, but I plan to put them in an "other miscellaneous topics" chapter because they're not used very often.
I'm having a heck of a time trying to figure out how to forward declare enumerated classes/structs (same thing, I know). I know you haven't touched on scoped and unscoped enums here yet, but you probably will in the future. I think they're cool and all, but I can't figure out how to make a forward declaration work for them. It seems easier to just stuff the whole definition in a header file and include it to avoid the headache, but surely forward declarations for enums (and structs for that matter) exist for a reason?
Enum types can't be forward declared. Declare your enum type in a header and #include the header wherever needed.
Should the last enumerator variable have a comma after it?
Wouldn't the compiler expect another variable to follow and give an error? Mine doesn't so I don't know if this is okay or not.
enum MonsterType
{
MONSTER_ORC,
MONSTER_GOBLIN,
MONSTER_TROLL,
MONSTER_OGRE,
MONSTER_SKELETON, <---
};
This is a surprisingly complicated answer.
C++ didn't allow the last enumerator to have a comma until C++11, where they started allowing it.
C didn't allow the last enumerator to have a comma until C99.
So it really depends on what set of standards your compiler adheres to. Any C++11 compatible compiler should allow it. Any pre-C++11 compiler may or may not allow it for C99 compatibility purposes. It sounds like yours does allow it.
Can't I set enumerated values to be greater than int values? Example
The C++ standard says: "It is implementation-defined which integral type is used as the underlying type for an enumeration except that the underlying type shall not be larger than int unless the value of an enumerator cannot fit in an int or unsigned int".
So in theory, if you have an enumerated value that is larger than an int, the compiler should pick a larger integral type. Visual Studio 2010 errors on your example because it doesn't have any integral types larger than int. Compilers compliant with C++11 should allow this though, as they could pick a long long integral type.
Is non-unique enumerators useful in any case in practice?
I can't think of a case where it would be. But if you ever think of one, you can do it! 🙂
Awesome tutorial. I actually learned something really useful
Hi. I found these enumerated types really interesting. So I tried to make this program.
I keep on getting the following error.
error: no match for 'operator>>' in 'std::cin >> eColour'|
#include
using namespace std;
int main ()
{ //program to input a colour and output the lucky number. lol
enum colour
{
red = 1,
blue = 2,
green = 3,
};
colour eColour = red;
cout<<"Choose a colour "<>eColour ;
cout <<" Your lucky number is "<<eColour<<endl;
return 0;
}
What's wrong with cin ? can these enumerated data types not be input?
No, you can't use cin to input enumerated types. If you want to do this, have the user input an integer and then use a static_cast to convert it to your enumType.
This was an area that I haven't worked with before, so it was fun to get into.
My contribution:
prototype:
enum monsters
{
ORC,
GOBLIN,
TROLL,
OGRE,
SKELETON,
};
enum monsters
{
ORC,
GOBLIN,
TROLL,
OGRE,
SKELETON,
};
declaraction and assignment
monsters newMonster = TROLL;
monsters newMonster = TROLL;
test:
cout << endl << newMonster; //outputs the value 2
cout << endl << newMonster; //outputs the value 2
~KanedaSyndrome
Enumerations are a little confusing for me. I would better understand them if i had a practical use for them.. I know that no arithmetic operations are allowed on enum, and that since enums are an ordered set of values, you can use relational operators, and loops. this being said I guess I can see how using enum to make your program more readable might be benificial. But to really incorperate enums into your program you will have to input and output enums indirectly as you can not directly output or input enumeration data types.. So for now , i think you have to choose whether to make your program more readable with more work using enumerations, or not and save the extra programming.. Idk maybe as i learn and play with this more i will find its practicality
If I had not read the comments I would have never noticed enum uses commas! May I suggest having it written in the tutorial too so it draws more attention to it?
Simple well explained tutorial. Thanks.
I hope that is all in code !
When I run this, I get the exception in the PrintBodyPartStatus(), which prints 0 0.
And the check above the exception, is expecting a 0, 0.
What am I missing? Am I doing this wrong? It seems like a viable way to use Enums, as I've been using consts for EVERYTHING until I had a look at some open source game Enums.
I'm currently working on this, so don't think I'm commenting to expect you to do it for me (which would be nice, I admit)
But I really didnt't see the point in typing out
where in a few less line I coult just type in
Thanks in advance
EDIT:
changing the check from && to || make it work. I've always wondered why OR checks work properly and AND checks don't. (Maybe I've been doing those all wrong too, but I've always had the problem, even on simple checks.
even compound if's don't work very often
Strange.
should be:
note the 2 ='s, instead of one 🙂
the reason it works with || is because the second half comes up true as you have the == correct, as it is the first part is irrelevant.
edit - meh, just noticed it's a month old :D, i suck at remembering dates :p.
Great work, Alex.
Your site is better than any C++ book I know of.
Is there any other situation, in which enumerators are needed typically? Cause as of now I don't see any difference between doing this:
and this:
Obviously these are constants, thus they cannot be changed during runtime. However, if this is the only typical way of using enumerator types, then I don't see why you wouldn't just pre-define them using the preprocessor.
As I noted above, dont see the reason for usin enums instead of macros, I mean, if you use the enum it is necesary to initiate at least one instance of it, while the macros (#define) replace everyting right away without the memory cost.
Isn't this a better solution?
Enums and #defines have the same memory requirements. Enum definitions take up no additional memory space because they are just definitions. A good compiler should replace any enum with its integer equivalent at compile time, just like #defines are replaced by the preprocessor. will have to reread this lesson later. But i'm with Ben as far as seeing more use in the name of the enum type being printed in the stead of the actual integer. i tried to find a way to cout the name by feeding the integer value but that skill is beyond my scope so far. Once again you've fueled new 'what if's' Alex. Well done.
If I need the names of a set of enums for something, I'll usually write a function that takes the enum name to be printed and return a string version of the enum. Something like this:
Not sure I understand its interest. If you're trying to get a more understandable error message for example, I don't see much difference as it will still print an integer and not "ERROR_OPENING_FILE". Same idea with a list of names, etc...
Is there a way to print the name of the enum and not its integer value?
Thanks
Unfortunately, there's no easy way to print the name of the enum. The main benefits of using enums are:
1) Code readability is enhanced, since enums are descriptions and numbers could mean anything
2) If you ever want to change an enum's corresponding integer value, you only have to do so in one place, whereas if you use integers everywhere, you might have to change multiple values.
Enums are often used in conjunction with functions, either as parameters or return values to denote a particular mode or state.
When are the enumerators created? Can they be used independently of the enum-type variable? It appears that they are declared as -static const int-
Enums are handled at compile time, and they are generally treated as a const int. There is no such thing as a static type, so the static keyword is not applicable. The scope of enum type declarations is the same as normal variables: Enums declared outside of a class or function are treated as global, those inside a block are scoped to that block, and those in a class are considered part of that class.
For example:
Enum values can be used independently of the enum-type variable, as they are essentially treated as integers. For example, the following is valid:
Note that in the specification for the next version of C++ (C++0x), there will be a new type of enum (called a strongly typed enum) that will be treated as a unique type. These strongly typed enums will not be implicitly convertable to integers.
Can we define all of our Enums in a separate file (.cpp) and forward declaration them in a Header file and then include that? I tried to do that but compiler gave me error on this (in header file):
enum Color;
No, you can't forward declare enums.
However, there's no need. Because defining an enum doesn't use any memory, it's fine to define your enum types in a header and #include that header wherever you need access to the enum type.
Name (required)
Website | http://www.learncpp.com/cpp-tutorial/45-enumerated-types/comment-page-1/ | CC-MAIN-2018-13 | refinedweb | 2,980 | 72.46 |
Every now and then I stumble across an obvious reference that's just too good to ignore, and end up asking myself "How have I missed out on this for so long?" That's my story (and I'm sticking to it fervently) where Visual Studio Magazine is concerned. The March 2003 issue contains a wealth of treasures for VS aficionados, including a 5-page story by Travis Vandersypen entitled "Sure .NET Apps with Cryptography" that I'm abstracting to less than 20% of its original heft for the benefit of this tip.
Microsoft offers a set of classes to support a broad and fairly sophisticated range of cryptography services within the .NET Framework. Encased within its offerings, you'll find both private key encryption and public/private key encryption algorithms. Because these are also known as symmetric and asymmetric encryption algorithms, when the System.Security.Cryptography namespace provides classes for each one, it calls them SymmetricAlgorithm and AsymmetricAlgorithm respectively.
As far as the .NET Framework's symmetric encryption algorithms go, t
Each of these three serves as a super class for a .NET managed class. For each algorithm, you must define an encryption key and an initialization vector to make the associated encryption routines work. Suffice it to say that the key provides the mechanism for encryption and decryption (that's what makes it symmetric) and the initialization vector helps to randomize encryption so that two identical blocks of text won't ever encrypt the same way (that's a peachy way to break a code, and works better the longer the text block might be, so it's wise to avoid this by design whenever possible).
Working with private-key classes is relatively straightforward within the .NET Framework:
In my next tip, I'll provide some code examples that do this very thing, so you can move from the abstract to the hands-on. In the meantime, check out the SymmetricAlgorithm and AsymmetricAlgorithm namespaces.. | http://searchwindevelopment.techtarget.com/tip/0,289483,sid8_gci884695,00.html | crawl-002 | refinedweb | 326 | 51.89 |
Rich Felker wrote: > On Wed, Mar 01, 2006 at 02:31:48PM -0600, Brian Brice wrote: >> Rich Felker wrote: >>> On Wed, Mar 01, 2006 at 08:24:07AM +0000, M?ns Rullg?rd wrote: >>>> Steve Lhomme <slhomme at divxcorp.com> writes: >>>> >>>>> Michael Niedermayer wrote: >>>>>> Hi >>>>>> On Tue, Feb 28, 2006 at 03:33:07PM -1000, Steve Lhomme wrote: >>>>>>> ...so this patch renames libavformat's GUID to wGUID. Feel free to >>>>>>> rename it to something better if you need. >>>>>> put >>>>>> #define GUID microsuck_GUID >>>>>> around the #inlcude >>>>>> #undef >>>>>> or something similar >>>>> Impossible, I use the "real" GUID definition in my code too. >>>>. > > A namespace is not even needed. This is INTERNAL lavf code that should > never be included in the same file as windows stuff or any of Steve's > code. The only way it could have gotten together is if he: > a) incorrectly used lavf-internal headers in his code. OR > b) hacked lavf to use windows/directshow stuff internally. > > The latter is blatently wrong and I'm not even sure if it's > LGPL-compatible. (A somewhat technical issue of code using the library > versus extending the library itself, I think.) Given all the source code of DrFFMPEG is publicly accessible on SourceForge, I don't see where this claim comes from. And I'm perfectly fine with my working code. I'm just trying to share it so that other people don't end up with the same troubles as me when using FFMPEG. Steve | http://ffmpeg.org/pipermail/ffmpeg-devel/2006-March/013618.html | CC-MAIN-2017-30 | refinedweb | 246 | 73.07 |
Xcelerator for Excel 6.1
Sponsored Links
Xcelerator for Excel 6.1 Ranking & Summary
RankingClick at the star to rank
Ranking Level
User Review: 0 (0 times)
File size: 5.75MB
Platform: Windows Vista, 2003, XP, 2000, NT
License: Shareware
Price: $99.95
Downloads: 500
Date added: 2008-06-18
Publisher: Data Presentation Products, Inc.
Xcelerator for Excel 6.1 description
Xcelerator for Excel 6.1. Business & Finance
Xcelerator for Excel 6.1 Screenshot
Xcelerator for Excel 6.1 Keywords
Bookmark Xcelerator for Excel 6.1
Xcelerator for Excel 6.1 Copyright
WareSeeker.com do not provide cracks, serial numbers etc for Xcelerator for Excel 6.1. Any sharing links from rapidshare.com, yousendit.com or megaupload.com are also prohibited.
Featured Software
Want to place your software product here?
Please contact us for consideration.
Contact WareSeeker.com
Version History
Related Software
Automatically split the data in an Excel worksheet into multiple new separate Excel workbooks. Split the data for all values or for only the selected values in one field Free Download
Combines EZ-Total, EZ-Chart, EZ-Pivot and EZ-Calc into one economical solution for the ad-hoc formatting of data. Free Download
Creates PivotTables and PivotCharts in seconds Free Download
Automatically Summarize Data and Reuse Customized Excel Chart Types. Free Download. Free Download
import your data quickly from MS Excel 97-2007, MS Access, DBF, XML, TXT, CSV
EMS Data Import for MySQL is a powerful tool to import your data Free Download
Latest Software
- MS Access Combine Fields Merge Fields Merge Data 9.0
- office Convert Excel to Image Jpg Free 6.1
- Abacus Calculated Fields for ACT! by Sage 9.5
- PivotTable Helper for Microsoft Excel 1.1.0.17
- EMS Data Import 2007 for PostgreSQL 3.0.0.3
- EMS Data Import 2007 for DB2 3.1
- EZ-Forms ULTRA 5.50.ee.220
- EMS Data Export for SQL Server 3.1
Popular Software
Favourite Software | http://wareseeker.com/Business-Finance/xcelerator-for-excel-6.1.zip/438834 | CC-MAIN-2016-18 | refinedweb | 323 | 53.68 |
I've created two classes, with one of them having an implicit cast between them:
public class Class1 { public int Test1; } public class Class2 { public int Test2; public static implicit operator Class1(Class2 item) { return new Class1{Test1 = item.Test2}; } }
When I create a new list of one type and try to Cast<T> to the other, it fails with an InvalidCastException:
List<Class2> items = new List<Class2>{new Class2{Test2 = 9}}; foreach (Class1 item in items.Cast<Class1>()) { Console.WriteLine(item.Test1); }
This, however, works fine:
foreach (Class1 item in items) { Console.WriteLine(item.Test1); }
Why is the implicit cast not called when using Cast<T>?
Best Solution
Because, looking at the code via Reflector, Cast doesnt attempt to take any implicit cast operators (the LINQ Cast code is heavily optimised for special cases of all kinds, but nothing in that direction) into account (as many .NET languages won't).
Without getting into reflection and other things, generics doesnt offer any out of the box way to take such extra stuff into account in any case.
EDIT: In general, more complex facilities like implicit/explict, equality operators etc. are not generally handled by generic facilities like LINQ. | https://itecnote.com/tecnote/net-why-does-a-linq-cast-operation-fail-when-i-have-an-implicit-cast-defined/ | CC-MAIN-2022-40 | refinedweb | 198 | 51.38 |
Another low-bandwidth week for me. Grad school (and specifically Member's Week) is hard! Hoping to return to this week to do some more with networking and communications. To start, I just focused on programming the board I made two weeks ago. I already programmed this board two weeks ago using the Arduino IDE and the High Low Tech tutorial. Here's a video of the blinking light program I loaded then:
I wanted to be comfortable programming the board using gcc, C and a makefile. Briefly, here are the steps I used (cobbled together from this image and this tutorial):
Here is an image of the screen output of running the echo program and interacting with the program through the screen command. The formatting is a little funky. It also looks like the buffer saves whatever text you've typed in from the last session.
After a little investigation, I learned the format was funky because the serial monitor is getting just a newline ('\n' or 10) but no carriage return ('\r' or 13), which would bring the output back to the beginning of the line. (Perhaps term.py does this preprocessing for you, which is why this problem didn't come up for people using that serial interface?) I made a small modification in the code to add a carriage return, and my formatting in the serial monitor looked a lot better after that:
I also thought it could be nice to allow users to input a "clear" command and a "delete" command. With a bit of debugging (it's been a loooongggg time since I did string manipulation in C) I implemented these commands.
Playing around with the code like this got me more familiar with the toolchain. I felt pretty comfortable making quick changes, compiling and uploading them to the board, and testing the outcome. I realize this is made much easier by having the built-in "put_char" and "put_string" functions from Neil's code. For future steps, I'm hoping to mill another board to try some networking, and perhaps do something more interesting with the LED.
Code | http://fab.cba.mit.edu/classes/863.15/section.CBA/people/Jaffe/htm/wk7.html | CC-MAIN-2018-51 | refinedweb | 354 | 67.89 |
#include <usetiter.h>
This class is not intended to be subclassed. Consider any fields or methods declared as "protected" to be private. The use of protected in this class is an artifact of history.
To iterate over code points and strings, use a loop like this:
UnicodeSetIterator it(set); while (it.next()) { processItem(it.getString()); }
Each item in the set is accessed as a string. Set elements consisting of single code points are returned as strings containing just the one code point.
To iterate over code point ranges, instead of individual code points, use a loop like this:
UnicodeSetIterator it(set); while (it.nextRange()) { if (it.isString()) { processString(it.getString()); } else { processCodepointRange(it.getCodepoint(), it.getCodepointEnd()); } }
Definition at line 61 of file usetiter.h. | http://icu.sourcearchive.com/documentation/4.3.4-1/classUnicodeSetIterator.html | CC-MAIN-2017-39 | refinedweb | 124 | 51.85 |
Ok I made this program using IDLE and it runs perfect in windows xp.. when I try to run it on redhat linux it gives me the following errors
[python@ python]$ ./ksconfigwriter.py
./ksconfigwriter.py: line 2: import: command not found
./ksconfigwriter.py: line 6: syntax error near unexpected token `('
./ksconfigwriter.py: line 6: `def fileExists(f):'
I was wondering what I could do to get it to work... the first part of my code looks like this
Thank you in advance...
# Libs ----------------------------------------------
import sys,os,string,time
##open the name of the output file according to the user's selection
def fileExists(f):
try:
file = open(f)
except IOError: #no it doesn't exist
exists = '0'
else: #yes it does exist
exists = '1'
return exists
#----------------------------------------------------
print ("\n\n")
overwrite = ''
while overwrite != 'y':
overwrite = '' | http://forums.devshed.com/python-programming/91290-linux-xp-last-post.html | CC-MAIN-2017-47 | refinedweb | 134 | 62.38 |
Escalations run actions once a ticket has spent a set amount of time in a certain state.
They are useful to ensure that tickets are dealt with promptly. For example, you could use an escalation to increase the urgency of older tickets, or to automatically assign tickets that have gone unresolved for too long to a manager.
If you’re struggling to work out how to implement a particular automation, it’s also worth searching the Deskpro Knowledgebase, as we regularly add examples based on customer requests.
Creating an escalation
Create a new escalation by going to Tickets > Escalations and clicking Add.
Note
A new escalation will only apply to tickets that are created after you make it and after you enable it.
When you create an escalation, you define what state a ticket must be in for elapsed time to count:
- The ticket has been open for: total time the ticket has existed without being resolved.
- The user has been waiting: total time the ticket has been awaiting agent, continuously since the most recent status change; for example, if the status is changed from awaiting agent and then back again, the clock resets.
- The total time the user has been waiting: cumulative time the ticket has been awaiting agent over its whole life.
- The agent has been waiting for: how long the ticket has been awaiting user, resets if the status changes; useful to detect tickets where the user stopped replying before the problem was resolved.
- The ticket has been resolved for: time elapsed since the ticket was resolved.
- The ticket has been pending for: time elapsed since the ticket has been marked as pending.
You also set how long the ticket must spend in that state for the escalation to apply.
You can also set extra criteria that the ticket must meet for the escalation to run. For example, if you specify a department, the escalation will apply only to tickets in that department.
You then define the actions that run when the ticket has run up the correct elapsed time and meets any criteria.
Increase urgency after user has waited a day
This is a simple example escalation to increase the urgency of Support department tickets if the user has been waiting more than a day.
Note that, instead of setting the urgency to a particular value, we increase the urgency by 3 (up to the maximum of 10).
Follow up automatically when a user stops replying
This is an example of how you can use an escalation to send a follow-up email if a user stops replying before the ticket is resolved.
In Admin > Tickets > Escalations, make an escalation like this:
Set any criteria for the escalation. For example, you might only want to send the reminder email for tickets in the Support department.
For the escalation action, we want, for example, to send an email to the user. None of the default templates is right, so we need to choose from custom Email templates or just create a new one.
Email templates are built up from the phrases in Setup > Languages. This means you can edit the phrase in a single place and have it update all the email and portal templates that include it.
If you’re only using one language on your portal, and don’t plan to enable any more in future, you don’t need to use a custom phrase - you can just enter the email text directly.
To make a suitable custom template, open another admin window and look through the templates for similar built-in emails (Tickets > Email Templates) to find phrases you can re-use.
Any custom text you need to add should be added as a custom phrase under Setup > Languages; click your main language and select Edit Phrases, then All Custom Phrases and click the Add Custom Phrase button in the top right.
Here’s an example of a custom phrase:
Create the phrase (with the same ‘filename’) in each language you have installed.
Here’s an example reminder template, referencing the custom phrase:
Subject:
{{ phrase('user.email_subjects.tickets_re') }}
Body:
{{ phrase('user.emails.greeting') }} <br /><br /> {{ phrase('custom.ticket_reminder') }} <br /><br /> <dp:ticket-messages /> {% if app.isPortalEnabled() %} <br /><br /> {{ phrase('user.emails.ticket_access_ticket_online') }} <a href="{{ ticket.link }}">{{ ticket.link }}</a> {% endif %}
Now save the escalation. | https://support.deskpro.com/en/guides/admin-guide/agent-channel-setup/automating-the-helpdesk/escalations | CC-MAIN-2020-34 | refinedweb | 720 | 60.35 |
SPSE - SecurityTube Python Scripting Expert
I know the_grinch is currently taking this. Does anyone else have experience with this course? I think after I get my CISSP results (assuming a pass), this is my next venture...prior to pursuing OSCP.
- I've got the course, but am not going to start working on it till after I finish "Learn Python The Hard Way." Which is essentially a series of scripts/apps to write. I figured it would lay a nice foundation for the SPSE. The HTML of that book is free btw.Work in progress: picking up Postgres, elastisearch, redis, Cloudera, & AWS.
Next up: eventually the RHCE and to start blogging again.
Control Protocol; my blog of exam notes and IT randomness
- +1...Good recommendation. I've been working through Python for Dummies, but I'll never turn down a free resource without checking it out first.
- Thanks Hutch. I'll put something up about the course (spse) when I'm finished with it as well. The Learn Python The Hard Way is really just 50 exercises (with extra credit) that walk you through python, from the beginning.Work in progress: picking up Postgres, elastisearch, redis, Cloudera, & AWS.
Next up: eventually the RHCE and to start blogging again.
Control Protocol; my blog of exam notes and IT randomness
- Yeah...I already started...on exercise 4 now. I wanted to get the basics down before doing the SPSE course anyways. That was the reason that I got the Python for Dummies book. But honestly, I already like this better.
- Do you like the course so far?
-
- When I said "I already started"...I was referring to Learn Python the Hard Way, not SPSE. Personally, I kinda have mixed feelings about Learn Python the Hard Way. It does a good job of isolating one concept at a time. But it doesn't really teach you anything. Instead it just hands you a short program and its like "hey...figure out why this does this..."
- Oh gotcha. I was thinking about going straight into the course with little python experience.
- I'd probably do the same thing...but I'm not touching anything until I take my CISSP course in August and pass the exam. I've actually heard that the first module that covers Python basics is actually very thorough. From my understanding, the course is very doable, even with no python experience. Let me know how it goes for you if you decide to take it.
- I agree about Learn The Hard Way. It's repetitiveness is it's strong point. The "extra credit" essentially tells you to go out and learn what you just coded. Still, for me personally, I think I'll get more out of SPSE knowing some Python going in.Work in progress: picking up Postgres, elastisearch, redis, Cloudera, & AWS.
Next up: eventually the RHCE and to start blogging again.
Control Protocol; my blog of exam notes and IT randomness
- Well, one of the perks of SPSE is that there is no time constraint. So if you feel you are lacking in one area, getting sidetracked to catch up isn't going to cost you money like it would for something with a timed lab subscription like OSCP.
-
- Any updates on how the course is going? Would you recommend it?
contentpros Member Posts: 115 ■■■■□□□□□□I like the course so far. The material is easy to follow and Vivek does a good job tying everything together. My challenge has just been finding the free time during the last few weeks to stay on track. I don't regret the money I spend on the course. I have found that what I have learned so far in the course has allowed me to grab other peoples python scripts and understand what is going on behind the scenes and how to tweak the scripts for what I need. I can say that it is nice to look at a script and say "I get it" vs change stuff and hope I get lucky.
HTH
~Cp
- Thank you for your review so far. I was thinking about taking the course but I decided to go through learnpythonthehardway.org first and then possibly SPSE. So far I am really enjoying LPTHW because each lesson is straight to the point. In 3 hours ,I went from barely understanding [print "Hello World" to understand a good amount
from sys import argv script, filename = argv txt = open(filename) print "Here's your file %r:" % filename print txt.read() print "Type the filename again:" file_again = raw_input("> ") txt_again = open(file_again) print txt_again.read()
I would definitely recommend LPTHW to anyone who wants to learn Python. There are 53 lessons, and they are usually short and sweet. I look forward to hearing more reviews about the SPSE course.
- Does anyone have anymore reviews for SPSE? Great review so far which is cool. I probably will try to take it at the end of the year. Hopefully the price does not go up.Certifications: GPEN, SMFE, CISSP, OSCE, OSCP, OSWP, Security+, CEHv6, MCSE+Sec:2003
- I have enroled in the class, I did LPTHW first and half of the udacity course. Only on the 1st module but the review I have so far is excelent. He did start more at a intermediate programming level. Currently he also references other C+ programers would do this or that. I am a beginner but still grasping it from the other two courses.Jinverar, TSS
-
- So I just started video 5 of the first module. And at this point, I can't say much for the security aspects of the course, but the intro to Python is awesome. Very thorough and yet structured in such a way that it is easy to understand and retain. I tried to do LPTHW and I can say that this is a WAY better option. I am not a CompSci guy. My degree is in information systems, and pretty much the only language that I have ever really learned (besides dabbling with Java) is SQL. So the fact that I am picking this up so easy is a real testament to how effective this course is. Hope everyone is making good progress.
- A friend of mine is using CBT Nuggets for python and he seems to be happy with his purchase!
See the intro video on YouTube to get an idea about the course
Introductory Nugget: Python Programming Python Language - YouTube | https://community.infosecinstitute.com/discussion/comment/649103/ | CC-MAIN-2020-29 | refinedweb | 1,074 | 75.2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.