Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Make txrudp the sole distributed package.
"""Setup module for txrudp.""" import codecs from os import path import sys from setuptools import find_packages, setup _HERE = path.abspath(path.dirname(__file__)) with codecs.open(path.join(_HERE, 'README.md'), encoding='utf-8') as f: _LONG_DESCRIPTION = f.read() setup( name='txrudp', version='0.1.0'...
"""Setup module for txrudp.""" import codecs from os import path import sys from setuptools import setup _HERE = path.abspath(path.dirname(__file__)) with codecs.open(path.join(_HERE, 'README.md'), encoding='utf-8') as f: _LONG_DESCRIPTION = f.read() setup( name='txrudp', version='0.1.0', descripti...
Add the new contrail extension to neutron plugin config file
import string template = string.Template(""" [APISERVER] api_server_ip = $__contrail_api_server_ip__ api_server_port = $__contrail_api_server_port__ multi_tenancy = $__contrail_multi_tenancy__ contrail_extensions = ipam:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_ipam.NeutronPluginContrailIpam,policy:...
import string template = string.Template(""" [APISERVER] api_server_ip = $__contrail_api_server_ip__ api_server_port = $__contrail_api_server_port__ multi_tenancy = $__contrail_multi_tenancy__ contrail_extensions = ipam:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_ipam.NeutronPluginContrailIpam,policy:...
Delete images instead of printing
#!/usr/bin/env python from collections import defaultdict import subprocess import os KEEP_LAST_VERSIONS = os.environ.get('KEEP_LAST_VERSIONS', 4) def find_obsolete_images(images): for image_name, versions in images.items(): if len(versions) > KEEP_LAST_VERSIONS: obsolete_versions = sorted(ve...
#!/usr/bin/env python from collections import defaultdict import subprocess import os KEEP_LAST_VERSIONS = os.environ.get('KEEP_LAST_VERSIONS', 4) def find_obsolete_images(images): for image_name, versions in images.items(): if len(versions) > KEEP_LAST_VERSIONS: obsolete_versions = sorted(ve...
Make sure the local version of the craft ai module is used in tests
import sys import os CRAFTAI_MODULE_SRC_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) sys.path = [CRAFTAI_MODULE_SRC_DIR] + sys.path
Make it easy to do a full deploy with fab
from fabric.api import * env.runtime = 'production' env.hosts = ['chimera.ericholscher.com'] env.user = 'docs' env.code_dir = '/home/docs/sites/readthedocs.org/checkouts/readthedocs.org' env.virtualenv = '/home/docs/sites/readthedocs.org' env.rundir = '/home/docs/sites/readthedocs.org/run' def update_requirements(): ...
from fabric.api import * env.runtime = 'production' env.hosts = ['chimera.ericholscher.com'] env.user = 'docs' env.code_dir = '/home/docs/sites/readthedocs.org/checkouts/readthedocs.org' env.virtualenv = '/home/docs/sites/readthedocs.org' env.rundir = '/home/docs/sites/readthedocs.org/run' def push(): "Push new c...
Change default python string name str to mystr as str is a reserved name
#!/usr/bin/env python -u import cPickle import sys import urllib import base64 # # Output the maximum number of instances of this 'callable' to spawn # The absolute maximum is set in the configuration file via 'warpscript.call.maxcapacity' # print 10 # # Loop, reading stdin, doing our stuff and outputing to stdout...
#!/usr/bin/env python -u import cPickle import sys import urllib import base64 # # Output the maximum number of instances of this 'callable' to spawn # The absolute maximum is set in the configuration file via 'warpscript.call.maxcapacity' # print 10 # # Loop, reading stdin, doing our stuff and outputing to stdout...
Fix tag cloud weird size
from django import template register = template.Library() @register.filter def get_style(tags, priority): max_priority = max(tags, key=lambda tag: tag["priority"])["priority"] size = (max_priority / 10.) * priority return "font-size: {}em;".format(size)
from django import template register = template.Library() @register.filter def get_style(tags, priority): max_priority = max(tags, key=lambda tag: tag["priority"])["priority"] size = 100 / max_priority / priority / 2 return "font-size: {}em;".format(size)
Use BMI method to get ALT value
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue Jan 10 10:56:16 2017 @author: kangwang """ import os import sys from permamodel.components import bmi_Ku_component from permamodel.tests import examples_directory cfg_file = os.path.join(examples_directory, 'Ku_method.cfg') x = bmi_Ku_component.BmiKu...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue Jan 10 10:56:16 2017 @author: kangwang """ import os import sys from permamodel.components import bmi_Ku_component from permamodel.tests import examples_directory cfg_file = os.path.join(examples_directory, 'Ku_method.cfg') x = bmi_Ku_component.BmiKu...
Increase character limit for pages
from django.db import models class Page(models.Model): def __str__(self): return self.name name = models.CharField(max_length=64, blank=False) name.help_text='Internal name of page' title = models.CharField(max_length=64, blank=True) title.help_text='Page title to display in titlebar of browser/tab' body = ...
from django.db import models class Page(models.Model): def __str__(self): return self.name name = models.CharField(max_length=64, blank=False) name.help_text='Internal name of page' title = models.CharField(max_length=64, blank=True) title.help_text='Page title to display in titlebar of browser/tab' body = ...
Add tests for login oauth links
# coding: utf-8 from findaconf import app, db from findaconf.tests.config import set_app, unset_app from unittest import TestCase class TestSiteRoutes(TestCase): def setUp(self): self.app = set_app(app, db) def tearDown(self): unset_app(db) # test routes from blueprint/site.py def ...
# coding: utf-8 from findaconf import app, db from findaconf.tests.config import set_app, unset_app from unittest import TestCase class TestSiteRoutes(TestCase): def setUp(self): self.app = set_app(app, db) def tearDown(self): unset_app(db) # test routes from blueprint/site.py def ...
Test fuer WAV write und read gleichheit
import scipy.io.wavfile as wav import numpy import warnings def wavread(filename): with warnings.catch_warnings(): warnings.simplefilter("ignore") fs,x = wav.read(filename) maxv = numpy.iinfo(x.dtype).max x = x.astype('float') x = x / maxv return (fs,x) def wavwrite(filename, fs, x): maxv = numpy.iinfo(nump...
import scipy.io.wavfile as wav import numpy import warnings def wavread(filename): with warnings.catch_warnings(): warnings.simplefilter("ignore") fs,x = wav.read(filename) maxv = numpy.iinfo(x.dtype).max return (fs,x.astype('float') / maxv) def wavwrite(filename, fs, x): maxv = numpy.iinfo(numpy.int16).max ...
Add logging to email daemon
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public License, # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at http://mozilla.org/MPL/2.0/. import bottle import stoneridge @bottle.post('/email') def email(): r = bottle.request.form...
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public License, # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at http://mozilla.org/MPL/2.0/. import bottle import logging import stoneridge @bottle.post('/email') def email(): logging....
Use correct latest commit in __version__ endpoint
#!/usr/bin/env python import time now = time.time() formatted = time.strftime("%B %d, %Y %H:%M:%S UTC", time.gmtime()) print 'exports.string = %r' % formatted # Note Javascript uses milliseconds: print 'exports.timestamp = %i' % int(now * 1000) import subprocess print 'exports.gitrevision = %r' % subprocess.check_ou...
#!/usr/bin/env python import time now = time.time() formatted = time.strftime("%B %d, %Y %H:%M:%S UTC", time.gmtime()) print 'exports.string = %r' % formatted # Note Javascript uses milliseconds: print 'exports.timestamp = %i' % int(now * 1000) import subprocess print 'exports.gitrevision = %r' % subprocess.check_ou...
Remove category serializer from subcategory serializer
from categories.models import Category, Keyword, Subcategory from rest_framework import serializers class SubcategoryListSerializer(serializers.ModelSerializer): class Meta: model = Subcategory fields = ('pk', 'name') class CategorySerializer(serializers.ModelSerializer): subcategories = Sub...
from categories.models import Category, Keyword, Subcategory from rest_framework import serializers class SubcategoryListSerializer(serializers.ModelSerializer): class Meta: model = Subcategory fields = ('pk', 'name') class CategorySerializer(serializers.ModelSerializer): subcategories = Sub...
Complete Overhaul. Argeparse used. Outputs to csv
from os import getenv import sqlite3 import win32crypt csv_file = open("chromepass.csv",'wb') csv_file.write("link,username,password\n".encode('utf-8')) appdata = getenv("APPDATA") if appdata[-7:] == "Roaming": #Some WINDOWS Installations point to Roaming. appdata = appdata[:-8] connection = sqlite3.connect(appdata +...
from os import getenv import sqlite3 import win32crypt import argparse def args_parser(): parser = argparse.ArgumentParser(description="Retrieve Google Chrome Passwords") parser.add_argument("--output", help="Output to csv file", action="store_true") args = parser.parse_args() if args.output: ...
Fix __version__ missing for setuptools
# Copyright (c) 2013 Facebook # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
# Copyright (c) 2013 Facebook # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
Set config contained a bug after refactoring
import argparse import logging.config import os from intexration import settings from intexration.server import Server # Logger logging.config.fileConfig(settings.LOGGING_FILE) def main(): parser = argparse.ArgumentParser() parser.add_argument('-host', help='Change the hostname') parser.add_argument('-po...
import argparse import logging.config from intexration import settings from intexration.server import Server # Logger logging.config.fileConfig(settings.LOGGING_FILE) def main(): parser = argparse.ArgumentParser() parser.add_argument('-host', help='Change the hostname') parser.add_argument('-port', help=...
Add select modules to the welcome steps. Redirect fixes to skip
from django.conf.urls.defaults import * # Smrtr # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^1$', 'welcome.views.profile', name='welcome-1' ), url(r'^2$', 'network.views.search', {'next': 'home'}, name='welcome-2'...
from django.conf.urls.defaults import * from django.core.urlresolvers import reverse # Smrtr # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^1$', 'welcome.views.profile', name='welcome-1' ), url(r'^2$', 'network.view...
Make it so we don't rely on weird rounding in python to assign card to the correct index
import random class Blackjack: def __init__(self): self.deck = range(1, 53) self.shuffle() self.deal() def shuffle(self): random.shuffle(self.deck) def deal(self): self.player = [None, None] self.dealer = [None, None] for i in xrange(4): ...
import random class Blackjack: def __init__(self): self.deck = range(1, 53) self.shuffle() self.deal() def shuffle(self): random.shuffle(self.deck) def deal(self): self.player = [None, None] self.dealer = [None, None] for i in xrange(4): ...
Clean up after cloned repo if needed. (partial checkin)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ cookiecutter.main ----------------- Main entry point for the `cookiecutter` command. The code in this module is also a good example of how to use Cookiecutter as a library rather than a script. """ import argparse import os from .find import find_template from .gen...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ cookiecutter.main ----------------- Main entry point for the `cookiecutter` command. The code in this module is also a good example of how to use Cookiecutter as a library rather than a script. """ import argparse import os from .cleanup import remove_repo from .fi...
Mark some builtin list() tests as passing
from .. utils import TranspileTestCase, BuiltinFunctionTestCase class ListTests(TranspileTestCase): pass class BuiltinListFunctionTests(BuiltinFunctionTestCase, TranspileTestCase): functions = ["list"] not_implemented = [ 'test_bool', 'test_bytearray', 'test_bytes', 'tes...
from .. utils import TranspileTestCase, BuiltinFunctionTestCase class ListTests(TranspileTestCase): pass class BuiltinListFunctionTests(BuiltinFunctionTestCase, TranspileTestCase): functions = ["list"] not_implemented = [ 'test_bytearray', 'test_bytes', 'test_class', 'te...
Add translation files to package data
from setuptools import setup, find_packages import sys, os version = '0.1' setup(name='kotti_contactform', version=version, description="Simple contact form for Kotti sites", long_description="""\ This is an extension to Kotti that allows to add simple contact forms to your website.""", classi...
from setuptools import setup, find_packages import sys, os version = '0.1' setup(name='kotti_contactform', version=version, description="Simple contact form for Kotti sites", long_description="""\ This is an extension to Kotti that allows to add simple contact forms to your website.""", classi...
Use python3 version of cappy
############################################################################### # Copyright 2015-2019 University of Florida. All rights reserved. # This file is part of UF CTS-IT's NACCulator project. # Use of this source code is governed by the license found in the LICENSE file. #######################################...
############################################################################### # Copyright 2015-2019 University of Florida. All rights reserved. # This file is part of UF CTS-IT's NACCulator project. # Use of this source code is governed by the license found in the LICENSE file. #######################################...
Fix for 'Unknown distribution option: install_requires' warning during install
from distutils.core import setup setup( name='pystash', version='0.0.14', author='Alexander Davydov', author_email='nyddle@gmail.com', packages=[ 'pystash' ], scripts=[ 'bin/stash' ], url='http://pypi.python.org/pypi/pystash/', license='LICENSE.txt', description='Save your code snip...
try: from setuptools import setup except ImportError: from distutils.core import setup setup( name='pystash', version='0.0.14', author='Alexander Davydov', author_email='nyddle@gmail.com', packages=[ 'pystash' ], scripts=[ 'bin/stash' ], url='http://pypi.python.org/pypi/pystash/', ...
Rename model Article to Post
from django.contrib import admin # Register your models here. from .models import Post from .models import UserProfile from .models import SocialMedia class ArticleAdmin(admin.ModelAdmin): list_display = ("title", "category", "created", "updated", "status") search_fields = ("title", "category", "content") ...
from django.contrib import admin # Register your models here. from .models import Post from .models import UserProfile from .models import SocialMedia class PostAdmin(admin.ModelAdmin): list_display = ("title", "category", "created", "updated", "status") search_fields = ("title", "category", "content") ...
Add Python 3.7 to the list of Trove classifiers
from setuptools import setup import codecs import schema setup( name=schema.__name__, version=schema.__version__, author="Vladimir Keleshev", author_email="vladimir@keleshev.com", description="Simple data validation library", license="MIT", keywords="schema json validation", url="http...
from setuptools import setup import codecs import schema setup( name=schema.__name__, version=schema.__version__, author="Vladimir Keleshev", author_email="vladimir@keleshev.com", description="Simple data validation library", license="MIT", keywords="schema json validation", url="http...
Remove the non-ASCII character. Safer.
# -*- coding: utf-8 -*- import os from setuptools import setup, find_packages from hsync._version import __version__ setup( name = 'hsync', version = __version__, author = 'André Lucas', author_email = 'andre.lucas@devinfotech.co.uk', license = 'BSD', packages = [ 'hsy...
# -*- coding: utf-8 -*- import os from setuptools import setup, find_packages from hsync._version import __version__ setup( name = 'hsync', version = __version__, author = 'Andre Lucas', author_email = 'andre.lucas@devinfotech.co.uk', license = 'BSD', packages = [ 'hsy...
Install assets when installing the package.
from distutils.core import setup setup( name='pypicache', version='0.1', description='PyPI caching and proxying server', author='Michael Twomey', author_email='mick@twomeylee.name', url='http://readthedocs.org/projects/pypicache/', packages=['pypicache'], )
from distutils.core import setup setup( name='pypicache', version='0.1', description='PyPI caching and proxying server', author='Michael Twomey', author_email='mick@twomeylee.name', url='http://readthedocs.org/projects/pypicache/', packages=['pypicache'], package_data={ 'pypicac...
Add Django auth as a stock application
from distutils.version import StrictVersion from django import get_version QADMIN_DEFAULT_EXCLUDES = [ 'django.contrib.sessions', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.comments', 'django.contrib.flatpages', 'django.contrib.sitema...
from distutils.version import StrictVersion from django import get_version QADMIN_DEFAULT_EXCLUDES = [ 'django.contrib.sessions', 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.comments', 'django.contrib.flatpages',...
Allow log level to be changed via environment variable
""" tagversion Entrypoints """ import logging import sys from tagversion.argparse import ArgumentParser from tagversion.git import GitVersion from tagversion.write import WriteFile def main(): logging.basicConfig(level=logging.WARNING) parser = ArgumentParser() subcommand = parser.add_subparsers(dest='s...
""" tagversion Entrypoints """ import logging import os import sys from tagversion.argparse import ArgumentParser from tagversion.git import GitVersion from tagversion.write import WriteFile LOG_LEVEL = os.environ.get('LOG_LEVEL', 'warning') def main(): logging.basicConfig(level=getattr(logging, LOG_LEVEL.upper...
Add initial views for google login.
from eve import Eve app = Eve() if __name__ == '__main__': app.run()
import json import settings from flask import request, session from requests import HTTPError from requests_oauthlib import OAuth2Session from eve import Eve from flask_login import LoginManager app = Eve() login_manager = LoginManager(app) login_manager.login_view = "login" login_manager.session_protection = "stron...
Change migration so newly added field is nullable
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-12-20 13:11 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('partner', '0042_auto_20171220_1305'), ] operations...
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-12-20 13:11 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('partner', '0042_auto_20171220_1305'), ] operations...
Revert "<1.9 gets you 1.9rc1 >_>"
import os from setuptools import setup README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='mdot-rest', version='0.1', packages=['mdot_rest'], inc...
import os from setuptools import setup README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='mdot-rest', version='0.1', packages=['mdot_rest'], inc...
Fix asset loading in skeleton
import konstrukteur.Konstrukteur @task def build(regenerate = False): """Generate source (development) version""" konstrukteur.Konstrukteur.build(regenerate)
import konstrukteur.Konstrukteur @task def build(regenerate = False): """Generate source (development) version""" # Initialize assets AssetManager.AssetManager(profile, session) # Build static website konstrukteur.Konstrukteur.build(regenerate)
Add final newline to make pylint happy
from activate import deactivate """ Script to deactivate LUFA for Arduino. More info can be found in the activate.py script. """ if __name__ == '__main__': deactivate()
from activate import deactivate """ Script to deactivate LUFA for Arduino. More info can be found in the activate.py script. """ if __name__ == '__main__': deactivate()
Switch student model to unicode
from django.contrib.auth.models import User from django.db import models class UserProfile(models.Model): user = models.ForeignKey(User, unique = True) dionysos_username = models.CharField(max_length = 15, unique = True) dionysos_password = models.CharField(max_length = 30) eclass_username = models.Cha...
from django.contrib.auth.models import User from django.db import models class UserProfile(models.Model): user = models.ForeignKey(User, unique = True) dionysos_username = models.CharField(max_length = 15, unique = True) dionysos_password = models.CharField(max_length = 30) eclass_username = models.Cha...
Use a separate method to get all peers of a torrent
from urlparse import urlparse from torrent import Torrent from trackers.udp import UDPTracker class Client(object): __TORRENTS = {} @property def torrents(self): return self.__TORRENTS @torrents.setter def torrents(self, new_torrent): self.__TORRENTS[new_torrent] = Torrent(new_torrent) def dow...
import urllib from random import randint from urlparse import urlparse from torrent import Torrent from trackers.udp import UDPTracker class Client(object): __TORRENTS = {} def __init__(self): self.peer_id = urllib.quote("-AZ2470-" + "".join([str(randint(0, 9)) for i in xrange(12)])) @property def torr...
Use cycle instead of counting an index ourselves
from itertools import cycle from psycopg2.extras import register_hstore, register_json import psycopg2 import threading import ujson class DBAffinityConnectionsNoLimit(object): # Similar to the db affinity pool, but without keeping track of # the connections. It's the caller's responsibility to call us #...
from itertools import cycle from psycopg2.extras import register_hstore, register_json import psycopg2 import threading import ujson class DBAffinityConnectionsNoLimit(object): # Similar to the db affinity pool, but without keeping track of # the connections. It's the caller's responsibility to call us #...
Set index main view to return post ordered by updated and title field
from flask import render_template from flask_classy import FlaskView from ..models import PostModel class Main(FlaskView): """ Main page view. """ route_base = "/" def index(self): posts = PostModel.fetch() return render_template("index.html", posts=posts)
from flask import render_template from flask_classy import FlaskView from ..models import PostModel class Main(FlaskView): """ Main page view. """ route_base = "/" def index(self): PostModel.set_query() PostModel.query.order = ['-updated', 'title'] posts = PostModel.fetch() ...
Simplify formulation and change from print() to assert()
#!/usr/bin/env python # -*- coding: utf-8 -*- """Exercise 4.1 from Kane 1985""" from sympy.physics.mechanics import dot, dynamicsymbols, MechanicsStrPrinter from sympy.physics.mechanics import ReferenceFrame, Point from sympy import solve, symbols, pi from sympy.simplify.simplify import trigsimp def msprint(expr): ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Exercise 4.1 from Kane 1985""" from sympy.physics.mechanics import dot, dynamicsymbols, MechanicsStrPrinter from sympy.physics.mechanics import ReferenceFrame, Point from sympy import solve, symbols, pi, sin, cos from sympy.simplify.simplify import trigsimp def msprint...
Add support for generic pages
import requests from bs4 import BeautifulSoup def parse_html(html, **kwargs): parsed_html = BeautifulSoup(html, 'lxml') headline = parsed_html.body.find('h1') paragraph = None # Parse Paragraph content_container = parsed_html.body.find( 'div', attrs={'id': 'bodyContent'} ) ...
import re import requests from bs4 import BeautifulSoup def parse_html(html, **kwargs): is_wikipedia_page = kwargs.get('is_wikipedia_page') parsed_html = BeautifulSoup(html, 'html.parser') headline = parsed_html.body.find('h1') paragraph = None if is_wikipedia_page: # Parse Paragraph ...
Remove extraneous vim editor configuration comments
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
Add `@dca.dataclass_array` decorator to customize dca params. Change default values
# Copyright 2022 The visu3d Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
# Copyright 2022 The visu3d Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
Fix incorrect models field name for MailgunLog
from django.db import models class MailgunLog(models.Model): log_hash = models.CharField(max_length=64, unique=True) data = models.TextField() timestamp = models.DateTime()
from django.db import models class MailgunLog(models.Model): log_hash = models.CharField(max_length=64, unique=True) data = models.TextField() timestamp = models.DateTimeField()
Return the actual return code
from plumbum import local import subprocess PY_ENV = 'py_env' def install_environment(): assert local.path('setup.py').exists() # Return immediately if we already have a virtualenv if local.path(PY_ENV).exists(): return # Install a virtualenv local['virtualenv'][PY_ENV]() local['bas...
from plumbum import local import subprocess PY_ENV = 'py_env' def install_environment(): assert local.path('setup.py').exists() # Return immediately if we already have a virtualenv if local.path(PY_ENV).exists(): return # Install a virtualenv local['virtualenv'][PY_ENV]() local['bas...
Add registration to cost tracking
from django.apps import AppConfig class OracleConfig(AppConfig): name = 'nodeconductor_paas_oracle' verbose_name = 'Oracle' service_name = 'Oracle' def ready(self): from nodeconductor.structure import SupportedServices from .backend import OracleBackend SupportedServices.regis...
from django.apps import AppConfig class OracleConfig(AppConfig): name = 'nodeconductor_paas_oracle' verbose_name = 'Oracle' service_name = 'Oracle' def ready(self): from nodeconductor.structure import SupportedServices from nodeconductor.cost_tracking import CostTrackingRegister ...
Remove type annotation from `VERSION` as setuptools can't handle it
""" DBB Ranking Parser ~~~~~~~~~~~~~~~~~~ Extract league rankings from the DBB (Deutscher Basketball Bund e.V.) website. The resulting data is structured as a list of dictionaries. Please note that rankings are usually only available for the current season, but not those of the past. :Copyright: 2006-2021 Jochen Ku...
""" DBB Ranking Parser ~~~~~~~~~~~~~~~~~~ Extract league rankings from the DBB (Deutscher Basketball Bund e.V.) website. The resulting data is structured as a list of dictionaries. Please note that rankings are usually only available for the current season, but not those of the past. :Copyright: 2006-2021 Jochen Ku...
Add test-runner option to run zpop* tests.
#!/usr/bin/env python import optparse import sys import unittest from walrus import tests def runtests(verbose=False, failfast=False, names=None): if names: suite = unittest.TestLoader().loadTestsFromNames(names, tests) else: suite = unittest.TestLoader().loadTestsFromModule(tests) runner...
#!/usr/bin/env python import optparse import os import sys import unittest def runtests(verbose=False, failfast=False, names=None): if names: suite = unittest.TestLoader().loadTestsFromNames(names, tests) else: suite = unittest.TestLoader().loadTestsFromModule(tests) runner = unittest.Text...
Fix Thompson to pay attention to the RNG.
""" Acquisition functions based on (GP) UCB. """ # future imports from __future__ import division from __future__ import absolute_import from __future__ import print_function # use this to simplify (slightly) the Thompson implementation with sampled # models. from collections import deque # local imports from ..util...
""" Implementation of Thompson sampling for continuous spaces. """ from __future__ import division from __future__ import absolute_import from __future__ import print_function from collections import deque from ..utils import params __all__ = ['Thompson'] @params('n') def Thompson(model, n=100, rng=None): """ ...
Use an immutable tagged version of the Docker CLI container
import os from girder.utility.webroot import Webroot from .rest_slicer_cli import genRESTEndPointsForSlicerCLIsInDocker _template = os.path.join( os.path.dirname(__file__), 'webroot.mako' ) def load(info): girderRoot = info['serverRoot'] histomicsRoot = Webroot(_template) histomicsRoot.updateHt...
import os from girder.utility.webroot import Webroot from .rest_slicer_cli import genRESTEndPointsForSlicerCLIsInDocker _template = os.path.join( os.path.dirname(__file__), 'webroot.mako' ) def load(info): girderRoot = info['serverRoot'] histomicsRoot = Webroot(_template) histomicsRoot.updateHt...
Make it possible for modules to send a response
from module_interface import Module, ModuleType class Say(Module): def __init__(self): self.trigger = "say" self.moduleType = ModuleType.ACTIVE self.messagesTypes = ["PRIVMSG"] self.helpText = "Usage: say <message> | Makes the bot say the given line" def execute(self, message, ...
from module_interface import Module, ModuleType from message import IRCResponse, ResponseType class Say(Module): def __init__(self): self.trigger = "say" self.moduleType = ModuleType.ACTIVE self.messagesTypes = ["PRIVMSG"] self.helpText = "Usage: say <message> | Makes the bot say th...
Fix missing space between lede and rest of article
from bs4 import BeautifulSoup import json import re def extract_from_b64(encoded_doc): #doc = base64.urlsafe_b64decode(encoded_doc) doc = encoded_doc.decode("base64") doc = re.sub("</p><p>", " ", doc) soup = BeautifulSoup(doc) news_source = soup.find("meta", {"name":"sourceName"})['content'] ar...
from bs4 import BeautifulSoup import json import re def extract_from_b64(encoded_doc): #doc = base64.urlsafe_b64decode(encoded_doc) doc = encoded_doc.decode("base64") doc = re.sub("</p><p>", " ", doc) doc = re.sub('<div class="BODY-2">', " ", doc) soup = BeautifulSoup(doc) news_source = soup.fi...
Rename version field in Choice to question
from django.db import models from rest_framework import serializers class Question(models.Model): version = models.CharField(primary_key=True, max_length=8) text = models.TextField() created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) class Choice(mode...
from django.db import models from rest_framework import serializers class Question(models.Model): version = models.CharField(primary_key=True, max_length=8) text = models.TextField() created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) class Choice(mode...
Fix alembic migration for rpms->artifacts rename
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
Correct the url for the rating instance resource
from django.conf.urls import patterns, include, url from django.views import generic as views from . import resources # Uncomment the next two lines to enable the admin: from django.contrib.gis import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'project.views.home', name='ho...
from django.conf.urls import patterns, include, url from django.views import generic as views from . import resources # Uncomment the next two lines to enable the admin: from django.contrib.gis import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'project.views.home', name='ho...
Make stage outputter a little cleaner
''' Display clean output of an overstate stage ''' #[{'group2': {'match': ['fedora17-2', 'fedora17-3'], # 'require': ['group1'], # 'sls': ['nginx', 'edit']} # } # ] # Import Salt libs import salt.utils def output(data): ''' Format the data for printing stage ...
''' Display clean output of an overstate stage ''' #[{'group2': {'match': ['fedora17-2', 'fedora17-3'], # 'require': ['group1'], # 'sls': ['nginx', 'edit']} # } # ] # Import Salt libs import salt.utils def output(data): ''' Format the data for printing stage ...
Write out page cache as unicode utf8
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import json from datetime import datetime from bigbuild.models import PageList from bigbuild import get_archive_directory from django.core.management.base import BaseCommand def serializer(obj): """ JSON serializer for objects not serializable by default...
#!/usr/bin/env python # -*- coding: utf-8 -*- import io import os import json from datetime import datetime from bigbuild.models import PageList from bigbuild import get_archive_directory from django.core.management.base import BaseCommand def serializer(obj): """ JSON serializer for objects not serializable ...
Add test of callback function.
from django.test import TestCase # Create your tests here.
from django.test import TestCase from models import * class SubscriptionTests(TestCase): @classmethod def setUpTestData(cls): sub = MQTTSubscription(server='localhost', topic='#') sub.save() cls.sub = sub def test_callback_function(self): sub = type(self).sub # C...
Add common predicate for can_vote
from likes.signals import likes_enabled_test, can_vote_test from likes.exceptions import LikesNotEnabledException, CannotVoteException def _votes_enabled(obj): """See if voting is enabled on the class. Made complicated because secretballot.enable_voting_on takes parameters to set attribute names, so we can...
from secretballot.models import Vote from likes.signals import likes_enabled_test, can_vote_test from likes.exceptions import LikesNotEnabledException, CannotVoteException def _votes_enabled(obj): """See if voting is enabled on the class. Made complicated because secretballot.enable_voting_on takes parameters...
Fix parsing make with || on line.
# vim: set ts=4 sw=4 et: coding=UTF-8 from rpmsection import Section class RpmBuild(Section): """ Replace various troublemakers in build phase """ def add(self, line): line = self._complete_cleanup(line) # smp_mflags for jobs if not self.reg.re_comment.match(line): ...
# vim: set ts=4 sw=4 et: coding=UTF-8 from rpmsection import Section class RpmBuild(Section): """ Replace various troublemakers in build phase """ def add(self, line): line = self._complete_cleanup(line) # smp_mflags for jobs if not self.reg.re_comment.match(line): ...
Make the openquake namespace compatible with old setuptools
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2010-2016 GEM Foundation # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the Licen...
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2010-2016 GEM Foundation # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the Licen...
Make abnormal_exit docstring be in the imperative mood - pydocstyle
"""Write data out to console.""" from __future__ import print_function import sys def abnormal_exit(): """Exits program under abnormal conditions.""" sys.exit(1) def error_message(message): """Write message to STDERR, when message is valid.""" if message: print('{}'.format(message), file=sy...
"""Write data out to console.""" from __future__ import print_function import sys def abnormal_exit(): """Exit program under abnormal conditions.""" sys.exit(1) def error_message(message): """Write message to STDERR, when message is valid.""" if message: print('{}'.format(message), file=sys...
Use odoo instead of openerp
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from functools import partial import openerp from openerp import api, SUPERUSER_ID from . import models # noqa from . import report # noqa def uninstall_hook(cr, registry): def recreate_view(dbname): ...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from functools import partial import odoo from odoo import api, SUPERUSER_ID from . import models # noqa from . import report # noqa def uninstall_hook(cr, registry): def recreate_view(dbname): d...
Fix plan details test name
from changes.testutils import APITestCase class PlanIndexTest(APITestCase): def test_simple(self): project1 = self.create_project() project2 = self.create_project() plan1 = self.create_plan(label='Foo') plan1.projects.append(project1) plan1.projects.append(project2) ...
from changes.testutils import APITestCase class PlanDetailsTest(APITestCase): def test_simple(self): project1 = self.create_project() project2 = self.create_project() plan1 = self.create_plan(label='Foo') plan1.projects.append(project1) plan1.projects.append(project2) ...
Add EscapeHtml function (need to change it to a class)
"""Utilities for general operations.""" def IsNumeric(num_str): try: val = int(num_str) except ValueError: return False else: return True def GuaranteeUnicode(obj): if type(obj) == unicode: return obj elif type(obj) == str: return unicode(obj, "utf-8") ...
"""Utilities for general operations.""" def IsNumeric(num_str): try: val = int(num_str) except ValueError: return False else: return True def GuaranteeUnicode(obj): if type(obj) == unicode: return obj elif type(obj) == str: return unicode(obj, "utf-8") ...
Remove unneeded field specifier from EditPage form to make Django 1.8 happy
from django.http import Http404 from django.core.exceptions import PermissionDenied from django.views.generic import DetailView, TemplateView, UpdateView from wafer.pages.models import Page from wafer.pages.forms import PageForm class ShowPage(DetailView): template_name = 'wafer.pages/page.html' model = Page...
from django.http import Http404 from django.core.exceptions import PermissionDenied from django.views.generic import DetailView, TemplateView, UpdateView from wafer.pages.models import Page from wafer.pages.forms import PageForm class ShowPage(DetailView): template_name = 'wafer.pages/page.html' model = Page...
Fix for old numpy versions without cbrt
# -*- coding: utf-8 -*- """A small module for computing the smoothing length of a Gadget/Arepo simulation.""" import numpy as np def get_smooth_length(bar): """Figures out if the particles are from AREPO or GADGET and computes the smoothing length. Note the Volume array in HDF5 is comoving and this return...
# -*- coding: utf-8 -*- """A small module for computing the smoothing length of a Gadget/Arepo simulation.""" import numpy as np def get_smooth_length(bar): """Figures out if the particles are from AREPO or GADGET and computes the smoothing length. Note the Volume array in HDF5 is comoving and this return...
Increment minor version to 0.8
"""yolk. Author: Rob Cakebread <cakebread at gmail> License : BSD """ __version__ = '0.8a0'
"""yolk. Author: Rob Cakebread <cakebread at gmail> License : BSD """ __version__ = '0.8'
Use Dash's new CamelCase convention to lookup words that contain whitespace
import sublime import sublime_plugin import os import subprocess def syntax_name(view): syntax = os.path.basename(view.settings().get('syntax')) syntax = os.path.splitext(syntax)[0] return syntax def docset_prefix(view, settings): syntax_docset_map = settings.get('syntax_docset_map', {}) syntax ...
import sublime import sublime_plugin import os import subprocess def syntax_name(view): syntax = os.path.basename(view.settings().get('syntax')) syntax = os.path.splitext(syntax)[0] return syntax def camel_case(word): return ''.join(w.capitalize() if i > 0 else w for i, w in enume...
Add links to source code in documentation
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys sys.path....
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys sys.path....
Add param for turning on date formating.
import logging from django.http import HttpResponse from django.utils import simplejson as json from myuw_mobile.views.rest_dispatch import RESTDispatch, data_not_found from myuw_mobile.dao.library import get_account_info_for_current_user from myuw_mobile.logger.timer import Timer from myuw_mobile.logger.logresp import...
import logging from django.http import HttpResponse from django.utils import simplejson as json from myuw_mobile.views.rest_dispatch import RESTDispatch, data_not_found from myuw_mobile.dao.library import get_account_info_for_current_user from myuw_mobile.logger.timer import Timer from myuw_mobile.logger.logresp import...
Remove key while opening a door
from onirim.card._base import ColorCard from onirim.card._location import LocationKind def _openable(door_card, card): """Check if the door can be opened by another card.""" return card.kind == LocationKind.key and door_card.color == card.color def _may_open(door_card, content): """Check if the door may ...
from onirim.card._base import ColorCard from onirim.card._location import LocationKind def _is_openable(door_card, card): """Check if the door can be opened by another card.""" return card.kind == LocationKind.key and door_card.color == card.color def _may_open(door_card, content): """Check if the door ...
Add initial support for win32 fortran compiler support.
import sys import warnings from SCons.Util import \ WhereIs from SCons.Tool.ifort import \ generate as old_generate def generate_linux(env): ifort = WhereIs('ifort') if not ifort: warnings.warn("ifort not found") return old_generate(env) def generate(env): if sys.platform.star...
import sys import warnings from SCons.Util import \ WhereIs from SCons.Tool.ifort import \ generate as old_generate from numscons.tools.intel_common import get_abi def generate_linux(env): ifort = WhereIs('ifort') if not ifort: warnings.warn("ifort not found") return old_generate(...
Adjust OSF Storage default region names
# encoding: utf-8 import importlib import os import logging from website import settings logger = logging.getLogger(__name__) DEFAULT_REGION_NAME = 'N. Virginia' DEFAULT_REGION_ID = 'us-east-1' WATERBUTLER_CREDENTIALS = { 'storage': {} } WATERBUTLER_SETTINGS = { 'storage': { 'provider': 'filesystem...
# encoding: utf-8 import importlib import os import logging from website import settings logger = logging.getLogger(__name__) DEFAULT_REGION_NAME = 'United States' DEFAULT_REGION_ID = 'us' WATERBUTLER_CREDENTIALS = { 'storage': {} } WATERBUTLER_SETTINGS = { 'storage': { 'provider': 'filesystem', ...
Fix AttributeError on ListedColormap from_list method
import matplotlib.cm as cm import matplotlib.colors as clr import matplotlib.pyplot as plt from ..palettes import SEABORN def create_discrete_cmap(n): """Create an n-bin discrete colormap.""" if n <= len(SEABORN): colors = list(SEABORN.values())[:n] else: base = plt.cm.get_cmap('Paired') ...
import matplotlib.cm as cm import matplotlib.colors as clr import matplotlib.pyplot as plt from ..palettes import SEABORN def create_discrete_cmap(n): """Create an n-bin discrete colormap.""" if n <= len(SEABORN): colors = list(SEABORN.values())[:n] else: base = plt.cm.get_cmap('Paired') ...
Update python lib erpbrasil.assinatura version 1.4.0
# Copyright 2019 KMEE INFORMATICA LTDA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "NFS-e", "summary": """ NFS-e""", "version": "14.0.1.7.0", "license": "AGPL-3", "author": "KMEE, Odoo Community Association (OCA)", "maintainers": ["gabrielcardoso21", "mileo...
# Copyright 2019 KMEE INFORMATICA LTDA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "NFS-e", "summary": """ NFS-e""", "version": "14.0.1.7.0", "license": "AGPL-3", "author": "KMEE, Odoo Community Association (OCA)", "maintainers": ["gabrielcardoso21", "mileo...
Use the json module from stdlib (Python 2.6+) as fallback
import simplejson json_encode = lambda data: simplejson.dumps(data, separators=(',', ':')) json_decode = lambda data: simplejson.loads(data) JSONDecodeError = ValueError # Protocol handlers CONNECT = 'o' DISCONNECT = 'c' MESSAGE = 'm' HEARTBEAT = 'h' # Various protocol helpers def disconnect(code, reason): """R...
try: import simplejson except ImportError: import json as simplejson json_encode = lambda data: simplejson.dumps(data, separators=(',', ':')) json_decode = lambda data: simplejson.loads(data) JSONDecodeError = ValueError # Protocol handlers CONNECT = 'o' DISCONNECT = 'c' MESSAGE = 'm' HEARTBEAT = 'h' # Vari...
Fix the GNU diff error to not mention Subversion.
import os import subprocess import sys from rbtools.utils.process import die, execute GNU_DIFF_WIN32_URL = 'http://gnuwin32.sourceforge.net/packages/diffutils.htm' def check_install(command): """ Try executing an external command and return a boolean indicating whether that command is installed or not....
import os import subprocess import sys from rbtools.utils.process import die, execute GNU_DIFF_WIN32_URL = 'http://gnuwin32.sourceforge.net/packages/diffutils.htm' def check_install(command): """ Try executing an external command and return a boolean indicating whether that command is installed or not....
Allow both instance and model classes in Media.objects.for_model()
from django.db import models from django.contrib.contenttypes.models import ContentType class MediaAssociationManager(models.Manager): def for_model(self, model, content_type=None): content_type = content_type or ContentType.objects.get_for_model(model) objects = self.get_query_set().filter(...
from django.db import models from django.contrib.contenttypes.models import ContentType from django.utils.encoding import force_unicode class MediaAssociationManager(models.Manager): def for_model(self, model, content_type=None): """ QuerySet for all media for a particular model (either an instanc...
Move seq size to const
import os from os.path import join, dirname, abspath from dotenv import load_dotenv class Config: loaded = False @staticmethod def load(file_name='../config/.env'): load_dotenv(join(dirname(__file__), file_name)) env_file_path = abspath(join(dirname(__file__), '../config', os.environ.get(...
import os from os.path import join, dirname, abspath from dotenv import load_dotenv class Config: max_seq_size = 1000 loaded = False @staticmethod def load(file_name='../config/.env'): load_dotenv(join(dirname(__file__), file_name)) env_file_path = abspath(join(dirname(__file__), '../...
Fix "make me room owner"
# This file is part of Indico. # Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (a...
# This file is part of Indico. # Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (a...
Fix using mock in production
import mock BookingCreateProcessor = mock.MagicMock() BookingDeleteProcessor = mock.MagicMock()
from waldur_mastermind.marketplace import processors class BookingCreateProcessor(processors.CreateResourceProcessor): def get_serializer_class(self): pass def get_viewset(self): pass def get_post_data(self): pass def get_scope_from_response(self, response): pass c...
Make sound generator use common
from wavebender import * import sys start = 10 final = 200 end_time= 10 def val(i): time = float(i) / 44100 k = (final - start) / end_time return math.sin(2.0 * math.pi * (start * time + ((k * time * time) / 2))) def sweep(): return (val(i) for i in count(0)) channels = ((sweep(),),) samples = comp...
from wavebender import * import sys from common import * def sweep(): return (val(i) for i in count(0)) channels = ((sweep(),),) samples = compute_samples(channels, 44100 * 60 * 1) write_wavefile(sys.stdout, samples, 44100 * 60 * 1, nchannels=1)
Add new fields to label document
#!/usr/bin/env python3 """Document models for mongoengine""" from mongoengine import * from bson import ObjectId class Label(Document): """Model for labels of events""" name = StringField(required=True, unique=True) # TODO: set to primary key? description = StringField() url = URLField()
#!/usr/bin/env python3 """Document models for mongoengine""" from mongoengine import * from bson import ObjectId class Label(Document): """Model for labels of events""" name = StringField(required=True, unique=True) # TODO: set to primary key? description = StringField() url = URLField() default ...
Cut fbcode_builder dep for thrift on krb5
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import specs.folly as folly import specs.fizz as fizz import specs.rsocket as rsocket import spec...
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import specs.folly as folly import specs.fizz as fizz import specs.rsocket as rsocket import spec...
Set max threads for MKL.
import logging, gensim, bz2 from knub.thesis.util.memory import limit_memory logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) def main(): logging.info("Starting Wikipedia LDA") # limit memory to 32 GB limit_memory(32000) id2word = gensim.corpora.Dictionary.l...
import logging, gensim, bz2 import mkl from knub.thesis.util.memory import limit_memory logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) mkl.set_num_threads(8) def main(): logging.info("Starting Wikipedia LDA") # limit memory to 32 GB limit_memory(32000) id2...
Add polling_district_id in Sheffield import script
""" Import Sheffield """ from data_collection.management.commands import BaseShpShpImporter class Command(BaseShpShpImporter): """ Imports the Polling Station data from Sheffield """ council_id = 'E08000019' districts_name = 'SCCPollingDistricts2015' stations_name = 'SCCPollingStations2015...
""" Import Sheffield """ from data_collection.management.commands import BaseShpShpImporter class Command(BaseShpShpImporter): """ Imports the Polling Station data from Sheffield """ council_id = 'E08000019' districts_name = 'SCCPollingDistricts2015' stations_name = 'SCCPollingStations2015...
Add input_pattern instead of min_pattern_length
import deoplete.util from .base import Base class Source(Base): def __init__(self, vim): Base.__init__(self, vim) self.name = 'go' self.mark = '[go]' self.filetypes = ['go'] self.min_pattern_length = 0 self.is_bytepos = True def get_complete_api(self, findstar...
import deoplete.util from .base import Base class Source(Base): def __init__(self, vim): Base.__init__(self, vim) self.name = 'go' self.mark = '[go]' self.filetypes = ['go'] self.input_pattern = '[^. \t0-9]\.\w*' self.is_bytepos = True def get_complete_api(sel...
Change env variables for node setup to single URI varieable
from django.conf import settings from web3 import HTTPProvider, Web3 from web3.middleware import geth_poa_middleware from .utils import Singleton class Web3Service(metaclass=Singleton): """Creates a `web3` instance based on the given Provider.""" def __init__(self, *args, **kwargs): """Initializes ...
from django.conf import settings from web3 import HTTPProvider, Web3 from web3.middleware import geth_poa_middleware from .utils import Singleton class Web3Service(metaclass=Singleton): """Creates a `web3` instance based on the given Provider.""" def __init__(self, *args, **kwargs): """Initializes t...
Remove y-axis ticks and top x-axis ticks
import matplotlib.pyplot as plt import numpy as np def horizontal_bar(sorted_streaks, sort): """ Render a horizontal bar chart of streaks. Values have already been sorted by sort. """ # Only extract those users & streaks for streaks that are non-zero: users, streaks = zip(*[(user, streak.get(...
import matplotlib.pyplot as plt import numpy as np def horizontal_bar(sorted_streaks, sort): """ Render a horizontal bar chart of streaks. Values have already been sorted by sort. """ # Only extract those users & streaks for streaks that are non-zero: users, streaks = zip(*[(user, streak.get(...
Reduce the name of a function
#!/usr/bin/env python import rospy,copy from geometry_msgs.msg import Twist from std_srvs.srv import Trigger, TriggerResponse from pimouse_ros.msg import LightSensorValues class WallStop(): def __init__(self): self.cmd_vel = rospy.Publisher('/cmd_vel',Twist,queue_size=1) self.sensor_values = Light...
#!/usr/bin/env python import rospy,copy from geometry_msgs.msg import Twist from std_srvs.srv import Trigger, TriggerResponse from pimouse_ros.msg import LightSensorValues class WallStop(): def __init__(self): self.cmd_vel = rospy.Publisher('/cmd_vel',Twist,queue_size=1) self.sensor_values = Light...
Allow 0-9 in song names.
#!/usr/bin/env python2.7 import os import re import sys from mutagen.easyid3 import EasyID3 replaceChars = ( (" ", "-"), ("(", ""), (")", ""), (",", ""), (".", ""), ("'", ""), ("?", "") ) def toNeat(s): s = s.lower() for r in replaceChars: s = s.replace(r[0], r[1]) search = re.search("[^a-z\-]", s...
#!/usr/bin/env python2.7 import os import re import sys from mutagen.easyid3 import EasyID3 replaceChars = ( (" ", "-"), ("(", ""), (")", ""), (",", ""), (".", ""), ("'", ""), ("?", "") ) def toNeat(s): s = s.lower() for r in replaceChars: s = s.replace(r[0], r[1]) search = re.search("[^0-9a-z\-]"...
Test settings when setup.py test is run.
import os import unittest def suite(): test_dir = os.path.dirname(__file__) return unittest.TestLoader().discover(test_dir, ) test_suite = suite() if __name__ == '__main__': unittest.main(defaultTest='suite')
import os import unittest from Orange.widgets.tests import test_settings, test_setting_provider def suite(): test_dir = os.path.dirname(__file__) return unittest.TestSuite([ unittest.TestLoader().discover(test_dir), unittest.TestLoader().loadTestsFromModule(test_settings), unittest.Te...
Add logging of tested package version
#!/usr/bin/env python # encoding: utf8 from __future__ import (absolute_import, print_function, division, unicode_literals) # REV - This has no effect - http://stackoverflow.com/q/18558666/656912 def pytest_report_header(config): return "Testing Enigma functionality"
#!/usr/bin/env python # encoding: utf8 from __future__ import (absolute_import, print_function, division, unicode_literals) from crypto_enigma import __version__ def pytest_report_header(config): return "version: {}".format(__version__)
Add shebang to cli_tets.py module
import unittest from unittest.mock import patch, call from crc import main class CliTests(unittest.TestCase): def test_cli_no_arguments_provided(self): expected_exit_code = -1 argv = [] with patch('sys.exit') as exit_mock: main(argv) self.assertTrue(exit_mock.calle...
#!/usr/bin/env python3 # # Copyright (c) 2021, Nicola Coretti # All rights reserved. import unittest from unittest.mock import patch, call from crc import main class CliTests(unittest.TestCase): def test_cli_no_arguments_provided(self): expected_exit_code = -1 argv = [] with patch('sys.ex...
Add extra test for regression
from django.test import TestCase from ..models import Game class QuerySetTests(TestCase): def test_get_by_name(self): gta_v = Game.objects.create(name='GTA V') Game.objects.create(name='Grand Theft Auto V', alias_for=gta_v) game = Game.objects.get_by_name('gta V') self.assertEq...
# -*- coding: utf-8 -*- from django.test import TestCase from ..models import Game class QuerySetTests(TestCase): def test_get_by_name(self): gta_v = Game.objects.create(name='GTA V') Game.objects.create(name='Grand Theft Auto V', alias_for=gta_v) game = Game.objects.get_by_name('gta V...
Add tracking for lessons 1, 2, 3
# See also examples/example_track/track_meta.py for a longer, commented example track = dict( author_username='ryanholbrook', course_name='computer_vision', course_url='https://www.kaggle.com/ryanholbrook/computer-vision' ) lessons = [ dict( # By convention, this should be a lowercase n...
# See also examples/example_track/track_meta.py for a longer, commented example track = dict( author_username='ryanholbrook', course_name='Computer Vision', course_url='https://www.kaggle.com/ryanholbrook/computer-vision' ) lessons = [ {'topic': topic_name} for topic_name in [ 'The Convolut...
Fix value is "" hand value being None in prepare
from __future__ import absolute_import from enum import Enum from typing import TypeVar, Optional, Any, Type # noqa from odin.exceptions import ValidationError from . import Field __all__ = ("EnumField",) ET = TypeVar("ET", Enum, Enum) class EnumField(Field): """ Field for handling Python enums. """...
from __future__ import absolute_import from enum import Enum from typing import TypeVar, Optional, Any, Type # noqa from odin.exceptions import ValidationError from . import Field __all__ = ("EnumField",) ET = TypeVar("ET", Enum, Enum) class EnumField(Field): """ Field for handling Python enums. """...
Fix the temp file initialization
# -*- coding: utf-8 -*- from flask.ext.testing import TestCase import os import tempfile import shutil import websmash class ModelTestCase(TestCase): def create_app(self): self.app = websmash.app self.dl = websmash.dl self.app.config['TESTING'] = True self.app.config['SQLALCHEMY_DA...
# -*- coding: utf-8 -*- from flask.ext.testing import TestCase import os import tempfile import shutil import websmash class ModelTestCase(TestCase): def create_app(self): self.app = websmash.app self.dl = websmash.dl self.app.config['TESTING'] = True self.app.config['SQLALCHEMY_DA...
Improve integrate tool wrapper with arguments
#!/usr/bin/env python # -*- coding: utf-8 -*- from bioblend import galaxy from bioblend import toolshed if __name__ == '__main__': gi_url = "http://172.21.23.6:8080/" ts_url = "http://172.21.23.6:9009/" name = "qiime" owner = "iuc" tool_panel_section_id = "qiime_rRNA_taxonomic_assignation" g...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import argparse import re from bioblend import galaxy from bioblend import toolshed def retrieve_changeset_revision(ts_url, name, owner): ts = toolshed.ToolShedInstance(url=ts_url) ts_repositories = ts.repositories.get_repositories() ts_...