commit
stringlengths
40
40
old_file
stringlengths
5
117
new_file
stringlengths
5
117
old_contents
stringlengths
0
1.93k
new_contents
stringlengths
19
3.3k
subject
stringlengths
17
320
message
stringlengths
18
3.28k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
7
42.4k
completion
stringlengths
19
3.3k
prompt
stringlengths
21
3.65k
0ff0e770babe4c1e1d07f5b8f0722774d5bcb2b0
benchexec/tools/kissat.py
benchexec/tools/kissat.py
# This file is part of BenchExec, a framework for reliable benchmarking: # https://github.com/sosy-lab/benchexec # # SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org> # # SPDX-License-Identifier: Apache-2.0 import benchexec.result as result import benchexec.tools.template class Tool(benchexec.t...
Add a tool-info module for Kissat SAT solver
Add a tool-info module for Kissat SAT solver
Python
apache-2.0
sosy-lab/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec
# This file is part of BenchExec, a framework for reliable benchmarking: # https://github.com/sosy-lab/benchexec # # SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org> # # SPDX-License-Identifier: Apache-2.0 import benchexec.result as result import benchexec.tools.template class Tool(benchexec.t...
Add a tool-info module for Kissat SAT solver
158f1101c3c13db5df916329a66517c7bb85e132
plata/context_processors.py
plata/context_processors.py
import plata def plata_context(request): """ Adds a few variables from Plata to the context if they are available: * ``plata.shop``: The current :class:`plata.shop.views.Shop` instance * ``plata.order``: The current order * ``plata.contact``: The current contact instance * ``plata.price_inclu...
import plata def plata_context(request): """ Adds a few variables from Plata to the context if they are available: * ``plata.shop``: The current :class:`plata.shop.views.Shop` instance * ``plata.order``: The current order * ``plata.contact``: The current contact instance * ``plata.price_inclu...
Add current value for price_includes_tax to context
Add current value for price_includes_tax to context
Python
bsd-3-clause
armicron/plata,armicron/plata,armicron/plata
import plata def plata_context(request): """ Adds a few variables from Plata to the context if they are available: * ``plata.shop``: The current :class:`plata.shop.views.Shop` instance * ``plata.order``: The current order * ``plata.contact``: The current contact instance * ``plata.price_inclu...
Add current value for price_includes_tax to context import plata def plata_context(request): """ Adds a few variables from Plata to the context if they are available: * ``plata.shop``: The current :class:`plata.shop.views.Shop` instance * ``plata.order``: The current order * ``plata.contact``: T...
e5daa53aab94360c2e06a6cb608c4992b25becc6
test/helpers.py
test/helpers.py
# -*- coding: utf-8 -*- """ helpers ~~~~~~~ This module contains helpers for the h2 tests. """ from hyperframe.frame import HeadersFrame, DataFrame from hpack.hpack import Encoder class FrameFactory(object): """ A class containing lots of helper methods and state to build frames. This allows test cases t...
# -*- coding: utf-8 -*- """ helpers ~~~~~~~ This module contains helpers for the h2 tests. """ from hyperframe.frame import HeadersFrame, DataFrame from hpack.hpack import Encoder class FrameFactory(object): """ A class containing lots of helper methods and state to build frames. This allows test cases t...
Allow stream ids != 1 in frame factory.
Allow stream ids != 1 in frame factory.
Python
mit
Kriechi/hyper-h2,mhils/hyper-h2,bhavishyagopesh/hyper-h2,Kriechi/hyper-h2,vladmunteanu/hyper-h2,python-hyper/hyper-h2,python-hyper/hyper-h2,vladmunteanu/hyper-h2
# -*- coding: utf-8 -*- """ helpers ~~~~~~~ This module contains helpers for the h2 tests. """ from hyperframe.frame import HeadersFrame, DataFrame from hpack.hpack import Encoder class FrameFactory(object): """ A class containing lots of helper methods and state to build frames. This allows test cases t...
Allow stream ids != 1 in frame factory. # -*- coding: utf-8 -*- """ helpers ~~~~~~~ This module contains helpers for the h2 tests. """ from hyperframe.frame import HeadersFrame, DataFrame from hpack.hpack import Encoder class FrameFactory(object): """ A class containing lots of helper methods and state to b...
edeffbcbe8fb239553c73fa37e73c0188ffc2479
tests/test_cli.py
tests/test_cli.py
import sys import fixtures import imgurpython import testtools import imgur_cli.cli as cli FAKE_ENV = {'IMGUR_CLIENT_ID': 'client_id', 'IMGUR_CLIENT_SECRET': 'client_secret', 'IMGUR_ACCESS_TOKEN': 'access_token', 'IMGUR_REFRESH_TOKEN': 'refresh_token', 'IMGUR_MASHAPE_K...
Add unit test for retrieving credentials from environment variables
Add unit test for retrieving credentials from environment variables
Python
mit
ueg1990/imgur-cli
import sys import fixtures import imgurpython import testtools import imgur_cli.cli as cli FAKE_ENV = {'IMGUR_CLIENT_ID': 'client_id', 'IMGUR_CLIENT_SECRET': 'client_secret', 'IMGUR_ACCESS_TOKEN': 'access_token', 'IMGUR_REFRESH_TOKEN': 'refresh_token', 'IMGUR_MASHAPE_K...
Add unit test for retrieving credentials from environment variables
5a4401df95d3b8cb72e78edb30669d6fa88e4712
transaction_downloader/transaction_downloader.py
transaction_downloader/transaction_downloader.py
"""Transaction Downloader. Usage: transaction-downloader auth --account=<account-name> transaction-downloader -h | --help transaction-downloader --version Options: -h --help Show this screen. --version Show version. --account=<account-name> Account to work with. """ import...
"""Transaction Downloader. Usage: transaction-downloader auth --account=<account-name> transaction-downloader -h | --help transaction-downloader --version Options: -h --help Show this screen. --version Show version. --account=<account-name> Account to work with. """ import...
Read credentials based on account.
Read credentials based on account.
Python
mit
ebridges/plaid2qif,ebridges/plaid2qif,ebridges/plaid2qif
"""Transaction Downloader. Usage: transaction-downloader auth --account=<account-name> transaction-downloader -h | --help transaction-downloader --version Options: -h --help Show this screen. --version Show version. --account=<account-name> Account to work with. """ import...
Read credentials based on account. """Transaction Downloader. Usage: transaction-downloader auth --account=<account-name> transaction-downloader -h | --help transaction-downloader --version Options: -h --help Show this screen. --version Show version. --account=<account-nam...
96776b33fcf2ebbd2de4748c38d8be9c63fdec71
tests/conftest.py
tests/conftest.py
from django.conf import settings from django.core.management import call_command def pytest_configure(): settings.configure( ROOT_URLCONF='tests.urls', ALLOWED_HOSTS=['testserver'], DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', ...
from django.conf import settings from django.core.management import call_command def pytest_configure(): settings.configure( ROOT_URLCONF='tests.urls', ALLOWED_HOSTS=['testserver'], DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', ...
Replace --noinput with interactive=False in syncdb command call
Replace --noinput with interactive=False in syncdb command call
Python
bsd-2-clause
yprez/django-rest-assured,pombredanne/django-rest-assured,ydaniv/django-rest-assured
from django.conf import settings from django.core.management import call_command def pytest_configure(): settings.configure( ROOT_URLCONF='tests.urls', ALLOWED_HOSTS=['testserver'], DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', ...
Replace --noinput with interactive=False in syncdb command call from django.conf import settings from django.core.management import call_command def pytest_configure(): settings.configure( ROOT_URLCONF='tests.urls', ALLOWED_HOSTS=['testserver'], DATABASES={ 'default': { ...
7f74911cf02c624afbb85e63dedde68cda2f53f6
modules/bilingual_generator/bilingual-preprocess.py
modules/bilingual_generator/bilingual-preprocess.py
import itertools import codecs d=[] for entry in a.findall("ar"): foo = [x.text.split(";") for x in entry if x.text] if len(foo) == 2: english,hindi = foo english = [e.strip() for e in english ] hindi = [h.strip() for h in hindi] english = [e for e in english if not " " in...
Add script for preprocess of Universal bilingual dictionary database
Add script for preprocess of Universal bilingual dictionary database
Python
mit
KshitijKarthick/tvecs,KshitijKarthick/tvecs,KshitijKarthick/tvecs
import itertools import codecs d=[] for entry in a.findall("ar"): foo = [x.text.split(";") for x in entry if x.text] if len(foo) == 2: english,hindi = foo english = [e.strip() for e in english ] hindi = [h.strip() for h in hindi] english = [e for e in english if not " " in...
Add script for preprocess of Universal bilingual dictionary database
eb84efd25b8c5e9ba06434ad78c9611b3f8350f0
every_election/apps/elections/management/commands/add_tags.py
every_election/apps/elections/management/commands/add_tags.py
import json from django.contrib.gis.gdal import DataSource from django.core.management import BaseCommand from django.db.models import Value from core.mixins import ReadFromFileMixin from core.models import JsonbSet from elections.models import Election def get_layer(data, layer_index=0): data_source = DataSour...
Add command to add tags to Election model
Add command to add tags to Election model
Python
bsd-3-clause
DemocracyClub/EveryElection,DemocracyClub/EveryElection,DemocracyClub/EveryElection
import json from django.contrib.gis.gdal import DataSource from django.core.management import BaseCommand from django.db.models import Value from core.mixins import ReadFromFileMixin from core.models import JsonbSet from elections.models import Election def get_layer(data, layer_index=0): data_source = DataSour...
Add command to add tags to Election model
b3b7e2fcbff5cd0ec2d2b4457b7a46d1846d55a8
glue_vispy_viewers/common/vispy_viewer.py
glue_vispy_viewers/common/vispy_viewer.py
from __future__ import absolute_import, division, print_function import sys from vispy import scene from glue.external.qt import QtGui, get_qapp class VispyWidget(QtGui.QWidget): def __init__(self, parent=None): super(VispyWidget, self).__init__(parent=parent) # Prepare Vispy canvas s...
Implement a generic Vispy widget
Implement a generic Vispy widget
Python
bsd-2-clause
PennyQ/glue-3d-viewer,PennyQ/astro-vispy,glue-viz/glue-vispy-viewers,glue-viz/glue-3d-viewer,astrofrog/glue-vispy-viewers,astrofrog/glue-3d-viewer
from __future__ import absolute_import, division, print_function import sys from vispy import scene from glue.external.qt import QtGui, get_qapp class VispyWidget(QtGui.QWidget): def __init__(self, parent=None): super(VispyWidget, self).__init__(parent=parent) # Prepare Vispy canvas s...
Implement a generic Vispy widget
b6a85378d210dc3954a43f25c855ca20f68972b3
software/dev/fade_pat.py
software/dev/fade_pat.py
#!/usr/bin/python import os import sys import math from colorsys import hsv_to_rgb from hippietrap.chandelier import Chandelier, BROADCAST, NUM_NODES from hippietrap.color import Color from time import sleep, time from random import random STEPS = 5000 device = "/dev/serial0" ch = Chandelier() ch.open(device) ch.cl...
Add test script for fade pattern
Add test script for fade pattern
Python
mit
mayhem/led-chandelier,mayhem/led-chandelier,mayhem/led-chandelier
#!/usr/bin/python import os import sys import math from colorsys import hsv_to_rgb from hippietrap.chandelier import Chandelier, BROADCAST, NUM_NODES from hippietrap.color import Color from time import sleep, time from random import random STEPS = 5000 device = "/dev/serial0" ch = Chandelier() ch.open(device) ch.cl...
Add test script for fade pattern
10ccc510deab5c97ce8a6c5ee57232c5e399986e
decision_tree.py
decision_tree.py
import pandas as pd from sklearn import tree # X = [[0, 1], [1, 1]] # Y = [0, 1] #clf = tree.DecisionTreeClassifier() #clf = clf.fit(X, Y) data = pd.read_excel('/home/andre/sandbox/jhu-immuno/journal.pcbi.1003266.s001-2.XLS') resp_cols = [ 'MHC' ] data['y'] = data.Immunogenicity.map({'non-immunogenic': 0, 'immunoge...
Add decision tree classifier attempt.
Add decision tree classifier attempt.
Python
mit
andretadeu/jhu-immuno,andretadeu/jhu-immuno
import pandas as pd from sklearn import tree # X = [[0, 1], [1, 1]] # Y = [0, 1] #clf = tree.DecisionTreeClassifier() #clf = clf.fit(X, Y) data = pd.read_excel('/home/andre/sandbox/jhu-immuno/journal.pcbi.1003266.s001-2.XLS') resp_cols = [ 'MHC' ] data['y'] = data.Immunogenicity.map({'non-immunogenic': 0, 'immunoge...
Add decision tree classifier attempt.
150058856f10992d0f65f47d79ac14e2f52818cc
cellcounter/urls.py
cellcounter/urls.py
from django.conf.urls import patterns, include, url from django.views.generic.simple import direct_to_template from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin from django.contrib.auth.views import login, logout from cellcounter.main.views import new_count, view_cou...
from django.conf.urls import patterns, include, url from django.views.generic.simple import direct_to_template from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin from django.contrib.auth.views import login, logout from cellcounter.main.views import new_count, view_cou...
Add URL to enable user list view
Add URL to enable user list view
Python
mit
cellcounter/cellcounter,oghm2/hackdayoxford,cellcounter/cellcounter,cellcounter/cellcounter,haematologic/cellcountr,haematologic/cellcounter,cellcounter/cellcounter,haematologic/cellcountr,haematologic/cellcounter,haematologic/cellcounter,oghm2/hackdayoxford
from django.conf.urls import patterns, include, url from django.views.generic.simple import direct_to_template from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin from django.contrib.auth.views import login, logout from cellcounter.main.views import new_count, view_cou...
Add URL to enable user list view from django.conf.urls import patterns, include, url from django.views.generic.simple import direct_to_template from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin from django.contrib.auth.views import login, logout from cellcounter.mai...
d4f21288e7ba6bdc27f0f01fd0dba394a9786aa6
open_humans/utilities.py
open_humans/utilities.py
import io import os from ConfigParser import RawConfigParser def apply_env(): """ Read the `.env` file and apply it to os.environ just like using `foreman run` would. """ env = '[root]\n' + io.open('.env', 'r').read() config = RawConfigParser(allow_no_value=True) # Use `str` instead of ...
import io import os from ConfigParser import RawConfigParser def apply_env(): """ Read the `.env` file and apply it to os.environ just like using `foreman run` would. """ try: env = '[root]\n' + io.open('.env', 'r').read() except IOError: return config = RawConfigParser(a...
Fix crash if .env does not exist
Fix crash if .env does not exist
Python
mit
PersonalGenomesOrg/open-humans,OpenHumans/open-humans,OpenHumans/open-humans,PersonalGenomesOrg/open-humans,OpenHumans/open-humans,OpenHumans/open-humans,PersonalGenomesOrg/open-humans,PersonalGenomesOrg/open-humans
import io import os from ConfigParser import RawConfigParser def apply_env(): """ Read the `.env` file and apply it to os.environ just like using `foreman run` would. """ try: env = '[root]\n' + io.open('.env', 'r').read() except IOError: return config = RawConfigParser(a...
Fix crash if .env does not exist import io import os from ConfigParser import RawConfigParser def apply_env(): """ Read the `.env` file and apply it to os.environ just like using `foreman run` would. """ env = '[root]\n' + io.open('.env', 'r').read() config = RawConfigParser(allow_no_value=...
d46d908f5cfafcb6962207c45f923d3afb7f35a7
pyrobus/__init__.py
pyrobus/__init__.py
from .robot import Robot from .modules import *
import logging from .robot import Robot from .modules import * nh = logging.NullHandler() logging.getLogger(__name__).addHandler(nh)
Add null handler as default for logging.
Add null handler as default for logging.
Python
mit
pollen/pyrobus
import logging from .robot import Robot from .modules import * nh = logging.NullHandler() logging.getLogger(__name__).addHandler(nh)
Add null handler as default for logging. from .robot import Robot from .modules import *
71d6176b1468a5bf9aef1ced5214c32b69efaf50
apps/countdown/views.py
apps/countdown/views.py
from django.shortcuts import render_to_response from django.template import RequestContext from django.http import HttpResponse from django.utils.http import urlencode import json import urllib2 def index(request, year, month, day, hour, text): params = { 'year': year, 'month': int(month) - 1, #JS takes month...
from django.shortcuts import render_to_response from django.template import RequestContext from django.http import HttpResponse from django.utils.http import urlencode import json import urllib2 def index(request, year, month, day, hour, text): params = { 'year': year, 'month': int(month) - 1, #JS takes month...
Fix bug in countdonw hours calculation
Fix bug in countdonw hours calculation
Python
bsd-3-clause
Teknologforeningen/tf-info,Teknologforeningen/tf-info,Teknologforeningen/tf-info
from django.shortcuts import render_to_response from django.template import RequestContext from django.http import HttpResponse from django.utils.http import urlencode import json import urllib2 def index(request, year, month, day, hour, text): params = { 'year': year, 'month': int(month) - 1, #JS takes month...
Fix bug in countdonw hours calculation from django.shortcuts import render_to_response from django.template import RequestContext from django.http import HttpResponse from django.utils.http import urlencode import json import urllib2 def index(request, year, month, day, hour, text): params = { 'year': year, ...
ee629fca605b27ee6f34c8fa7584f670ae60b121
whylog/constraints/constraint_manager.py
whylog/constraints/constraint_manager.py
from whylog.constraints import DifferentConstraint, IdenticalConstraint, TimeConstraint from whylog.constraints.exceptions import UnsupportedConstraintTypeError class ConstraintRegistry(object): CONSTRAINTS = { 'identical': IdenticalConstraint, 'time': TimeConstraint, 'different': Differen...
from whylog.constraints import DifferentConstraint, IdenticalConstraint, TimeConstraint from whylog.constraints.exceptions import UnsupportedConstraintTypeError class ConstraintRegistry(object): CONSTRAINTS = { 'identical': IdenticalConstraint, 'time': TimeConstraint, 'different': Differen...
Add constraint from name method
Add constraint from name method
Python
bsd-3-clause
epawlowska/whylog,kgromadzki/whylog,kgromadzki/whylog,konefalg/whylog,9livesdata/whylog,konefalg/whylog,andrzejgorski/whylog,epawlowska/whylog,9livesdata/whylog,andrzejgorski/whylog
from whylog.constraints import DifferentConstraint, IdenticalConstraint, TimeConstraint from whylog.constraints.exceptions import UnsupportedConstraintTypeError class ConstraintRegistry(object): CONSTRAINTS = { 'identical': IdenticalConstraint, 'time': TimeConstraint, 'different': Differen...
Add constraint from name method from whylog.constraints import DifferentConstraint, IdenticalConstraint, TimeConstraint from whylog.constraints.exceptions import UnsupportedConstraintTypeError class ConstraintRegistry(object): CONSTRAINTS = { 'identical': IdenticalConstraint, 'time': TimeConstrai...
315aedbfff9e345b1e4a4ffab999741bb9a802da
oopconcepts.py
oopconcepts.py
class Person: def __init__(self, name): self.name = name def say_hello(self): print("Hello, ", self.name) p1 = Person("Allan") p1.say_hello() p2 = Person("John") p2.say_hello()
class Classroom: def __init__(self): self._people = [] def add_person(self, person): self._people.append(person) def remove_person(self, person): self._people.remove(person) def greet(self): for person in self._people: person.say_hello() class Person: ...
Create classroom and some encapsulation
Create classroom and some encapsulation
Python
mit
cunctat0r/pythonstudy
class Classroom: def __init__(self): self._people = [] def add_person(self, person): self._people.append(person) def remove_person(self, person): self._people.remove(person) def greet(self): for person in self._people: person.say_hello() class Person: ...
Create classroom and some encapsulation class Person: def __init__(self, name): self.name = name def say_hello(self): print("Hello, ", self.name) p1 = Person("Allan") p1.say_hello() p2 = Person("John") p2.say_hello()
3e33849ded2c69760ce93b4b1e9ab8094904040f
space-age/space_age.py
space-age/space_age.py
class SpaceAge(object): def __init__(self, seconds): self.seconds = seconds @property def years(self): return self.seconds/31557600 def on_earth(self): return round(self.years, 2) def on_mercury(self): return round(self.years/0.2408467, 2) def on_venus(self): ...
class SpaceAge(object): YEARS = {"on_earth": 1, "on_mercury": 0.2408467, "on_venus": 0.61519726, "on_mars": 1.8808158, "on_jupiter": 11.862615, "on_saturn": 29.447498, "on_uranus": 84.016846, "on_neptune": 164.79132} def...
Implement __getattr__ to reduce code
Implement __getattr__ to reduce code
Python
agpl-3.0
CubicComet/exercism-python-solutions
class SpaceAge(object): YEARS = {"on_earth": 1, "on_mercury": 0.2408467, "on_venus": 0.61519726, "on_mars": 1.8808158, "on_jupiter": 11.862615, "on_saturn": 29.447498, "on_uranus": 84.016846, "on_neptune": 164.79132} def...
Implement __getattr__ to reduce code class SpaceAge(object): def __init__(self, seconds): self.seconds = seconds @property def years(self): return self.seconds/31557600 def on_earth(self): return round(self.years, 2) def on_mercury(self): return round(self.years/0...
caddef7500241135965e6d91ca94a38224bfd0cd
ui2/path_helpers.py
ui2/path_helpers.py
import ui def get_path_image(path): """ Get an image of a path """ bounds = path.bounds with ui.ImageContext(bounds.max_x, bounds.max_y) as ctx: path.fill() return ctx.get_image() def copy_path(path): """ Make a copy of a ui.Path and return it. Preserves all data. """ new = ui.Pa...
import ui import objc_util def get_path_image(path): """ Get an image of a path """ bounds = path.bounds with ui.ImageContext(bounds.max_x, bounds.max_y) as ctx: path.fill() return ctx.get_image() def copy_path(path): """ Make a copy of a ui.Path and return it. Preserves all data. ""...
Add method for scaling path
Add method for scaling path
Python
mit
controversial/ui2
import ui import objc_util def get_path_image(path): """ Get an image of a path """ bounds = path.bounds with ui.ImageContext(bounds.max_x, bounds.max_y) as ctx: path.fill() return ctx.get_image() def copy_path(path): """ Make a copy of a ui.Path and return it. Preserves all data. ""...
Add method for scaling path import ui def get_path_image(path): """ Get an image of a path """ bounds = path.bounds with ui.ImageContext(bounds.max_x, bounds.max_y) as ctx: path.fill() return ctx.get_image() def copy_path(path): """ Make a copy of a ui.Path and return it. Preserves ...
cda63e96b042de04b3aa12348a411229e9b9d973
tools/glidein_cat.py
tools/glidein_cat.py
#!/bin/env python # # glidein_cat # # Execute a cat command on the job directory # # Usage: # glidein_ls.py <cluster>.<process> [-name <schedd_name>] [-pool <pool_name> ] [-timeout <nr secs> # import os import string import stat import sys sys.path.append("lib") sys.path.append("../lib") import glideinMonitor def c...
#!/bin/env python # # glidein_cat.py # # Description: # Execute a cat command on a condor job working directory # # Usage: # glidein_cat.py <cluster>.<process> [<file>] [-name <schedd_name>] [-pool <pool_name> ] [-timeout <nr secs>] # # Author: # Igor Sfiligoi (May 2007) # # License: # Fermitools # import sys,os...
Change rel paths into abspaths and use helper module
Change rel paths into abspaths and use helper module
Python
bsd-3-clause
bbockelm/glideinWMS,holzman/glideinwms-old,bbockelm/glideinWMS,bbockelm/glideinWMS,holzman/glideinwms-old,holzman/glideinwms-old,bbockelm/glideinWMS
#!/bin/env python # # glidein_cat.py # # Description: # Execute a cat command on a condor job working directory # # Usage: # glidein_cat.py <cluster>.<process> [<file>] [-name <schedd_name>] [-pool <pool_name> ] [-timeout <nr secs>] # # Author: # Igor Sfiligoi (May 2007) # # License: # Fermitools # import sys,os...
Change rel paths into abspaths and use helper module #!/bin/env python # # glidein_cat # # Execute a cat command on the job directory # # Usage: # glidein_ls.py <cluster>.<process> [-name <schedd_name>] [-pool <pool_name> ] [-timeout <nr secs> # import os import string import stat import sys sys.path.append("lib") s...
d641d7d843899258d88da0d1dffaa762c1378712
opps/fields/widgets.py
opps/fields/widgets.py
#!/usr/bin/env python # -*- coding: utf-8 -* import json from django import forms from django.template.loader import render_to_string from .models import Field, Option, FieldOption class JSONField(forms.TextInput): model = Field def render(self, name, value, attrs=None): elements = [] values ...
#!/usr/bin/env python # -*- coding: utf-8 -* import json from django import forms from django.template.loader import render_to_string from .models import Field, FieldOption class JSONField(forms.TextInput): model = Field def render(self, name, value, attrs=None): elements = [] try: ...
Fix bug TypeError, not exist values (json) is dict None
Fix bug TypeError, not exist values (json) is dict None
Python
mit
williamroot/opps,jeanmask/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,opps/opps,williamroot/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,opps/opps,opps/opps,YACOWS/opps,opps/opps
#!/usr/bin/env python # -*- coding: utf-8 -* import json from django import forms from django.template.loader import render_to_string from .models import Field, FieldOption class JSONField(forms.TextInput): model = Field def render(self, name, value, attrs=None): elements = [] try: ...
Fix bug TypeError, not exist values (json) is dict None #!/usr/bin/env python # -*- coding: utf-8 -* import json from django import forms from django.template.loader import render_to_string from .models import Field, Option, FieldOption class JSONField(forms.TextInput): model = Field def render(self, name, ...
b9cf2f0daf2ca360c64d1268d50cab9c07020222
test_engine.py
test_engine.py
import engine VALID_COORDS = [(x, y) for x in xrange(97, 105) for y in xrange(49, 57)] INVALID_COORDS = [ (0, 0), (-1, -1), (96, 49), (96, 48), (105, 49), (104, 48), (96, 56), (97, 57), (105, 56), (104, 57) ] VALID_A1 = [chr(x) + chr(y) for x in xrange(97, 105) for y in xrange(49, 57)] INVALID...
import engine VALID_COORDS = [(x, y) for x in xrange(97, 105) for y in xrange(49, 57)] INVALID_COORDS = [ (0, 0), (-1, -1), (96, 49), (96, 48), (105, 49), (104, 48), (96, 56), (97, 57), (105, 56), (104, 57) ] VALID_A1 = [chr(x) + chr(y) for x in xrange(97, 105) for y in xrange(49, 57)] INVALID...
Add test_is_coord_on_board() to assert the function returns True if the coordinate is on the board and False otherwise
Add test_is_coord_on_board() to assert the function returns True if the coordinate is on the board and False otherwise
Python
mit
EyuelAbebe/gamer,EyuelAbebe/gamer
import engine VALID_COORDS = [(x, y) for x in xrange(97, 105) for y in xrange(49, 57)] INVALID_COORDS = [ (0, 0), (-1, -1), (96, 49), (96, 48), (105, 49), (104, 48), (96, 56), (97, 57), (105, 56), (104, 57) ] VALID_A1 = [chr(x) + chr(y) for x in xrange(97, 105) for y in xrange(49, 57)] INVALID...
Add test_is_coord_on_board() to assert the function returns True if the coordinate is on the board and False otherwise import engine VALID_COORDS = [(x, y) for x in xrange(97, 105) for y in xrange(49, 57)] INVALID_COORDS = [ (0, 0), (-1, -1), (96, 49), (96, 48), (105, 49), (104, 48), (96, 56), (97, 5...
3d399d33302c004122773af52a740da1c736540e
test/functional/test_miscellaneous.py
test/functional/test_miscellaneous.py
import time import pytest def test_version(client): expected_keys = {"Repo", "Commit", "Version"} resp_version = client.version() assert set(resp_version.keys()).issuperset(expected_keys) def test_id(client): expected_keys = {"PublicKey", "ProtocolVersion", "ID", "AgentVersion", "Addresses"} resp_id = client...
import time import pytest def test_version(client): expected_keys = {"Repo", "Commit", "Version"} resp_version = client.version() assert set(resp_version.keys()).issuperset(expected_keys) def test_id(client): expected_keys = {"PublicKey", "ProtocolVersion", "ID", "AgentVersion", "Addresses"} resp_id = client...
Increase daemon shutdown timeout to 20s for slow Travis CI Windows runs
Increase daemon shutdown timeout to 20s for slow Travis CI Windows runs
Python
mit
ipfs/py-ipfs-api,ipfs/py-ipfs-api
import time import pytest def test_version(client): expected_keys = {"Repo", "Commit", "Version"} resp_version = client.version() assert set(resp_version.keys()).issuperset(expected_keys) def test_id(client): expected_keys = {"PublicKey", "ProtocolVersion", "ID", "AgentVersion", "Addresses"} resp_id = client...
Increase daemon shutdown timeout to 20s for slow Travis CI Windows runs import time import pytest def test_version(client): expected_keys = {"Repo", "Commit", "Version"} resp_version = client.version() assert set(resp_version.keys()).issuperset(expected_keys) def test_id(client): expected_keys = {"PublicKey",...
49891ea015c082443b2c709650d125a649e36187
poolwatcher/poolWatcher.py
poolwatcher/poolWatcher.py
# # Description: # This is the main of the poolWatcher # # Arguments: (eventually) # $1 = poll period (in seconds) # $2 = advertize rate (every $2 loops) # $3 = glidein submit_dir # # Author: # Igor Sfiligoi (Feb 13th 2007) # import os import os.path import sys import traceback import time sys.path.append("....
# # Description: # This is the main of the poolWatcher # # Arguments: (eventually) # $1 = poll period (in seconds) # $2 = advertize rate (every $2 loops) # $3 = glidein submit_dir # # Author: # Igor Sfiligoi (Feb 13th 2007) # import os import os.path import sys import traceback import time sys.path.append("....
Add distinction between claimed and unclaimed
Add distinction between claimed and unclaimed
Python
bsd-3-clause
holzman/glideinwms-old,bbockelm/glideinWMS,bbockelm/glideinWMS,bbockelm/glideinWMS,holzman/glideinwms-old,bbockelm/glideinWMS,holzman/glideinwms-old
# # Description: # This is the main of the poolWatcher # # Arguments: (eventually) # $1 = poll period (in seconds) # $2 = advertize rate (every $2 loops) # $3 = glidein submit_dir # # Author: # Igor Sfiligoi (Feb 13th 2007) # import os import os.path import sys import traceback import time sys.path.append("....
Add distinction between claimed and unclaimed # # Description: # This is the main of the poolWatcher # # Arguments: (eventually) # $1 = poll period (in seconds) # $2 = advertize rate (every $2 loops) # $3 = glidein submit_dir # # Author: # Igor Sfiligoi (Feb 13th 2007) # import os import os.path import sys ...
04287120372a6fdb906ed9f27ead4c5f91d5690e
tota/heroes/lenovo.py
tota/heroes/lenovo.py
from tota.utils import closest, distance, sort_by_distance, possible_moves from tota import settings __author__ = "angvp" def create(): def lenovo_hero_logic(self, things, t): # some useful data about the enemies I can see in the map enemy_team = settings.ENEMY_TEAMS[self.team] enemies =...
Add a modified version of simple bot
Add a modified version of simple bot
Python
mit
fisadev/tota
from tota.utils import closest, distance, sort_by_distance, possible_moves from tota import settings __author__ = "angvp" def create(): def lenovo_hero_logic(self, things, t): # some useful data about the enemies I can see in the map enemy_team = settings.ENEMY_TEAMS[self.team] enemies =...
Add a modified version of simple bot
171b0c16698b47a6b0771f2ec2de01079c9a8041
src/armet/connectors/cyclone/http.py
src/armet/connectors/cyclone/http.py
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, division from armet import utils from armet.http import request, response class Request(request.Request): """Implements the request abstraction for cyclone. """ @property @utils.memoize_single def method(self): ...
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, division from armet.http import request, response class Request(request.Request): """Implements the request abstraction for cyclone. """ def __init__(self, handler): self.handler = handler # This is the pyth...
Implement the cyclone request/response object
Implement the cyclone request/response object
Python
mit
armet/python-armet
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, division from armet.http import request, response class Request(request.Request): """Implements the request abstraction for cyclone. """ def __init__(self, handler): self.handler = handler # This is the pyth...
Implement the cyclone request/response object # -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, division from armet import utils from armet.http import request, response class Request(request.Request): """Implements the request abstraction for cyclone. """ @property @u...
ef2b13ec19d28b56647c0a11044cba6d400f9175
vimiv/image_enhance.py
vimiv/image_enhance.py
# vim: ft=python fileencoding=utf-8 sw=4 et sts=4 """Wrapper functions for the _image_enhance C extension.""" from gi.repository import GdkPixbuf, GLib from vimiv import _image_enhance def enhance_bc(pixbuf, brightness, contrast): """Enhance brightness and contrast of a GdkPixbuf.Pixbuf. Args: pixbu...
# vim: ft=python fileencoding=utf-8 sw=4 et sts=4 """Wrapper functions for the _image_enhance C extension.""" from gi.repository import GdkPixbuf, GLib from vimiv import _image_enhance def enhance_bc(pixbuf, brightness, contrast): """Enhance brightness and contrast of a GdkPixbuf.Pixbuf. Args: pixbu...
Use rowstride directly from GdkPixbuf in enhance
Use rowstride directly from GdkPixbuf in enhance The custom calculation of rowstride failed for images with weird dimensions and completely broke enhance. fixes #51
Python
mit
karlch/vimiv,karlch/vimiv,karlch/vimiv
# vim: ft=python fileencoding=utf-8 sw=4 et sts=4 """Wrapper functions for the _image_enhance C extension.""" from gi.repository import GdkPixbuf, GLib from vimiv import _image_enhance def enhance_bc(pixbuf, brightness, contrast): """Enhance brightness and contrast of a GdkPixbuf.Pixbuf. Args: pixbu...
Use rowstride directly from GdkPixbuf in enhance The custom calculation of rowstride failed for images with weird dimensions and completely broke enhance. fixes #51 # vim: ft=python fileencoding=utf-8 sw=4 et sts=4 """Wrapper functions for the _image_enhance C extension.""" from gi.repository import GdkPixbuf, GLib...
068862dc72fa82ec35e7fabc6a0a99dc10f7f034
octavia/common/service.py
octavia/common/service.py
# Copyright 2014 Rackspace # # 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 t...
# Copyright 2014 Rackspace # # 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 t...
Remove bad INFO log "Starting Octavia API server"
Remove bad INFO log "Starting Octavia API server" This log is also display for health_manager and house_keeping service. Api service already display "Starting API server on..." in INFO level. Change-Id: I0a3ff91b556accdfadbad797488d17ae7a95d85b
Python
apache-2.0
openstack/octavia,openstack/octavia,openstack/octavia
# Copyright 2014 Rackspace # # 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 t...
Remove bad INFO log "Starting Octavia API server" This log is also display for health_manager and house_keeping service. Api service already display "Starting API server on..." in INFO level. Change-Id: I0a3ff91b556accdfadbad797488d17ae7a95d85b # Copyright 2014 Rackspace # # Licensed under the Apache License, Ver...
fea7a2c0e4f4f3da50935d03db4b9e19a0fc477c
shakespearelang/utils.py
shakespearelang/utils.py
def parseinfo_context(parseinfo, context_amount = 3): buffer = parseinfo.buffer context_start_line = max(parseinfo.line - 1 - context_amount, 0) before_context_lines = buffer.get_lines(context_start_line, parseinfo.line - 1) lines = buffer.get_lines(parseinfo.line, parseinfo.endline) after_context_l...
def parseinfo_context(parseinfo, context_amount = 3): buffer = parseinfo.buffer context_start_line = max(parseinfo.line - 1 - context_amount, 0) before_context_lines = buffer.get_lines(context_start_line, parseinfo.line - 1) lines = buffer.get_lines(parseinfo.line, parseinfo.endline) after_context_l...
Use ">>" for indicating next event, fix bug with indexing
Use ">>" for indicating next event, fix bug with indexing
Python
mit
zmbc/shakespearelang,zmbc/shakespearelang,zmbc/shakespearelang
def parseinfo_context(parseinfo, context_amount = 3): buffer = parseinfo.buffer context_start_line = max(parseinfo.line - 1 - context_amount, 0) before_context_lines = buffer.get_lines(context_start_line, parseinfo.line - 1) lines = buffer.get_lines(parseinfo.line, parseinfo.endline) after_context_l...
Use ">>" for indicating next event, fix bug with indexing def parseinfo_context(parseinfo, context_amount = 3): buffer = parseinfo.buffer context_start_line = max(parseinfo.line - 1 - context_amount, 0) before_context_lines = buffer.get_lines(context_start_line, parseinfo.line - 1) lines = buffer.get_l...
147d545b7118d7d8974cfe2ee95648d62fc0d1e9
microcms/admin.py
microcms/admin.py
# -*- coding: utf-8 -*- from django.contrib import admin from django.contrib.flatpages.models import FlatPage from django.contrib.flatpages.admin import FlatPageAdmin as StockFlatPageAdmin from django.contrib.sites.models import Site from microcms.conf import settings from microcms.models import Meta class MetaAdmin(...
# -*- coding: utf-8 -*- from django.contrib import admin from django.contrib.flatpages.models import FlatPage from django.contrib.flatpages.admin import FlatPageAdmin as StockFlatPageAdmin from django.contrib.sites.models import Site from django.utils.translation import ugettext_lazy as _ from microcms.conf import set...
Insert automatically flatpage default site
Insert automatically flatpage default site
Python
bsd-3-clause
eriol/django-microcms,eriol/django-microcms
# -*- coding: utf-8 -*- from django.contrib import admin from django.contrib.flatpages.models import FlatPage from django.contrib.flatpages.admin import FlatPageAdmin as StockFlatPageAdmin from django.contrib.sites.models import Site from django.utils.translation import ugettext_lazy as _ from microcms.conf import set...
Insert automatically flatpage default site # -*- coding: utf-8 -*- from django.contrib import admin from django.contrib.flatpages.models import FlatPage from django.contrib.flatpages.admin import FlatPageAdmin as StockFlatPageAdmin from django.contrib.sites.models import Site from microcms.conf import settings from m...
e9f3b6f9eb59ef7290498e8ceaf81c2bc66c8f59
ichnaea/gunicorn_config.py
ichnaea/gunicorn_config.py
# This file contains gunicorn configuration setttings, as described at # http://docs.gunicorn.org/en/latest/settings.html # The file is loaded via the -c ichnaea.gunicorn_config command line option # Be explicit about the worker class worker_class = "sync" # Set timeout to the same value as the default one from Amazo...
# This file contains gunicorn configuration setttings, as described at # http://docs.gunicorn.org/en/latest/settings.html # The file is loaded via the -c ichnaea.gunicorn_config command line option # Be explicit about the worker class worker_class = "sync" # Set timeout to the same value as the default one from Amazo...
Update gunicorn timeout after gunicorn issue was answered.
Update gunicorn timeout after gunicorn issue was answered.
Python
apache-2.0
mozilla/ichnaea,therewillbecode/ichnaea,mozilla/ichnaea,therewillbecode/ichnaea,mozilla/ichnaea,therewillbecode/ichnaea,mozilla/ichnaea
# This file contains gunicorn configuration setttings, as described at # http://docs.gunicorn.org/en/latest/settings.html # The file is loaded via the -c ichnaea.gunicorn_config command line option # Be explicit about the worker class worker_class = "sync" # Set timeout to the same value as the default one from Amazo...
Update gunicorn timeout after gunicorn issue was answered. # This file contains gunicorn configuration setttings, as described at # http://docs.gunicorn.org/en/latest/settings.html # The file is loaded via the -c ichnaea.gunicorn_config command line option # Be explicit about the worker class worker_class = "sync" #...
05e19922a5a0f7268ce1a34e25e5deb8e9a2f5d3
sfmtools.py
sfmtools.py
""" Utility functions for PhotoScan processing """ import os, sys import PhotoScan def align_and_clean_photos(chunk): ncameras = len(chunk.cameras) for frame in chunk.frames: frame.matchPhotos() chunk.alignCameras() for camera in chunk.cameras: if camera.transform is None: ...
""" Utility functions for PhotoScan processing """ import os, sys import PhotoScan def align_and_clean_photos(chunk): ncameras = len(chunk.cameras) for frame in chunk.frames: frame.matchPhotos() chunk.alignCameras() for camera in chunk.cameras: if camera.transform is None: ...
Check for trailing slash in path
Check for trailing slash in path
Python
mit
rmsare/sfmtools
""" Utility functions for PhotoScan processing """ import os, sys import PhotoScan def align_and_clean_photos(chunk): ncameras = len(chunk.cameras) for frame in chunk.frames: frame.matchPhotos() chunk.alignCameras() for camera in chunk.cameras: if camera.transform is None: ...
Check for trailing slash in path """ Utility functions for PhotoScan processing """ import os, sys import PhotoScan def align_and_clean_photos(chunk): ncameras = len(chunk.cameras) for frame in chunk.frames: frame.matchPhotos() chunk.alignCameras() for camera in chunk.cameras: if came...
4d83306f89710d70571e2b2fc2f3a61af8b5793b
setup.py
setup.py
from setuptools import setup setup( name='aws-helpers', description='Set of AWS helper scripts', url='https://github.com/otype/aws-helpers', author='Hans-Gunther Schmidt', author_email='hans@otype.de', version='0.1', install_requires=['awscli', 'boto'], scripts=['src/aws-instances', 'src...
from setuptools import setup setup( name='aws-helpers', description='Set of AWS helper scripts', url='https://github.com/otype/aws-helpers', author='Hans-Gunther Schmidt', author_email='hans@otype.de', version='0.1', install_requires=['awscli==1.12.2'], scripts=['src/aws-instances', 'src...
Fix awscli to 1.12.2 as there are errors in later versions
Fix awscli to 1.12.2 as there are errors in later versions
Python
mit
otype/aws-helpers,otype/aws-helpers
from setuptools import setup setup( name='aws-helpers', description='Set of AWS helper scripts', url='https://github.com/otype/aws-helpers', author='Hans-Gunther Schmidt', author_email='hans@otype.de', version='0.1', install_requires=['awscli==1.12.2'], scripts=['src/aws-instances', 'src...
Fix awscli to 1.12.2 as there are errors in later versions from setuptools import setup setup( name='aws-helpers', description='Set of AWS helper scripts', url='https://github.com/otype/aws-helpers', author='Hans-Gunther Schmidt', author_email='hans@otype.de', version='0.1', install_require...
cd4152a9ea9953e4f6482bd51046fd754ffb7457
setup.py
setup.py
# -*- coding: utf-8 -*- from setuptools import setup, find_packages deps = [ line.strip() for line in open("deps.txt") if line and not line.startswith("#") ] metadata = dict( name='Yaka Core', version='0.1dev', url='http://www.yaka.biz/', license='LGPL', author='Stefane Fermigier', auth...
# -*- coding: utf-8 -*- from setuptools import setup, find_packages def get_deps(): import re deps_raw = [ line.strip() for line in open("deps.txt")] deps = [] for dep in deps_raw: if not dep or dep.startswith("#"): continue m = re.search("#egg=(.*)", dep) if m: dep = m.group(1) ...
Fix build broken by previous commit.
Fix build broken by previous commit.
Python
lgpl-2.1
abilian/abilian-core,abilian/abilian-core,abilian/abilian-core,abilian/abilian-core,abilian/abilian-core
# -*- coding: utf-8 -*- from setuptools import setup, find_packages def get_deps(): import re deps_raw = [ line.strip() for line in open("deps.txt")] deps = [] for dep in deps_raw: if not dep or dep.startswith("#"): continue m = re.search("#egg=(.*)", dep) if m: dep = m.group(1) ...
Fix build broken by previous commit. # -*- coding: utf-8 -*- from setuptools import setup, find_packages deps = [ line.strip() for line in open("deps.txt") if line and not line.startswith("#") ] metadata = dict( name='Yaka Core', version='0.1dev', url='http://www.yaka.biz/', license='LGPL'...
1e716c71395d2df5e34fe403115d0dab630f36cf
tests/config/test_defaults.py
tests/config/test_defaults.py
from __future__ import absolute_import, unicode_literals from mopidy import config def test_core_schema_has_cache_dir(): assert 'cache_dir' in config._core_schema assert isinstance(config._core_schema['cache_dir'], config.Path) def test_core_schema_has_config_dir(): assert 'config_dir' in config._core_...
Add tests for defaults in core schema config
tests: Add tests for defaults in core schema config Tests check if default core schema has cache_dir, config_dir, data_dir and max_tracklist_length and if they have proper type
Python
apache-2.0
jmarsik/mopidy,bencevans/mopidy,adamcik/mopidy,ZenithDK/mopidy,vrs01/mopidy,kingosticks/mopidy,diandiankan/mopidy,kingosticks/mopidy,ZenithDK/mopidy,bacontext/mopidy,jcass77/mopidy,ali/mopidy,SuperStarPL/mopidy,SuperStarPL/mopidy,bencevans/mopidy,adamcik/mopidy,ali/mopidy,vrs01/mopidy,hkariti/mopidy,jmarsik/mopidy,king...
from __future__ import absolute_import, unicode_literals from mopidy import config def test_core_schema_has_cache_dir(): assert 'cache_dir' in config._core_schema assert isinstance(config._core_schema['cache_dir'], config.Path) def test_core_schema_has_config_dir(): assert 'config_dir' in config._core_...
tests: Add tests for defaults in core schema config Tests check if default core schema has cache_dir, config_dir, data_dir and max_tracklist_length and if they have proper type
9fc92a176fbc9425229d02a032d3494566139e6a
tests/Physics/TestNTC.py
tests/Physics/TestNTC.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from numpy.testing import assert_approx_equal, assert_allclose, assert_array_less from nose.tools import raises, assert_true, assert_equal from UliEngineering.Physics.NTC import * from UliEngineering.Exceptions import * import functools import numpy as np class TestNTC(ob...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from numpy.testing import assert_approx_equal, assert_allclose, assert_array_less from nose.tools import raises, assert_true, assert_equal from UliEngineering.Physics.NTC import * from UliEngineering.Exceptions import * import functools import numpy as np class TestNTC(ob...
Add more NTC unit tests
Add more NTC unit tests
Python
apache-2.0
ulikoehler/UliEngineering
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from numpy.testing import assert_approx_equal, assert_allclose, assert_array_less from nose.tools import raises, assert_true, assert_equal from UliEngineering.Physics.NTC import * from UliEngineering.Exceptions import * import functools import numpy as np class TestNTC(ob...
Add more NTC unit tests #!/usr/bin/env python3 # -*- coding: utf-8 -*- from numpy.testing import assert_approx_equal, assert_allclose, assert_array_less from nose.tools import raises, assert_true, assert_equal from UliEngineering.Physics.NTC import * from UliEngineering.Exceptions import * import functools import nump...
818e15028c4dd158fa93fe4bcd351255585c2f4f
src/model/predict_rf_model.py
src/model/predict_rf_model.py
import numpy as np import pandas as pd import sys import os from sklearn.externals import joblib from sklearn.ensemble import RandomForestClassifier scriptpath = os.path.dirname(os.path.realpath(sys.argv[0])) + '/../' sys.path.append(os.path.abspath(scriptpath)) import utils parameter_str = '_'.join(['top', str(utils...
import numpy as np import pandas as pd import sys import os from sklearn.externals import joblib from sklearn.ensemble import RandomForestClassifier scriptpath = os.path.dirname(os.path.realpath(sys.argv[0])) + '/../' sys.path.append(os.path.abspath(scriptpath)) import utils parameter_str = '_'.join(['top', str(utils...
Handle missing value in predit rf
Handle missing value in predit rf
Python
bsd-3-clause
parkerzf/kaggle-expedia,parkerzf/kaggle-expedia,parkerzf/kaggle-expedia
import numpy as np import pandas as pd import sys import os from sklearn.externals import joblib from sklearn.ensemble import RandomForestClassifier scriptpath = os.path.dirname(os.path.realpath(sys.argv[0])) + '/../' sys.path.append(os.path.abspath(scriptpath)) import utils parameter_str = '_'.join(['top', str(utils...
Handle missing value in predit rf import numpy as np import pandas as pd import sys import os from sklearn.externals import joblib from sklearn.ensemble import RandomForestClassifier scriptpath = os.path.dirname(os.path.realpath(sys.argv[0])) + '/../' sys.path.append(os.path.abspath(scriptpath)) import utils paramet...
49990a967471f615936025c17ac1411e2976f159
neuroimaging/utils/tests/test_odict.py
neuroimaging/utils/tests/test_odict.py
"""Test file for the ordered dictionary module, odict.py.""" from neuroimaging.externals.scipy.testing import * from neuroimaging.utils.odict import odict class TestOdict(TestCase): def setUp(self): print 'setUp' self.thedict = odict((('one', 1.0), ('two', 2.0), ('three', 3.0))) def test_cop...
"""Test file for the ordered dictionary module, odict.py.""" from neuroimaging.externals.scipy.testing import * from neuroimaging.utils.odict import odict class TestOdict(TestCase): def setUp(self): print 'setUp' self.thedict = odict((('one', 1.0), ('two', 2.0), ('three', 3.0))) def test_cop...
Fix nose call so tests run in __main__.
BUG: Fix nose call so tests run in __main__.
Python
bsd-3-clause
yarikoptic/NiPy-OLD,yarikoptic/NiPy-OLD
"""Test file for the ordered dictionary module, odict.py.""" from neuroimaging.externals.scipy.testing import * from neuroimaging.utils.odict import odict class TestOdict(TestCase): def setUp(self): print 'setUp' self.thedict = odict((('one', 1.0), ('two', 2.0), ('three', 3.0))) def test_cop...
BUG: Fix nose call so tests run in __main__. """Test file for the ordered dictionary module, odict.py.""" from neuroimaging.externals.scipy.testing import * from neuroimaging.utils.odict import odict class TestOdict(TestCase): def setUp(self): print 'setUp' self.thedict = odict((('one', 1.0), ('t...
e0c19574995224fe56fad411ce6f0796b71f8af5
l10n_br_zip/__openerp__.py
l10n_br_zip/__openerp__.py
# -*- coding: utf-8 -*- # Copyright (C) 2009 Renato Lima - Akretion # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html { 'name': 'Brazilian Localisation ZIP Codes', 'license': 'AGPL-3', 'author': 'Akretion, Odoo Community Association (OCA)', 'version': '8.0.1.0.1', 'depends': [ ...
# -*- coding: utf-8 -*- # Copyright (C) 2009 Renato Lima - Akretion # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html { 'name': 'Brazilian Localisation ZIP Codes', 'license': 'AGPL-3', 'author': 'Akretion, Odoo Community Association (OCA)', 'version': '9.0.1.0.0', 'depends': [ ...
Change the version of module.
[MIG] Change the version of module.
Python
agpl-3.0
akretion/l10n-brazil,OCA/l10n-brazil,akretion/l10n-brazil,OCA/l10n-brazil,akretion/l10n-brazil,OCA/l10n-brazil
# -*- coding: utf-8 -*- # Copyright (C) 2009 Renato Lima - Akretion # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html { 'name': 'Brazilian Localisation ZIP Codes', 'license': 'AGPL-3', 'author': 'Akretion, Odoo Community Association (OCA)', 'version': '9.0.1.0.0', 'depends': [ ...
[MIG] Change the version of module. # -*- coding: utf-8 -*- # Copyright (C) 2009 Renato Lima - Akretion # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html { 'name': 'Brazilian Localisation ZIP Codes', 'license': 'AGPL-3', 'author': 'Akretion, Odoo Community Association (OCA)', 'version'...
ab0492c1c71bf9e77a0327efa2c8eca5be9ae728
tests/formatter/test_yamler.py
tests/formatter/test_yamler.py
import unittest, argparse from echolalia.formatter.yamler import Formatter class YamlerTestCase(unittest.TestCase): def setUp(self): self.parser = argparse.ArgumentParser() self.data = [{'char': chr(i), 'order': i - 96} for i in xrange(97, 100)] self.formatter = Formatter() def test_add_args(self): ...
Add tests for formatter yaml
Add tests for formatter yaml
Python
mit
eiri/echolalia-prototype
import unittest, argparse from echolalia.formatter.yamler import Formatter class YamlerTestCase(unittest.TestCase): def setUp(self): self.parser = argparse.ArgumentParser() self.data = [{'char': chr(i), 'order': i - 96} for i in xrange(97, 100)] self.formatter = Formatter() def test_add_args(self): ...
Add tests for formatter yaml
511030652f4f411b4a97e3412899c6c7980348d4
dailydevo/cac_actions.py
dailydevo/cac_actions.py
# coding=utf8 # Local modules from common import debug from common.action import action_classes from common.telegram import telegram_utils from dailydevo import cac_utils class CACDevoAction(action_classes.Action): def identifier(self): return "/cacdevo" def name(self): return "Center for Ac...
# coding=utf8 # Local modules from common import debug from common.action import action_classes from common.telegram import telegram_utils from dailydevo import cac_utils class CACDevoAction(action_classes.Action): def identifier(self): return "/cacdevo" def name(self): return "Center for Ac...
Fix for CACDevo hidden functionality
Fix for CACDevo hidden functionality
Python
mit
julwrites/biblicabot
# coding=utf8 # Local modules from common import debug from common.action import action_classes from common.telegram import telegram_utils from dailydevo import cac_utils class CACDevoAction(action_classes.Action): def identifier(self): return "/cacdevo" def name(self): return "Center for Ac...
Fix for CACDevo hidden functionality # coding=utf8 # Local modules from common import debug from common.action import action_classes from common.telegram import telegram_utils from dailydevo import cac_utils class CACDevoAction(action_classes.Action): def identifier(self): return "/cacdevo" def nam...
f95460070e80e1d83394fa6ed08bad9dad34802c
ovp_users/emails.py
ovp_users/emails.py
from ovp_core.emails import BaseMail class UserMail(BaseMail): """ This class is responsible for firing emails for Users """ def __init__(self, user, async_mail=None): super(UserMail, self).__init__(user.email, async_mail) def sendWelcome(self, context={}): """ Sent when user registers """ ...
from ovp_core.emails import BaseMail class UserMail(BaseMail): """ This class is responsible for firing emails for Users """ def __init__(self, user, async_mail=None): super(UserMail, self).__init__(user.email, async_mail) def sendWelcome(self, context={}): """ Sent when user registers """ ...
Revert "fix getting user email for recoveryToken"
Revert "fix getting user email for recoveryToken" This reverts commit a47b098e4d644391213958f9e05c179a7410208d.
Python
agpl-3.0
OpenVolunteeringPlatform/django-ovp-users,OpenVolunteeringPlatform/django-ovp-users
from ovp_core.emails import BaseMail class UserMail(BaseMail): """ This class is responsible for firing emails for Users """ def __init__(self, user, async_mail=None): super(UserMail, self).__init__(user.email, async_mail) def sendWelcome(self, context={}): """ Sent when user registers """ ...
Revert "fix getting user email for recoveryToken" This reverts commit a47b098e4d644391213958f9e05c179a7410208d. from ovp_core.emails import BaseMail class UserMail(BaseMail): """ This class is responsible for firing emails for Users """ def __init__(self, user, async_mail=None): super(UserMail, self).__i...
9a81879bd4eb01be5ed74acfdaf22acb635a9817
pikalang/__init__.py
pikalang/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """pikalang module. A brainfuck derivative based off the vocabulary of Pikachu from Pokemon. Copyright (c) 2019 Blake Grotewold """ import sys import os from pikalang.interpreter import PikalangProgram def load_source(file): if os.path.isfile(file): if os.p...
#!/usr/bin/env python # -*- coding: utf-8 -*- """pikalang module. A brainfuck derivative based off the vocabulary of Pikachu from Pokemon. Copyright (c) 2019 Blake Grotewold """ from __future__ import print_function import sys import os from pikalang.interpreter import PikalangProgram def load_source(file): i...
Add proper printing for py2
Add proper printing for py2
Python
mit
groteworld/pikalang,grotewold/pikalang
#!/usr/bin/env python # -*- coding: utf-8 -*- """pikalang module. A brainfuck derivative based off the vocabulary of Pikachu from Pokemon. Copyright (c) 2019 Blake Grotewold """ from __future__ import print_function import sys import os from pikalang.interpreter import PikalangProgram def load_source(file): i...
Add proper printing for py2 #!/usr/bin/env python # -*- coding: utf-8 -*- """pikalang module. A brainfuck derivative based off the vocabulary of Pikachu from Pokemon. Copyright (c) 2019 Blake Grotewold """ import sys import os from pikalang.interpreter import PikalangProgram def load_source(file): if os.path....
75e0c323871d6eae6959523b105a06cfe8460a28
etk2/etk.py
etk2/etk.py
import json class ETK(object): def __init__(self): pass def get_glossary(self, file_path): res = dict() with open(file_path) as fp: line = fp.readline().rstrip('\n') while line: res[line] = line line = fp.readline().rstrip('\n') ...
from typing import List import json class ETK(object): def __init__(self): pass def get_glossary(self, file_path) -> List[str]: """ A glossary is a text file, one entry per line. Args: file_path (str): path to a text file containing a glossary. Returns: L...
Add comments and typing annotations
Add comments and typing annotations
Python
mit
usc-isi-i2/etk,usc-isi-i2/etk,usc-isi-i2/etk
from typing import List import json class ETK(object): def __init__(self): pass def get_glossary(self, file_path) -> List[str]: """ A glossary is a text file, one entry per line. Args: file_path (str): path to a text file containing a glossary. Returns: L...
Add comments and typing annotations import json class ETK(object): def __init__(self): pass def get_glossary(self, file_path): res = dict() with open(file_path) as fp: line = fp.readline().rstrip('\n') while line: res[line] = line ...
805e67ad540e3072929dea30b8894af87fc622ef
uiharu/__init__.py
uiharu/__init__.py
import logging from flask import Flask log = logging.getLogger(__name__) def create_app(config_dict): app = Flask(__name__, static_folder=None) app.config.update(**config_dict) from uiharu.api.views import api as api_blueprint from uiharu.weather.views import weather as weather_blueprint app....
import logging log = logging.getLogger(__name__)
Remove flask usage in init
Remove flask usage in init
Python
mit
kennydo/uiharu
import logging log = logging.getLogger(__name__)
Remove flask usage in init import logging from flask import Flask log = logging.getLogger(__name__) def create_app(config_dict): app = Flask(__name__, static_folder=None) app.config.update(**config_dict) from uiharu.api.views import api as api_blueprint from uiharu.weather.views import weather as...
d57d572d91a5df06bbab97864c6187c7423c0135
main.py
main.py
# Import blockmodels file import BlockModels import webapp2, jinja2, os from datetime import * jinja_environment = jinja2.Environment(autoescape=True, loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates'))) class CST(tzinfo): def utcoffset(self, dt): return timedelta(hour...
# Import blockmodels file import BlockModels import webapp2, jinja2, os from datetime import * jinja_environment = jinja2.Environment(autoescape=True, loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates'))) class CST(tzinfo): def utcoffset(self, dt): return timedelta(hour...
Change the MainHandler to Schedule_Handler and changed the “/“ to “/schedule”
Change the MainHandler to Schedule_Handler and changed the “/“ to “/schedule”
Python
mit
shickey/BearStatus,shickey/BearStatus,shickey/BearStatus
# Import blockmodels file import BlockModels import webapp2, jinja2, os from datetime import * jinja_environment = jinja2.Environment(autoescape=True, loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates'))) class CST(tzinfo): def utcoffset(self, dt): return timedelta(hour...
Change the MainHandler to Schedule_Handler and changed the “/“ to “/schedule” # Import blockmodels file import BlockModels import webapp2, jinja2, os from datetime import * jinja_environment = jinja2.Environment(autoescape=True, loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))...
4bb1c93f1e88b6472c1e3ec058a52156160a0aaf
dipy/reconst/tests/test_dsi.py
dipy/reconst/tests/test_dsi.py
import numpy as np from nose.tools import assert_true, assert_false, assert_equal, assert_raises from numpy.testing import assert_array_equal, assert_array_almost_equal import nibabel as nib from dipy.data import get_data, get_sphere from dipy.reconst.recspeed import peak_finding from dipy.reconst.gqi import Generaliz...
TEST added test for dsi
TEST added test for dsi
Python
bsd-3-clause
rfdougherty/dipy,oesteban/dipy,nilgoyyou/dipy,samuelstjean/dipy,matthieudumont/dipy,sinkpoint/dipy,beni55/dipy,mdesco/dipy,oesteban/dipy,samuelstjean/dipy,rfdougherty/dipy,JohnGriffiths/dipy,jyeatman/dipy,maurozucchelli/dipy,StongeEtienne/dipy,Messaoud-Boudjada/dipy,villalonreina/dipy,samuelstjean/dipy,demianw/dipy,nil...
import numpy as np from nose.tools import assert_true, assert_false, assert_equal, assert_raises from numpy.testing import assert_array_equal, assert_array_almost_equal import nibabel as nib from dipy.data import get_data, get_sphere from dipy.reconst.recspeed import peak_finding from dipy.reconst.gqi import Generaliz...
TEST added test for dsi
450cb155d87b49a718e465d582bd2ccafb3244dd
tests/test_calculator.py
tests/test_calculator.py
import unittest from app.calculator import Calculator class TestCalculator(unittest.TestCase): def setUp(self): self.calc = Calculator() def test_calculator_addition_method_returns_correct_result(self): calc = Calculator() result = calc.addition(2,2) self.assertEqual(4, resu...
import unittest from app.calculator import Calculator class TestCalculator(unittest.TestCase): def setUp(self): self.calc = Calculator() def test_calculator_addition_method_returns_correct_result(self): calc = Calculator() result = calc.addition(2,2) self.assertEqual(4, resu...
Add new test for division
Add new test for division
Python
apache-2.0
kamaxeon/fap
import unittest from app.calculator import Calculator class TestCalculator(unittest.TestCase): def setUp(self): self.calc = Calculator() def test_calculator_addition_method_returns_correct_result(self): calc = Calculator() result = calc.addition(2,2) self.assertEqual(4, resu...
Add new test for division import unittest from app.calculator import Calculator class TestCalculator(unittest.TestCase): def setUp(self): self.calc = Calculator() def test_calculator_addition_method_returns_correct_result(self): calc = Calculator() result = calc.addition(2,2) ...
e4824f3357c6329e84e0d3f1ad206300c43d62c5
src/h5_to_tif_dir.py
src/h5_to_tif_dir.py
#!/usr/bin/python """ T Macrina 160314 Make TIF images of all H5 files in directory **All H5 files must have "img" group Args: sys.argv[1]: full path to the H5 image directory Returns: TIF files (extension changed to .tif) saved in the same directory """ from PIL import Image import numpy as np import h5py import...
Include Python script to convert 3D stack into dir of tif images
Include Python script to convert 3D stack into dir of tif images
Python
mit
seung-lab/Julimaps,seung-lab/Julimaps
#!/usr/bin/python """ T Macrina 160314 Make TIF images of all H5 files in directory **All H5 files must have "img" group Args: sys.argv[1]: full path to the H5 image directory Returns: TIF files (extension changed to .tif) saved in the same directory """ from PIL import Image import numpy as np import h5py import...
Include Python script to convert 3D stack into dir of tif images
374f32a1d5feaf2e912d901b9398f50f00e7d481
scripts/most_recent.py
scripts/most_recent.py
from datetime import datetime from optparse import OptionParser from urllib2 import urlopen from BeautifulSoup import BeautifulSoup if __name__ == '__main__': usage = "%prog <USERNAME> <WEB SERVER>" parser = OptionParser(usage=usage) opts,args = parser.parse_args() if len(args) != 2: parser.e...
Add script to print time of most recent gobble.
Add script to print time of most recent gobble.
Python
agpl-3.0
foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm
from datetime import datetime from optparse import OptionParser from urllib2 import urlopen from BeautifulSoup import BeautifulSoup if __name__ == '__main__': usage = "%prog <USERNAME> <WEB SERVER>" parser = OptionParser(usage=usage) opts,args = parser.parse_args() if len(args) != 2: parser.e...
Add script to print time of most recent gobble.
93cd0d5dc6388582bbcfdafe21c4f41793af75dc
hamlpy/template/utils.py
hamlpy/template/utils.py
import imp from django.template import loaders from os import listdir from os.path import dirname, splitext MODULE_EXTENSIONS = tuple([suffix[0] for suffix in imp.get_suffixes()]) def get_django_template_loaders(): return [(loader.__name__.rsplit('.', 1)[1], loader) for loader in get_submodules(load...
from importlib import machinery from django.template import loaders from os import listdir from os.path import dirname, splitext MODULE_EXTENSIONS = tuple(machinery.all_suffixes()) def get_django_template_loaders(): return [(loader.__name__.rsplit('.', 1)[1], loader) for loader in get_submodules(loa...
Replace deprecated imp usage with importlib
Replace deprecated imp usage with importlib
Python
mit
nyaruka/django-hamlpy,nyaruka/django-hamlpy
from importlib import machinery from django.template import loaders from os import listdir from os.path import dirname, splitext MODULE_EXTENSIONS = tuple(machinery.all_suffixes()) def get_django_template_loaders(): return [(loader.__name__.rsplit('.', 1)[1], loader) for loader in get_submodules(loa...
Replace deprecated imp usage with importlib import imp from django.template import loaders from os import listdir from os.path import dirname, splitext MODULE_EXTENSIONS = tuple([suffix[0] for suffix in imp.get_suffixes()]) def get_django_template_loaders(): return [(loader.__name__.rsplit('.', 1)[1], loader) ...
8ea0a6b9986996e40fea906a855fba5547b27c89
recalculate_gene_ranks.py
recalculate_gene_ranks.py
import django_rq import logging import os import time os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'varify.conf.settings') from django.core import management log = logging.getLogger(__name__) # We don't want this job to run forever so limit to this many attempts and # if the queue is still not empty just give up...
Add script to call gene-ranks command after samples load
Add script to call gene-ranks command after samples load This will need to be added as a cron job like the recalculate_allele_frequencies script is used now.
Python
bsd-2-clause
chop-dbhi/varify,chop-dbhi/varify,chop-dbhi/varify,chop-dbhi/varify
import django_rq import logging import os import time os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'varify.conf.settings') from django.core import management log = logging.getLogger(__name__) # We don't want this job to run forever so limit to this many attempts and # if the queue is still not empty just give up...
Add script to call gene-ranks command after samples load This will need to be added as a cron job like the recalculate_allele_frequencies script is used now.
b881b75624f636d7b4b3d65232655339e0fb9d0b
examples/example_ipython_notebook_config.py
examples/example_ipython_notebook_config.py
c = get_config() # Tell IPython to use PostgresContentsManager. c.NotebookApp.contents_manager_class = 'pgcontents.pgmanager.PostgresContentsManager' # Set the url for the database used to store files. See # http://docs.sqlalchemy.org/en/rel_0_9/core/engines.html#postgresql # for more info on db url formatting. # c....
Add an example configuration file.
DOC: Add an example configuration file.
Python
apache-2.0
quantopian/pgcontents
c = get_config() # Tell IPython to use PostgresContentsManager. c.NotebookApp.contents_manager_class = 'pgcontents.pgmanager.PostgresContentsManager' # Set the url for the database used to store files. See # http://docs.sqlalchemy.org/en/rel_0_9/core/engines.html#postgresql # for more info on db url formatting. # c....
DOC: Add an example configuration file.
86d12c7d13bd7a11a93deccf42f93df4328e70fd
admin_honeypot/urls.py
admin_honeypot/urls.py
from admin_honeypot import views from django.conf.urls import url app_name = 'admin_honeypot' urlpatterns = [ url(r'^login/$', views.AdminHoneypot.as_view(), name='login'), url(r'^.*$', views.AdminHoneypot.as_view(), name='index'), ]
from admin_honeypot import views from django.urls import path, re_path app_name = 'admin_honeypot' urlpatterns = [ path('login/', views.AdminHoneypot.as_view(), name='login'), re_path(r'^.*$', views.AdminHoneypot.as_view(), name='index'), ]
Update url() to path() in the urlconf.
Update url() to path() in the urlconf.
Python
mit
dmpayton/django-admin-honeypot,dmpayton/django-admin-honeypot
from admin_honeypot import views from django.urls import path, re_path app_name = 'admin_honeypot' urlpatterns = [ path('login/', views.AdminHoneypot.as_view(), name='login'), re_path(r'^.*$', views.AdminHoneypot.as_view(), name='index'), ]
Update url() to path() in the urlconf. from admin_honeypot import views from django.conf.urls import url app_name = 'admin_honeypot' urlpatterns = [ url(r'^login/$', views.AdminHoneypot.as_view(), name='login'), url(r'^.*$', views.AdminHoneypot.as_view(), name='index'), ]
4d95e5cb938c43cacd14085bf752485334ab6f1a
prf/tests/test_mongodb.py
prf/tests/test_mongodb.py
from prf.tests.prf_testcase import PrfTestCase from prf.mongodb import get_document_cls class TestMongoDB(PrfTestCase): def setUp(self): super(TestMongoDB, self).setUp() self.drop_databases() self.unload_documents() def test_get_document_cls(self): cls = self.create_collection...
import mock from prf.tests.prf_testcase import PrfTestCase from prf.mongodb import get_document_cls, connect_dataset_aliases class TestMongoDB(PrfTestCase): def setUp(self): super(TestMongoDB, self).setUp() self.drop_databases() self.unload_documents() def test_get_document_cls(self):...
Make sure no crashes happen when no namespaces are set
Make sure no crashes happen when no namespaces are set
Python
mit
vahana/prf
import mock from prf.tests.prf_testcase import PrfTestCase from prf.mongodb import get_document_cls, connect_dataset_aliases class TestMongoDB(PrfTestCase): def setUp(self): super(TestMongoDB, self).setUp() self.drop_databases() self.unload_documents() def test_get_document_cls(self):...
Make sure no crashes happen when no namespaces are set from prf.tests.prf_testcase import PrfTestCase from prf.mongodb import get_document_cls class TestMongoDB(PrfTestCase): def setUp(self): super(TestMongoDB, self).setUp() self.drop_databases() self.unload_documents() def test_get_...
3c0e434385558871e75ffb0d1810382ad9893143
functional_tests.py
functional_tests.py
from selenium import webdriver import pytest @pytest.fixture(scope='function') def browser(request): browser_ = webdriver.Firefox() def fin(): browser_.quit() request.addfinalizer(fin) return browser_ def test_can_show_a_relevant_code_snippet(browser): browser.get('http://localhost:800...
from selenium import webdriver import pytest @pytest.fixture(scope='function') def browser(request): browser_ = webdriver.Firefox() def fin(): browser_.quit() request.addfinalizer(fin) return browser_ def test_can_show_a_relevant_code_snippet(browser): # Jan visits the site browser...
Change FT to expect site name in title
Change FT to expect site name in title
Python
mit
jvanbrug/scout,jvanbrug/scout
from selenium import webdriver import pytest @pytest.fixture(scope='function') def browser(request): browser_ = webdriver.Firefox() def fin(): browser_.quit() request.addfinalizer(fin) return browser_ def test_can_show_a_relevant_code_snippet(browser): # Jan visits the site browser...
Change FT to expect site name in title from selenium import webdriver import pytest @pytest.fixture(scope='function') def browser(request): browser_ = webdriver.Firefox() def fin(): browser_.quit() request.addfinalizer(fin) return browser_ def test_can_show_a_relevant_code_snippet(browser...
1b5ad9a8e2b06218d511ce8f97521235c14a9507
src/app.py
src/app.py
import os import json import random import flask from hashlib import md5 records = {} # Create a hash table of all records. for record in json.loads(open('data/records-2015.json').read())['records']: records[md5(str(record['id']).encode('utf-8')).hexdigest()] = record app = flask.Flask(__name__) @app.route('/...
import os import json import random import flask import requests import hashlib DNZ_URL = 'http://api.digitalnz.org/v3/records/' DNZ_KEY = os.environ.get('DNZ_KEY') records = {} # TODO This should be switched to records associated with days. # Create a hash table of all records. for record in json.loads(open('data/re...
Add method to query DNZ Metadata API
Add method to query DNZ Metadata API
Python
mit
judsonsam/tekautoday,judsonsam/tekautoday,judsonsam/tekautoday,judsonsam/tekautoday
import os import json import random import flask import requests import hashlib DNZ_URL = 'http://api.digitalnz.org/v3/records/' DNZ_KEY = os.environ.get('DNZ_KEY') records = {} # TODO This should be switched to records associated with days. # Create a hash table of all records. for record in json.loads(open('data/re...
Add method to query DNZ Metadata API import os import json import random import flask from hashlib import md5 records = {} # Create a hash table of all records. for record in json.loads(open('data/records-2015.json').read())['records']: records[md5(str(record['id']).encode('utf-8')).hexdigest()] = record app =...
1f40edb5c567d85c621339a28d2b20c8f5406460
jacquard/service/commands.py
jacquard/service/commands.py
import werkzeug.debug import werkzeug.serving from jacquard.commands import BaseCommand from jacquard.service import get_wsgi_app class RunServer(object): help = "run a (local, debug) server" def add_arguments(self, parser): parser.add_argument( '-p', '--port', ty...
import werkzeug.debug import werkzeug.serving from jacquard.commands import BaseCommand from jacquard.service import get_wsgi_app class RunServer(BaseCommand): help = "run a (local, debug) server" def add_arguments(self, parser): parser.add_argument( '-p', '--port', ...
Make this derive from the correct type
Make this derive from the correct type
Python
mit
prophile/jacquard,prophile/jacquard
import werkzeug.debug import werkzeug.serving from jacquard.commands import BaseCommand from jacquard.service import get_wsgi_app class RunServer(BaseCommand): help = "run a (local, debug) server" def add_arguments(self, parser): parser.add_argument( '-p', '--port', ...
Make this derive from the correct type import werkzeug.debug import werkzeug.serving from jacquard.commands import BaseCommand from jacquard.service import get_wsgi_app class RunServer(object): help = "run a (local, debug) server" def add_arguments(self, parser): parser.add_argument( '-...
f3b57ef7713086a86f51a8ed98d52367b02c8959
project_fish/whats_fresh/test_models.py
project_fish/whats_fresh/test_models.py
from django.test import TestCase from django.conf import settings from whats_fresh.models import * from django.contrib.gis.db import models import os import time import sys import datetime class ImageTestCase(TestCase): def setUp(self): # Set MEDIA ROOT to sample data for this test TEST_ROOT = os...
Make preparation model tests actually work
Make preparation model tests actually work
Python
apache-2.0
iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api,osu-cass/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api,iCHAIT/whats-fresh-api
from django.test import TestCase from django.conf import settings from whats_fresh.models import * from django.contrib.gis.db import models import os import time import sys import datetime class ImageTestCase(TestCase): def setUp(self): # Set MEDIA ROOT to sample data for this test TEST_ROOT = os...
Make preparation model tests actually work
1f1699bb7b8cf537b8d2e206ac0ff03b74d5b3a7
container_files/init/mldb_finish.py
container_files/init/mldb_finish.py
#!/usr/bin/env python # Copyright Datacratic 2016 # Author: Jean Raby <jean@datacratic.com> # This script is called by runsv when the mldb service exits. # See http://smarden.org/runit/runsv.8.html for more details. # Two arguments are given to ./finish: # The first one is ./run's exit code, or -1 if ./run didn't exit...
#!/usr/bin/env python # Copyright Datacratic 2016 # Author: Jean Raby <jean@datacratic.com> # This script is called by runsv when the mldb service exits. # See http://smarden.org/runit/runsv.8.html for more details. # Two arguments are given to ./finish: # The first one is ./run's exit code, or -1 if ./run didn't exit...
Add signal map and human readable description
Add signal map and human readable description
Python
apache-2.0
mldbai/mldb,mldbai/mldb,mldbai/mldb,mldbai/mldb,mldbai/mldb,mldbai/mldb,mldbai/mldb
#!/usr/bin/env python # Copyright Datacratic 2016 # Author: Jean Raby <jean@datacratic.com> # This script is called by runsv when the mldb service exits. # See http://smarden.org/runit/runsv.8.html for more details. # Two arguments are given to ./finish: # The first one is ./run's exit code, or -1 if ./run didn't exit...
Add signal map and human readable description #!/usr/bin/env python # Copyright Datacratic 2016 # Author: Jean Raby <jean@datacratic.com> # This script is called by runsv when the mldb service exits. # See http://smarden.org/runit/runsv.8.html for more details. # Two arguments are given to ./finish: # The first one i...
71ca6c8516e5b887a22d2e16f3fdea72f7d041d9
STAF/__init__.py
STAF/__init__.py
# Copyright 2012 Kevin Goodsell # # This software is licensed under the Eclipse Public License (EPL) V1.0. ''' Interface to the STAF API. ''' # Using __all__ makes pydoc work properly. Otherwise it looks at the modules the # items actually come from and assumes they don't belong in the docs for # __init__. __all__ = ...
# Copyright 2012 Kevin Goodsell # # This software is licensed under the Eclipse Public License (EPL) V1.0. ''' Interface to the STAF API. ''' # Using __all__ makes pydoc work properly. Otherwise it looks at the modules the # items actually come from and assumes they don't belong in the docs for # __init__. __all__ = ...
Add missing function in __all__.
Add missing function in __all__.
Python
epl-1.0
KevinGoodsell/caduceus
# Copyright 2012 Kevin Goodsell # # This software is licensed under the Eclipse Public License (EPL) V1.0. ''' Interface to the STAF API. ''' # Using __all__ makes pydoc work properly. Otherwise it looks at the modules the # items actually come from and assumes they don't belong in the docs for # __init__. __all__ = ...
Add missing function in __all__. # Copyright 2012 Kevin Goodsell # # This software is licensed under the Eclipse Public License (EPL) V1.0. ''' Interface to the STAF API. ''' # Using __all__ makes pydoc work properly. Otherwise it looks at the modules the # items actually come from and assumes they don't belong in t...
d790a9e1a83d4a7bc1555c23235c2b0a31a5b69a
functest/tests/unit/features/test_domino.py
functest/tests/unit/features/test_domino.py
#!/usr/bin/env python # Copyright (c) 2017 Orange and others. # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 # pylint: d...
Add unit tests for domino
Add unit tests for domino Change-Id: Ie6671080a3d38a17da0ee608a362605a6d9df9db Signed-off-by: Cédric Ollivier <d48310251a4a484d041bc5d09a9ac4d86d20f793@orange.com>
Python
apache-2.0
opnfv/functest,mywulin/functest,opnfv/functest,mywulin/functest
#!/usr/bin/env python # Copyright (c) 2017 Orange and others. # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 # pylint: d...
Add unit tests for domino Change-Id: Ie6671080a3d38a17da0ee608a362605a6d9df9db Signed-off-by: Cédric Ollivier <d48310251a4a484d041bc5d09a9ac4d86d20f793@orange.com>
9fbcb33089b20003e042c2f6210a68d2121913ee
setup.py
setup.py
from setuptools import setup, find_packages setup( name="hubblestack", version="2.0", packages=find_packages(), entry_points={ 'console_scripts': [ 'hubble = hubble.daemon:run', ], }, install_requires=[ 'salt >= 2016.3.4', ], data_files=[('/etc/init.d'...
from setuptools import setup, find_packages import platform distro, version, _ = platform.dist() # Default to cent7 data_files = [('/usr/lib/systemd/system', ['pkg/hubble.service']),] if distro == 'redhat' or distro == 'centos': if version.startswith('6'): data_files = [('/etc/init.d', ['pkg/hubble']),] ...
Add platform detection for centos 6/7
Add platform detection for centos 6/7
Python
apache-2.0
basepi/hubble,madchills/hubble,madchills/hubble,basepi/hubble
from setuptools import setup, find_packages import platform distro, version, _ = platform.dist() # Default to cent7 data_files = [('/usr/lib/systemd/system', ['pkg/hubble.service']),] if distro == 'redhat' or distro == 'centos': if version.startswith('6'): data_files = [('/etc/init.d', ['pkg/hubble']),] ...
Add platform detection for centos 6/7 from setuptools import setup, find_packages setup( name="hubblestack", version="2.0", packages=find_packages(), entry_points={ 'console_scripts': [ 'hubble = hubble.daemon:run', ], }, install_requires=[ 'salt >= 2016.3.4'...
f7c9bbd5ac49254d564a56ba3713b55abcfa4079
byceps/blueprints/news/views.py
byceps/blueprints/news/views.py
# -*- coding: utf-8 -*- """ byceps.blueprints.news.views ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2016 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from flask import abort, g from ...services.news import service as news_service from ...util.framework import create_blueprint from .....
# -*- coding: utf-8 -*- """ byceps.blueprints.news.views ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2016 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from flask import abort, current_app, g from ...services.news import service as news_service from ...util.framework import create_blue...
Allow configuration of the number of news items per page
Allow configuration of the number of news items per page
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps
# -*- coding: utf-8 -*- """ byceps.blueprints.news.views ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2016 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from flask import abort, current_app, g from ...services.news import service as news_service from ...util.framework import create_blue...
Allow configuration of the number of news items per page # -*- coding: utf-8 -*- """ byceps.blueprints.news.views ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2016 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from flask import abort, g from ...services.news import service as news_serv...
2c164f6154e565225d593d82579975380bf1ed1f
scripts/klayout/scrotLayout.py
scripts/klayout/scrotLayout.py
import pya import re WIDTH = 2048 HEIGHT = 2048 app = pya.Application.instance() win = app.main_window() # Load technology file tech = pya.Technology() tech.load(tech_file) layoutOptions = tech.load_layout_options # Load def file in the main window cell_view = win.load_layout(input_layout, layoutOptions, 0) layout_...
Add a klayout script to screenshot layouts
Add a klayout script to screenshot layouts
Python
apache-2.0
efabless/openlane,efabless/openlane,efabless/openlane,efabless/openlane
import pya import re WIDTH = 2048 HEIGHT = 2048 app = pya.Application.instance() win = app.main_window() # Load technology file tech = pya.Technology() tech.load(tech_file) layoutOptions = tech.load_layout_options # Load def file in the main window cell_view = win.load_layout(input_layout, layoutOptions, 0) layout_...
Add a klayout script to screenshot layouts
4ac3c1d5feaadd46a13bc78f9834c29a789e0d9a
manage.py
manage.py
#!/usr/bin/env python import os import unittest from flask.ext.script import Manager, Server from app import app manager = Manager(app) server = Server(host='0.0.0.0', use_debugger=True) manager.add_command("runserver", server) @manager.command def test(): """Runs all the tests""" parent_dir = os.path.dir...
#!/usr/bin/env python import os import sys import unittest from flask.ext.script import Manager, Server from app import app manager = Manager(app) server = Server(host='0.0.0.0', use_debugger=True) manager.add_command("runserver", server) @manager.command def test(): """Runs all the tests""" parent_dir = ...
Set the exit code when running tests correctly
Set the exit code when running tests correctly
Python
mit
andytom/snippets,andytom/snippets
#!/usr/bin/env python import os import sys import unittest from flask.ext.script import Manager, Server from app import app manager = Manager(app) server = Server(host='0.0.0.0', use_debugger=True) manager.add_command("runserver", server) @manager.command def test(): """Runs all the tests""" parent_dir = ...
Set the exit code when running tests correctly #!/usr/bin/env python import os import unittest from flask.ext.script import Manager, Server from app import app manager = Manager(app) server = Server(host='0.0.0.0', use_debugger=True) manager.add_command("runserver", server) @manager.command def test(): """Ru...
ca53296d4f7af651905657d533ac18517531ca32
pybloom/slidingwindow.py
pybloom/slidingwindow.py
import time from collections import deque from pybloom import ScalableBloomFilter class DecayScalableBloomFilter(ScalableBloomFilter): ''' Stepwise decaying Bloom Filter ''' def __init__(self, initial_capacity=1000, error_rate=0.01, window_period = 60): super(DecayScalableBloomFilter, self)._...
Add simple SlidingWindowScalableBloomFilter for combating overengineer habit
Add simple SlidingWindowScalableBloomFilter for combating overengineer habit
Python
mit
Parsely/python-bloomfilter
import time from collections import deque from pybloom import ScalableBloomFilter class DecayScalableBloomFilter(ScalableBloomFilter): ''' Stepwise decaying Bloom Filter ''' def __init__(self, initial_capacity=1000, error_rate=0.01, window_period = 60): super(DecayScalableBloomFilter, self)._...
Add simple SlidingWindowScalableBloomFilter for combating overengineer habit
c2dd4d666e5d68a387ea48cabb99006d778b6d56
rng.py
rng.py
def get_random_number(start=1, end=10): """https://xkcd.com/221/""" return 4
from random import randint def get_random_number(start=1, end=10): """Generates and returns random number between :start: and :end:""" return randint(start, end)
Fix python random number generator.
Fix python random number generator.
Python
mit
1yvT0s/illacceptanything,illacceptanything/illacceptanything,paladique/illacceptanything,ultranaut/illacceptanything,tjhorner/illacceptanything,1yvT0s/illacceptanything,dushmis/illacceptanything,tjhorner/illacceptanything,caioproiete/illacceptanything,triggerNZ/illacceptanything,illacceptanything/illacceptanything,caio...
from random import randint def get_random_number(start=1, end=10): """Generates and returns random number between :start: and :end:""" return randint(start, end)
Fix python random number generator. def get_random_number(start=1, end=10): """https://xkcd.com/221/""" return 4
7f9a31a03e68e1d9dc6f420c6aa157e657da4157
apps/core/templatetags/files.py
apps/core/templatetags/files.py
from pathlib import Path from django import template from django.template.defaultfilters import stringfilter register = template.Library() @register.filter @stringfilter def filename(path): """Removes traceback lines from a string (if any). It has no effect when no 'Traceback' pattern has been found. R...
from pathlib import Path from django import template from django.template.defaultfilters import stringfilter register = template.Library() @register.filter @stringfilter def filename(path): """Removes parent path from a relative or absolute filename Returns: the filename """ return Path(path).name
Fix filename template tag docstring
Fix filename template tag docstring
Python
bsd-3-clause
Candihub/pixel,Candihub/pixel,Candihub/pixel,Candihub/pixel,Candihub/pixel
from pathlib import Path from django import template from django.template.defaultfilters import stringfilter register = template.Library() @register.filter @stringfilter def filename(path): """Removes parent path from a relative or absolute filename Returns: the filename """ return Path(path).name
Fix filename template tag docstring from pathlib import Path from django import template from django.template.defaultfilters import stringfilter register = template.Library() @register.filter @stringfilter def filename(path): """Removes traceback lines from a string (if any). It has no effect when no 'Trac...
ddb8d2f3078af9ded041b9eaacdfd3b8d69099bc
resolwe/flow/migrations/0025_entity_type.py
resolwe/flow/migrations/0025_entity_type.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.14 on 2018-11-07 08:44 from __future__ import unicode_literals from django.db import migrations def populate_entity_type(apps, schema_editor): """Populate entity type from attached descriptor schema.""" Entity = apps.get_model('flow', 'Entity') for enti...
Add migration to populate Entity type
Add migration to populate Entity type
Python
apache-2.0
jberci/resolwe,genialis/resolwe,jberci/resolwe,genialis/resolwe
# -*- coding: utf-8 -*- # Generated by Django 1.11.14 on 2018-11-07 08:44 from __future__ import unicode_literals from django.db import migrations def populate_entity_type(apps, schema_editor): """Populate entity type from attached descriptor schema.""" Entity = apps.get_model('flow', 'Entity') for enti...
Add migration to populate Entity type
684ac5e6e6011581d5abcb42a7c0e54742f20606
Arduino/IMUstream_WifiUDP_iot33/read_UDP_JSON_IMU.py
Arduino/IMUstream_WifiUDP_iot33/read_UDP_JSON_IMU.py
# ------------------------------------------------------- import socket, traceback import time import json host = '' port = 2390 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.bind((host, port)) fi...
# ------------------------------------------------------- import socket, traceback import time import json import numpy as np from scipy.spatial.transform import Rotation as R host = '' port = 2390 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsocko...
Add computations of great roll, pitch and small yaw angle (kite angles)
Add computations of great roll, pitch and small yaw angle (kite angles)
Python
mit
baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite
# ------------------------------------------------------- import socket, traceback import time import json import numpy as np from scipy.spatial.transform import Rotation as R host = '' port = 2390 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsocko...
Add computations of great roll, pitch and small yaw angle (kite angles) # ------------------------------------------------------- import socket, traceback import time import json host = '' port = 2390 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setso...
2cd0412ab14b92b7607d283d51e1650d008b6ad4
scipy/spatial/setupscons.py
scipy/spatial/setupscons.py
#!/usr/bin/env python from os.path import join def configuration(parent_package = '', top_path = None): from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs config = Configuration('cluster', parent_package, top_path) config.add_data_dir('tests') #config.add_extension('_vq', ...
#!/usr/bin/env python from os.path import join def configuration(parent_package = '', top_path = None): from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs config = Configuration('spatial', parent_package, top_path) config.add_data_dir('tests') #config.add_extension('_vq', ...
Update setup.py file for numscons build.
Update setup.py file for numscons build. git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@4958 d6536bca-fef9-0310-8506-e4c0a848fbcf
Python
bsd-3-clause
scipy/scipy-svn,scipy/scipy-svn,scipy/scipy-svn,jasonmccampbell/scipy-refactor,jasonmccampbell/scipy-refactor,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,lesserwhirls/scipy-cwt,scipy/scipy-svn,lesserwhirls/scipy-cwt,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor
#!/usr/bin/env python from os.path import join def configuration(parent_package = '', top_path = None): from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs config = Configuration('spatial', parent_package, top_path) config.add_data_dir('tests') #config.add_extension('_vq', ...
Update setup.py file for numscons build. git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@4958 d6536bca-fef9-0310-8506-e4c0a848fbcf #!/usr/bin/env python from os.path import join def configuration(parent_package = '', top_path = None): from numpy.distutils.misc_util import Configuration, get_numpy_include_d...
1c951a5aa3ff604177087e847faaeca1570bd898
experiments/keras_tensorflow/kuza55/original_examples/kuza55_blog_example.py
experiments/keras_tensorflow/kuza55/original_examples/kuza55_blog_example.py
# Multi-GPU Keras training. # Captured from https://github.com/kuza55/keras-extras and # https://medium.com/@kuza55/transparent-multi-gpu-training-on-tensorflow-with-keras-8b0016fd9012. from keras.layers import merge from keras.layers.core import Lambda from keras.models import Model import tensorflow as tf def make...
Add an example from kuza55.
Add an example from kuza55.
Python
mit
rossumai/keras-multi-gpu,rossumai/keras-multi-gpu
# Multi-GPU Keras training. # Captured from https://github.com/kuza55/keras-extras and # https://medium.com/@kuza55/transparent-multi-gpu-training-on-tensorflow-with-keras-8b0016fd9012. from keras.layers import merge from keras.layers.core import Lambda from keras.models import Model import tensorflow as tf def make...
Add an example from kuza55.
dddcec5d7712750617118843915fbae260eb8ffc
problem_3.py
problem_3.py
# Simple function for primeness test def is_prime(number): import math limit = int(math.sqrt(number)) + 1 if number == 2: return True if number % 2 == 0: return False for i in range(3, limit, 2): if number % i == 0: return False return True import math large_number = 600851475143 lim...
Solve problem 3 in Python
Solve problem 3 in Python
Python
mit
sirodoht/project-euler,sirodoht/project-euler,sirodoht/project-euler
# Simple function for primeness test def is_prime(number): import math limit = int(math.sqrt(number)) + 1 if number == 2: return True if number % 2 == 0: return False for i in range(3, limit, 2): if number % i == 0: return False return True import math large_number = 600851475143 lim...
Solve problem 3 in Python
deef2f98deeeaf51bd9ddda4c5a200d082e16522
arcutils/test/base.py
arcutils/test/base.py
import json import django.test from .user import UserMixin class Client(django.test.Client): def patch_json(self, path, data=None, **kwargs): return self.patch(path, **self._json_kwargs(data, kwargs)) def post_json(self, path, data=None, **kwargs): return self.post(path, **self._json_kwarg...
import json import django.test from .user import UserMixin class Client(django.test.Client): def patch_json(self, path, data=None, **kwargs): return self.patch(path, **self._json_kwargs(data, kwargs)) def post_json(self, path, data=None, **kwargs): return self.post(path, **self._json_kwarg...
Add patch_json method to our test Client
Add patch_json method to our test Client
Python
mit
wylee/django-arcutils,wylee/django-arcutils,PSU-OIT-ARC/django-arcutils,PSU-OIT-ARC/django-arcutils
import json import django.test from .user import UserMixin class Client(django.test.Client): def patch_json(self, path, data=None, **kwargs): return self.patch(path, **self._json_kwargs(data, kwargs)) def post_json(self, path, data=None, **kwargs): return self.post(path, **self._json_kwarg...
Add patch_json method to our test Client import json import django.test from .user import UserMixin class Client(django.test.Client): def patch_json(self, path, data=None, **kwargs): return self.patch(path, **self._json_kwargs(data, kwargs)) def post_json(self, path, data=None, **kwargs): ...
91d4c3a27002f62fbdd949e40dce96d58bdf5394
billjobs/permissions.py
billjobs/permissions.py
from rest_framework import permissions class CustomUserAPIPermission(permissions.BasePermission): """ Define custom permission for UserAPI and UserDetailAPI GET : only accessible by admin POST: public """ def has_permission(self, request, view): if request.method == 'GET': ...
Write permission for user api, make POST public
Write permission for user api, make POST public
Python
mit
ioO/billjobs
from rest_framework import permissions class CustomUserAPIPermission(permissions.BasePermission): """ Define custom permission for UserAPI and UserDetailAPI GET : only accessible by admin POST: public """ def has_permission(self, request, view): if request.method == 'GET': ...
Write permission for user api, make POST public
858f993ceffb497bee12457d1d4102339af410a4
typer/__init__.py
typer/__init__.py
"""Typer, build great CLIs. Easy to code. Based on Python type hints.""" __version__ = "0.0.4" from click.exceptions import ( # noqa Abort, BadArgumentUsage, BadOptionUsage, BadParameter, ClickException, FileError, MissingParameter, NoSuchOption, UsageError, ) from click.termui im...
"""Typer, build great CLIs. Easy to code. Based on Python type hints.""" __version__ = "0.0.4" from click.exceptions import ( # noqa Abort, Exit, ) from click.termui import ( # noqa clear, confirm, echo_via_pager, edit, get_terminal_size, getchar, launch, pause, progressb...
Clean exports from typer, remove unneeded Click components
:fire: Clean exports from typer, remove unneeded Click components and add Exit exception
Python
mit
tiangolo/typer,tiangolo/typer
"""Typer, build great CLIs. Easy to code. Based on Python type hints.""" __version__ = "0.0.4" from click.exceptions import ( # noqa Abort, Exit, ) from click.termui import ( # noqa clear, confirm, echo_via_pager, edit, get_terminal_size, getchar, launch, pause, progressb...
:fire: Clean exports from typer, remove unneeded Click components and add Exit exception """Typer, build great CLIs. Easy to code. Based on Python type hints.""" __version__ = "0.0.4" from click.exceptions import ( # noqa Abort, BadArgumentUsage, BadOptionUsage, BadParameter, ClickException, ...
8c1b7f8a5a7403e464938aa0aa6876557ec6a2b3
daphne/server.py
daphne/server.py
import time from twisted.internet import reactor from .http_protocol import HTTPFactory class Server(object): def __init__(self, channel_layer, host="127.0.0.1", port=8000): self.channel_layer = channel_layer self.host = host self.port = port def run(self): self.factory = HT...
import time from twisted.internet import reactor from .http_protocol import HTTPFactory class Server(object): def __init__(self, channel_layer, host="127.0.0.1", port=8000, signal_handlers=True): self.channel_layer = channel_layer self.host = host self.port = port self.signal_han...
Allow signal handlers to be disabled to run in subthread
Allow signal handlers to be disabled to run in subthread
Python
bsd-3-clause
django/daphne,maikhoepfel/daphne
import time from twisted.internet import reactor from .http_protocol import HTTPFactory class Server(object): def __init__(self, channel_layer, host="127.0.0.1", port=8000, signal_handlers=True): self.channel_layer = channel_layer self.host = host self.port = port self.signal_han...
Allow signal handlers to be disabled to run in subthread import time from twisted.internet import reactor from .http_protocol import HTTPFactory class Server(object): def __init__(self, channel_layer, host="127.0.0.1", port=8000): self.channel_layer = channel_layer self.host = host self...
4c2dd9dd6dc0f9ff66a36a114c90897dab8da7e5
goodreadsapi.py
goodreadsapi.py
#!/usr/bin/env python import re import requests import xmltodict from settings import goodreads_api_key def get_goodreads_ids(comment_msg): # receives goodreads url # returns the id using regex regex = r'goodreads.com/book/show/(\d+)' return set(re.findall(regex, comment_msg)) def get_book_detail...
#!/usr/bin/env python import re from xml.parsers.expat import ExpatError import requests import xmltodict from settings import goodreads_api_key def get_goodreads_ids(comment_msg): # receives goodreads url # returns the id using regex regex = r'goodreads.com/book/show/(\d+)' return set(re.findall(r...
Update GR API to handle Expat Error
Update GR API to handle Expat Error
Python
mit
avinassh/Reddit-GoodReads-Bot
#!/usr/bin/env python import re from xml.parsers.expat import ExpatError import requests import xmltodict from settings import goodreads_api_key def get_goodreads_ids(comment_msg): # receives goodreads url # returns the id using regex regex = r'goodreads.com/book/show/(\d+)' return set(re.findall(r...
Update GR API to handle Expat Error #!/usr/bin/env python import re import requests import xmltodict from settings import goodreads_api_key def get_goodreads_ids(comment_msg): # receives goodreads url # returns the id using regex regex = r'goodreads.com/book/show/(\d+)' return set(re.findall(regex...
1747fa822c6daf63d0875cf7b3da37423b0932dc
apps/api/paginators.py
apps/api/paginators.py
from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response class QuotesResultsSetPagination(PageNumberPagination): page_size = 10 page_size_query_param = 'page_size' max_page_size = 10000 def get_paginated_response(self, data): return Response({ ...
from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response class QuotesResultsSetPagination(PageNumberPagination): page_size = 25 page_size_query_param = 'page_size' max_page_size = 10000 def get_paginated_response(self, data): return Response({ ...
Change page size to 25
Change page size to 25
Python
bsd-3-clause
lucifurtun/myquotes,lucifurtun/myquotes,lucifurtun/myquotes,lucifurtun/myquotes
from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response class QuotesResultsSetPagination(PageNumberPagination): page_size = 25 page_size_query_param = 'page_size' max_page_size = 10000 def get_paginated_response(self, data): return Response({ ...
Change page size to 25 from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response class QuotesResultsSetPagination(PageNumberPagination): page_size = 10 page_size_query_param = 'page_size' max_page_size = 10000 def get_paginated_response(self, data): ...
875e25231dec76760bde97107d52036560347914
salt/modules/win_shadow.py
salt/modules/win_shadow.py
''' Manage the shadow file ''' import salt.utils def __virtual__(): ''' Only works on Windows systems ''' if salt.utils.is_windows(): return 'shadow' return False def info(name): ''' Return information for the specified user This is just returns dummy data so that salt state...
''' Manage the shadow file ''' import salt.utils def __virtual__(): ''' Only works on Windows systems ''' if salt.utils.is_windows(): return 'shadow' return False def info(name): ''' Return information for the specified user This is just returns dummy data so that salt state...
Rename 'pwd' field in windows shadow.info output
Rename 'pwd' field in windows shadow.info output This makes the field name consistent with the other shadow modules. Note that the passwd field is not used at all in Windows user management, so this is merely a cosmetic change.
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
''' Manage the shadow file ''' import salt.utils def __virtual__(): ''' Only works on Windows systems ''' if salt.utils.is_windows(): return 'shadow' return False def info(name): ''' Return information for the specified user This is just returns dummy data so that salt state...
Rename 'pwd' field in windows shadow.info output This makes the field name consistent with the other shadow modules. Note that the passwd field is not used at all in Windows user management, so this is merely a cosmetic change. ''' Manage the shadow file ''' import salt.utils def __virtual__(): ''' Only wo...
66289d6620758de0da80e91c6a492e39626c9029
tests/integration.py
tests/integration.py
#!/usr/bin/env python import unittest import subprocess class TestSimpleMapping(unittest.TestCase): def test_map_1_read(self): subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa']) result = subprocess.run(['python', 'bin/sillymap', 'map', 'tests/test_data/reference.fa'...
#!/usr/bin/env python import unittest import subprocess class TestSimpleMapping(unittest.TestCase): def test_map_1_read(self): subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa']) result = subprocess.run(['python', 'bin/sillymap', 'map', 'tests/test_data/reference.fa'...
Remove index file created in test
Remove index file created in test
Python
mit
alneberg/sillymap
#!/usr/bin/env python import unittest import subprocess class TestSimpleMapping(unittest.TestCase): def test_map_1_read(self): subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa']) result = subprocess.run(['python', 'bin/sillymap', 'map', 'tests/test_data/reference.fa'...
Remove index file created in test #!/usr/bin/env python import unittest import subprocess class TestSimpleMapping(unittest.TestCase): def test_map_1_read(self): subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa']) result = subprocess.run(['python', 'bin/sillymap', 'm...
a48b7bc7606d85705d8798f7823adb032df6dc0d
u2fval/__init__.py
u2fval/__init__.py
# Copyright (c) 2014 Yubico AB # All rights reserved. # # Redistribution and use in source and binary forms, with or # without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditi...
# Copyright (c) 2014 Yubico AB # All rights reserved. # # Redistribution and use in source and binary forms, with or # without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditi...
Set a development build version.
Set a development build version.
Python
bsd-2-clause
Yubico/u2fval
# Copyright (c) 2014 Yubico AB # All rights reserved. # # Redistribution and use in source and binary forms, with or # without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditi...
Set a development build version. # Copyright (c) 2014 Yubico AB # All rights reserved. # # Redistribution and use in source and binary forms, with or # without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of source code must retain the above copyright # ...
ad79f01358aa83162730b15507d7d6d3c3575ab3
akanda/horizon/configuration/tabs.py
akanda/horizon/configuration/tabs.py
import collections import logging from django.utils.translation import ugettext as _ from horizon.api import quantum from horizon import tabs from akanda.horizon.configuration.tables.publicips import PublicIPsTable # The table rendering code assumes it is getting an # object with an "id" property and other propert...
import collections import logging from django.utils.translation import ugettext as _ from horizon.api import quantum from horizon import tabs from akanda.horizon.configuration.tables.publicips import PublicIPsTable # The table rendering code assumes it is getting an # object with an "id" property and other propert...
Handle missing port and router data
Handle missing port and router data On some systems routers have no ports and ports have no fixed IPs, so don't assume they do. Also includes some pep8 fixes. Change-Id: I73b5f22754958b897a6ae55e453c294f47bf9539 Signed-off-by: Doug Hellmann <8c845c26a3868dadec615703cd974244eb2ac6d1@dreamhost.com>
Python
apache-2.0
dreamhost/akanda-horizon,dreamhost/akanda-horizon
import collections import logging from django.utils.translation import ugettext as _ from horizon.api import quantum from horizon import tabs from akanda.horizon.configuration.tables.publicips import PublicIPsTable # The table rendering code assumes it is getting an # object with an "id" property and other propert...
Handle missing port and router data On some systems routers have no ports and ports have no fixed IPs, so don't assume they do. Also includes some pep8 fixes. Change-Id: I73b5f22754958b897a6ae55e453c294f47bf9539 Signed-off-by: Doug Hellmann <8c845c26a3868dadec615703cd974244eb2ac6d1@dreamhost.com> import collections...
15cdcfe30e8599ff2968a0848169e48ad1ade831
fetch_configs/syzygy.py
fetch_configs/syzygy.py
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import sys import config_util # pylint: disable=F0401 # This class doesn't need an __init__ method, so we disable the warning # pylint: disable=W0232 cla...
Add a Syzygy fetch config.
Add a Syzygy fetch config. Review URL: https://codereview.chromium.org/1749213002 git-svn-id: fd409f4bdeea2bb50a5d34bb4d4bfc2046a5a3dd@299057 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
CoherentLabs/depot_tools,CoherentLabs/depot_tools,primiano/depot_tools,primiano/depot_tools,primiano/depot_tools
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import sys import config_util # pylint: disable=F0401 # This class doesn't need an __init__ method, so we disable the warning # pylint: disable=W0232 cla...
Add a Syzygy fetch config. Review URL: https://codereview.chromium.org/1749213002 git-svn-id: fd409f4bdeea2bb50a5d34bb4d4bfc2046a5a3dd@299057 0039d316-1c4b-4281-b951-d872f2087c98
859a82df7804f181ffc12052a4af59ab52a44560
test/goldstandard/benchmark_confirm.py
test/goldstandard/benchmark_confirm.py
import sqlite3 as sql import os import sys import logging import benchmark # bmVerify(['final_r7', 'final_r8'], filepath="/home/ysun/disambig/newcode/all/", outdir = "/home/ayu/results_v2/") # Text Files txt_file = 'benchmark_errors.txt' opened_file = open(txt_file, 'U') log_file = 'benchmark_results.log' #...
import sqlite3 as sql import os import sys import logging import benchmark # bmVerify(['final_r7', 'final_r8'], filepath="/home/ysun/disambig/newcode/all/", outdir = "/home/ayu/results_v2/") # Text Files txt_file = 'benchmark_errors.txt' opened_file = open(txt_file, 'U') log_file = 'benchmark_results.log' #...
Set up reading lines from file, print count for testing purposes
Set up reading lines from file, print count for testing purposes
Python
bsd-2-clause
yngcan/patentprocessor,nikken1/patentprocessor,funginstitute/patentprocessor,nikken1/patentprocessor,yngcan/patentprocessor,yngcan/patentprocessor,funginstitute/patentprocessor,funginstitute/patentprocessor,nikken1/patentprocessor
import sqlite3 as sql import os import sys import logging import benchmark # bmVerify(['final_r7', 'final_r8'], filepath="/home/ysun/disambig/newcode/all/", outdir = "/home/ayu/results_v2/") # Text Files txt_file = 'benchmark_errors.txt' opened_file = open(txt_file, 'U') log_file = 'benchmark_results.log' #...
Set up reading lines from file, print count for testing purposes import sqlite3 as sql import os import sys import logging import benchmark # bmVerify(['final_r7', 'final_r8'], filepath="/home/ysun/disambig/newcode/all/", outdir = "/home/ayu/results_v2/") # Text Files txt_file = 'benchmark_errors.txt' opene...
90def43806ca31e449ab70b1daa09fa354b7fd74
bin/generate_test_queries.py
bin/generate_test_queries.py
#!/usr/bin/env python import os import sys import time try: import wikipedia except ImportError: print('Queries generation requires wikipedia package. \n' 'You can install it by running "pip install wikipedia"') exit() # If user in bin directory set correct path to queries if os.getcwd().endswith...
Create script for generation test queries
Create script for generation test queries
Python
lgpl-2.1
daminisatya/loklak_server,PiotrKowalski/loklak_server,singhpratyush/loklak_server,smokingwheels/loklak_server_frontend_hdd,arashahmadi/sensemi_ai,singhpratyush/loklak_server,smsunarto/loklak_server,loklak/loklak_server,sudheesh001/loklak_server,singhpratyush/loklak_server,smsunarto/loklak_server,singhpratyush/loklak_se...
#!/usr/bin/env python import os import sys import time try: import wikipedia except ImportError: print('Queries generation requires wikipedia package. \n' 'You can install it by running "pip install wikipedia"') exit() # If user in bin directory set correct path to queries if os.getcwd().endswith...
Create script for generation test queries
b278eef6eb0f92694e70118e1e07855ea92dec5b
pulsar/client/transport/requests.py
pulsar/client/transport/requests.py
from __future__ import absolute_import try: from galaxy import eggs eggs.require("requets") except ImportError: pass try: import requests except ImportError: requests = None requests_multipart_post_available = False try: import requests_toolbelt requests_multipart_post_available = True exce...
from __future__ import absolute_import try: from galaxy import eggs eggs.require("requests") except ImportError: pass try: import requests except ImportError: requests = None requests_multipart_post_available = False try: import requests_toolbelt requests_multipart_post_available = True exc...
Fix typo Nate caught in Galaxy.
Fix typo Nate caught in Galaxy.
Python
apache-2.0
natefoo/pulsar,galaxyproject/pulsar,ssorgatem/pulsar,galaxyproject/pulsar,jmchilton/pulsar,natefoo/pulsar,ssorgatem/pulsar,jmchilton/pulsar
from __future__ import absolute_import try: from galaxy import eggs eggs.require("requests") except ImportError: pass try: import requests except ImportError: requests = None requests_multipart_post_available = False try: import requests_toolbelt requests_multipart_post_available = True exc...
Fix typo Nate caught in Galaxy. from __future__ import absolute_import try: from galaxy import eggs eggs.require("requets") except ImportError: pass try: import requests except ImportError: requests = None requests_multipart_post_available = False try: import requests_toolbelt requests_mul...
4ab14b3de299b58aee94511910d199cd1d1737a5
zou/app/utils/emails.py
zou/app/utils/emails.py
from flask_mail import Message from zou.app import mail def send_email(subject, body, recipient_email, html=None): """ Send an email with given subject and body to given recipient. """ if html is None: html = body message = Message( body=body, html=html, subject=su...
from flask_mail import Message from zou.app import mail, app def send_email(subject, body, recipient_email, html=None): """ Send an email with given subject and body to given recipient. """ if html is None: html = body with app.app_context(): message = Message( body=bo...
Fix email sending in production environment
Fix email sending in production environment
Python
agpl-3.0
cgwire/zou
from flask_mail import Message from zou.app import mail, app def send_email(subject, body, recipient_email, html=None): """ Send an email with given subject and body to given recipient. """ if html is None: html = body with app.app_context(): message = Message( body=bo...
Fix email sending in production environment from flask_mail import Message from zou.app import mail def send_email(subject, body, recipient_email, html=None): """ Send an email with given subject and body to given recipient. """ if html is None: html = body message = Message( bod...
99449881029eb29255d0dd9b2b4eb4e4ddd36af8
recorder.py
recorder.py
#!/usr/bin/env python from gevent.pywsgi import WSGIServer from flask import Flask import views from handler import PatchedWebSocketHandler from util import generate_filename, massage_record, make_trace_folder def setup_routes(app): app.add_url_rule('/', 'index', views.visualization, methods=['GET']) app.add...
#!/usr/bin/env python from flask import Flask import views from util import generate_filename, massage_record, make_trace_folder def setup_routes(app): app.add_url_rule('/', 'index', views.visualization, methods=['GET']) app.add_url_rule('/visualization', 'visualization', views.visualization, met...
Use built-in Flask server when debugging - websockets won't work.
Use built-in Flask server when debugging - websockets won't work.
Python
bsd-3-clause
openxc/web-logging-example,openxc/web-logging-example
#!/usr/bin/env python from flask import Flask import views from util import generate_filename, massage_record, make_trace_folder def setup_routes(app): app.add_url_rule('/', 'index', views.visualization, methods=['GET']) app.add_url_rule('/visualization', 'visualization', views.visualization, met...
Use built-in Flask server when debugging - websockets won't work. #!/usr/bin/env python from gevent.pywsgi import WSGIServer from flask import Flask import views from handler import PatchedWebSocketHandler from util import generate_filename, massage_record, make_trace_folder def setup_routes(app): app.add_url_r...
a1679be616d6d0d6ee807a708690549ec1798d04
python/array_manipulation.py
python/array_manipulation.py
#!/bin/python3 import math import os import random import re import sys def arrayManipulation(n, queries): array = [0] * n for a, b, k in queries: # Start is a - 1 because this is a one indexed array for i in range(a - 1, b): array[i] += k print(array) return max(a...
#!/bin/python3 import math import os import random import re import sys def arrayManipulation(n, queries): # An array used to capture the difference of an element # compared to the previous element. # Therefore the value of diffs[n] after all array manipulations is # the cumulative sum of values from...
Improve runtime by using an array of diffs
Improve runtime by using an array of diffs
Python
mit
rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank
#!/bin/python3 import math import os import random import re import sys def arrayManipulation(n, queries): # An array used to capture the difference of an element # compared to the previous element. # Therefore the value of diffs[n] after all array manipulations is # the cumulative sum of values from...
Improve runtime by using an array of diffs #!/bin/python3 import math import os import random import re import sys def arrayManipulation(n, queries): array = [0] * n for a, b, k in queries: # Start is a - 1 because this is a one indexed array for i in range(a - 1, b): array[i] +=...
329c3d31b76b22c481278a7c0994c9a7ba3f2852
migrations/versions/1020_add_buyer_email_domain_table.py
migrations/versions/1020_add_buyer_email_domain_table.py
"""Add buyer email domain table Revision ID: 1020 Revises: 1010 Create Date: 2017-10-10 15:18:22.683693 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '1020' down_revision = '1010' def upgrade(): op.create_table( 'buyer_email_domains', sa...
Add new buyer email domain table
Add new buyer email domain table A simple table to store the email domain (currently held in a text file). The domain_name field has a uniqueness constraint.
Python
mit
alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api
"""Add buyer email domain table Revision ID: 1020 Revises: 1010 Create Date: 2017-10-10 15:18:22.683693 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '1020' down_revision = '1010' def upgrade(): op.create_table( 'buyer_email_domains', sa...
Add new buyer email domain table A simple table to store the email domain (currently held in a text file). The domain_name field has a uniqueness constraint.
ed20a93e917cfdddc5cd49cc6446b6e80fb4573d
makam/migrations/0007_auto_20150812_1615.py
makam/migrations/0007_auto_20150812_1615.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django_extensions.db.fields class Migration(migrations.Migration): dependencies = [ ('makam', '0006_auto_20150727_1631'), ] operations = [ migrations.AlterField( m...
Migrate symbtr uuid field to django type
Migrate symbtr uuid field to django type
Python
agpl-3.0
MTG/dunya,MTG/dunya,MTG/dunya,MTG/dunya
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django_extensions.db.fields class Migration(migrations.Migration): dependencies = [ ('makam', '0006_auto_20150727_1631'), ] operations = [ migrations.AlterField( m...
Migrate symbtr uuid field to django type
c3b0d4b05314dc9fd51c790a86d30659d09c5250
wagtailgeowidget/helpers.py
wagtailgeowidget/helpers.py
import re geos_ptrn = re.compile( "^SRID=([0-9]{1,});POINT\(([0-9\.]{1,})\s([0-9\.]{1,})\)$" ) def geosgeometry_str_to_struct(value): ''' Parses a geosgeometry string into struct. Example: SRID=5432;POINT(12.0 13.0) Returns: >> [5432, 12.0, 13.0] ''' result = geos_ptrn.m...
import re geos_ptrn = re.compile( "^SRID=([0-9]{1,});POINT\((-?[0-9\.]{1,})\s(-?[0-9\.]{1,})\)$" ) def geosgeometry_str_to_struct(value): ''' Parses a geosgeometry string into struct. Example: SRID=5432;POINT(12.0 13.0) Returns: >> [5432, 12.0, 13.0] ''' result = geos_pt...
Allow negative numbers in the GEOS string
Allow negative numbers in the GEOS string The regular expression for parsing the GEOS string did not accept negative numbers. This means if you selected a location in most parts of the world the retrieve would fail and the map would center around the default location. Add optional hypen symbol to the GEOS regular exp...
Python
mit
Frojd/wagtail-geo-widget,Frojd/wagtail-geo-widget,Frojd/wagtail-geo-widget,Frojd/wagtail-geo-widget
import re geos_ptrn = re.compile( "^SRID=([0-9]{1,});POINT\((-?[0-9\.]{1,})\s(-?[0-9\.]{1,})\)$" ) def geosgeometry_str_to_struct(value): ''' Parses a geosgeometry string into struct. Example: SRID=5432;POINT(12.0 13.0) Returns: >> [5432, 12.0, 13.0] ''' result = geos_pt...
Allow negative numbers in the GEOS string The regular expression for parsing the GEOS string did not accept negative numbers. This means if you selected a location in most parts of the world the retrieve would fail and the map would center around the default location. Add optional hypen symbol to the GEOS regular exp...
1c5f2bd553666607328ca16816db882cd5496364
tests/test_client.py
tests/test_client.py
from flask import url_for from app import user_datastore from app.models import Post from tests.general import AppTestCase class TestClient(AppTestCase): def setUp(self): super().setUp() self.client = self.app.test_client(use_cookies=True) # Create user and log in user_datastore....
Add test case for post creation
Add test case for post creation
Python
mit
Encrylize/flask-blogger,Encrylize/flask-blogger,Encrylize/flask-blogger
from flask import url_for from app import user_datastore from app.models import Post from tests.general import AppTestCase class TestClient(AppTestCase): def setUp(self): super().setUp() self.client = self.app.test_client(use_cookies=True) # Create user and log in user_datastore....
Add test case for post creation
9e2669539c5d7662bb6d6a89877b30235eef1bc2
xor.py
xor.py
# http://www.codechef.com/DEC14/problems/XORSUB import operator def f(p): if p == []: return 0 elif len(p) == 1: return p[0] else: return reduce(operator.xor, p) def list_powerset(lst): result = [[]] for x in lst: result.extend([subset + [x] for subset in result]) return result t = int(ra...
Write solution to DEC14 XOR question.
Write solution to DEC14 XOR question.
Python
mit
paramsingh/cp,paramsingh/codechef-solutions,paramsingh/cp,paramsingh/codechef-solutions,paramsingh/cp,paramsingh/cp,paramsingh/codechef-solutions,paramsingh/codechef-solutions,paramsingh/cp
# http://www.codechef.com/DEC14/problems/XORSUB import operator def f(p): if p == []: return 0 elif len(p) == 1: return p[0] else: return reduce(operator.xor, p) def list_powerset(lst): result = [[]] for x in lst: result.extend([subset + [x] for subset in result]) return result t = int(ra...
Write solution to DEC14 XOR question.
f0f22d018d5dae1a362512da1f8e5290ac755795
examples/python/forum/router_spin.py
examples/python/forum/router_spin.py
import random import json import tornado.ioloop import tornado.httpclient http_client = tornado.httpclient.AsyncHTTPClient() schema_json = json.load(open('example_forum_sharded.json')) schema_json['name'] = 'example_forum' # set the datastore id schema_json['datastores'][0]['datastore']['_id'] = 54 @tornado.gen.co...
Add database provision test script
Add database provision test script This just constantly adds/removes (at random) the database to ensure it doesn't cause problems
Python
mit
jacksontj/dataman
import random import json import tornado.ioloop import tornado.httpclient http_client = tornado.httpclient.AsyncHTTPClient() schema_json = json.load(open('example_forum_sharded.json')) schema_json['name'] = 'example_forum' # set the datastore id schema_json['datastores'][0]['datastore']['_id'] = 54 @tornado.gen.co...
Add database provision test script This just constantly adds/removes (at random) the database to ensure it doesn't cause problems
e2d565bb283f2425005a93c0dd3abc9a422520d7
nodeconductor/iaas/cost_tracking.py
nodeconductor/iaas/cost_tracking.py
import logging import calendar import datetime from nodeconductor.cost_tracking import CostTrackingStrategy from nodeconductor.iaas.models import Instance from nodeconductor.structure import ServiceBackendError logger = logging.getLogger(__name__) class IaaSCostTracking(CostTrackingStrategy): @classmethod ...
import logging import calendar import datetime from nodeconductor.cost_tracking import CostTrackingStrategy from nodeconductor.iaas.models import Instance from nodeconductor.structure import ServiceBackendError logger = logging.getLogger(__name__) class IaaSCostTracking(CostTrackingStrategy): @classmethod ...
Fix killbill cost estimate logic
Fix killbill cost estimate logic - NC-738
Python
mit
opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor
import logging import calendar import datetime from nodeconductor.cost_tracking import CostTrackingStrategy from nodeconductor.iaas.models import Instance from nodeconductor.structure import ServiceBackendError logger = logging.getLogger(__name__) class IaaSCostTracking(CostTrackingStrategy): @classmethod ...
Fix killbill cost estimate logic - NC-738 import logging import calendar import datetime from nodeconductor.cost_tracking import CostTrackingStrategy from nodeconductor.iaas.models import Instance from nodeconductor.structure import ServiceBackendError logger = logging.getLogger(__name__) class IaaSCostTracking(...
a04f3d167011e6d0e50d6a088f5877769fbedaa2
testfixtures/shop_order.py
testfixtures/shop_order.py
""" testfixtures.shop_order ~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from byceps.services.shop.order.models.order import Order from byceps.services.shop.order.models.orderer import Orderer from byceps.services.shop.order import service fro...
""" testfixtures.shop_order ~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from byceps.services.shop.order.models.order import Order from byceps.services.shop.order.models.orderer import Orderer from byceps.services.shop.order.transfer.models im...
Remove unused test fixture `create_order_item`
Remove unused test fixture `create_order_item`
Python
bsd-3-clause
homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps
""" testfixtures.shop_order ~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from byceps.services.shop.order.models.order import Order from byceps.services.shop.order.models.orderer import Orderer from byceps.services.shop.order.transfer.models im...
Remove unused test fixture `create_order_item` """ testfixtures.shop_order ~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from byceps.services.shop.order.models.order import Order from byceps.services.shop.order.models.orderer import Orderer fr...
bb9e15a2415cba3dfcc871ea64aeaa14199fd293
plantcv/plantcv/color_palette.py
plantcv/plantcv/color_palette.py
# Color palette returns an array of colors (rainbow) from matplotlib import pyplot as plt import numpy as np from plantcv.plantcv import params def color_palette(num): """color_palette: Returns a list of colors length num Inputs: num = number of colors to return. Returns: colors = a ...
# Color palette returns an array of colors (rainbow) import numpy as np from plantcv.plantcv import params def color_palette(num): """color_palette: Returns a list of colors length num Inputs: num = number of colors to return. Returns: colors = a list of color lists (RGB values) ...
Move matplotlib import into function
Move matplotlib import into function I think importing it at the top-level causes a conflict with our global matplotlib backend settings
Python
mit
stiphyMT/plantcv,danforthcenter/plantcv,danforthcenter/plantcv,stiphyMT/plantcv,stiphyMT/plantcv,danforthcenter/plantcv
# Color palette returns an array of colors (rainbow) import numpy as np from plantcv.plantcv import params def color_palette(num): """color_palette: Returns a list of colors length num Inputs: num = number of colors to return. Returns: colors = a list of color lists (RGB values) ...
Move matplotlib import into function I think importing it at the top-level causes a conflict with our global matplotlib backend settings # Color palette returns an array of colors (rainbow) from matplotlib import pyplot as plt import numpy as np from plantcv.plantcv import params def color_palette(num): """col...