commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
f99a898d66c9f88496dee73ec574c7b9b69e8dc2
ocds/storage/backends/design/tenders.py
ocds/storage/backends/design/tenders.py
from ocds.storage.helpers import CouchView class AllDocs(CouchView): design = 'docs' @staticmethod def map(doc): yield (doc['tenderID'], doc) class DateView(CouchView): design = 'dates' @staticmethod def map(doc): yield (doc['dateModified'], doc) views = [ AllDocs()...
from ocds.storage.helpers import CouchView class AllDocs(CouchView): design = 'docs' @staticmethod def map(doc): if 'doc_type' in doc and doc['doc_type'] != 'Tender': return yield doc['_id'], doc class DateView(CouchView): design = 'dates' @staticmethod def m...
Add filter in design docs
Add filter in design docs
Python
apache-2.0
yshalenyk/openprocurement.ocds.export,yshalenyk/ocds.export,yshalenyk/openprocurement.ocds.export
d3f33af2fa7d4e7bf9969752e696aaf8120642bc
panoptes/environment/weather_station.py
panoptes/environment/weather_station.py
import datetime import zmq from . import monitor from panoptes.utils import logger, config, messaging, threads @logger.has_logger @config.has_config class WeatherStation(monitor.EnvironmentalMonitor): """ This object is used to determine the weather safe/unsafe condition. It inherits from the monitor.En...
import datetime import zmq from . import monitor from panoptes.utils import logger, config, messaging, threads @logger.has_logger @config.has_config class WeatherStation(monitor.EnvironmentalMonitor): """ This object is used to determine the weather safe/unsafe condition. It inherits from the monitor.En...
Set up weather station to receive updates
Set up weather station to receive updates
Python
mit
Guokr1991/POCS,fmin2958/POCS,AstroHuntsman/POCS,panoptes/POCS,panoptes/POCS,fmin2958/POCS,Guokr1991/POCS,AstroHuntsman/POCS,AstroHuntsman/POCS,panoptes/POCS,panoptes/POCS,joshwalawender/POCS,Guokr1991/POCS,AstroHuntsman/POCS,fmin2958/POCS,joshwalawender/POCS,joshwalawender/POCS,Guokr1991/POCS
dc40793ad27704c83dbbd2e923bf0cbcd7cb00ed
polyaxon/event_manager/event_service.py
polyaxon/event_manager/event_service.py
from libs.services import Service class EventService(Service): __all__ = ('record', 'setup') event_manager = None def can_handle(self, event_type): return isinstance(event_type, str) and self.event_manager.knows(event_type) def get_event(self, event_type, instance, **kwargs): return...
from libs.services import Service class EventService(Service): __all__ = ('record', 'setup') event_manager = None def can_handle(self, event_type): return isinstance(event_type, str) and self.event_manager.knows(event_type) def get_event(self, event_type, event_data=None, instance=None, **k...
Handle both event instanciation from object and from serialized events
Handle both event instanciation from object and from serialized events
Python
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
38d298a81aa8fcd85b16b3879c1665085e5450be
exercises/control_flow/prime.py
exercises/control_flow/prime.py
#!/bin/python def is_prime(integer): """Determines weather integer is prime, returns a boolean value""" for i in range(2, integer): if integer % i == 0: return False return True print("Should be False (0): %r" % is_prime(0)) print("Should be False (1): %r" % is_prime(1)) print("Sho...
#!/bin/python def is_prime(integer): """Determines weather integer is prime, returns a boolean value""" # add logic here to make sure number < 2 are not prime for i in range(2, integer): if integer % i == 0: return False return True print("Should be False (0): %r" % is_prime(0...
Add description where student should add logic
Add description where student should add logic
Python
mit
introprogramming/exercises,introprogramming/exercises,introprogramming/exercises
d5b326d8d368d2ac75c6e078572df8c28704c163
vcs/models.py
vcs/models.py
from django.db import models class Activity(models.Model): group = models.CharField(max_length=4) grouptype = models.TextField() groupdetail = models.TextField() details = models.TextField() disabled = models.BooleanField() time = models.DecimalField(decimal_places=2, max_digits=10) unique_...
from django.db import models class Activity(models.Model): group = models.CharField(max_length=4) grouptype = models.TextField() groupdetail = models.TextField() details = models.TextField() disabled = models.BooleanField() time = models.DecimalField(decimal_places=2, max_digits=10) unique_...
Use the app string version of foreign keying. It prevents a circular import.
Use the app string version of foreign keying. It prevents a circular import.
Python
bsd-3-clause
AeroNotix/django-timetracker,AeroNotix/django-timetracker,AeroNotix/django-timetracker
1163bc40a15eb2461c6ead570db8a8d211f1f5be
web/blueprints/facilities/tables.py
web/blueprints/facilities/tables.py
from web.blueprints.helpers.table import BootstrapTable, Column class SiteTable(BootstrapTable): def __init__(self, *a, **kw): super().__init__(*a, columns=[ Column('site', 'Site', formatter='table.linkFormatter'), Column('buildings', 'Buildings', formatter='table.multiBtnFormatter...
from web.blueprints.helpers.table import BootstrapTable, Column class SiteTable(BootstrapTable): def __init__(self, *a, **kw): super().__init__(*a, columns=[ Column('site', 'Site', formatter='table.linkFormatter'), Column('buildings', 'Buildings', formatter='table.multiBtnFormatter...
Sort room table by room name by default
Sort room table by room name by default
Python
apache-2.0
agdsn/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,agdsn/pycroft
1abbca6200fa3da0a3216b18b1385f3575edb49a
registration/__init__.py
registration/__init__.py
from django.utils.version import get_version as django_get_version VERSION = (0, 9, 0, 'beta', 1) def get_version(): return django_get_version(VERSION) # pragma: no cover
VERSION = (0, 9, 0, 'beta', 1) def get_version(): from django.utils.version import get_version as django_get_version return django_get_version(VERSION) # pragma: no cover
Move import of Django's get_version into django-registration's get_version, to avoid dependency-order problems.
Move import of Django's get_version into django-registration's get_version, to avoid dependency-order problems.
Python
bsd-3-clause
myimages/django-registration,Troyhy/django-registration,futurecolors/django-registration,hacklabr/django-registration,akvo/django-registration,sandipagr/django-registration,futurecolors/django-registration,liberation/django-registration,euanlau/django-registration,tdruez/django-registration,Troyhy/django-registration,g...
cd9a51ab2fe6b99c0665b8f499363a4d557b4a4d
DataWrangling/CaseStudy/sample_file.py
DataWrangling/CaseStudy/sample_file.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import xml.etree.ElementTree as ET # Use cElementTree or lxml if too slow import os OSM_FILE = "san-francisco-bay_california.osm" # Replace this with your osm file SAMPLE_FILE = "sample_sfb.osm" k = 20 # Parameter: take every k-th top level element def get_element(osm...
#!/usr/bin/env python # -*- coding: utf-8 -*- import xml.etree.ElementTree as ET # Use cElementTree or lxml if too slow import os OSM_FILE = "san-francisco-bay_california.osm" # Replace this with your osm file SAMPLE_FILE = "sample_sfb.osm" k = 20 # Parameter: take every k-th top level element def get_element(osm...
Modify script which split your region in smaller sample
feat: Modify script which split your region in smaller sample
Python
mit
aguijarro/DataSciencePython
828e75919bd71912baf75a64010efcfcd93d07f1
library_magic.py
library_magic.py
import sys import subprocess import shutil executable = sys.argv[1] execfolder = sys.argv[1].rsplit("/",1)[0] libdir = execfolder+"/lib" otool_cmd = ["otool", "-L",executable] # Run otool otool_out = subprocess.check_output(otool_cmd).split("\n\t") # Find all the dylib files for l in otool_out: s = l.split(".dylib"...
import sys import subprocess import shutil copied = [] def update_libraries(executable): # Find all the dylib files and recursively add dependencies print "\nChecking dependencies of " + executable otool_cmd = ["otool", "-L",executable] execfolder = executable.rsplit("/",1)[0] otool_out = subprocess.check_outp...
Update library magic to be recursive
Update library magic to be recursive
Python
bsd-3-clause
baubie/SpikeDB,baubie/SpikeDB,baubie/SpikeDB,baubie/SpikeDB
dfa39db42cc5ce2c29da2ec0c388865ec7f41030
oauth2_provider/forms.py
oauth2_provider/forms.py
from django import forms class AllowForm(forms.Form): redirect_uri = forms.URLField(widget=forms.HiddenInput()) scopes = forms.CharField(required=False, widget=forms.HiddenInput()) client_id = forms.CharField(widget=forms.HiddenInput()) state = forms.CharField(required=False, widget=forms.HiddenInput(...
from django import forms class AllowForm(forms.Form): allow = forms.BooleanField(required=False) redirect_uri = forms.URLField(widget=forms.HiddenInput()) scopes = forms.CharField(required=False, widget=forms.HiddenInput()) client_id = forms.CharField(widget=forms.HiddenInput()) state = forms.Char...
Add allow field to form
Add allow field to form
Python
bsd-2-clause
trbs/django-oauth-toolkit,DeskConnect/django-oauth-toolkit,jensadne/django-oauth-toolkit,vmalavolta/django-oauth-toolkit,JensTimmerman/django-oauth-toolkit,JensTimmerman/django-oauth-toolkit,Gr1N/django-oauth-toolkit,andrefsp/django-oauth-toolkit,jensadne/django-oauth-toolkit,drgarcia1986/django-oauth-toolkit,bleib1dj/...
11cd074f67668135d606f68dddb66c465ec01756
opps/core/tags/models.py
opps/core/tags/models.py
# -*- coding: utf-8 -*- from django.db import models from django.utils.translation import ugettext_lazy as _ from django.template.defaultfilters import slugify from opps.core.models import Date, Slugged class Tag(Date, Slugged): name = models.CharField(_(u'Name'), max_length=255, unique=True) def save(self,...
# -*- coding: utf-8 -*- from django.db import models from django.utils.translation import ugettext_lazy as _ from django.template.defaultfilters import slugify from opps.core.models import Date, Slugged class Tag(Date, Slugged): name = models.CharField(_(u'Name'), max_length=255, unique=True, ...
Add db index on field tag name
Add db index on field tag name
Python
mit
jeanmask/opps,YACOWS/opps,williamroot/opps,YACOWS/opps,opps/opps,opps/opps,YACOWS/opps,YACOWS/opps,opps/opps,opps/opps,jeanmask/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,williamroot/opps,williamroot/opps
38a2d86aed4ea1e94691993c5f49722f9a69ac8d
lisa/__init__.py
lisa/__init__.py
#! /usr/bin/env python3 import warnings import os import sys from lisa.version import __version__ # Raise an exception when a deprecated API is used from within a lisa.* # submodule. This ensures that we don't use any deprecated APIs internally, so # they are only kept for external backward compatibility purposes. ...
#! /usr/bin/env python3 import warnings import os import sys from lisa.version import __version__ # Raise an exception when a deprecated API is used from within a lisa.* # submodule. This ensures that we don't use any deprecated APIs internally, so # they are only kept for external backward compatibility purposes. ...
Remove Python < 3.6 version check
lisa: Remove Python < 3.6 version check Since Python >= 3.6 is now mandatory, remove the check and the warning.
Python
apache-2.0
ARM-software/lisa,credp/lisa,credp/lisa,credp/lisa,credp/lisa,ARM-software/lisa,ARM-software/lisa,ARM-software/lisa
7fd76d87cfda8f02912985cb3cf650ee8ff2e11e
mica/report/tests/test_write_report.py
mica/report/tests/test_write_report.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst import tempfile import os import shutil import pytest from .. import report try: import Ska.DBI with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='aca_ops', database='axafocat') as db: assert db.conn._is_connected == 1 HAS_SYBA...
# Licensed under a 3-clause BSD style license - see LICENSE.rst import tempfile import os import shutil import pytest from .. import report try: import Ska.DBI with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='aca_ops', database='axafocat') as db: HAS_SYBASE_ACCESS = True except: HAS_SYBASE_AC...
Remove py2 Ska.DBI assert in report test
Remove py2 Ska.DBI assert in report test
Python
bsd-3-clause
sot/mica,sot/mica
462312c3acf2d6daf7d8cd27f251b8cb92647f5e
pybossa/auth/category.py
pybossa/auth/category.py
from flaskext.login import current_user def create(app=None): if current_user.is_authenticated(): if current_user.admin is True: return True else: return False else: return False def read(app=None): return True def update(app): return create(app) d...
from flaskext.login import current_user def create(category=None): if current_user.is_authenticated(): if current_user.admin is True: return True else: return False else: return False def read(category=None): return True def update(category): return ...
Fix a typo in the variable name
Fix a typo in the variable name
Python
agpl-3.0
jean/pybossa,geotagx/geotagx-pybossa-archive,OpenNewsLabs/pybossa,stefanhahmann/pybossa,proyectos-analizo-info/pybossa-analizo-info,stefanhahmann/pybossa,proyectos-analizo-info/pybossa-analizo-info,Scifabric/pybossa,geotagx/geotagx-pybossa-archive,geotagx/geotagx-pybossa-archive,OpenNewsLabs/pybossa,harihpr/tweetclicke...
1ee2e880872c4744f4159df7fc64bb64b3f35632
pygametemplate/button.py
pygametemplate/button.py
import time class Button(object): """Class representing keyboard keys.""" def __init__(self, game, number): self.game = game self.number = number self.event = None # The last event that caused the button press self.pressed = 0 # If the button was just pressed sel...
import time class Button(object): """Class representing keyboard keys.""" def __init__(self, game, number): self.game = game self.number = number self.event = None # The last event that caused the button press self.pressed = 0 # If the button was just pressed sel...
Add docstring to Button.time_held() method
Add docstring to Button.time_held() method
Python
mit
AndyDeany/pygame-template
6708830ab2bde841bbc3da2befbbe5ab9f3d21aa
ansi_str.py
ansi_str.py
import re _ansi_re = re.compile('\033\[((?:\d|;)*)([a-zA-Z])') def strip_ansi(value): return _ansi_re.sub('', value) def len_exclude_ansi(value): return len(strip_ansi(value)) class ansi_str(str): """A str subclass, specialized for strings containing ANSI escapes. When you call the ``len`` metho...
import re _ansi_re = re.compile('\033\[((?:\d|;)*)([a-zA-Z])') def strip_ansi(value): return _ansi_re.sub('', value) def len_exclude_ansi(value): return len(strip_ansi(value)) class ansi_str(str): """A str subclass, specialized for strings containing ANSI escapes. When you call the ``len`` metho...
Put test stuff inside `if __name__ == '__main__'`
Put test stuff inside `if __name__ == '__main__'`
Python
mit
msabramo/ansi_str
1056c3f489b162d77b6c117fad2b45bfa06beee1
app/urls.py
app/urls.py
from django.conf.urls import patterns, include, url from django.contrib import admin from django.conf import settings #from . import views urlpatterns = patterns('', # Examples: # url(r'^$', 'app.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^$', 'app.views.splash', name='...
from django.conf.urls import patterns, include, url from django.contrib import admin from django.conf import settings #from . import views urlpatterns = patterns('', # Examples: # url(r'^$', 'app.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^$', 'app.views.splash', name='sp...
Revert "Added a post view"
Revert "Added a post view" This reverts commit b1063480e7b2e1128c457e9e65c52f742109d90d.
Python
unlicense
yourbuddyconner/cs399-social,yourbuddyconner/cs399-social
4e74723aac53956fb0316ae0d438da623de133d5
tests/extensions/video/test_renderer.py
tests/extensions/video/test_renderer.py
import pytest from mfr.core.provider import ProviderMetadata from mfr.extensions.video import VideoRenderer @pytest.fixture def metadata(): return ProviderMetadata('test', '.mp4', 'text/plain', '1234', 'http://wb.osf.io/file/test.mp4?token=1234') @pytest.fixture def file_path(): return '/tmp/test.mp4' @...
import pytest from mfr.core.provider import ProviderMetadata from mfr.extensions.video import VideoRenderer @pytest.fixture def metadata(): return ProviderMetadata('test', '.mp4', 'text/plain', '1234', 'http://wb.osf.io/file/test.mp4?token=1234') @pytest.fixture def file_path(): ...
Add and update tests for video renderer
Add and update tests for video renderer
Python
apache-2.0
felliott/modular-file-renderer,CenterForOpenScience/modular-file-renderer,felliott/modular-file-renderer,CenterForOpenScience/modular-file-renderer,CenterForOpenScience/modular-file-renderer,CenterForOpenScience/modular-file-renderer,felliott/modular-file-renderer,felliott/modular-file-renderer
0b048cef1f0efd190d8bf8f50c69df35c59b91a3
xdc-plugin/tests/compare_output_json.py
xdc-plugin/tests/compare_output_json.py
#!/usr/bin/env python3 """ This script extracts the top module cells and their corresponding parameters from json files produced by Yosys. The return code of this script is used to check if the output is equivalent. """ import sys import json def read_cells(json_file): with open(json_file) as f: data = j...
#!/usr/bin/env python3 """ This script extracts the top module cells and their corresponding parameters from json files produced by Yosys. The return code of this script is used to check if the output is equivalent. """ import sys import json parameters = ["IOSTANDARD", "DRIVE", "SLEW", "IN_TERM"] def read_cells(js...
Add verbosity on JSON compare fail
XDC: Add verbosity on JSON compare fail Signed-off-by: Tomasz Michalak <a2fdaa543b4cc5e3d6cd8672ec412c0eb393b86e@antmicro.com>
Python
apache-2.0
SymbiFlow/yosys-symbiflow-plugins,SymbiFlow/yosys-symbiflow-plugins,SymbiFlow/yosys-f4pga-plugins,SymbiFlow/yosys-symbiflow-plugins,chipsalliance/yosys-f4pga-plugins,antmicro/yosys-symbiflow-plugins,chipsalliance/yosys-f4pga-plugins,antmicro/yosys-symbiflow-plugins,antmicro/yosys-symbiflow-plugins,SymbiFlow/yosys-f4pga...
5bde6ca1fd62277463156875e874c4c6843923fd
pytest-{{cookiecutter.plugin_name}}/tests/test_{{cookiecutter.plugin_name}}.py
pytest-{{cookiecutter.plugin_name}}/tests/test_{{cookiecutter.plugin_name}}.py
# -*- coding: utf-8 -*- def test_bar_fixture(testdir): """Make sure that pytest accepts our fixture.""" # create a temporary pytest test module testdir.makepyfile(""" def test_sth(bar): assert bar == "europython2015" """) # run pytest with the following cmd args result = t...
# -*- coding: utf-8 -*- def test_bar_fixture(testdir): """Make sure that pytest accepts our fixture.""" # create a temporary pytest test module testdir.makepyfile(""" def test_sth(bar): assert bar == "europython2015" """) # run pytest with the following cmd args result = t...
Use the correct variable for the test
Use the correct variable for the test
Python
mit
luzfcb/cookiecutter-pytest-plugin,pytest-dev/cookiecutter-pytest-plugin,s0undt3ch/cookiecutter-pytest-plugin
2549a66b6785d5a0ed0658a4f375a21c486792df
sifr/util.py
sifr/util.py
import datetime from dateutil import parser import six def normalize_time(t): try: if isinstance(t, datetime.datetime): return t elif isinstance(t, datetime.date): return datetime.datetime(t.year, t.month, t.day) elif isinstance(t, (int, float)): return ...
import datetime from dateutil import parser import six def normalize_time(t): try: if isinstance(t, datetime.datetime): return t elif isinstance(t, datetime.date): return datetime.datetime(t.year, t.month, t.day) elif isinstance(t, (int, float)): return ...
Raise explicit exception on no type match
Raise explicit exception on no type match
Python
mit
alisaifee/sifr,alisaifee/sifr
66d1bce2cb497954749b211a26fd00ae4db6f7e7
foodsaving/conversations/serializers.py
foodsaving/conversations/serializers.py
from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers from rest_framework.exceptions import PermissionDenied from foodsaving.conversations.models import Conversation, ConversationMessage class ConversationSerializer(serializers.ModelSerializer): class Meta: model ...
from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers from rest_framework.exceptions import PermissionDenied from foodsaving.conversations.models import Conversation, ConversationMessage class ConversationSerializer(serializers.ModelSerializer): class Meta: model ...
Remove random bit of code
Remove random bit of code I have no idea what that is doing there. It is not called from what I can tell, and the tests work without it. And it makes no sense whatsoever, create a message each time you retrieve the conversation info??!?!?!
Python
agpl-3.0
yunity/foodsaving-backend,yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend,yunity/yunity-core
d3847357c446c4a1ac50735b983b20cf57f9c7c6
malcolm/controllers/countercontroller.py
malcolm/controllers/countercontroller.py
from malcolm.core.controller import Controller from malcolm.core.attribute import Attribute from malcolm.core.numbermeta import NumberMeta from malcolm.core.method import takes import numpy as np class CounterController(Controller): def create_attributes(self): self.counter = Attribute(NumberMeta("counte...
from malcolm.core.controller import Controller from malcolm.core.attribute import Attribute from malcolm.core.numbermeta import NumberMeta from malcolm.core.method import takes, returns import numpy as np class CounterController(Controller): def create_attributes(self): self.counter = Attribute(NumberMet...
Fix args and return of CounterController functions
Fix args and return of CounterController functions Even though they're not used, functions to be wrapped by Methods have to take arguments and return something (at least an empty dict).
Python
apache-2.0
dls-controls/pymalcolm,dls-controls/pymalcolm,dls-controls/pymalcolm
270af43ffbe8974698d17ff6d5cae20fbf410f73
admin/urls.py
admin/urls.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from .views import CubeHandler, ConnectionHandler from .views import ElementHandler, DashboardHandler, APIElementCubeHandler INCLUDE_URLS = [ (r"/admin/connection/?(?P<slug>[\w-]+)?", ConnectionHandler), (r"/admin/cube/?(?P<slug>[\w-]+)?", CubeHandler), (r"/ad...
#!/usr/bin/env python # -*- coding: utf-8 -*- from .views import CubeHandler, ConnectionHandler, DeleteHandler from .views import ElementHandler, DashboardHandler, APIElementCubeHandler INCLUDE_URLS = [ (r"/admin/delete/(?P<bucket>[\w-]+)/(?P<slug>[\w-]+)", DeleteHandler), (r"/admin/connection/?(?P<slug>[\w-]...
Add url enter delete element on riak
Add url enter delete element on riak
Python
mit
jgabriellima/mining,avelino/mining,chrisdamba/mining,seagoat/mining,avelino/mining,AndrzejR/mining,mlgruby/mining,mlgruby/mining,mining/mining,mlgruby/mining,mining/mining,chrisdamba/mining,AndrzejR/mining,seagoat/mining,jgabriellima/mining
4e12aea0a5479bad8289cbf6c9f460931d51f701
database.py
database.py
import MySQLdb class database(object): def __init__(self): config = {} execfile("config.py",config) self.db = MySQLdb.connect(config["host"],config["user"],config["password"],config["database"]) def insert(self,txt): dbc = self.db.cursor() try: dbc.execute("insert into " + txt) dbc...
import MySQLdb class database(object): def __init__(self): config = {} execfile("config.py",config) self.db = MySQLdb.connect(config["host"],config["user"],config["password"],config["database"]) self.db.autocommit(True) def insert(self,txt): dbc = self.db.cursor() try: dbc.execute("i...
Add autocommit to 1 to avoid select cache ¿WTF?
Add autocommit to 1 to avoid select cache ¿WTF?
Python
agpl-3.0
p4u/projecte_frigos,p4u/projecte_frigos,p4u/projecte_frigos,p4u/projecte_frigos
f25e0fe435f334e19fc84a9c9458a1bea4a051f9
money/parser/__init__.py
money/parser/__init__.py
import csv from money.models import Movement def parse_csv(raw_csv, parser, header_lines=0): reader = csv.reader(raw_csv, delimiter=',', quotechar='"') rows = [] for row in reader: if reader.line_num > header_lines and row: rows.append(parser.parse_row(row)) return rows def import_movements(data, bank_ac...
import csv from money.models import Movement def parse_csv(raw_csv, parser, header_lines=0, reverse_order=False): reader = csv.reader(raw_csv, delimiter=',', quotechar='"') rows = [] for row in reader: if reader.line_num > header_lines and row: rows.append(parser.parse_row(row)) ...
Allow to reverse the order of the CSV for a proper reading
Allow to reverse the order of the CSV for a proper reading
Python
bsd-3-clause
shakaran/casterly,shakaran/casterly
d52c4340a62802bcd0fcbd68516c5ac66fb10436
ftfy/streamtester/__init__.py
ftfy/streamtester/__init__.py
""" This file defines a general method for evaluating ftfy using data that arrives in a stream. A concrete implementation of it is found in `twitter_tester.py`. """ from __future__ import print_function, unicode_literals from ftfy.fixes import fix_text_encoding from ftfy.chardata import possible_encoding class Stream...
""" This file defines a general method for evaluating ftfy using data that arrives in a stream. A concrete implementation of it is found in `twitter_tester.py`. """ from __future__ import print_function, unicode_literals from ftfy.fixes import fix_encoding from ftfy.chardata import possible_encoding class StreamTeste...
Update function name used in the streamtester
Update function name used in the streamtester
Python
mit
LuminosoInsight/python-ftfy
7a786fd031c3faa057256abc5d9cb47618041696
checks.d/veneur.py
checks.d/veneur.py
import datetime from urlparse import urljoin import requests # project from checks import AgentCheck class Veneur(AgentCheck): VERSION_METRIC_NAME = 'veneur.deployed_version' BUILDAGE_METRIC_NAME = 'veneur.build_age' MAX_AGE_CHECK_NAME = 'veneur.build_age.fresh' # Check that the build is no more th...
import datetime from urlparse import urljoin import requests # project from checks import AgentCheck class Veneur(AgentCheck): VERSION_METRIC_NAME = 'veneur.deployed_version' BUILDAGE_METRIC_NAME = 'veneur.build_age' def check(self, instance): success = 0 host = instance['host'] ...
Configure max build age on the monitoring side
Configure max build age on the monitoring side
Python
mit
stripe/stripe-datadog-checks,stripe/datadog-checks
859d5ce6553b7651f05f27adec28e8c4330ca9bb
handler/supervisor_to_serf.py
handler/supervisor_to_serf.py
#!/usr/bin/env python import json import sys from utils import serf_event def write_stdout(s): sys.stdout.write(s) sys.stdout.flush() def write_stderr(s): sys.stderr.write(s) sys.stderr.flush() def main(): while True: write_stdout('READY\n') # transition from ACKNOWLEDGED to READY ...
#!/usr/bin/env python import json import sys from utils import serf_event def write_stdout(s): sys.stdout.write(s) sys.stdout.flush() def write_stderr(s): sys.stderr.write(s) sys.stderr.flush() def main(): while True: write_stdout('READY\n') # transition from ACKNOWLEDGED to READY ...
Add id of node generating the supervisor event
Add id of node generating the supervisor event
Python
mit
waltermoreira/serfnode,waltermoreira/serfnode,waltermoreira/serfnode
020015cccceb3c2391c4764ee2ec29dfc5c461c6
__init__.py
__init__.py
from . import LayerView def getMetaData(): return { "name": "LayerView", "type": "View" } def register(app): app.getController().addView("LayerView", LayerView.LayerView())
from . import LayerView def getMetaData(): return { "name": "LayerView", "type": "View" } def register(app): return LayerView.LayerView()
Update plugin's register functions to return the object instance instead of performing the registration themselves
Update plugin's register functions to return the object instance instead of performing the registration themselves
Python
agpl-3.0
Curahelper/Cura,bq/Ultimaker-Cura,ad1217/Cura,bq/Ultimaker-Cura,senttech/Cura,lo0ol/Ultimaker-Cura,quillford/Cura,derekhe/Cura,ynotstartups/Wanhao,markwal/Cura,lo0ol/Ultimaker-Cura,senttech/Cura,DeskboxBrazil/Cura,ynotstartups/Wanhao,totalretribution/Cura,ad1217/Cura,fieldOfView/Cura,quillford/Cura,fxtentacle/Cura,dere...
b186ed26e3250d8b02c94f5bb3b394c35986bcf6
__init__.py
__init__.py
""" Spyral, an awesome library for making games. """ __version__ = '0.1.1' __license__ = 'MIT' __author__ = 'Robert Deaton' import compat import memoize import point import camera import sprite import scene import _lib import event import animator import animation import pygame import image import color import rect ...
""" Spyral, an awesome library for making games. """ __version__ = '0.1.1' __license__ = 'MIT' __author__ = 'Robert Deaton' import compat import memoize import point import camera import sprite import scene import _lib import event import animator import animation import pygame import image import color import rect ...
Remove an import which snuck in but does not belong.
Remove an import which snuck in but does not belong. Signed-off-by: Robert Deaton <eb00a885478926d5d594195591fb94a03acb1062@udel.edu>
Python
lgpl-2.1
platipy/spyral
0ec01e1c5770c87faa5300b80c3b9d6bcb0df41b
tcxparser.py
tcxparser.py
"Simple parser for Garmin TCX files." from lxml import objectify __version__ = '0.3.0' class TcxParser: def __init__(self, tcx_file): tree = objectify.parse(tcx_file) self.root = tree.getroot() self.activity = self.root.Activities.Activity @property def latitude(self): ...
"Simple parser for Garmin TCX files." from lxml import objectify __version__ = '0.4.0' class TcxParser: def __init__(self, tcx_file): tree = objectify.parse(tcx_file) self.root = tree.getroot() self.activity = self.root.Activities.Activity @property def latitude(self): ...
Make sure to return python values, not lxml objects
Make sure to return python values, not lxml objects Bump version to 0.4.0
Python
bsd-2-clause
vkurup/python-tcxparser,vkurup/python-tcxparser,SimonArnu/python-tcxparser
3f18e4891b64c45fbda9ae88e9b508b5bc2cb03a
temp2dash.py
temp2dash.py
import json import requests import sys from temperusb import TemperHandler URL="http://dashing:3030/widgets/inside" SCALE=1.0 OFFSET=-3.0 th = TemperHandler() devs = th.get_devices() if len(devs) != 1: print "Expected exactly one TEMPer device, found %d" % len(devs) sys.exit(1) dev = devs[0] dev.set_calibr...
import json import os import requests import sys import time import traceback from temperusb import TemperHandler URL = os.environ['DASHING_URL'] SCALE = float(os.environ['TEMP_SCALE']) OFFSET = float(os.environ['TEMP_OFFSET']) SENSOR = int(os.environ['TEMP_SENSOR']) SLEEP = int(os.environ['SLEEP_TIME']) th = TemperH...
Add infinite loop; Add env vars
Add infinite loop; Add env vars
Python
mit
ps-jay/temp2dash
5768d1ebcfec46e564c8b420773d911c243327ff
dddp/msg.py
dddp/msg.py
"""Django DDP utils for DDP messaging.""" import collections from django.core.serializers import get_serializer _SERIALIZER = None def obj_change_as_msg(obj, msg): """Generate a DDP msg for obj with specified msg type.""" global _SERIALIZER if _SERIALIZER is None: _SERIALIZER = get_serializer('ddp...
"""Django DDP utils for DDP messaging.""" from dddp import THREAD_LOCAL as this from django.core.serializers import get_serializer def serializer_factory(): """Make a new DDP serializer.""" return get_serializer('ddp')() def obj_change_as_msg(obj, msg): """Generate a DDP msg for obj with specified msg t...
Fix non-threadsafe failure in serializer - now using thread local serializer instance.
Fix non-threadsafe failure in serializer - now using thread local serializer instance.
Python
mit
commoncode/django-ddp,commoncode/django-ddp,commoncode/django-ddp,django-ddp/django-ddp,django-ddp/django-ddp,django-ddp/django-ddp,commoncode/django-ddp,django-ddp/django-ddp
12130cef6c9b08e0928ed856972ace3c2000e6f8
mooc_aggregator_restful_api/udacity.py
mooc_aggregator_restful_api/udacity.py
''' This module retrieves the course catalog and overviews of the Udacity API Link to Documentation: https://s3.amazonaws.com/content.udacity-data.com/techdocs/UdacityCourseCatalogAPIDocumentation-v0.pdf ''' import json import requests class UdacityAPI(object): ''' This class defines attributes and method...
''' This module retrieves the course catalog and overviews of the Udacity API Link to Documentation: https://s3.amazonaws.com/content.udacity-data.com/techdocs/UdacityCourseCatalogAPIDocumentation-v0.pdf ''' import json import requests class UdacityAPI(object): ''' This class defines attributes and method...
Fix error accessing class variable
Fix error accessing class variable
Python
mit
ueg1990/mooc_aggregator_restful_api
977cf58125a204010197c95827457843503e2c5b
ideascube/conf/kb_rca_alliancefrancaise.py
ideascube/conf/kb_rca_alliancefrancaise.py
# -*- coding: utf-8 -*- """KoomBook conf""" from .kb import * # noqa LANGUAGE_CODE = 'fr' IDEASCUBE_NAME = 'Alliance française de Bangui'
# -*- coding: utf-8 -*- """KoomBook conf""" from .kb import * # noqa LANGUAGE_CODE = 'fr' IDEASCUBE_NAME = 'Alliance française de Bangui' # Disable BSF Campus for now HOME_CARDS = [card for card in HOME_CARDS if card['id'] != 'bsfcampus']
Disable BSF Campus for RCA Alliance Française
Disable BSF Campus for RCA Alliance Française @barbayellow said so.
Python
agpl-3.0
ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube
cc12728d7160a10f0c182c0cccfde0fd15cadb75
spicedham/basewrapper.py
spicedham/basewrapper.py
class BaseWrapper(object): """ A base class for backend plugins. """ def get_key(self, tag, key, default=None): """ Gets the value held by the tag, key composite key. If it doesn't exist, return default. """ raise NotImplementedError() def get_key_list(sel...
class BaseWrapper(object): """ A base class for backend plugins. """ def reset(self, really): """ Resets the training data to a blank slate. """ if really: raise NotImplementedError() def get_key(self, tag, key, default=None): """ Gets ...
Add a reset function stub
Add a reset function stub Also fix a typo.
Python
mpl-2.0
mozilla/spicedham,mozilla/spicedham
cf6ddfdac8a56194ad1297921a390be541d773cc
app_info.py
app_info.py
# coding=UTF8 import datetime name = "Devo" release_date = datetime.date(2012, 12, 13) version = (1, 0, 0) version_string = ".".join(str(x) for x in version) identifier = "com.iogopro.devo" copyright = u"Copyright © 2010-2012 Luke McCarthy" developer = "Developer: Luke McCarthy <luke@iogopro.co.uk>" company_na...
# coding=UTF8 import datetime name = "Devo" release_date = datetime.date(2012, 12, 13) version = (1, 0, 0) version_string = ".".join(str(x) for x in (version if version[2] != 0 else version[:2])) identifier = "com.iogopro.devo" copyright = u"Copyright © 2010-2012 Luke McCarthy" developer = "Developer: Luke McCa...
Remove last digit of version number if it's 0.
Remove last digit of version number if it's 0.
Python
mit
shaurz/devo
5efddf26176ac778556a3568bf97c2e70daac866
anchorhub/settings/default_settings.py
anchorhub/settings/default_settings.py
""" Defaults for all settings used by AnchorHub """ WRAPPER = "{ }" INPUT = "." OUTPUT = "out-anchorhub" ARGPARSER = { "description": "anchorhub parses through Markdown files and precompiles " "links to specially formatted anchors." } ARGPARSE_INPUT = { "help": "Path of directory tree to b...
""" Defaults for all settings used by AnchorHub """ WRAPPER = '{ }' INPUT = '.' OUTPUT = 'out-anchorhub' ARGPARSER = { 'description': "anchorhub parses through Markdown files and precompiles " "links to specially formatted anchors." } ARGPARSE_INPUT = { 'help': "Path of directory tree to b...
Replace many double quotes with single quotes
Replace many double quotes with single quotes
Python
apache-2.0
samjabrahams/anchorhub
2e7271a33e098d7cdef15207e8caa05e644c3223
changes/buildfailures/testfailure.py
changes/buildfailures/testfailure.py
from __future__ import absolute_import from jinja2 import Markup from changes.buildfailures.base import BuildFailure class TestFailure(BuildFailure): def get_html_label(self, build): link = '/projects/{0}/builds/{1}/tests/?result=failed'.format(build.project.slug, build.id.hex) try: ...
from __future__ import absolute_import from jinja2 import Markup from changes.buildfailures.base import BuildFailure from changes.utils.http import build_uri class TestFailure(BuildFailure): def get_html_label(self, build): link = build_uri('/projects/{0}/builds/{1}/tests/?result=failed'.format(build.pr...
Use full URI for build failure reasons
Use full URI for build failure reasons
Python
apache-2.0
bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,wfxiang08/changes,wfxiang08/changes,bowlofstew/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes,dropbox/changes,dropbox/changes,dropbox/changes
4c303007d6418e2a2f1b2e1778d6b7d0c0573c74
gitfs/views/read_only.py
gitfs/views/read_only.py
import os from errno import EROFS from fuse import FuseOSError from gitfs import FuseMethodNotImplemented from .view import View class ReadOnlyView(View): def getxattr(self, path, fh): raise FuseMethodNotImplemented def open(self, path, flags): return 0 def create(self, path, fh): ...
from errno import EROFS from fuse import FuseOSError from gitfs import FuseMethodNotImplemented from .view import View class ReadOnlyView(View): def getxattr(self, path, fh): raise FuseMethodNotImplemented def open(self, path, flags): return 0 def create(self, path, fh): raise...
Raise read-only fs on touch
Raise read-only fs on touch
Python
apache-2.0
bussiere/gitfs,PressLabs/gitfs,PressLabs/gitfs,ksmaheshkumar/gitfs,rowhit/gitfs
a307c5fc2555d282dfa6193cdbcfb2d15e185c0c
aq/parsers.py
aq/parsers.py
from collections import namedtuple import collections from six import string_types from aq.errors import QueryParsingError from aq.select_parser import select_stmt, ParseException TableId = namedtuple('TableId', ('database', 'table', 'alias')) QueryMetadata = namedtuple('QueryMetadata', ('tables',)) class SelectP...
import collections from collections import namedtuple from six import string_types from aq.errors import QueryParsingError from aq.select_parser import select_stmt, ParseException TableId = namedtuple('TableId', ('database', 'table', 'alias')) QueryMetadata = namedtuple('QueryMetadata', ('tables',)) class SelectPa...
Allow query without table to run
Allow query without table to run
Python
mit
lebinh/aq
583a6319230b89a5f19c26e5bab83e28a5a4792e
pywps/processes/dummyprocess.py
pywps/processes/dummyprocess.py
""" DummyProcess to check the WPS structure Author: Jorge de Jesus (jorge.de-jesus@jrc.it) as suggested by Kor de Jong """ from pywps.Process import WPSProcess class Process(WPSProcess): def __init__(self): # init process WPSProcess.__init__(self, i...
""" DummyProcess to check the WPS structure Author: Jorge de Jesus (jorge.jesus@gmail.com) as suggested by Kor de Jong """ from pywps.Process import WPSProcess import types class Process(WPSProcess): def __init__(self): # init process WPSProcess.__init__(self, ...
Fix the but There is an error (cannot concatenate str and int objects) when the user does not specify the inputs.
Fix the but There is an error (cannot concatenate str and int objects) when the user does not specify the inputs.
Python
mit
ricardogsilva/PyWPS,jonas-eberle/pywps,geopython/pywps,ldesousa/PyWPS,bird-house/PyWPS,jachym/PyWPS,tomkralidis/pywps
454c7d322af3328279582aef629736b92c87e869
backports/__init__.py
backports/__init__.py
# This file is part of a backport of 'lzma' included with Python 3.3, # exposed under the namespace of backports.lzma following the conventions # laid down here: http://pypi.python.org/pypi/backports/1.0 # Backports homepage: http://bitbucket.org/brandon/backports # A Python "namespace package" http://www.python.org/d...
# This file is part of a backport of 'lzma' included with Python 3.3, # exposed under the namespace of backports.lzma following the conventions # laid down here: http://pypi.python.org/pypi/backports/1.0 # Backports homepage: http://bitbucket.org/brandon/backports # A Python "namespace package" http://www.python.org/d...
Revert "It seems the mechanism to declare a namespace package changed."
Revert "It seems the mechanism to declare a namespace package changed." This reverts commit 68658fe9a3fee91963944937b80fcdaf3af4c8a1. Changing the backport to use setuptools namespaces broke all the other packages using the backports namespace. Switch back to standard python namespaces.
Python
bsd-3-clause
peterjc/backports.lzma,peterjc/backports.lzma
d1be7f345529594ba25ed5d0f22e544735a64404
qubs_data_centre/urls.py
qubs_data_centre/urls.py
from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^api/', include('api.urls')), url(r'^admin/', admin.site.urls), ]
from django.conf.urls import url, include from django.contrib import admin admin.site.site_header = 'QUBS Data Centre Admin' urlpatterns = [ url(r'^api/', include('api.urls')), url(r'^admin/', admin.site.urls), ]
Add a custom admin site header.
Add a custom admin site header.
Python
apache-2.0
qubs/climate-data-api,qubs/climate-data-api,qubs/data-centre,qubs/data-centre
bf336d99484cc3804f469631b513a927940ada30
profile_collection/startup/50-scans.py
profile_collection/startup/50-scans.py
# vim: sw=4 ts=4 sts expandtab smarttab # HXN step-scan configuration import hxntools.scans from bluesky.global_state import get_gs gs = get_gs() hxntools.scans.setup() ct = hxntools.scans.count ascan = hxntools.scans.absolute_scan dscan = hxntools.scans.relative_scan fermat = hxntools.scans.relative_fermat spiral =...
# vim: sw=4 ts=4 sts expandtab smarttab # HXN step-scan configuration import hxntools.scans from bluesky.global_state import get_gs gs = get_gs() hxntools.scans.setup() ct = hxntools.scans.count ascan = hxntools.scans.absolute_scan dscan = hxntools.scans.relative_scan fermat = hxntools.scans.relative_fermat spiral =...
Add scan_steps wrapper for scan_nd
Add scan_steps wrapper for scan_nd
Python
bsd-2-clause
NSLS-II-HXN/ipython_ophyd,NSLS-II-HXN/ipython_ophyd
a537f049bfb61488a056333d362d9983e8e9f88d
2020/10/p1.py
2020/10/p1.py
# Python 3.8.3 def get_input(): with open('input.txt', 'r') as f: return set(int(i) for i in f.read().split()) def main(): puzzle = get_input() last_joltage = 0 one_jolt = 0 three_jolts = 1 # this is bad lmao while len(puzzle) != 0: if last_joltage + 1 in puzzle: ...
# Python 3.8.3 def get_input(): with open('input.txt', 'r') as f: return set(int(i) for i in f.read().split()) def main(): puzzle = get_input() last_joltage = 0 one_jolt = 0 three_jolts = 1 while len(puzzle) != 0: if last_joltage + 1 in puzzle: last_joltage = last_...
Fix minor issues in 2020.10.1 file
Fix minor issues in 2020.10.1 file The comment about the 1 being bad was incorrect, in fact it was good. I had forgotten about adding the extra three-jolt difference for the final adapter in the device, and didn't make the connection between it and the three-jolt count being one short lol.
Python
mit
foxscotch/advent-of-code,foxscotch/advent-of-code
77ddff664ad1e10037a43c3ffabd816387c35e42
rotational-cipher/rotational_cipher.py
rotational-cipher/rotational_cipher.py
import string UPPER = string.ascii_uppercase LOWER = string.ascii_lowercase def rotate(s, n): rules = shift_rules(n) return "".join(map(lambda k: rules.get(k, k), s)) def shift_rules(n): shifted = UPPER[n:] + UPPER[:n] + LOWER[n:] + LOWER[:n] return {k:v for k,v in zip(UPPER+LOWER, shifted)}
import string UPPER = string.ascii_uppercase LOWER = string.ascii_lowercase def rotate(s, n): rules = shift_rules(n) return "".join(rules.get(ch, ch) for ch in s) def shift_rules(n): shifted = UPPER[n:] + UPPER[:n] + LOWER[n:] + LOWER[:n] return {k:v for k,v in zip(UPPER+LOWER, shifted)}
Use a comprehension instead of a lambda function
Use a comprehension instead of a lambda function
Python
agpl-3.0
CubicComet/exercism-python-solutions
513c7a2f5c5fb5a8c47b3173a8d5854755f7928f
pylab/website/tests/test_about_page.py
pylab/website/tests/test_about_page.py
import datetime from django_webtest import WebTest from django.contrib.auth.models import User from pylab.core.models import Event class AboutPageTests(WebTest): def setUp(self): self.user = User.objects.create(username='u1') def test_no_events_on_about_page(self): resp = self.app.get('/ab...
import datetime from django_webtest import WebTest from pylab.core.models import Event from pylab.core.factories import EventFactory class AboutPageTests(WebTest): def test_no_events_on_about_page(self): resp = self.app.get('/about/') self.assertEqual(resp.status_int, 200) self.assertTr...
Use factories instead of creating instance from model
Use factories instead of creating instance from model
Python
agpl-3.0
python-dirbtuves/website,python-dirbtuves/website,python-dirbtuves/website
df6b13a70241b616f49d4dcc25073084c371f5b1
share/models/creative/base.py
share/models/creative/base.py
from django.db import models from share.models.base import ShareObject from share.models.people import Person from share.models.base import TypedShareObjectMeta from share.models.creative.meta import Venue, Institution, Funder, Award, Tag from share.models.fields import ShareForeignKey, ShareManyToManyField class Ab...
from django.db import models from share.models.base import ShareObject from share.models.people import Person from share.models.base import TypedShareObjectMeta from share.models.creative.meta import Venue, Institution, Funder, Award, Tag from share.models.fields import ShareForeignKey, ShareManyToManyField class Ab...
Swap out license with rights
Swap out license with rights
Python
apache-2.0
CenterForOpenScience/SHARE,aaxelb/SHARE,zamattiac/SHARE,zamattiac/SHARE,CenterForOpenScience/SHARE,CenterForOpenScience/SHARE,aaxelb/SHARE,zamattiac/SHARE,laurenbarker/SHARE,aaxelb/SHARE,laurenbarker/SHARE,laurenbarker/SHARE
9f44888c00d29bd1d1a53eb09ab90b61f33c5e05
awx/main/migrations/0002_v300_changes.py
awx/main/migrations/0002_v300_changes.py
# -*- coding: utf-8 -*- # Copyright (c) 2016 Ansible, Inc. # All Rights Reserved. from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER...
# -*- coding: utf-8 -*- # Copyright (c) 2016 Ansible, Inc. # All Rights Reserved. from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER...
Update existing settings migration with minor field change.
Update existing settings migration with minor field change.
Python
apache-2.0
snahelou/awx,wwitzel3/awx,snahelou/awx,wwitzel3/awx,snahelou/awx,wwitzel3/awx,snahelou/awx,wwitzel3/awx
18618a56ce674c479a0737dcabd4a47913ae2dde
scripts/compare_dir.py
scripts/compare_dir.py
import os dropboxFiles = [] localFiles = [] for dirpath, dirnames, filenames in os.walk( '/media/itto/TOSHIBA EXT/Photos/Dropbox/ITTO/Southeast Asia 2017'): dropboxFiles += filenames for dirpath, dirnames, filenames in os.walk( '/media/itto/TOSHIBA EXT/Photos/Southeast Asia'): if ('Process' no...
import os from shutil import copyfile FOLDER_A = '/media/itto/TOSHIBA EXT/Photos/Southeast Asia' FOLDER_B = '/media/itto/disk/PRIVATE/AVCHD/BDMV/STREAM' files_a = [] files_b = [] for dirpath, dirnames, filenames in os.walk(FOLDER_A): files_a += filenames for dirpath, dirnames, filenames in os.walk(FOLDER_B): ...
Add functionality to copy any missing files to the other folder
Add functionality to copy any missing files to the other folder
Python
mit
itko/itko.github.io,itko/itko.github.io,itko/itko.github.io,itko/itko.github.io
31231afea71b3fd9213b39cf1bb32e10b2a9e843
djangovirtualpos/admin.py
djangovirtualpos/admin.py
# coding=utf-8 from django.contrib import admin from djangovirtualpos.models import VirtualPointOfSale, VPOSRefundOperation, VPOSCeca, VPOSRedsys, VPOSSantanderElavon, VPOSPaypal admin.site.register(VirtualPointOfSale) admin.site.register(VPOSRefundOperation) admin.site.register(VPOSCeca) admin.site.register(VPOSReds...
# coding=utf-8 from django.contrib import admin from djangovirtualpos.models import VirtualPointOfSale, VPOSRefundOperation, VPOSCeca, VPOSRedsys, VPOSSantanderElavon, VPOSPaypal, VPOSBitpay admin.site.register(VirtualPointOfSale) admin.site.register(VPOSRefundOperation) admin.site.register(VPOSCeca) admin.site.regis...
Add Bitpay config model to Django Admin panel
Add Bitpay config model to Django Admin panel
Python
mit
intelligenia/django-virtual-pos,intelligenia/django-virtual-pos,intelligenia/django-virtual-pos
7e6dc283dbecf4bf9674559198b4a2c06e9f4c2e
spacy/tests/regression/test_issue1799.py
spacy/tests/regression/test_issue1799.py
'''Test sentence boundaries are deserialized correctly, even for non-projective sentences.''' import pytest import numpy from ... tokens import Doc from ... vocab import Vocab from ... attrs import HEAD, DEP def test_issue1799(): problem_sentence = 'Just what I was looking for.' heads_deps = numpy.asarray([[...
'''Test sentence boundaries are deserialized correctly, even for non-projective sentences.''' from __future__ import unicode_literals import pytest import numpy from ... tokens import Doc from ... vocab import Vocab from ... attrs import HEAD, DEP def test_issue1799(): problem_sentence = 'Just what I was looking...
Fix unicode import in test
Fix unicode import in test
Python
mit
aikramer2/spaCy,aikramer2/spaCy,explosion/spaCy,spacy-io/spaCy,explosion/spaCy,honnibal/spaCy,explosion/spaCy,explosion/spaCy,spacy-io/spaCy,recognai/spaCy,honnibal/spaCy,spacy-io/spaCy,honnibal/spaCy,explosion/spaCy,aikramer2/spaCy,aikramer2/spaCy,spacy-io/spaCy,aikramer2/spaCy,recognai/spaCy,spacy-io/spaCy,aikramer2/...
2cd19b395f4320330b66dff1ef98d149f3a40a31
ckanext/syndicate/tests/test_plugin.py
ckanext/syndicate/tests/test_plugin.py
from mock import patch import unittest import ckan.model as model from ckan.model.domain_object import DomainObjectOperation from ckanext.syndicate.plugin import SyndicatePlugin class TestPlugin(unittest.TestCase): def test_notify_syndicates_task(self): entity = model.Package() entity.extras = ...
from mock import patch import unittest import ckan.model as model from ckan.model.domain_object import DomainObjectOperation from ckanext.syndicate.plugin import SyndicatePlugin class TestNotify(unittest.TestCase): def setUp(self): super(TestNotify, self).setUp() self.entity = model.Package() ...
Add test for notify dataset/update
Add test for notify dataset/update
Python
agpl-3.0
aptivate/ckanext-syndicate,sorki/ckanext-redmine-autoissues,aptivate/ckanext-syndicate,sorki/ckanext-redmine-autoissues
80a1912ce69fd356d6c54bb00f946fbc7874a9ce
bluecanary/set_cloudwatch_alarm.py
bluecanary/set_cloudwatch_alarm.py
import boto3 from bluecanary.exceptions import NamespaceError from bluecanary.utilities import throttle @throttle() def set_cloudwatch_alarm(identifier, **kwargs): if not kwargs.get('Dimensions'): kwargs['Dimensions'] = _get_dimensions(identifier, **kwargs) if not kwargs.get('AlarmName'): kw...
import boto3 from bluecanary.exceptions import NamespaceError from bluecanary.utilities import throttle @throttle() def set_cloudwatch_alarm(identifier, **kwargs): if not kwargs.get('Dimensions'): kwargs['Dimensions'] = _get_dimensions(identifier, **kwargs) if not kwargs.get('AlarmName'): kw...
Allow multiple alarms for same metric type
Allow multiple alarms for same metric type
Python
mit
voxy/bluecanary
7611a4b3e064868c37b9f52778c8fe9f721e86c5
polyaxon/events/management/commands/monitor_namespace.py
polyaxon/events/management/commands/monitor_namespace.py
import time from kubernetes.client.rest import ApiException from django.conf import settings from clusters.models import Cluster from events.management.commands._base_monitor import BaseMonitorCommand from events.monitors import namespace from polyaxon_k8s.manager import K8SManager class Command(BaseMonitorCommand...
import time from kubernetes.client.rest import ApiException from django.conf import settings from django.db import InterfaceError, ProgrammingError, OperationalError from clusters.models import Cluster from events.management.commands._base_monitor import BaseMonitorCommand from events.monitors import namespace from ...
Update namespace monitor with exception handling
Update namespace monitor with exception handling
Python
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
2a852c3ca1ff30cb02740f7934d97c1fe2da3bbe
compress.py
compress.py
""" compression """ class Compress(): """Compress""" def encode(self, string): """Encodes string to byte representation""" return b'0' def decode(self, byteString): """Decodes bytes into a text string""" return ""
""" compression """ import Queue as queue class HuffmanNode: """Node in the Huffman coding tree""" def __init__(self, symbol, freq): self.parent = None self.children = [] self.symbol = symbol self.freq = freq def set_parent(self, node): node.add_child(self) ...
Build tree for huffman coding
Build tree for huffman coding
Python
apache-2.0
rylans/text-compression-english
3b412830710018abadacd148be544b4bfb1ec2f0
compare_mt/formatting.py
compare_mt/formatting.py
import re class Formatter(object): pat_square_open = re.compile("\[") pat_square_closed = re.compile("\]") pat_lt = re.compile("<") pat_gt = re.compile(">") latex_substitutions = { pat_square_open: "{[}", pat_square_closed: "{]}", pat_lt: r"\\textless", pat_gt: r...
import re class Formatter(object): latex_substitutions = { re.compile("\["): "{[}", re.compile("\]"): "{]}", re.compile("<"): r"\\textless", re.compile(">"): r"\\textgreater" } def __init__(self, decimals=4): self.set_decimals(decimals) def set_decimals(self, ...
Move definition of substitution patterns inside the latex_substitutions dictionary
Move definition of substitution patterns inside the latex_substitutions dictionary
Python
bsd-3-clause
neulab/compare-mt,neulab/compare-mt
8b598333c06698185762cc98e414853e03c427f2
src/reviews/resources.py
src/reviews/resources.py
from import_export import fields, resources from .models import Review class ReviewResource(resources.ModelResource): reviewer = fields.Field( attribute='reviewer__email', readonly=True, ) proposal = fields.Field( attribute='proposal__title', readonly=True, ) cla...
from import_export import fields, resources from .models import Review class ReviewResource(resources.ModelResource): reviewer = fields.Field( attribute='reviewer__email', readonly=True, ) proposal = fields.Field( attribute='proposal__title', readonly=True, ) stag...
Mark fields except appropriateness as readonly
Mark fields except appropriateness as readonly
Python
mit
pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016
b355d61edc413f8fd60c7ce3ac37d9c1da7caa67
tests/nimoy/runner/test_spec_finder.py
tests/nimoy/runner/test_spec_finder.py
import tempfile import unittest import os from nimoy.runner.spec_finder import SpecFinder class TestSpecFinder(unittest.TestCase): def setUp(self): self.temp_spec = tempfile.NamedTemporaryFile(suffix='_spec.py') def tearDown(self): os.remove(self.temp_spec.name) def test_implicit_locatio...
import os import tempfile import unittest from nimoy.runner.spec_finder import SpecFinder class TestSpecFinder(unittest.TestCase): def setUp(self): self.temp_spec = tempfile.NamedTemporaryFile(suffix='_spec.py') def test_implicit_location(self): spec_locations = SpecFinder(os.path.dirname(se...
Remove the code cleans up the temp file as temp files are already automatically cleaned
Remove the code cleans up the temp file as temp files are already automatically cleaned
Python
apache-2.0
Luftzig/nimoy,browncoat-ninjas/nimoy
ddce385c22284ec68797b512fade8599c76ce3d1
datawire/manage.py
datawire/manage.py
from flask.ext.script import Manager from datawire.core import app, db from datawire.model import Service from datawire.views import index manager = Manager(app) @manager.command def create_db(): """ Create the database entities. """ db.create_all() if __name__ == "__main__": manager.run()
from flask.ext.script import Manager from datawire.core import app, db from datawire.model import User from datawire.views import index manager = Manager(app) @manager.command def createdb(): """ Create the database entities. """ db.create_all() admin_data = {'screen_name': 'admin', 'display_name': 'Sys...
Create an admin user on db initialisation.
Create an admin user on db initialisation.
Python
mit
arc64/datawi.re,arc64/datawi.re,arc64/datawi.re
bdcdeee5c913f65dc2ea7f611a0ca0882b4e910f
tests/views/test_view.py
tests/views/test_view.py
# Copyright 2014 PressLabs SRL # # 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 2014 PressLabs SRL # # 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,...
Update test for the getattr method.
Update test for the getattr method.
Python
apache-2.0
rowhit/gitfs,PressLabs/gitfs,ksmaheshkumar/gitfs,PressLabs/gitfs,bussiere/gitfs
c37af8399decdbe3e1303f236891d694985b9040
consulrest/keyvalue.py
consulrest/keyvalue.py
import json import re import requests class KeyValue(object): def __init__(self, url): self._url = "%s/kv" % url def _get(self, key, recurse=None, keys=None): url = self._url + '/' + key params = dict() if recurse is not None: params['recurse'] = True if k...
import json import re import requests class KeyValue(object): def __init__(self, url): self._url = "%s/kv" % url def _get(self, key, recurse=None, keys=None): url = self._url + '/' + key params = dict() if recurse is not None: params['recurse'] = True if k...
Allow use of Check-And-Set option and raise exception if status is 4xx or 5xx
Allow use of Check-And-Set option and raise exception if status is 4xx or 5xx
Python
mit
vcoque/consul-ri
244f9ad92683a1b3a3bc8409724fea9c671f38b6
src/mcedit2/widgets/layout.py
src/mcedit2/widgets/layout.py
from __future__ import absolute_import, division, print_function, unicode_literals from PySide import QtGui def _Box(box, *a): for arg in a: if isinstance(arg, tuple): item = arg[0] else: item = arg arg = (item,) if isinstance(item, QtGui.QLayout): ...
from __future__ import absolute_import, division, print_function, unicode_literals from PySide import QtGui def _Box(box, *a): for arg in a: if isinstance(arg, tuple): item = arg[0] else: item = arg arg = (item,) if isinstance(item, QtGui.QLayout): ...
Check margin keyword to Row/Column is not None
Check margin keyword to Row/Column is not None
Python
bsd-3-clause
Rubisk/mcedit2,Rubisk/mcedit2,vorburger/mcedit2,vorburger/mcedit2
bd6bb741db3b5403ec8ee590a919b0f9ff29bf14
plugins/logging.py
plugins/logging.py
import logging import sublime PACKAGE_NAME = __package__.split(".", 1)[0] logging.basicConfig( level=logging.ERROR, format="%(name)s [%(levelname)s]: %(message)s" ) logger = logging.getLogger(PACKAGE_NAME) def load_logger(): """ Subscribe to Markdown changes in to get log level from user settings. ...
import logging import sublime PACKAGE_NAME = __package__.split(".", 1)[0] logging.basicConfig( level=logging.ERROR, format="%(name)s [%(levelname)s]: %(message)s" ) logger = logging.getLogger(PACKAGE_NAME) def load_logger(): """ Subscribe to Preferences changes in to get log level from user settings...
Read logger config from Preferences
Plugins: Read logger config from Preferences required due to 9b30d85d1b60fef4f4d7c35868dd406f0c5d94f3
Python
mit
SublimeText-Markdown/MarkdownEditing
c6298a573dc3188b8c57954287d78e7da253483a
lot/urls.py
lot/urls.py
# -*- coding: utf-8 -*- from django.conf.urls import patterns, url from . import views urlpatterns = patterns("", url(r"^login/(?P<uuid>[\da-f]{8}-([\da-f]{4}-){3}[\da-f]{12})/$", views.LOTLogin.as_view(), name="login"), )
# -*- coding: utf-8 -*- from django.conf.urls import url from . import views urlpatterns = [ url(r"^login/(?P<uuid>[\da-f]{8}-([\da-f]{4}-){3}[\da-f]{12})/$", views.LOTLogin.as_view(), name="login"), ]
Update to new-style urlpatterns format
Update to new-style urlpatterns format
Python
bsd-3-clause
ABASystems/django-lot
d86144aa09ea0d6a679a661b0b2f887d6a2a725d
examples/python/values.py
examples/python/values.py
#! /usr/bin/env python # # values.py # """ An example of using values via Python API """ from opencog.atomspace import AtomSpace, TruthValue from opencog.type_constructors import * a = AtomSpace() set_type_ctor_atomspace(a) a = FloatValue([1.0, 2.0, 3.0]) b = FloatValue([1.0, 2.0, 3.0]) c = FloatValue(1.0) print('{}...
#! /usr/bin/env python # # values.py # """ An example of using values via Python API """ from opencog.atomspace import AtomSpace, TruthValue from opencog.type_constructors import * a = AtomSpace() set_type_ctor_atomspace(a) a = FloatValue([1.0, 2.0, 3.0]) b = FloatValue([1.0, 2.0, 3.0]) c = FloatValue(1.0) print('{}...
Add example of Value to Python list conversion
Add example of Value to Python list conversion
Python
agpl-3.0
rTreutlein/atomspace,AmeBel/atomspace,AmeBel/atomspace,rTreutlein/atomspace,AmeBel/atomspace,rTreutlein/atomspace,rTreutlein/atomspace,AmeBel/atomspace,AmeBel/atomspace,rTreutlein/atomspace
c1fdbcf724ac7cc713cf3f5f3ca3cfca50007e34
application.py
application.py
#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager application = create_app(os.getenv('FLASH_CONFIG') or 'default') manager = Manager(application) if __name__ == '__main__': manager.run()
#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager, Server application = create_app(os.getenv('FLASH_CONFIG') or 'default') manager = Manager(application) manager.add_command("runserver", Server(port=5002)) if __name__ == '__main__': manager.run()
Update to run on port 5002
Update to run on port 5002 For development we will want to run multiple apps, so they should each bind to a different port number.
Python
mit
mtekel/digitalmarketplace-buyer-frontend,mtekel/digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,mtekel/digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmar...
07fd8bf23917e18ba419859d788d9f51735f3b39
conda_gitenv/__init__.py
conda_gitenv/__init__.py
from __future__ import absolute_import, division, print_function, unicode_literals from distutils.version import StrictVersion from conda import __version__ as CONDA_VERSION from ._version import get_versions __version__ = get_versions()['version'] del get_versions _conda_base = StrictVersion('4.3.0') _conda_supp...
from __future__ import absolute_import, division, print_function, unicode_literals from distutils.version import StrictVersion from conda import __version__ as CONDA_VERSION from ._version import get_versions __version__ = get_versions()['version'] del get_versions _conda_base = StrictVersion('4.3.0') _conda_vers...
Update minimum conda version diagnostic
Update minimum conda version diagnostic
Python
bsd-3-clause
SciTools/conda-gitenv
845aee2341b3beeb6c96c0a2b830e2729f5f30d2
tests/GrammarCopyTest.py
tests/GrammarCopyTest.py
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 16.08.2017 19:16 :Licence GNUv3 Part of grammpy """ from unittest import main, TestCase from grammpy import * class GrammarCopyTest(TestCase): pass if __name__ == '__main__': main()
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 16.08.2017 19:16 :Licence GNUv3 Part of grammpy """ from copy import deepcopy, copy from unittest import main, TestCase from grammpy import * class A(Nonterminal): pass class B(Nonterminal): pass class RuleAtoB(Rule): rule = ([A], [B]) cla...
Add tests for grammar's __clone__ method
Add tests for grammar's __clone__ method
Python
mit
PatrikValkovic/grammpy
41df71518ba23460194194cb82d9dbb183afcc19
gtlaunch.py
gtlaunch.py
#/usr/bin/env python import json import os import subprocess def run(): with open('gtlaunch.json', 'r') as fp: config = json.load(fp) project = config['test'] args = ['gnome-terminal', '--maximize'] args.extend(['--working-directory', os.path.expanduser(project['cwd'])]) for idx, tab in e...
#/usr/bin/env python import argparse import json import os import subprocess def run(args): with open(os.path.expanduser(args.config), 'r') as fp: config = json.load(fp) project = config['test'] args = ['gnome-terminal', '--maximize'] args.extend(['--working-directory', os.path.expanduser(pro...
Use argparse to locate config file.
Use argparse to locate config file.
Python
mit
GoldenLine/gtlaunch
7531fbb5cea5ef71f75e344c6a9e84e05377573a
jarn/mkrelease/process.py
jarn/mkrelease/process.py
import os import tee class Process(object): """Process related functions using the tee module (mostly).""" def __init__(self, quiet=False, env=None): self.quiet = quiet self.env = env def popen(self, cmd, echo=True, echo2=True): if self.quiet: echo = echo2 = False ...
import os import tee class Process(object): """Process related functions using the tee module (mostly).""" def __init__(self, quiet=False, env=None): self.quiet = quiet self.env = env def popen(self, cmd, echo=True, echo2=True): if self.quiet: echo = echo2 = False ...
Remove NotEmpty filter from Process.system.
Remove NotEmpty filter from Process.system.
Python
bsd-2-clause
Jarn/jarn.mkrelease
3864ef6773000d516ee6542a11db3c3b636d5b49
test/framework/killer.py
test/framework/killer.py
# Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT # All rights reserved. This work is under a BSD license, see LICENSE.TXT. from __future__ import print_function import sys, os, signal, time, subprocess32 def _killer(pid, sleep_time, num_kills): print("\nKiller going to sleep for", sleep_time, "sec...
# Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT # All rights reserved. This work is under a BSD license, see LICENSE.TXT. from __future__ import print_function import sys, os, signal, time, subprocess32 sys.path.append('../../..') from jenkinsflow.mocked import hyperspeed def _killer(pid, sleep_time...
Prepare kill test for mock - use hyperspeed
Prepare kill test for mock - use hyperspeed
Python
bsd-3-clause
lhupfeldt/jenkinsflow,lechat/jenkinsflow,lhupfeldt/jenkinsflow,lhupfeldt/jenkinsflow,lechat/jenkinsflow,lhupfeldt/jenkinsflow,lechat/jenkinsflow,lechat/jenkinsflow
7d9e3dd9a3eca107ddcdb7304e0b0c3f61b0af18
test/mitmproxy/addons/test_intercept.py
test/mitmproxy/addons/test_intercept.py
import pytest from mitmproxy.addons import intercept from mitmproxy import exceptions from mitmproxy.test import taddons from mitmproxy.test import tflow def test_simple(): r = intercept.Intercept() with taddons.context(r) as tctx: assert not r.filt tctx.configure(r, intercept="~q") a...
import pytest from mitmproxy.addons import intercept from mitmproxy import exceptions from mitmproxy.test import taddons from mitmproxy.test import tflow def test_simple(): r = intercept.Intercept() with taddons.context(r) as tctx: assert not r.filt tctx.configure(r, intercept="~q") a...
Add tests for TCP flow interception
Add tests for TCP flow interception
Python
mit
mitmproxy/mitmproxy,mitmproxy/mitmproxy,mhils/mitmproxy,vhaupert/mitmproxy,Kriechi/mitmproxy,mitmproxy/mitmproxy,Kriechi/mitmproxy,mhils/mitmproxy,Kriechi/mitmproxy,mhils/mitmproxy,vhaupert/mitmproxy,Kriechi/mitmproxy,mitmproxy/mitmproxy,mitmproxy/mitmproxy,mhils/mitmproxy,vhaupert/mitmproxy,mhils/mitmproxy,vhaupert/mi...
ca4a312e09138d295932d200cebf787b911cd2b2
blog/tests.py
blog/tests.py
from django.test import TestCase from django.urls import reverse from .models import Post # Create your tests here. class PostModelTest(TestCase): def test_render_markdown(self): p = Post(content='aa') self.assertEqual(p.html_content, '<p>aa</p>\n') class PostViewTest(TestCase): def test_p...
from django.test import TestCase from django.urls import reverse from .models import Post # Create your tests here. class PostModelTest(TestCase): def test_render_markdown(self): p = Post(content='aa') self.assertEqual(p.html_content, '<p>aa</p>\n') class PostViewTest(TestCase): def test_p...
Test fail not to deploy
Test fail not to deploy
Python
mit
graycarl/iamhhb,graycarl/iamhhb,graycarl/iamhhb,graycarl/iamhhb
ae600fdf602d12f1a2f8082df49693117fba2596
test/test_cxx_imports.py
test/test_cxx_imports.py
def test_cxx_import(): from microscopes.mixture.model import \ state, fixed_state, \ bind, bind_fixed, \ initialize, initialize_fixed, \ deserialize, deserialize_fixed assert state and fixed_state assert bind and bind_fixed assert initialize and initialize_fixed asser...
def test_cxx_import(): from microscopes.mixture.model import \ state, \ bind, \ initialize, \ deserialize assert state assert bind assert initialize assert deserialize
Remove fixed references from test_cxx.py
Remove fixed references from test_cxx.py
Python
bsd-3-clause
datamicroscopes/mixturemodel,datamicroscopes/mixturemodel,datamicroscopes/mixturemodel
dea384bf25e48c0f9a5dd7bc324a1a611e41c7dd
flask_jq.py
flask_jq.py
from flask import Flask, jsonify, render_template, request, current_app, redirect, flash from functools import wraps import json app = Flask(__name__) def jsonp(f): '''Wrap JSONified output for JSONP''' @wraps(f) def decorated_function(*args, **kwargs): callback = request.args.get('callback', False) if callbac...
from flask import Flask, jsonify, render_template, request, current_app, redirect, flash from functools import wraps import json app = Flask(__name__) def jsonp(f): '''Wrap JSONified output for JSONP''' @wraps(f) def decorated_function(*args, **kwargs): callback = request.args.get('callback', False) if callbac...
Add route for commenting page test
Add route for commenting page test
Python
mit
avidas/flask-jquery,avidas/flask-jquery,avidas/flask-jquery
1685dcf871e529220f98f92a75833c388223f2c8
features.py
features.py
from re import search "Some baseline features for testing the classifier." def make_searcher(substring, field='content'): def result(datum): if search(substring, datum.__dict__[field]): return ['has_substring_' + substring] else: return [] return result def f2(datum): return [str(len(datum.content) % 8)...
from re import search, IGNORECASE "Some baseline features for testing the classifier." def make_searcher(substring, field='content', flags=IGNORECASE): def result(datum): if search(substring, datum.__dict__[field], flags): return ['has_substring_' + substring] else: return [] return result def f2(datum):...
Allow for case insensitivity (and any other flag).
Allow for case insensitivity (and any other flag).
Python
isc
aftran/classify-outbreak
ddc6a446a5b728d0ae6190cfca5b8962cac89b7c
twisted/plugins/vumi_worker_starter.py
twisted/plugins/vumi_worker_starter.py
from zope.interface import implements from twisted.application.service import IServiceMaker from twisted.plugin import IPlugin from vumi.start_worker import VumiService, StartWorkerOptions # This create the service, runnable on command line with twistd class VumiServiceMaker(object): implements(IServiceMaker, IP...
from zope.interface import implements from twisted.application.service import IServiceMaker from twisted.plugin import IPlugin from vumi.start_worker import VumiService, StartWorkerOptions # This create the service, runnable on command line with twistd class VumiServiceMaker(object): implements(IServiceMaker, IP...
Make vumi worker service available as vumi_worker and deprecate start_worker.
Make vumi worker service available as vumi_worker and deprecate start_worker.
Python
bsd-3-clause
TouK/vumi,harrissoerja/vumi,TouK/vumi,harrissoerja/vumi,vishwaprakashmishra/xmatrix,vishwaprakashmishra/xmatrix,harrissoerja/vumi,TouK/vumi,vishwaprakashmishra/xmatrix
f374ac8bb3789ed533a2371eae78a9f98e1def60
tests/integrations/current/test_read.py
tests/integrations/current/test_read.py
import os from tests.integrations.base import BaseTest class TestReadCurrentView(BaseTest): def test_listdirs(self): assert os.listdir("%s/current" % self.mount_path) == ['testing', 'me']
import os from tests.integrations.base import BaseTest class TestReadCurrentView(BaseTest): def test_listdirs(self): assert os.listdir("%s/current" % self.mount_path) == ['testing', 'me'] def test_read_from_a_file(self): with open("%s/current/testing" % self.mount_path) as f: ass...
Test file reading for current view
Test file reading for current view
Python
apache-2.0
PressLabs/gitfs,ksmaheshkumar/gitfs,bussiere/gitfs,rowhit/gitfs,PressLabs/gitfs
c4f51fd3c030f3d88f8545a94698ed4e9f5ef9bc
timpani/webserver/webhelpers.py
timpani/webserver/webhelpers.py
import flask from .. import auth import urllib.parse def checkForSession(): if "uid" in flask.session: session = auth.validateSession(flask.session["uid"]) if session != None: return session return None def redirectAndSave(path): flask.session["donePage"] = urllib.parse.urlparse(flask.request.url).path re...
import flask from .. import auth import urllib.parse def checkForSession(): if "uid" in flask.session: session = auth.validateSession(flask.session["uid"]) if session != None: return session return None def redirectAndSave(path): flask.session["donePage"] = urllib.parse.urlparse(flask.request.url).path re...
Remove unneeded recoverFromRedirect and add markRedirectAsRecovered
Remove unneeded recoverFromRedirect and add markRedirectAsRecovered
Python
mit
ollien/Timpani,ollien/Timpani,ollien/Timpani
a017c75c7e2b8915cd2ab0bce29a0ed68c306f38
get_data.py
get_data.py
import urllib, json import numpy as np from secrets import API_KEY # JCDECAUX's API KEY def retrieve_data(contract="paris"): url = "https://api.jcdecaux.com/vls/v1/stations?apiKey={}&contract={}".format(API_KEY, contract) response = urllib.urlopen(url) data = json.loads(response.read()) return data d...
import urllib, json import numpy as np import time from secrets import API_KEY # JCDECAUX's API KEY def retrieve_data(contract="paris"): url = "https://api.jcdecaux.com/vls/v1/stations?apiKey={}&contract={}".format(API_KEY, contract) response = urllib.urlopen(url) data = json.loads(response.read()) re...
Save the data fron cron
Save the data fron cron
Python
mit
Evarin/velib-exp
34abe198ccfb906735e68ae95ad36e603a4001ca
integration-test/1147-bicycle-ramps.py
integration-test/1147-bicycle-ramps.py
# Add ramp properties to paths in roads layer # Steps with ramp:bicycle=yes in Copenhagen # https://www.openstreetmap.org/way/91275149 assert_has_feature( 15, 17527, 10257, 'roads', { 'id': 91275149, 'kind': 'path', 'kind_detail': 'steps', 'is_bicycle_related': True, 'ramp_bicycle': 'yes'}) # Footway with ram...
# Add ramp properties to paths in roads layer # Steps with ramp:bicycle=yes in Copenhagen # https://www.openstreetmap.org/way/91275149 assert_has_feature( 15, 17527, 10257, 'roads', { 'id': 91275149, 'kind': 'path', 'kind_detail': 'steps', 'is_bicycle_related': True, 'ramp_bicycle': 'yes'}) # Footway with ram...
Use z16 test to ensure no merging is done which would remove the id.
Use z16 test to ensure no merging is done which would remove the id.
Python
mit
mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource
1e16c3810e41df7a4d6273750c713c086ad82c14
weaveserver/core/plugins/virtualenv.py
weaveserver/core/plugins/virtualenv.py
import os import subprocess import virtualenv class VirtualEnvManager(object): def __init__(self, path): self.venv_home = path def install(self, requirements_file=None): if os.path.exists(self.venv_home): return True virtualenv.create_environment(self.venv_home) ...
import os import subprocess import virtualenv def execute_file(path): global_vars = {"__file__": path} with open(path, 'rb') as pyfile: exec(compile(pyfile.read(), path, 'exec'), global_vars) class VirtualEnvManager(object): def __init__(self, path): self.venv_home = path def inst...
Replace execfile with something compatible with both Py2/3.
Replace execfile with something compatible with both Py2/3.
Python
mit
supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer
c673c562836c207d25d799bfd9e7189a25f51fea
tests/test_swagger-tester.py
tests/test_swagger-tester.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import socket import threading import connexion from swagger_tester import swagger_test def test_swagger_test(): swagger_test(os.path.join(os.path.dirname(__file__), 'swagger.yaml')) def get_open_port(): """Get an open port on localhost""" s = s...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import socket import threading import time import connexion from swagger_tester import swagger_test def test_swagger_test(): swagger_test(os.path.join(os.path.dirname(__file__), 'swagger.yaml')) def get_open_port(): """Get an open port on localhost"...
Make sure the server has starded before launching tests
Make sure the server has starded before launching tests
Python
mit
Trax-air/swagger-tester
fb8fb61303dd567038ca812a61e6702b8b3f4edc
tests/test_exceptions.py
tests/test_exceptions.py
# -*- coding: utf-8 -*- from cookiecutter import exceptions def test_undefined_variable_to_str(): undefined_var_error = exceptions.UndefinedVariableInTemplate( 'Beautiful is better than ugly', exceptions.CookiecutterException('Errors should never pass silently'), {'cookiecutter': {'foo': ...
# -*- coding: utf-8 -*- from jinja2.exceptions import UndefinedError from cookiecutter import exceptions def test_undefined_variable_to_str(): undefined_var_error = exceptions.UndefinedVariableInTemplate( 'Beautiful is better than ugly', UndefinedError('Errors should never pass silently'), ...
Create a jinja2 error in the test to ensure it has a message attribute
Create a jinja2 error in the test to ensure it has a message attribute
Python
bsd-3-clause
hackebrot/cookiecutter,dajose/cookiecutter,dajose/cookiecutter,willingc/cookiecutter,audreyr/cookiecutter,Springerle/cookiecutter,terryjbates/cookiecutter,hackebrot/cookiecutter,Springerle/cookiecutter,willingc/cookiecutter,pjbull/cookiecutter,stevepiercy/cookiecutter,michaeljoseph/cookiecutter,luzfcb/cookiecutter,audr...
031e7e584a6566586c1ee7758a4f619bb161f4cd
utils/parse_worksheet.py
utils/parse_worksheet.py
def __open_worksheet(): pass def __get_data(): pass def __write_data(): pass
def __open_worksheet(): pass def __get_data(): pass def __write_data(): pass def parse_worksheet(): pass
Add code to fix failing test
Add code to fix failing test
Python
mit
jdgillespie91/trackerSpend,jdgillespie91/trackerSpend
bb4bff73a1eefad6188f1d1544f3b4106b606d36
driller/LibcSimProc.py
driller/LibcSimProc.py
import simuvex from simuvex.s_type import SimTypeFd, SimTypeChar, SimTypeArray, SimTypeLength class DrillerRead(simuvex.SimProcedure): ''' A custom version of read which has a symbolic return value. ''' def run(self, fd, dst, length): self.argument_types = {0: SimTypeFd(), ...
import simuvex from simuvex.s_type import SimTypeFd, SimTypeChar, SimTypeArray, SimTypeLength class DrillerRead(simuvex.SimProcedure): ''' A custom version of read which has a symbolic return value. ''' def run(self, fd, dst, length): self.argument_types = {0: SimTypeFd(), ...
Update libc's DrillerRead to use the new posix read calling convention to support variable read
Update libc's DrillerRead to use the new posix read calling convention to support variable read
Python
bsd-2-clause
shellphish/driller
d01217875a1c720b3c6fabe05fd3b0c2b0d3b287
qtpy/QtWebEngineQuick.py
qtpy/QtWebEngineQuick.py
# ----------------------------------------------------------------------------- # Copyright © 2009- The Spyder Development Team # # Licensed under the terms of the MIT License # (see LICENSE.txt for details) # ----------------------------------------------------------------------------- """ Provides QtWebEngineQuick c...
# ----------------------------------------------------------------------------- # Copyright © 2009- The Spyder Development Team # # Licensed under the terms of the MIT License # (see LICENSE.txt for details) # ----------------------------------------------------------------------------- """ Provides QtWebEngineQuick c...
Replace generic PythonQtError with QtModuleNotInstalledError
Replace generic PythonQtError with QtModuleNotInstalledError
Python
mit
spyder-ide/qtpy
d7598e96ba5bd0bb53635a62b61df077280967cc
jenkins/scripts/xstatic_check_version.py
jenkins/scripts/xstatic_check_version.py
#! /usr/bin/env python # # 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, softw...
#! /usr/bin/env python # # 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, softw...
Fix script to include repos in PYTHONPATH
Fix script to include repos in PYTHONPATH The repos checkout needs to be in the PYTHONPATH for the import of the xstatic module to work. Since we invoke the xstatic_check_version.py by absolute path, Python does not include the cwd() in the PYTHONPATH. Change-Id: Idd4f8db6334c9f29168e3bc39de3ed95a4e1c60f
Python
apache-2.0
dongwenjuan/project-config,Tesora/tesora-project-config,dongwenjuan/project-config,openstack-infra/project-config,openstack-infra/project-config,Tesora/tesora-project-config
ec85333da83e1c7de16dd7a5a3551dc9a1f660b4
mediachain/reader/main.py
mediachain/reader/main.py
import sys import argparse import os import mediachain.reader.api from mediachain.reader.api import Config def main(arguments=None): if arguments == None: arguments = sys.argv[1:] parser = argparse.ArgumentParser( prog='mediachain-reader', description='Mediachain Reader CLI' ) ...
import sys import argparse import os import mediachain.reader.api def main(arguments=None): if arguments == None: arguments = sys.argv[1:] parser = argparse.ArgumentParser( prog='mediachain-reader', description='Mediachain Reader CLI' ) parser.add_argument('-h', '--host', ...
Remove ref to dead Config class
Remove ref to dead Config class
Python
mit
mediachain/mediachain-client,mediachain/mediachain-client
a2af3446bbb9ff2cc46fdde4a96c539f57a972f9
tests/integration/directconnect/test_directconnect.py
tests/integration/directconnect/test_directconnect.py
# Copyright (c) 2013 Amazon.com, Inc. or its affiliates. # All Rights Reserved # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights...
# Copyright (c) 2013 Amazon.com, Inc. or its affiliates. # All Rights Reserved # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights...
Fix integration test for Python 2.6
Fix integration test for Python 2.6
Python
mit
Asana/boto,vijaylbais/boto,felix-d/boto,zachmullen/boto,vishnugonela/boto,weka-io/boto,revmischa/boto,weebygames/boto,nexusz99/boto,TiVoMaker/boto,garnaat/boto,alex/boto,ocadotechnology/boto,campenberger/boto,alex/boto,ddzialak/boto,awatts/boto,appneta/boto,clouddocx/boto,disruptek/boto,j-carl/boto,kouk/boto,darjus-amz...
3b1a04b20dee933792f3f9da78c2d76941beb54f
davstorage/storage.py
davstorage/storage.py
from __future__ import unicode_literals import requests from django.core.files import File from django.core.files.storage import Storage from davstorage.utils import trim_trailing_slash class DavStorage(Storage): def __init__(self, internal_url, external_url): self._internal_url = trim_trailing_slash(inte...
from __future__ import unicode_literals import requests from django.core.files import File from django.core.files.storage import Storage from davstorage.utils import trim_trailing_slash class DavStorage(Storage): def __init__(self, internal_url, external_url): self._internal_url = trim_trailing_slash(inte...
Handle situation where dav does not send length
Handle situation where dav does not send length
Python
bsd-2-clause
oinopion/davstorage,oinopion/davstorage,oinopion/davstorage
eb4c308bbe2824acc1016be761dd2a9713a909a3
vlcclient/vlcmessages.py
vlcclient/vlcmessages.py
''' Minimal VLC client for AceProxy. Messages class. ''' class VlcMessage(object): class request(object): SHUTDOWN = 'shutdown' @staticmethod def startBroadcast(stream_name, input, out_port, muxer='ts', pre_access=''): return 'new "' + stream_name + '" broadcast input "' + in...
''' Minimal VLC client for AceProxy. Messages class. ''' class VlcMessage(object): class request(object): SHUTDOWN = 'shutdown' @staticmethod def startBroadcast(stream_name, input, out_port, muxer='ts', pre_access=''): return 'new "' + stream_name + '" broadcast input "' + in...
Include all audio, video and subtitles streams
Include all audio, video and subtitles streams
Python
mit
deseven/aceproxy,pepsik-kiev/aceproxy,cosynus/python,Ivshti/aceproxy,ValdikSS/aceproxy
c8c0f6ec8abbcc845df38bfbba36b5ae916f77cd
vinotes/apps/api/urls.py
vinotes/apps/api/urls.py
from django.conf.urls import url from rest_framework.urlpatterns import format_suffix_patterns from . import views urlpatterns = [ url(r'^notes/$', views.NoteList.as_view()), url(r'^notes/(?P<pk>[0-9]+)/$', views.NoteDetail.as_view()), url(r'^traits/$', views.TraitList.as_view()), url(r'^traits/(?P<pk...
from django.conf.urls import include, url from rest_framework.urlpatterns import format_suffix_patterns from . import views urlpatterns = [ url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^notes/$', views.NoteList.as_view()), url(r'^notes/(?P<pk>[0-9]+)/$', views.Note...
Add login to browsable API.
Add login to browsable API.
Python
unlicense
rcutmore/vinotes-api,rcutmore/vinotes-api
2e4b4afd3b70543df7c72b81ce5c5318d00e3ff3
opps/sitemaps/sitemaps.py
opps/sitemaps/sitemaps.py
# -*- coding: utf-8 -*- from django.contrib.sitemaps import GenericSitemap as DjangoGenericSitemap from django.contrib.sitemaps import Sitemap as DjangoSitemap from django.utils import timezone from opps.containers.models import Container def InfoDisct(googlenews=False): container = Container.objects.filter(date...
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.contrib.sitemaps import GenericSitemap as DjangoGenericSitemap from django.contrib.sitemaps import Sitemap as DjangoSitemap from django.utils import timezone from opps.containers.models import Container def InfoDisct(googlenews=False): containers = Contai...
Fix var name, is plural in site map
Fix var name, is plural in site map
Python
mit
jeanmask/opps,jeanmask/opps,YACOWS/opps,williamroot/opps,opps/opps,YACOWS/opps,williamroot/opps,opps/opps,williamroot/opps,jeanmask/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,opps/opps,opps/opps
b3808c39c942bcc2c1701a1dcb61db47c69f1daa
notebooks/machine_learning/track_meta.py
notebooks/machine_learning/track_meta.py
# See also examples/example_track/example_meta.py for a longer, commented example track = dict( author_username='dansbecker', ) lessons = [ dict(topic='How Models Work'), dict(topic='Explore Your Data') ] notebooks = [ dict( filename='tut1.ipynb', lesson_idx=0, type='tu...
# See also examples/example_track/example_meta.py for a longer, commented example track = dict( author_username='dansbecker', ) lessons = [ dict(topic='how models work'), dict(topic='exploring your data'), dict(topic='building your first machine learning model'), ] notebooks = [ dict( ...
Add third lesson and reword lesson topics
Add third lesson and reword lesson topics
Python
apache-2.0
Kaggle/learntools,Kaggle/learntools
9a9100e201603e185965fff94de92db13caf45ae
wagtail/images/checks.py
wagtail/images/checks.py
import os from functools import lru_cache from django.core.checks import Warning, register from willow.image import Image @lru_cache() def has_jpeg_support(): wagtail_jpg = os.path.join(os.path.dirname(__file__), "check_files", "wagtail.jpg") succeeded = True with open(wagtail_jpg, "rb") as f: t...
import os from functools import lru_cache from django.core.checks import Warning, register from willow.image import Image @lru_cache() def has_jpeg_support(): wagtail_jpg = os.path.join(os.path.dirname(__file__), "check_files", "wagtail.jpg") succeeded = True with open(wagtail_jpg, "rb") as f: t...
Remove broken reference to Image.LoaderError
Remove broken reference to Image.LoaderError This exception has not existed since Willow 0.3. Type checking on the 'except' line only happens when an exception occurs, so most of the time this is harmless, but if an unrelated exception occurs here (such as that caused by a faulty filetype library: https://github.com/h...
Python
bsd-3-clause
wagtail/wagtail,wagtail/wagtail,zerolab/wagtail,zerolab/wagtail,thenewguy/wagtail,wagtail/wagtail,rsalmaso/wagtail,wagtail/wagtail,rsalmaso/wagtail,thenewguy/wagtail,thenewguy/wagtail,rsalmaso/wagtail,thenewguy/wagtail,wagtail/wagtail,rsalmaso/wagtail,thenewguy/wagtail,zerolab/wagtail,zerolab/wagtail,zerolab/wagtail,rs...
af072319100be47415613d39c6b2eab22b8b4f34
froide/helper/utils.py
froide/helper/utils.py
from django.shortcuts import render def get_next(request): # This is not a view return request.GET.get("next", request.META.get("HTTP_REFERER", "/")) def render_code(code, request, context={}): return render(request, "%d.html" % code, context, status=code) def render_400(request): retu...
from django.shortcuts import render, redirect from django.urls import reverse from django.utils.http import is_safe_url def get_next(request): # This is not a view return request.GET.get("next", request.META.get("HTTP_REFERER", "/")) def render_code(code, request, context={}): return render(request, "%d...
Add get_redirect_url and get_redirect helper
Add get_redirect_url and get_redirect helper
Python
mit
stefanw/froide,fin/froide,stefanw/froide,stefanw/froide,fin/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide