{"id":13936901,"url":"https://github.com/yasintoy/SnipLime","last_synced_at":"2025-07-19T22:33:09.545Z","repository":{"id":94296244,"uuid":"56460177","full_name":"yasintoy/SnipLime","owner":"yasintoy","description":"Best collections of design patterns/idioms/snippets for Sublime Text.","archived":false,"fork":false,"pushed_at":"2016-04-29T15:32:22.000Z","size":41,"stargazers_count":181,"open_issues_count":0,"forks_count":9,"subscribers_count":18,"default_branch":"master","last_synced_at":"2024-08-08T23:24:46.687Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/yasintoy.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-04-17T21:44:59.000Z","updated_at":"2024-01-04T16:04:18.000Z","dependencies_parsed_at":"2023-04-25T10:46:22.009Z","dependency_job_id":null,"html_url":"https://github.com/yasintoy/SnipLime","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yasintoy%2FSnipLime","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yasintoy%2FSnipLime/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yasintoy%2FSnipLime/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yasintoy%2FSnipLime/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yasintoy","download_url":"https://codeload.github.com/yasintoy/SnipLime/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":226693903,"owners_count":17667757,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-07T23:03:06.134Z","updated_at":"2024-11-27T05:30:40.444Z","avatar_url":"https://github.com/yasintoy.png","language":"Python","funding_links":[],"categories":["Python"],"sub_categories":[],"readme":"# SnipLime\nA collection of design patterns/idioms/snippets for Sublime Text.\n\u003cimg src=\"http://blogs.theage.com.au/schembri/rat1.jpg\" alt=\"Python Patterns logo\" align=\"right\" /\u003e\n# Python Patterns snippets \n\nDesign patterns/idioms/snippets for [Sublime Text](http://www.sublimetext.com/) with **good solutions\nfor regular problems.\n\n\u003e Debugging is twice as hard as writing the code in the first place.\n\u003e Therefore, if you write the code as cleverly as possible, you are, by definition,\n\u003e not smart enough to debug it.\n\u003e\n\u003e – Brian W. Kernighan, co-author of The C Programming Language and the \"K\" in \"AWK\"\n\n## Preview\n\u003cimg src=\"http://i.imgur.com/7Ve2yn7.gif\" alt=\"Preview\" /\u003e\n\n\n## Installation\n\n**Using Package Control**:\n\n\u003e Bring up the Command Palette(Command+Shift+P on OS X, Control+Shift+P on Linux/Windows)\n\n\u003e Select Package Control: Install Package.\n\n\u003e Select Sublime Text 3 Snippets to install.\n\n**Not Using Package Control**:\nSave files to the Packages/Sublime Text 3 Snippets directory, then relaunch Sublime:\n\n\u003e git clone https://github.com/yasintoy/SnipLime.git\n\n\u003e cd SnipLime\n\n\u003e Linux: sudo cp -r Python/ ~/.config/sublime-text-2/Packages/\n\n\u003e Mac: sudo cp Python/ ~/Library/Application Support/Sublime-Text-3/Packages/\n\n\u003e Windows: cp %APPDATA%/Sublime-Text-2/Packages/\n\n(if you want to install it for sublime-text-3, change sublime-text-2 with sublime-text-3 )\n\n## Snippets \n\u003e (You don't have to memorise triggers because it's really close to english sentences.)\nSome Python Patterns snippets in the wild.\n\n# Main Function\n\nHere are two that I use frequently.\n\n**trigger**: main⇥\n\n``` python\ndef main():\n    pass\n\nif __name__ == '__main__':\n    main()\n\n```\n\n## Factorial function\n\n**trigger**: factorial\n\nIt works also for bigger numbers, when the result becomes **long**\nReference:\n- [StackOverflow: Function for Factorial in Python](http://stackoverflow.com/questions/5136447/function-for-factorial-in-python)\n\n```python\nfrom itertools import imap\ndef factorial(x):\n    return reduce(long.__mul__, imap(long, xrange(1, x + 1))\n    \nprint factorial(1000)\n```\n\n\n## Get Twitter User Timeline\n\n**trigger**: twittergetusertimeline⇥\n\nJust change the api parameters and username that whatever you want!\n\n```python\nimport twitter\n\napi = twitter.Api(consumer_key='your-consumer-key',\n                  consumer_secret='your-consumer-secret',\n                  access_token_key='your-access-token-key',\n                  access_token_secret='your-access-token-secret')\n\n# set a handle\nusername = 'anthonydb'\n\n# get a user timeline\nstatuses = api.GetUserTimeline(screen_name=username, count=1)\nprint [s.text for s in statuses]\n```\n\n## Any Generate\n\n**trigger**: anygenerate⇥\n\nI like using **any** and a generator:\n\n```python\nif any(pred(x.item) for x in sequence):\n    ...\n});\n```\ninstead of code written like this:\n\n```python \nfound = False\nfor x in sequence:\n    if pred(x.n):\n        found = True\nif found:\n    ...\n```\nReference:\n- [this technique from a Peter Norvig](http://norvig.com/sudoku.html)\n\n## Dictionary Comprehension\n\n**trigger:** dictcomp⇥\n\nA faster and pythonic way to create a `dict`.\n\n```python\nd = {key: value for (key, value) in iterable}\n```\n\n## Open File\n\nAn easy and security way to open a file.\n**trigger**: readfile⇥\n\n```python\nwith open('file.txt',\"r\") as f:\n    for line in f:\n        ...\n```\n\n\n## Email Verification Pattern\n\n**trigger**: emailverify⇥\n\n```python\nimport re\n\naddressToVerify ='info@emailhippo.com' # change it\nmatch = re.match('^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,4})$', addressToVerify)\n\nif match == None:\n\tprint('Bad Syntax')\n```\n\n## Download Stock From Yahoo\n\nIteratively create a pandas dataframe by column and download stock data from Yahoo.com\n\n**trigger**: downloadstock⇥\n\n```python\nimport pandas.io.data as web\nimport pandas as p\nfrom datetime import datetime as dt\n\nstart = dt(2011,1,3)\n# end = dt.today()\nend = dt(2011,6,5)\n\nstocks = [        'XLY',  # XLY Consumer Discrectionary SPDR Fund   \n                       'XLF',  # XLF Financial SPDR Fund  \n                       'XLK',  # XLK Technology SPDR Fund  \n                       'XLE',  # XLE Energy SPDR Fund  \n                       'XLV',  # XLV Health Care SPRD Fund  \n                       'XLI',  # XLI Industrial SPDR Fund  \n                       'XLP',  # XLP Consumer Staples SPDR Fund   \n                       'XLB',  # XLB Materials SPDR Fund  \n                       'XLU' ]\n\nprices = p.DataFrame()\n\nfor stock in stocks:\n    prices[stock] = web.DataReader(stock, 'yahoo', start, end)['Adj Close']\n```\nReference:\n- [What are some nifty python snippets that you have found very useful and would like to share?](https://www.reddit.com/r/Python/comments/2ysd91/what_are_some_nifty_python_snippets_that_you_have/)\n\n## Get Links\n\n**trigger**: getlinks⇥\n\nGet all links from given website and print them.\n\n```python\nimport urllib\nimport BeautifulSoup\n\nhtmlSource = urllib.urlopen(\"${1:http://sebsauvage.net/index.html}\").read(200000)\nsoup = BeautifulSoup.BeautifulSoup(htmlSource)\nfor item in soup.fetch('a'):\n    print item['href'] \n```\n\n## Graph Search\n\n**trigger**: graphsearch⇥\n\nImplementation of Graph search with Python.\n\n```python\nclass GraphSearch:\n\n    \"\"\"comments\"\"\"\n\n    def __init__(self, graph):\n        self.graph = graph\n\n    def find_path(self, start, end, path=None):\n        self.start = start\n        self.end = end\n        self.path = path if path else []\n\n        self.path += [self.start]\n        if self.start == self.end:\n            return self.path\n        if self.start not in self.graph:\n            return None\n        for node in self.graph[self.start]:\n            if node not in self.path:\n                newpath = self.find_path(node, self.end, self.path)\n                if newpath:\n                    return newpath\n        return None\n\n    def find_all_path(self, start, end, path=None):\n        self.start = start\n        self.end = end\n        _path = path if path else []\n        _path += [self.start]\n        if self.start == self.end:\n            return [_path]\n        if self.start not in self.graph:\n            return []\n        paths = []\n        for node in self.graph[self.start]:\n            if node not in _path:\n                newpaths = self.find_all_path(node, self.end, _path[:])\n                for newpath in newpaths:\n                    paths.append(newpath)\n        return paths\n\n    def find_shortest_path(self, start, end, path=None):\n        self.start = start\n        self.end = end\n        _path = path if path else []\n\n        _path += [self.start]\n        if self.start == self.end:\n            return _path\n        if self.start not in self.graph:\n            return None\n        shortest = None\n        for node in self.graph[self.start]:\n            if node not in _path:\n                newpath = self.find_shortest_path(node, self.end, _path[:])\n                if newpath:\n                    if not shortest or len(newpath) \u003c len(shortest):\n                        shortest = newpath\n        return shortest\n\n\"\"\"\n\n# example of graph usage\ngraph = {'A': ['B', 'C'],\n         'B': ['C', 'D'],\n         'C': ['D'],\n         'D': ['C'],\n         'E': ['F'],\n         'F': ['C']\n         }\n\n# initialization of new graph search object\ngraph1 = GraphSearch(graph)\n\n\nprint(graph1.find_path('A', 'D'))\nprint(graph1.find_all_path('A', 'D'))\nprint(graph1.find_shortest_path('A', 'D'))\n\n### OUTPUT ###\n# ['A', 'B', 'C', 'D']\n# [['A', 'B', 'C', 'D'], ['A', 'B', 'D'], ['A', 'C', 'D']]\n# ['A', 'B', 'D'] \n\n\"\"\"\n\n```\n\n\n## FTP Send File\n\n**trigger**: ftpsendfile⇥\n\nSend a file by using the FTP.\n\n```python\nimport ftplib                                          # We import the FTP module\n\nsession = ftplib.FTP('adress like blabla.com','login','passord') # Connect to the FTP server\nmyfile = open('toto.txt','rb')                    # Open the file to send\nsession.storbinary('STOR toto.txt', myfile)       # Send the file\n\nmyfile.close()                                         # Close the file\nsession.quit()                                         # Close FTP session\n```\n\n## Timestamped Filename\n\n**trigger**: timestampedfilename⇥\n\n```python\nimport datetime, os\n\ndef timestamped_filename(file_name, date_time=None):\n    date_time = date_time or datetime.datetime.now()\n    root, ext = os.path.splitext(file_name)\n    return '{}{:_%Y_%m_%d_%H_%M_%S}{}'.format(root, date_time, ext)\n```\n\n\n## Merge Sort\n\n**trigger**: mergesort⇥\n\n```python\ndef merge(left, right, lt):\n    \"\"\"Assumes left and right are sorted lists.\n     lt defines an ordering on the elements of the lists.\n     Returns a new sorted(by lt) list containing the same elements\n     as (left + right) would contain.\"\"\"\n    result = []\n    i,j = 0, 0\n    while i \u003c len(left) and j \u003c len(right):\n        if lt(left[i], right[j]):\n            result.append(left[i])\n            i += 1\n        else:\n            result.append(right[j])\n            j += 1\n    while (i \u003c len(left)):\n        result.append(left[i])\n        i += 1\n    while (j \u003c len(right)):\n        result.append(right[j])\n        j += 1\n    return result\n            \ndef sort(L, lt = lambda x,y: x \u003c y):\n    \"\"\"Returns a new sorted list containing the same elements as L\"\"\"\n    if len(L) \u003c 2:\n        return L[:]\n    else:\n        middle = int(len(L)/2)\n        left = sort(L[:middle], lt)\n        right = sort(L[middle:], lt)\n        #print 'About to merge', left, 'and', right\n        return merge(left, right, lt)\n}());\n```\n## Tree Data Structure\n\n**trigger**: tree⇥\n\n```python\nclass Node:\n    \"\"\"\n    Class Node\n    \"\"\"\n    def __init__(self, value):\n        self.left = None\n        self.data = value\n        self.right = None\n\nclass Tree:\n    \"\"\"\n    Class tree will provide a tree as well as utility functions.\n    \"\"\"\n\n    def createNode(self, data):\n        \"\"\"\n        Utility function to create a node.\n        \"\"\"\n        return Node(data)\n\n    def insert(self, node , data):\n        \"\"\"\n        Insert function will insert a node into tree.\n        Duplicate keys are not allowed.\n        \"\"\"\n        #if tree is empty , return a root node\n        if node is None:\n            return self.createNode(data)\n        # if data is smaller than parent , insert it into left side\n        if data \u003c node.data:\n            node.left = self.insert(node.left, data)\n        elif data \u003e node.data:\n            node.right = self.insert(node.right, data)\n\n        return node\n\n\n    def search(self, node, data):\n        \"\"\"\n        Search function will search a node into tree.\n        \"\"\"\n        # if root is None or root is the search data.\n        if node is None or node.data == data:\n            return node\n\n        if node.data \u003c data:\n            return self.search(node.right, data)\n        else:\n            return self.search(node.left, data)\n\n\n\n    def deleteNode(self,node,data):\n        \"\"\"\n        Delete function will delete a node into tree.\n        Not complete , may need some more scenarion that we can handle\n        Now it is handling only leaf.\n        \"\"\"\n\n        # Check if tree is empty.\n        if node is None:\n            return None\n\n        # searching key into BST.\n        if data \u003c node.data:\n            node.left = self.deleteNode(node.left, data)\n        elif data \u003e node.data:\n            node.right = self.deleteNode(node.right, data)\n        else: # reach to the node that need to delete from BST.\n            if node.left is None and node.right is None:\n                del node\n            if node.left == None:\n                temp = node.right\n                del node\n                return  temp\n            elif node.right == None:\n                temp = node.left\n                del node\n                return temp\n\n        return node\n\n    def traverseInorder(self, root):\n        \"\"\"\n        traverse function will print all the node in the tree.\n        \"\"\"\n        if root is not None:\n            self.traverseInorder(root.left)\n            print root.data\n            self.traverseInorder(root.right)\n\n    def traversePreorder(self, root):\n        \"\"\"\n        traverse function will print all the node in the tree.\n        \"\"\"\n        if root is not None:\n            print root.data\n            self.traversePreorder(root.left)\n            self.traversePreorder(root.right)\n\n    def traversePostorder(self, root):\n        \"\"\"\n        traverse function will print all the node in the tree.\n        \"\"\"\n        if root is not None:\n            self.traversePreorder(root.left)\n            self.traversePreorder(root.right)\n            print root.data\n```\n\n## And we've much more samples but I think that's enough for now.\n\nThe MIT License (MIT)\n\nCopyright (c) 2016 Yasin Toy\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyasintoy%2FSnipLime","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyasintoy%2FSnipLime","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyasintoy%2FSnipLime/lists"}