Showing posts with label idiotic ideas. Show all posts
Showing posts with label idiotic ideas. Show all posts

Wednesday, April 5, 2017

The End

This is the end of Poquito Picante. I am now posting my stories at Breaking Bytes.

The URL of my new blog is:
"https://breakingbytes.github.io/".
For the how and why I am making this move from Google Blogger to Pelican and GitHub Pages, please read my first post.
Moving to Pelican at GitHub Pages
Good bye Google Blogger, you've served me well. And for anyone following Poquito Picante, I hope to see you soon at Breaking Bytes.

Sincerely Yours,
+Mark Mikofski (AKA BwanaMarko, AKA BreakingBytes)

Tuesday, November 1, 2016

robotic releases

Basic Auto-Versioning from Git

If you're using the winning workflow and the recommended Python project layout then you've set up a CI server to build releases when you tag them in Git, and you set your version in the __init__.py file of your package. But, "Oh, No!" you did it again. You created the Git tag, but forgot to update your code's __version__ string.

Okay, there is a Python package called Versioneer that handles this for you, and it's pretty awesome. But it turns out it's also pretty easy to roll your own, especially if you're just using Git, because Python has a Git implementation called Dulwich that can do this in just a few lines. Maybe it will get integrated into a future version of Dulwich - I've submitted a PR (#462) which was merged into v0.16.3 and an update (#489) which was also merged into v0.17 to also list tags that are not objects. Anyway, for now, the easiest way to use this is to copy this file into your package at the top level, Install the latest version of dulwich (>=0.17.1), import it and then add something like this to your package dunder init module so it works both in your repo during dev and then later when deployed to users.

"""
Example package dunder init module implementing
``dulwich.contrib.release_robot`` to get current version.
"""

import os
import importlib

# try to import Dulwich or create dummies
try:
    from dulwich.contrib.release_robot import get_current_version
    from dulwich.repo import NotGitRepository
except ImportError:
    NotGitRepository = NotImplementedError

    def get_current_version():
        raise NotGitRepository

BASEDIR = os.path.dirname(__file__)  # this directory
VER_FILE = 'version'  # name of file to store version
# use release robot to try to get current Git tag
try:
    GIT_TAG = get_current_version()
except NotGitRepository:
    GIT_TAG = None
# check version file
try:
    version = importlib.import_module('%s.%s' % (__name__, VER_FILE))
except ImportError:
    VERSION = None
else:
    VERSION = version.VERSION
# update version file if it differs from Git tag
if GIT_TAG is not None and VERSION != GIT_TAG:
    with open(os.path.join(BASEDIR, VER_FILE + '.py'), 'w') as vf:
        vf.write('VERSION = "%s"\n' % GIT_TAG)
else:
    GIT_TAG = VERSION  # if Git tag is none use version file
VERSION = GIT_TAG  # version

__author__ = u'your name'
__email__ = u'your.email@your.company.com'
__url__ = u'https://github.com/your-org/your-project'
__version__ = VERSION
__release__ = u'your release name'

Or you can also use it to get all recent tags.

get_recent_tags()[0][0]

assuming your tags all use semantic versions like "v0.3". Enjoy!

Wednesday, October 12, 2016

Winning Workflow

Intro

There are many blog posts on the topic of effective Git workflows, SO questions and answers, BitBucket tutorials and GitHub guides and an article that has been archived by former BBC Mark McDonnell. So why another post on git workflow? None of these workflows seemed right for us, but recently it's just clicked, and I feel like we've finally found the process that works for us. The key was finding the simplest workflow that included the most valuable best practices. In particular, we found that complicated multi-branch strategies were unnecessary, but test driven development (TDD) and continuous integration (CI) were a must.

Winning Workflow


Setting up Remotes

We start with the assumption that all of collaborators fork the upstream repository to their personal profile. Then each person clones their profile to their laptop as origin and adds another remote pointing to the upstream repository. For convenience, they may also create remotes to the forks of their most frequent collaborators.

[myusername@mycomputer ~/Projects]
$ git clone git@github.com:myusername/myrepo.git
[myusername@mycomputer ~/Projects]
$ cd myrepo
[myusername@mycomputer ~/Projects/myrepo]
$ git remote add upstream git@github.com:mycompany/myrepo.git
[myusername@mycomputer ~/Projects/myrepo]
$ git remote add mycollaborator git@github.com:mycollaborator/myrepo.git
[myusername@mycomputer ~/Projects/myrepo]
$ git remote show
  origin
  upstream
  mycollaborator

Ground Rules

The next assumption is that we all keep our version of master synchronized with upstream master. And we never work out of our own master branch! Basically this means at the start of any new work we do the following:

  1. I like to do git fetch --all to get the lay of the land. This combined with
    git log --all --graph --date=short --pretty=format:"%ad %h %s%d [%an]"
    let's me know what everyone is working on, assuming that I've made remotes to their forks.
  2. Then I pull from upstream master to get the latest nightly or release,
  3. and push to origin master to keep my fork current.

Recommended Project Layout

I'm also going to assume that everyone is following the recommended project layout. This means that their project has all dependencies listed in requirements.txt, is developed and deployed in its own virtual environment, includes testing and documentation that aims for >80% coverage, has a boilerplate design that allows testing, documentation and package data to be bundled into a distribution and enables use with a test runner with self discovery, and is written with docstrings for autodocumentation. Nothing is ever perfect, so being diligent of path clashes, aware of the arcana of Mac OS X1 or Windows2 and able to use Stack Overflow to find answers is still important.

Branching, Testing, Pull Requests and Collaboration

  1. Now I switch to a new feature branch with a meaningful name - I'll delete this branch everywhere later so it can be verbose.
  2. The very first code I write is a test or two that demonstrates more or less exactly what we want the feature or bug fix to do. This is one of the most valuable steps because it clearly defines the acceptance criteria. Although it's also important to be thoughtful and flexible - just because your tests pass doesn't necessarily mean the feature is implemented as intended. Some new tests or adjustments may be needed along the way.
  3. Now, before I write any more code, is when I submit a pull request (PR) from my fork's feature branch to upstream/master. So many people are surprised by this. Many collaborators have told me they thought that PR's should be submitted after their work is complete and passing all tests. But in my opinion that defeats the entire point of collaborating on a short iteration cycle.
    • If you wait until the end to submit your work you risk diverging from the feature's intended goals especially if the feature's requirements shift or you've misinterpreted the goals even slightly.
    • Waiting also means you're missing out on collaborating with your teammates and soliciting their feedback mid-project.
    On the other hand, by submitting your PR right after you write your tests means:
    • Every push to your fork will trigger a build that runs your tests.
    • Your teammates will get continuous updates so they can monitor your progress in real-time but also on their time so you won't have to hold a formal review, since collaborators can review your work anytime as the commits will all be queued in the PR.
    I think the reason people wait until the end to submit PR's is the same reason they like to write tests at the end. I used to hate seeing my tests fail because it made me feel like I was failing. I think people delay submitting their PR's because they're nervous about having incomplete work reviewed out of context and receiving unfair criticism or harsh judgment. IMO, punitive behavior is dysfunctional and a collaboration killer and should be rooted out with a frank discussion about what mutual success looks like. I also think some people aren't natural collaborators and don't want other's interfering with their work. Again, a constructive discussion can help promote new habits, although don't expect people to change overnight. You can take a hard stance on punitive behavior but you can't expect an introvert to feel comfortable sharing themselves freely without some accommodations.
  4. Now comes the really fun part. We hack and collaborate until the tests all pass. But we don't have too much fun - there should be at most 10 commits before we realize we've embarked on an epic that needs to be re-organized, otherwise the PR will become difficult to merge. That will sap moral and waste time. So keep it simple.
  5. The final bit of collaboration is the code review and merging the PR into upstream master. This is fairly easy, since there are
    • already tests that demonstrate what the code should do,
    • only a few commits,
    • and all of the collaborators have been following the commits as they've been queuing in the PR.
    So really the review and merge is a sanity check. Do these tests really demonstrate the feature as intended? Anything else major would have stood out already.
  6. Whoever the repository owner or maintainer is should add the tag and push it to upstream. This triggers the CI to test, build and deploy a new release.

Continuous Integration

This is key. Set up Travis, Circle, AppVeyor or Jenkins on upstream master to test and build every commit, every commit to an open PR and to deploy on every tag. Easy!

Wrapping Up

There are some features of this style that stand out:

  • There is only one master branch. Using CI to deploy only on tags eliminates our need for a dev or staging branch because any commits on master not tagged are the equivalent of the bleeding edge.
  • This method depends heavily on an online hosted Git repo like GitHub or BitBucket, use of TDD, strong collaboration and a CI server like Travis.

Happy Coding!


footnotes

  1. On Mac OS X matplotlib will not work in a virtual environment unless a framework interpreter is used. The easiest way to do this is to run python as PYTHONHOME=/home/you/path/to/project/venv/ python instead of using source venv/bin/activate.
  2. On Windows pip often creates an executable for scripts that is bound to the Python interpreter it was installed with. If the virtual environments was created with system site packages or if the package is not installed in the virtual environment then you may get a confusing path clash. For example running the nosetests script will use your system Python and therefore the Python path will not include your virtual environment. The solution is to never use system site packages and install all dependencies directly in your virtual environment.

Wednesday, April 15, 2015

Recommended Python Project Layout

[UPDATE 2018-09-04] Links to Cookiecutter and Bootstrap a Scientific Python Library from the National Synchrotron Light Source II (NLSL-II).

[UPDATE 2016-07-19] Lately I've preferred using core instead of lib for the main package modules.

[UPDATE 2015-06-04] Create top level package to bundle all sub-packages and package-data together for install.

Been looking for a good, comprehensive, credible guide:

  1. Pretty good links in this SO Q&A:
    1. What is the best project structure for a Python application?
    2. Especially this one:
      1. Open Sourcing a Python Project the Right Way
  2. And maybe, maybe theses ones:
    1. Learn Python The Hard Way Exercise 46: A Project Skeleton
    2. The Hitchhiker’s Guide to Python! Structuring Your Project by Kenneth Reitz
      1. Repository Structure and Python also by Kenneth Reitz
    3. How to Package Your Python Code: Minimal Structure by Scott Torborg
    4. Interesting Things, Largely Python and Twisted Related: Filesystem structure of a Python project by Jean-Paul Calderone
  3. Of course understanding Python Modules and Packages
    1. The Python Tutorial: 6. Modules
  4. An understanding of how to install packages, and roughly I guess how pip and setuptools interact with distutils is good
    1. Python Documentation: Installing Python Modules
  5. Way later down the line it helps to understand distutils and setuptools for deploying packages
    1. Python Packaging User Guide
    2. Setuptools
    3. Python Documentation: Distributing Python Modules
    4. How to Package Your Python Code by Scott Torborg
    5. The Hitchhiker’s Guide to Packaging
  6. There are also a packages that will create a boiler plate project layout for you but I wouldn't recommend them except as reference guides - the tutorial by NSLS-2 being the notable exception, PTAL!
    1. Bootstrap a Scientific Python Library: This is a tutorial with a template for packaging, testing, documenting, and publishing scientific Python code.
    2. Cookiecutter: A command-line utility that creates projects from cookiecutters (project templates), e.g. creating a Python package project from a Python package project template.
    3. PyPI: Python Boilerplate Template

It's hard to pin a standard style down. Here’s mine:

MyProject/ <- git repository
|
+- .gitignore <- *.pyc, IDE files, venv/, build/, dist/, doc/_build, etc.
|
+- requirements.txt <- to install into a virtualenv
|
+- setup.py <- use setuptools, include packages, extensions, scripts and data 
|
+- MANIFEST.in <- files to include in or exclude from sdist
|
+- readme.rst <- incorporate into setup.py and docs
|
+- changes.rst <- release notes, incorporate into setup.py and docs
|
+- myproject_script.py <- script to run myproject from command line, use Python
|                         argparse for command line arguments put shebang
|                         `#! /usr/bin/env python` on 1st line and end with a
|                         `if __name__ == "__main__":` section, include in
|                         setup.py scripts section for install
|
+- any_other_scripts.py <- scripts for configuration, documentation generation
|                          or downloading assets, etc., include in setup.py
|
+- venv/ <- virtual environment to run tests, validate setup.py, development
|
+- myproject/ <- top level package keeps sub-packages and package-data together
   |             for install
   |
   +- __init__.py <- contains __version__, an API by importing key modules,
   |                 classes, functions and constants, __all__ for easy import
   |
   +- docs/ <- use Sphinx to auto-generate documentation
   |
   +- tests/ <- use nose to perform unit tests
   |
   +- other_package_data/ <- images, data files, include in setup.py
   |
   +- core/ <- main source code for myproject, sometimes called `lib`
   |  |
   |  +- __init__.py <- necessary to make mypoject_lib a sub-package
   |  |
   |  +- … <- the rest of the folders and files in myproject
   |
   +- related_project/ <- a GUI library that uses myproject_lib or tools that
      |                   myproject_lib depends on that's bundled together, etc.
      |
      +- __init__.py <- necessary to make related_project a sub-package
      |
      +- … <- the rest of the folders and files in your the related project

Friday, March 21, 2014

Universal Scientific Prayer of Hope and Gratitude

Oh Great Universe!

I praise your infinite complexities,
your beautiful creations,
and above all your life giving ability.

[Please let our understanding of <insert whatever>
be sufficient for <insert whatever>.]

Thanks!

Friday, August 23, 2013

Jedi Nation

In Star Wars when Naboo, Leia's homeworld is destroyed by the Death Star, Obi Wan slumps over in the Millennium Falcon and utters something like, "I feel as if ten thousand souls suddenly screamed out, and then were silenced."

Hmm, is Obi Wan using his Jedi powers to snoop on the universe? One could see it that way, but the verb "snoop" carries the connotation that he did not have the snoopee's best interests at heart. And Obi Wan was all heart.

Hence the Jedi Nation.

Let us take the current climate of anti-terrorist snooping. It brings to mind images of kicked down doors in the middle of night, subjects disappearing based on flimsy wiretap evidence. But what if we take the Jedi approach? What if the next day, Obi Wan shows up to the subjects apartment, offers to buy her some coffee and says, "I got a feeling from the Force that you're feeling a but unhappy with the current government and some other stuff. You know all these wars over oil piss me off too. Want to talk to someone about it? Are you in a bad spot right now? I could help you with your rent for awhile. Are you looking for work? Let me measure your mitochondria. You're a bit old to start the training, but the force runs strong in you. We'll make a Jedi out of you yet!"

If she still resists, Obi Wan can try Jedi mind tricks. "Theses are not the innocent civilians you are looking for." If she tries to kill Obi Wan, then he might be forced to slice her up with his light-saber in self defense.

Tuesday, June 11, 2013

Religion can be philisophy, aristocracy or imaginary friend

Disclaimer: I know this is a touchy subject, and I am not the most tactful person, so please
stop reading now!
if you have strong views on religion. What I am about to express is my opinion, and is not meant to influence or offend anyone. If you are already offended then I apologize, and hope that by turning back now you can avert any more offense.

Another theory; religion could be dissected as either a philosophy or an aristocracy. Wait, hear me out. I know that is way oversimplifying something so complex and evidently intricately woven into the human condition. But I am expressly thinking about understanding the will of each religion's deity/deities - what is done with those instructions is a different topic.

So let's consider, hypothetically a religion has a deity or some deities. This essentially what defines a religion right? That it has gods? Perhaps a religion has no gods, merely guidelines that were divined by a group of humans that are now revered for their amazing insight. That sounds a bit like a philosophical cult which is my first proposition, but I'm getting ahead of myself. Now that we've established a god or gods, how does information exchange occur?

  1. There is an elite class of god listeners who alone hear god's messages and then repeat them to the rest of that god's followers.
  2. All of that god's followers attempt to divine their god's meaning and then share and debate their theories to come up with some consensus.
Number one is clearly a form of aristocracy because the god has divined who shall be the people who receive the message and make decisions for others just as a monarch is generally chosen through some cosmic means. However if the god-listener class is elected it might possibly be considered some form of democracy. More likely the god-listener class takes that right through an exertion of their power (either by force or through influence), which might make it either a tyranny or oligarchy. Perhaps these types of institutions are all called republics - a small group represents a larger group. But it can go terribly wrong if the larger group doesn't question the validity of the small group. I wonder is it a sin to question the pope? Or a pastor's interpretation of the bible. Even a simple Sunday morning comic strip has multiple interpretations; isn't it more likely that a literary work of unknown origin transcribed multiple times may have ambiguous meaning? I'm not saying that we can't ultimately come to a consensus, there is meaning everywhere that we can all agree on, e.g. that murder is generally bad is agreed by all. What I mean is that unquestioning acceptance of religious, governmental or scientific dogma is both lazy and very dangerous. As Socrates said in the Apology, "an unexamined life is not worth living."

Number two sounds like a philosophy to me. I like it.

OK, let's take this a few steps further. Now replace god or gods with some other belief. Say god = the universe? Or gods = scientific theories, because let's be frank, no matter how much proof we have, even acceptance of a law is still merely just a belief. We believe that electrons tunnel through energy barriers because we have seen so much evidence that suggests convincingly that it may be true. But Einstein and Copernicus and Galileo can attest to the fact that even "scientific" theories and laws evolve and shift as new evidence comes to light. So I digress, my point with this last exercise is that religion has many societal parallels.

I also realized, while talking with my wife about suffering and grief that even if you can't hear your deity or deities message, when you are in need, merely believing that they exist and love you, may be a solace, and I like that too. The universe is a cold hard place, and it's always nice to have a friend.

Equality increases self esteem

Similar to my post on "the second law of infodynamics" this post proposes another completely hypothetical theory of human social interaction.
Equality increases self esteem.
Right now my son loves wearing pink, and says today, "I'm wearing a dress." Next week it will be a different color. He is completely innocent. Theses issues seem trivial to us today in the socially enlightening 21st century. In fact we view it as a victory over the absurd and old-fashioned dogma about distinct gender roles.

So lets examine that dogma. What was its motivation? I propose that it was a defensive coping mechanism. To cope with what? What could possible happen if a boy did wear a dress? Or a woman was a combatant? Or a same sex marriage occurred? Did that mean that I might start wearing dresses, because secretly I wanted to but my society told me it was wrong so I felt insecure and bad about myself? If I was secure about my individuality, why would I care what another person did? Merely being irked or irritated is not a reason for outrage is it? No there has to be a deeper reason. Our prejudices are manifestations of our inward fears. We are racist because we seek to dehumanize and theretofore justify the luxuries we take for granted at the expense of others' suffering. We are sexist and homophobic for the same reasons.

But what happens when we remove these barriers? The we don't have to be defensive. There is nothing to cope with. We can feel good about ourselves whoever we are. Equality increases our self esteem.

Tuesday, February 28, 2012

Breaking Bytes

Since I started trying to develop Android, web and other apps, I started another blog Breaking Bytes. There are links to SifterReader an Android app that lets you read your Sifter issues. I also post updates and other relevant info related to the apps. Enjoy!

Monday, January 9, 2012

TortoiseSVN could be a DVCS

I've been using SVN for years, but it's about to become obsolete? Hard to believe, but Git's popularity is surging rapidly, and so are other distributed version control systems like Mercurial and Bazaar. But I just can't believe that Subversion can't adapt to the changing times. There are so many SVN users out there. And I really think TortoiseSVN (TSVN) is the key. With the very simple scripting I was able to duplicate a DVCS with 2 TSVN repositories. The basic idea is that each person, clones/forks an entire repository, which is stored on there machine. Now in SVN, these repositories might be able to sync with each other, but a repo can't be a mirror and a working copy at the same time. So the trick is to save the diffs and patches and play them back in order. I think the patches should be named with hashes just like in Git and Hg. Easy!

Update (2012-01-12): After thinking about this and rereading the response from Stefan King on the TSVN dev mailing list to my question about DVCS, I realized or starting to think that this was really an issue for SVN. Think about my experiment below, what commands are TSVN? None, they are all from SVN. So I searched the SVN mailing list for "DVCS" (zilch for DVCS on the TSVN mailing list) and I saw this article posted 2 years ago, Subversion Vision and Roadmap Proposal, which has a pretty compelling argument for not making SVN a DVCS; in fact it even made me question DVCS in general. Then I thought, what is the main feature of DVCS that trumps a centralized repo, and I think it's offline commits. Searching for "offline commits" I found this post, On Offline Commits and Why They Should Be Piloted in TSVN. Funny because the strategy was very similar to my experiment, but I haven't found any other work toward this goal. Oh well - I've already migrated to git (see label: git going) and git svn makes that super easy.

Here is an experiment I did to see if TSVN could actually act like a DVCS. It's incomplete and disorganzed, but it did work
  • Rationale:
    • Does anyone really care or want DVCS for svn?
    • especially when bzr, git and hg are already so good and can work with existing subversion repos!
    • but it would be sad to see tsvn go
      • there will still be many svn users
    • is offline the biggest strength of DVCS?
  • approach: 
    • need clone, push and fetch similar to other DVCS, leverage existing svn methods, pilot in tsvn
      • init a local repo
      • use patches to clone the remote svn repo to the local repo
      • work locally, commit locally
      • push to remote repo, replay all local patches on remote repo
      • fetch from remote repo, replay all remote patches on local repo
      • it works, but a lot of overhead, and overly simplified
  • notes: 
    • get log, date and author info and pipe to file output
      • svn propget -r <NUMBER/HEAD/etc.> -revprop svn:log
      • svn propget -r <NUMBER/HEAD/etc.> -revprop svn:date
      • svn propget -r <NUMBER/HEAD/etc.> -revprop svn:author
    • create diffs of local and patch to remote and vice versa
    • use export from remote to local
    • svn log also prints log messages and pipe to output, instead of propget
    • svn merge?
    • svn help and svn help command

Friday, August 12, 2011

new os

I'm sure linux or android already do this, but I'm tired of folders and directories. Isn't that idea a bit antiquated? I was thinking that in this day of objects and tags, can't files just have a tag attribute that can be set so that you can sort and cross reference your files anyway you want? to this user this could be transparent, so that it looks just like folders except it's so much better. Then you wouldn't have all of there ridiculous pathnames, everything would be in root/files.

corporate batman belt

I was thinking with 3G (and 4G lite) access, it wouldn't be too hard to develop a device, actually a system, that would be a corporate office away from the office. This device let's you receive and make calls of course, but also lets you access your laptop if you leave it in the office, even control the desktop, access the network. But most importantly, allows complete customization, for example, would allow an app to be installed that automatically detect when it was going into roaming and shut down all data transfer, and switch to something like Skype for calls.

Fork me on GitHub