commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
29c68602396f04f57de587231b87c9e137d51412
celery/discovery.py
celery/discovery.py
import imp from django.conf import settings from django.core import exceptions __all__ = ["autodiscover", "tasks_for_app", "find_related_module"] def autodiscover(): """Include tasks for all applications in settings.INSTALLED_APPS.""" return filter(None, [tasks_for_app(app) for ap...
from django.conf import settings __all__ = ["autodiscover", "find_related_module"] def autodiscover(): """Include tasks for all applications in settings.INSTALLED_APPS.""" return filter(None, [find_related_module(app, "tasks") for app in settings.INSTALLED_APPS]) def find_relate...
Make autodiscover() work with zipped eggs.
Make autodiscover() work with zipped eggs.
Python
bsd-3-clause
ask/celery,mitsuhiko/celery,ask/celery,WoLpH/celery,frac/celery,mitsuhiko/celery,frac/celery,cbrepo/celery,cbrepo/celery,WoLpH/celery
1d1fec3287abbddfb376ff1fcbcc85bbcf0b44a2
pyoanda/tests/test_client.py
pyoanda/tests/test_client.py
import unittest from ..client import Client class TestClient(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_connect(self): pass
import unittest from unittest.mock import patch from ..client import Client from ..exceptions import BadCredentials class TestClient(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_connect_pass(self): with patch.object(Client, '_Client__get_credential...
Add very simple client creator validator
Add very simple client creator validator
Python
mit
MonoCloud/pyoanda,toloco/pyoanda,elyobo/pyoanda
49a6a89d7666fc4369b034bcf79d3bd794a468c5
partner_industry_secondary/models/res_partner.py
partner_industry_secondary/models/res_partner.py
# Copyright 2015 Antiun Ingenieria S.L. - Javier Iniesta # Copyright 2016 Tecnativa S.L. - Vicent Cubells # Copyright 2018 Eficent Business and IT Consulting Services, S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, exceptions, fields, models, _ class ResPartner(models...
# Copyright 2015 Antiun Ingenieria S.L. - Javier Iniesta # Copyright 2016 Tecnativa S.L. - Vicent Cubells # Copyright 2018 Eficent Business and IT Consulting Services, S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, exceptions, fields, models, _ class ResPartner(models...
Make api constrains multi to avoid error when create a company with 2 contacts
[FIX] partner_industry_Secondary: Make api constrains multi to avoid error when create a company with 2 contacts
Python
agpl-3.0
Vauxoo/partner-contact,Vauxoo/partner-contact
9efa2ccc3067d20dc50fd5e3746b291cc670af90
rembed/test/response_test.py
rembed/test/response_test.py
from rembed import response from hamcrest import * import pytest def test_should_load_from_dictionary(): dict = {'title' : 'Bees'} oembed_response = response.OEmbedResponse(dict) assert_that(oembed_response.title, equal_to('Bees')) def test_response_should_be_immutable(): dict = {'title' : 'Bees'} ...
from rembed import response from hamcrest import * import pytest def test_should_load_from_dictionary(): dict = {'type' : 'link', 'version' : '1.0'} oembed_response = response.OEmbedResponse(dict) assert_that(oembed_response.type, equal_to('link')) def test_response_should_be_immutable(): dict = {'t...
Make test match spec more closely
Make test match spec more closely
Python
mit
tino/pyembed,pyembed/pyembed,pyembed/pyembed
8d40e514228e93af50fbe5264b15f79c2832de46
plantcv/plantcv/plot_image.py
plantcv/plantcv/plot_image.py
# Plot image to screen import os import cv2 import numpy as np def plot_image(img, cmap=None): """Plot an image to the screen. :param img: numpy.ndarray :param cmap: str :return: """ import matplotlib matplotlib.use('Agg', warn=False) from matplotlib import pyplot as plt dimensio...
# Plot image to screen import os import cv2 import numpy as np def plot_image(img, cmap=None): """Plot an image to the screen. :param img: numpy.ndarray :param cmap: str :return: """ from matplotlib import pyplot as plt dimensions = np.shape(img) # If the image is color then OpenCV ...
Remove Agg backend in plot
Remove Agg backend in plot Looks like applying the Agg backend in the plot_image function disables displaying images in Jupyter because the Agg backed is a non-GUI backend.
Python
mit
danforthcenter/plantcv,danforthcenter/plantcv,stiphyMT/plantcv,stiphyMT/plantcv,stiphyMT/plantcv,danforthcenter/plantcv
b11750b83e0fe99bb3c0a058d88ca21d0a64c332
data/load_data.py
data/load_data.py
import csv from chemtools.ml import get_decay_feature_vector from chemtools.mol_name import get_exact_name from models import DataPoint def main(path): with open(path, "r") as csvfile: reader = csv.reader(csvfile, delimiter=',', quotechar='"') points = [] count = 0 for row in read...
import csv from chemtools.ml import get_decay_feature_vector from chemtools.mol_name import get_exact_name from models import DataPoint def main(path): with open(path, "r") as csvfile: reader = csv.reader(csvfile, delimiter=',', quotechar='"') points = [] count = 0 for row in read...
Add fix for sqlite bulk_create breaking with loading lots of points
Add fix for sqlite bulk_create breaking with loading lots of points
Python
mit
crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp
806b19db6f50d63f5b0893e9d695f32830890dd2
crm/tests/test_contact_user.py
crm/tests/test_contact_user.py
from django.contrib.auth.models import User from django.test import TestCase from crm.tests.model_maker import ( make_contact, make_user_contact, ) from login.tests.model_maker import make_user class TestContactUser(TestCase): def test_link_user_to_contact(self): """Create a contact and link it ...
from django.contrib.auth.models import User from django.db import IntegrityError from django.test import TestCase from crm.tests.model_maker import ( make_contact, make_user_contact, ) from login.tests.model_maker import make_user class TestContactUser(TestCase): def test_link_user_to_contact(self): ...
Make sure a user can only link to one contact
Make sure a user can only link to one contact
Python
apache-2.0
pkimber/crm,pkimber/crm,pkimber/crm
02cfc3a53bf3f38dc676359eace0e258bfda682a
plotly/graph_objs/__init__.py
plotly/graph_objs/__init__.py
""" graph_objs ========== This package imports definitions for all of Plotly's graph objects. For more information, run help(Obj) on any of the following objects defined here. """ from __future__ import absolute_import from plotly.graph_objs.graph_objs import * __all__ = ["Data", "Annotations", ...
""" graph_objs ========== This package imports definitions for all of Plotly's graph objects. For more information, run help(Obj) on any of the following objects defined here. The reason for the package graph_objs and the module graph_objs is to provide a clearer API for users. """ from . graph_objs import ( Dat...
Remove the `import *`. Explicitly import what we want to expose.
Remove the `import *`. Explicitly import what we want to expose. Before __all__ was used to manage these. But it's clearer to just import what we want users to see.
Python
mit
plotly/plotly.py,plotly/python-api,plotly/plotly.py,ee-in/python-api,plotly/plotly.py,ee-in/python-api,plotly/python-api,ee-in/python-api,plotly/python-api
601fe6fd1fc2f34f7cefe2fac0ff343144d139cc
src/ipf/ipfblock/rgb2gray.py
src/ipf/ipfblock/rgb2gray.py
# -*- coding: utf-8 -*- import ipfblock import ioport import ipf.ipfblock.processing from ipf.ipftype.ipfimage3ctype import IPFImage3cType from ipf.ipftype.ipfimage1ctype import IPFImage1cType class RGB2Gray(ipfblock.IPFBlock): """ Convert 3 channel image to 1 channel gray block class """ type = "RG...
# -*- coding: utf-8 -*- import ipfblock import ioport import ipf.ipfblock.processing from ipf.ipftype.ipfimage3ctype import IPFImage3cType from ipf.ipftype.ipfimage1ctype import IPFImage1cType class RGB2Gray(ipfblock.IPFBlock): """ Convert 3 channel image to 1 channel gray block class """ type = "RG...
Change get_preview_image to same as other blocks (because we fix ipl to pil convert for 1-channel images)
Change get_preview_image to same as other blocks (because we fix ipl to pil convert for 1-channel images)
Python
lgpl-2.1
anton-golubkov/Garland,anton-golubkov/Garland
8834b22654574b71bb891570c77acf2f42eade06
lock_tokens/managers.py
lock_tokens/managers.py
from django.contrib.contenttypes.models import ContentType from django.db.models import Manager from lock_tokens.utils import get_oldest_valid_tokens_datetime class LockTokenManager(Manager): def get_for_object(self, obj): contenttype = ContentType.objects.get_for_model(obj) return self.get(lock...
from django.contrib.contenttypes.models import ContentType from django.db.models import Manager from lock_tokens.utils import get_oldest_valid_tokens_datetime class LockTokenManager(Manager): def get_for_object(self, obj, allow_expired=True): contenttype = ContentType.objects.get_for_model(obj) ...
Add 'allow_expired' parameter to LockTokenManager.get_for_object
Add 'allow_expired' parameter to LockTokenManager.get_for_object
Python
mit
rparent/django-lock-tokens,rparent/django-lock-tokens,rparent/django-lock-tokens
e6e6918b54d691803c48f217f0074d5bcdd9df50
endpoint/csp.py
endpoint/csp.py
# -*- coding: utf-8 -*- import falcon, util, json, sys, traceback # Content-security policy reports of frontend # Every CSP report is forwarded to ksi-admin@fi.muni.cz. # This is testing solution, if a lot of spam occurs, some intelligence should # be added to this endpoint. class CSP(object): def on_post(self,...
# -*- coding: utf-8 -*- import falcon, util, json, sys, traceback # Content-security policy reports of frontend # Every CSP report is forwarded to ksi-admin@fi.muni.cz. # This is testing solution, if a lot of spam occurs, some intelligence should # be added to this endpoint. class CSP(object): def on_post(self,...
Send CSP reports right to apophis.
Send CSP reports right to apophis.
Python
mit
fi-ksi/web-backend,fi-ksi/web-backend
c42856ffd6ab8a762ea095fbfbfd7705e1eabd51
ideascube/serveradmin/battery.py
ideascube/serveradmin/battery.py
import batinfo class Lime2Battery(batinfo.Battery): @property def status(self): if self.charging == 0: return 'Discharging' elif self.capacity < 100: return 'Charging' else: return 'Full' def get_batteries(): batteries = batinfo.batteries() ...
import batinfo class Lime2Battery(batinfo.Battery): @property def status(self): if self.charging == 0: return 'Discharging' elif self.capacity < 100: return 'Charging' else: return 'Full' def get_batteries(): batteries = batinfo.batteries() ...
Order the batteries by name
settings: Order the batteries by name Eventually we'll want to do better than this, but batinfo doesn't export what we'd need to do better. Moving to udev+upower would help, but that's probably something we should do with cockpit anyway.
Python
agpl-3.0
ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube
362827987bb6587e1440f5f3fa804635e426eb5f
windpowerlib/__init__.py
windpowerlib/__init__.py
__copyright__ = "Copyright oemof developer group" __license__ = "MIT" __version__ = "0.2.1dev" from .wind_turbine import ( WindTurbine, get_turbine_types, create_power_curve, ) # noqa: F401 from .wind_farm import WindFarm # noqa: F401 from .wind_turbine_cluster import WindTurbineCluster # noqa: F401 fro...
__copyright__ = "Copyright oemof developer group" __license__ = "MIT" __version__ = "0.2.1dev" from .wind_turbine import WindTurbine # noqa: F401 from .wind_turbine import get_turbine_types # noqa: F401 from .wind_turbine import create_power_curve # noqa: F401 from .wind_farm import WindFarm # noqa: F401 from .win...
Use one line per import
Use one line per import
Python
mit
wind-python/windpowerlib
372d03b25f21d363138ecf340816dd04fb33ef71
docs/conf.py
docs/conf.py
extensions = [] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = u'django-soapbox' copyright = u'2011-2015, James Bennett' version = '1.1' release = '1.1' exclude_trees = ['_build'] pygments_style = 'sphinx' html_static_path = ['_static'] htmlhelp_basename = 'django-soapboxdoc' late...
import os on_rtd = os.environ.get('READTHEDOCS', None) == 'True' extensions = [] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = u'django-soapbox' copyright = u'2011-2015, James Bennett' version = '1.1' release = '1.1' exclude_trees = ['_build'] pygments_style = 'sphinx' html_sta...
Switch to RTD docs theme.
Switch to RTD docs theme.
Python
bsd-3-clause
ubernostrum/django-soapbox,ubernostrum/django-soapbox
8093c239128b1e8f607054c99eca3934da04a31e
comics/comics/dieselsweetiesweb.py
comics/comics/dieselsweetiesweb.py
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Diesel Sweeties (web)" language = "en" url = "http://www.dieselsweeties.com/" start_date = "2000-01-01" rights = "Richard Stevens" class Crawle...
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Diesel Sweeties (web)" language = "en" url = "http://www.dieselsweeties.com/" start_date = "2000-01-01" rights = "Richard Stevens" class Crawle...
Correct history capability for "Diesel Sweeties (web)"
Correct history capability for "Diesel Sweeties (web)"
Python
agpl-3.0
jodal/comics,jodal/comics,datagutten/comics,jodal/comics,jodal/comics,datagutten/comics,datagutten/comics,datagutten/comics
5d61b4904057acbe235b74fc1122d09aa365bdeb
edx_data_research/monitor/monitor_tracking.py
edx_data_research/monitor/monitor_tracking.py
import sys import time from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler class TrackingEventHandler(FileSystemEventHandler): def on_created(self, event): pass def on_moved(self, event): pass if __name__ == "__main__": if len(sys.argv) > 1: ...
import sys import time from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler class TrackingLogHandler(PatternMatchingEventHandler): def on_created(self, event): print event.__repr__() print event.event_type, event.is_directory, event.src_path if __name_...
Define handler for tracking log files
Define handler for tracking log files
Python
mit
McGillX/edx_data_research,McGillX/edx_data_research,McGillX/edx_data_research
7a073da50676864506c3a5de781d3c83530169e8
fbmsgbot/bot.py
fbmsgbot/bot.py
from http_client import HttpClient from models.message import ReceivedMessage class Bot(): """ @brief Facebook messenger bot """ def __init__(self, token): self.api_token = token self.client = HttpClient(token) def send_message(self, message): response, error = self.cli...
import json from http_client import HttpClient from models.message import ReceivedMessage class Bot(): """ @brief Facebook messenger bot """ def __init__(self, token): self.api_token = token self.client = HttpClient(token) def send_message(self, message): response, err...
Fix remove message object from greeting
Fix remove message object from greeting
Python
mit
ben-cunningham/python-messenger-bot,ben-cunningham/pybot
8b3d73ce9bbdcf39e7babd5637fcff9d1ad1dbf9
smartcard/Synchronization.py
smartcard/Synchronization.py
""" from Thinking in Python, Bruce Eckel http://mindview.net/Books/TIPython Simple emulation of Java's 'synchronized' keyword, from Peter Norvig. """ from threading import RLock def synchronized(method): def f(*args): self = args[0] self.mutex.acquire() # print method.__name__, 'acquire...
""" from Thinking in Python, Bruce Eckel http://mindview.net/Books/TIPython Simple emulation of Java's 'synchronized' keyword, from Peter Norvig. """ from threading import RLock def synchronized(method): def f(*args): self = args[0] self.mutex.acquire() # print method.__name__, 'acquire...
Use setattr() instead of a direct access to __dict__
Use setattr() instead of a direct access to __dict__ Closes Feature Request 3110077 "new style classes" https://sourceforge.net/tracker/?func=detail&aid=3110077&group_id=196342&atid=957075
Python
lgpl-2.1
moreati/pyscard,moreati/pyscard,LudovicRousseau/pyscard,moreati/pyscard,LudovicRousseau/pyscard,LudovicRousseau/pyscard
c5f153ce69819acdc8f83704daa919fb0cc0b02b
bookmarks/default_settings.py
bookmarks/default_settings.py
import pkg_resources # part of setuptools USER_AGENT_NAME = 'bookmarks' VERSION_NUMBER = pkg_resources.require('bookmarks')[0].version SECRET_KEY = 'development key' DATABASE_USERNAME = 'bookmarks' DATABASE_PASSWORD = '' DATABASE_HOST = 'localhost' DATABASE_NAME = 'bookmarks'
import pkg_resources # part of setuptools USER_AGENT_NAME = 'bookmarks' VERSION_NUMBER = pkg_resources.require('bookmarks')[0].version SECRET_KEY = 'development key' DATABASE_USERNAME = 'bookmarks' DATABASE_PASSWORD = '' DATABASE_HOST = 'localhost' DATABASE_NAME = 'bookmarks' TEST_DATABASE_NAME = 'bookmarks_test'
Add default test database name to default settings
Add default test database name to default settings
Python
apache-2.0
byanofsky/bookmarks,byanofsky/bookmarks,byanofsky/bookmarks
97696fafb6ce556781c02a130ae5f0e610c9bf45
test/selenium/src/lib/file_ops.py
test/selenium/src/lib/file_ops.py
# Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> import os import logging logger = logging.getLogger(__name__) def create_directory(path): """ Creates a directory if it doesn't already exist. """ # Check if path is a file_path or a dir_path. Di...
# Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> import logging import os import shutil logger = logging.getLogger(__name__) def create_directory(path): """ Creates a directory if it doesn't already exist. """ # Check if path is a file_path or a...
Delete sub folders in log directory
Delete sub folders in log directory
Python
apache-2.0
AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,andrei-karalionak/ggrc-core,selahssea/ggrc-core,selahssea/ggrc-core,andrei-karalionak/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,AleksNeStu/ggrc-core,plamut/ggrc-core,VinnieJohns/ggrc-core,selahssea/ggrc-core,selahssea/ggrc-core...
aa4174fa44994a30cae5be9a59eee6dd55ece201
tests/acceptance/response_test.py
tests/acceptance/response_test.py
from .request_test import test_app def test_200_for_normal_response_validation(): settings = { 'pyramid_swagger.schema_directory': 'tests/sample_schemas/good_app/', 'pyramid_swagger.enable_response_validation': True, } test_app(settings).post_json( '/sample', {'foo': 'test'...
from .request_test import test_app def test_200_for_normal_response_validation(): settings = { 'pyramid_swagger.schema_directory': 'tests/sample_schemas/good_app/', 'pyramid_swagger.enable_swagger_spec_validation': False, 'pyramid_swagger.enable_response_validation': True, } test_a...
Test needs skipping if on p3k
Test needs skipping if on p3k
Python
bsd-3-clause
brianthelion/pyramid_swagger,prat0318/pyramid_swagger,striglia/pyramid_swagger,analogue/pyramid_swagger,striglia/pyramid_swagger
08812c8507fac2c57bd143dd7aad4c54d5c0aa75
panoptes_client/user.py
panoptes_client/user.py
from __future__ import absolute_import, division, print_function from panoptes_client.panoptes import PanoptesObject, LinkResolver from panoptes_client.utils import isiterable, split class User(PanoptesObject): _api_slug = 'users' _link_slug = 'users' _edit_attributes = ( 'valid_email', ) ...
from __future__ import absolute_import, division, print_function from panoptes_client.panoptes import PanoptesObject, LinkResolver from panoptes_client.utils import isiterable, split class User(PanoptesObject): _api_slug = 'users' _link_slug = 'users' _edit_attributes = ( 'valid_email', ) ...
Allow batched User lookups by login name
Allow batched User lookups by login name
Python
apache-2.0
zooniverse/panoptes-python-client
26fc7b48d2d019b3c83db0d518d5cd99204f7982
linux/keyman-config/keyman_config/__init__.py
linux/keyman-config/keyman_config/__init__.py
from .version import __version__ from .version import __majorversion__ from .version import __releaseversion__ from .version import __tier__ if __tier__ == 'alpha': # Alpha versions will work against the staging server so that they # can access new APIs etc that will only be available there. The staging # ...
from .version import __version__ from .version import __majorversion__ from .version import __releaseversion__ from .version import __tier__ if __tier__ == 'alpha': # Alpha versions will work against the staging server so that they # can access new APIs etc that will only be available there. The staging # ...
Use new staging site names
feat(linux): Use new staging site names
Python
apache-2.0
tavultesoft/keymanweb,tavultesoft/keymanweb
c1acf5904ba8c48bb58e104195380b0bbce1ed8e
rest_framework_captcha/decorators.py
rest_framework_captcha/decorators.py
from functools import wraps from dateutil.relativedelta import relativedelta from django.utils import timezone from rest_framework_captcha.models import Captcha from rest_framework_captcha.helpers import get_settings, get_request_from_args from rest_framework.response import Response from rest_framework.exceptions impo...
from functools import wraps from dateutil.relativedelta import relativedelta from django.utils import timezone from rest_framework_captcha.models import Captcha from rest_framework_captcha.helpers import get_settings, get_request_from_args from rest_framework.response import Response from rest_framework.exceptions impo...
Add error and detail field to captcha errors
Add error and detail field to captcha errors
Python
mit
leonardoarroyo/rest-framework-captcha
146f6204e58695ca469cec7a79757ce9a730719e
contrib/migrateticketmodel.py
contrib/migrateticketmodel.py
#!/usr/bin/env python # # This script completely migrates a <= 0.8.x Trac environment to use the new # default ticket model introduced in Trac 0.9. # # In particular, this means that the severity field is removed (or rather # disabled by removing all possible values), and the priority values are # changed to the more...
#!/usr/bin/env python # # This script completely migrates a <= 0.8.x Trac environment to use the new # default ticket model introduced in Trac 0.9. # # In particular, this means that the severity field is removed (or rather # disabled by removing all possible values), and the priority values are # changed to the more...
Fix missing import in contrib script added in [2630].
Fix missing import in contrib script added in [2630].
Python
bsd-3-clause
pkdevbox/trac,pkdevbox/trac,pkdevbox/trac,pkdevbox/trac
8213a758782a7ab6cecc5a986e193f204fe57691
scrapy_gridfsfilespipeline/images.py
scrapy_gridfsfilespipeline/images.py
from scrapy.pipelines.images import ImagesPipeline from .files import GridFSFilesPipeline class GridFSImagesPipeline(ImagesPipeline, GridFSFilesPipeline): """ An extension of ImagesPipeline that store files in MongoDB GridFS. Is using a guid to check if the file exists in GridFS and MongoDB ObjectId to r...
from scrapy.pipelines.images import ImagesPipeline from .files import GridFSFilesPipeline class GridFSImagesPipeline(ImagesPipeline, GridFSFilesPipeline): """ An extension of ImagesPipeline that store files in MongoDB GridFS. Is using a guid to check if the file exists in GridFS and MongoDB ObjectId to r...
Add GridFSImagesPipeline.from_settings to use MONGO_URI
Add GridFSImagesPipeline.from_settings to use MONGO_URI
Python
bsd-2-clause
zahariesergiu/scrapy-gridfsfilespipeline
fbb9c2bc6f29b059da09764b563441ae687aee47
contentcuration/contentcuration/utils/asynccommand.py
contentcuration/contentcuration/utils/asynccommand.py
from abc import abstractmethod from django.core.management.base import BaseCommand class TaskCommand(BaseCommand): def start_progress(self, *args, **options): # TODO: needs implementation pass def update_progress(self, *args, **options): # TODO: needs implementation pass ...
from abc import abstractmethod from collections import namedtuple from django.core.management.base import BaseCommand from django.core.management.base import CommandError Progress = namedtuple( 'Progress', [ 'progress', 'total', 'fraction', ] ) class TaskCommand(BaseCommand): ...
Add a progress tracker to the async task command
Add a progress tracker to the async task command
Python
mit
DXCanas/content-curation,fle-internal/content-curation,DXCanas/content-curation,fle-internal/content-curation,DXCanas/content-curation,fle-internal/content-curation,fle-internal/content-curation,DXCanas/content-curation
bc48dd6e6b28406874cb3c3fda6c91cc90c77bb7
examples/users.py
examples/users.py
from pyolite import Pyolite # initial olite object admin_repository = 'gitolite-admin/' olite = Pyolite(admin_repository=admin_repository) bob = olite.users.create(name='bob', key='my-awesome-key') alice = olite.users.create(name='alice', key_path='~/.ssh/id_rsa.pub')
from pyolite import Pyolite # initial olite object admin_repository = 'gitolite-admin/' olite = Pyolite(admin_repository=admin_repository) # create user object vlad = olite.users.create(name='vlad', key_path='/home/wok/.ssh/id_rsa.pub') # get user by name vlad = olite.users.get(name='vlad') # get_or_create django s...
Introduce a complete user operations example
Introduce a complete user operations example
Python
bsd-2-clause
shawkinsl/pyolite,PressLabs/pyolite
fa610209334a53cd29441429609c5b045641b4d7
exp/lib/models/content_node.py
exp/lib/models/content_node.py
from .. import api_utils class ContentNode(object): def __init__(self, document, _isChildrenPopulated=False): self.document = document self._isChildrenPopulated = _isChildrenPopulated def get_url(self): return api_utils.generate_url("/api/delivery" + self.document.get("path")) def get_children(sel...
import urllib from .. import api_utils class ContentNode(object): def __init__(self, document, _isChildrenPopulated=False): self.document = document self._isChildrenPopulated = _isChildrenPopulated def get_url(self): return api_utils.generate_url("/api/delivery" + self.document.get("path")) def g...
Add get_variant_url method to content node.
Add get_variant_url method to content node.
Python
mit
ScalaInc/exp-python2-sdk,ScalaInc/exp-python2-sdk
456aba54c0a0967cfca807fe193a959228a0576f
setup.py
setup.py
#!/usr/bin/env python2 from distutils.core import setup import codecs import os.path as path cwd = path.dirname(__file__) version = '0.0.0' with codecs.open(path.join(cwd, 'mlbgame/version.py'), 'r', 'ascii') as f: exec(f.read()) version = __version__ assert version != '0.0.0' setup( name='mlbgame', ...
#!/usr/bin/env python2 from distutils.core import setup import codecs import os.path as path cwd = path.dirname(__file__) version = '0.0.0' with codecs.open(path.join(cwd, 'mlbgame/version.py'), 'r', 'ascii') as f: exec(f.read()) version = __version__ assert version != '0.0.0' install_requires = [] try: ...
Make sure urllib2 is installed
Make sure urllib2 is installed
Python
mit
panzarino/mlbgame,zachpanz88/mlbgame
6dcfacb5c76305bb227674eac6d926e54a26f45c
utils.py
utils.py
import platform RUNNING_IN_HELL = platform.system() == 'Windows' RUNNING_IN_STEVE_JOBS = platform.system() == 'Darwin' RUNNING_IN_GANOO_LOONIX = platform.system() == 'Linux'
import platform import io from PyQt5.QtCore import * from PyQt5.QtWidgets import * from PyQt5.QtGui import * RUNNING_IN_HELL = platform.system() == 'Windows' RUNNING_IN_STEVE_JOBS = platform.system() == 'Darwin' RUNNING_IN_GANOO_LOONIX = platform.system() == 'Linux' def Pixmap2StringIO(pixmap): byteArray = QBy...
Write Pixmap to a StringIO for uploading.
Write Pixmap to a StringIO for uploading.
Python
mit
miniCruzer/postit-desktop
78d57a82383747b657522c35449d249cb17cd610
views.py
views.py
from django.conf import settings from django.http import HttpResponse from django.utils.importlib import import_module def warmup(request): """ Provides default procedure for handling warmup requests on App Engine. Just add this view to your main urls.py. """ for app in settings.INSTALLED_APPS: ...
from django.conf import settings from django.http import HttpResponse from django.utils.importlib import import_module def warmup(request): """ Provides default procedure for handling warmup requests on App Engine. Just add this view to your main urls.py. """ for app in settings.INSTALLED_APPS: ...
Expand pre loading on warmup
Expand pre loading on warmup
Python
bsd-3-clause
brstrat/djangoappengine,Implisit/djangoappengine,potatolondon/djangoappengine-1-4,dwdraju/djangoappengine,potatolondon/djangoappengine-1-4,django-nonrel/djangoappengine
6fabe58bda70c9f6f05a226585259d44b178d6de
tests/from_json_test.py
tests/from_json_test.py
from common import * import tempfile def test_from_json(ds_local): df = ds_local # Create temporary json files pandas_df = df.to_pandas_df(df) tmp = tempfile.mktemp('.json') with open(tmp, 'w') as f: f.write(pandas_df.to_json()) tmp_df = vaex.from_json(tmp, copy_index=False) ass...
from common import * import tempfile def test_from_json(ds_local): df = ds_local # Create temporary json files pandas_df = df.to_pandas_df(df) tmp = tempfile.mktemp('.json') with open(tmp, 'w') as f: f.write(pandas_df.to_json()) tmp_df = vaex.from_json(tmp, copy_index=False) ass...
Use set to compare elements between two lists (making them immutable)
Use set to compare elements between two lists (making them immutable)
Python
mit
maartenbreddels/vaex,maartenbreddels/vaex,maartenbreddels/vaex,maartenbreddels/vaex,maartenbreddels/vaex,maartenbreddels/vaex
84ebba9c7d9290a7c1b72e82c7ba99a1f3b0db9f
eli5/explain.py
eli5/explain.py
# -*- coding: utf-8 -*- """ Dispatch module. Explanation functions for conctere estimator classes are defined in submodules. """ from singledispatch import singledispatch @singledispatch def explain_prediction(estimator, doc, **kwargs): """ Return an explanation of an estimator """ return { "estimator...
# -*- coding: utf-8 -*- """ Dispatch module. Explanation functions for conctere estimator classes are defined in submodules. """ from singledispatch import singledispatch from eli5.base import Explanation @singledispatch def explain_prediction(estimator, doc, **kwargs): """ Return an explanation of an estimator ...
Fix return values of placeholder functions
Fix return values of placeholder functions This allows to get nicer type completions in the IDE.
Python
mit
TeamHG-Memex/eli5,TeamHG-Memex/eli5,TeamHG-Memex/eli5
28c326f61848e50bdc6a5e86fc790f8114bd0468
rencon.py
rencon.py
#!/usr/bin/env python import os import sys from string import Template import argparse import hashlib if __name__ == "__main__": parser = argparse.ArgumentParser(description='Rename files based on content.') parser.add_argument('files', metavar='FILE', type=str, nargs='+', help='Files ...
#!/usr/bin/env python import os import sys from string import Template import argparse import hashlib if __name__ == "__main__": parser = argparse.ArgumentParser(description='Rename files based on content.') parser.add_argument('files', metavar='FILE', type=str, nargs='+', help='Files ...
Fix error when already renamed
Fix error when already renamed
Python
mit
laurentb/rencon
c6fa98931feaf9514b84ae979f32013ca345ef5f
saleor/product/views.py
saleor/product/views.py
from __future__ import unicode_literals from django.http import HttpResponsePermanentRedirect from django.contrib import messages from django.shortcuts import get_object_or_404, redirect from django.template.response import TemplateResponse from django.utils.translation import ugettext as _ from .forms import get_for...
from __future__ import unicode_literals from django.http import HttpResponsePermanentRedirect from django.contrib import messages from django.shortcuts import get_object_or_404, redirect from django.template.response import TemplateResponse from django.utils.translation import ugettext as _ from .forms import get_for...
Allow to use custom templates for products details pages
Allow to use custom templates for products details pages
Python
bsd-3-clause
josesanch/saleor,car3oon/saleor,UITools/saleor,maferelo/saleor,avorio/saleor,tfroehlich82/saleor,avorio/saleor,laosunhust/saleor,KenMutemi/saleor,paweltin/saleor,mociepka/saleor,dashmug/saleor,HyperManTT/ECommerceSaleor,paweltin/saleor,HyperManTT/ECommerceSaleor,Drekscott/Motlaesaleor,taedori81/saleor,UITools/saleor,jo...
5786942c88420be913705790489676780dcd9fc0
nlppln/utils.py
nlppln/utils.py
"""NLP pipeline utility functionality""" import os def remove_ext(fname): """Removes the extension from a filename """ bn = os.path.basename(fname) return os.path.splitext(bn)[0] def create_dirs(fname): """Create (output) directories if they don't exist """ fname = os.path.dirname(fname) ...
"""NLP pipeline utility functionality""" import os def remove_ext(fname): """Removes the extension from a filename """ bn = os.path.basename(fname) return os.path.splitext(bn)[0] def create_dirs(fname): """Create (output) directories if they don't exist """ fname = os.path.dirname(os.path...
Update createdirs to determine the absolute path of files
Update createdirs to determine the absolute path of files
Python
apache-2.0
WhatWorksWhenForWhom/nlppln,WhatWorksWhenForWhom/nlppln,WhatWorksWhenForWhom/nlppln
411117bf057e8835b6c9140b6a86b7ea85c6e80d
taskrunner/runners/result.py
taskrunner/runners/result.py
class Result: def __init__(self, return_code, stdout, stderr): self.return_code = return_code self.stdout = stdout self.stderr = stderr self.succeeded = self.return_code == 0 self.failed = not self.succeeded self.stdout_lines = stdout.splitlines() if stdout else [] ...
from ..util import cached_property class Result: def __init__(self, return_code, stdout, stderr): self.return_code = return_code self.stdout = stdout self.stderr = stderr self.succeeded = self.return_code == 0 self.failed = not self.succeeded @cached_property def ...
Make Result.stdout_lines and stderr_lines cached properties
Make Result.stdout_lines and stderr_lines cached properties I guess it probably doesn't matter much for performance, but we might as well avoid splitting output into lines eagerly since it's typically not used.
Python
mit
wylee/runcommands,wylee/runcommands
ccd5c79d1a574fa4cc551675ae12d1e47e46c15d
chrome/test/chromeos/autotest/files/client/site_tests/desktopui_SyncIntegrationTests/desktopui_SyncIntegrationTests.py
chrome/test/chromeos/autotest/files/client/site_tests/desktopui_SyncIntegrationTests/desktopui_SyncIntegrationTests.py
# Copyright (c) 2010 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. from autotest_lib.client.cros import chrome_test class desktopui_SyncIntegrationTests(chrome_test.ChromeTestBase): version = 1 def run_once(sel...
# Copyright (c) 2011 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. from autotest_lib.client.cros import chrome_test class desktopui_SyncIntegrationTests(chrome_test.ChromeTestBase): version = 1 binary_to_run = ...
Make the sync integration tests self-contained on autotest
Make the sync integration tests self-contained on autotest In the past, the sync integration tests used to require a password file stored on every test device in order to do a gaia sign in using production gaia servers. This caused the tests to be brittle. As of today, the sync integration tests no longer rely on a p...
Python
bsd-3-clause
Crystalnix/house-of-life-chromium,adobe/chromium,gavinp/chromium,adobe/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,ropik/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,Crystalnix/house-of-li...
1863c2cd57d2d09a8655ed15b741b1a038355321
tests/util/get_passed_env.py
tests/util/get_passed_env.py
import os from bonobo import Graph def extract(): env_test_user = os.getenv('ENV_TEST_USER') env_test_number = os.getenv('ENV_TEST_NUMBER') env_test_string = os.getenv('ENV_TEST_STRING') return env_test_user, env_test_number, env_test_string def load(s: str): print(s) graph = Graph(extract, l...
import os import bonobo def extract(): env_test_user = os.getenv('ENV_TEST_USER') env_test_number = os.getenv('ENV_TEST_NUMBER') env_test_string = os.getenv('ENV_TEST_STRING') return env_test_user, env_test_number, env_test_string def load(s: str): print(s) graph = bonobo.Graph(extract, load)...
Change import style in example.
Change import style in example.
Python
apache-2.0
python-bonobo/bonobo,hartym/bonobo,hartym/bonobo,python-bonobo/bonobo,hartym/bonobo,python-bonobo/bonobo
b2a2cd52d221b377af57b649d66c0df5e44b7712
src/mist/io/tests/features/environment.py
src/mist/io/tests/features/environment.py
import os import random from shutil import copyfile from behaving import environment as benv from behaving.web.steps import * from behaving.personas.steps import * from test_config import CREDENTIALS, MISTCREDS, TESTNAMES PERSONAS = { 'NinjaTester': dict( creds=CREDENTIALS, mistcreds=MISTCREDS, ...
import os import random from shutil import copyfile from behaving import environment as benv from behaving.web.steps import * from behaving.personas.steps import * try: from test_config import CREDENTIALS, MISTCREDS, TESTNAMES PERSONAS = { 'NinjaTester': dict( creds=CREDENTIALS, ...
Fix auto importing test_config if it is not there
Fix auto importing test_config if it is not there
Python
agpl-3.0
DimensionDataCBUSydney/mist.io,kelonye/mist.io,Lao-liu/mist.io,munkiat/mist.io,zBMNForks/mist.io,johnnyWalnut/mist.io,afivos/mist.io,Lao-liu/mist.io,Lao-liu/mist.io,DimensionDataCBUSydney/mist.io,johnnyWalnut/mist.io,munkiat/mist.io,zBMNForks/mist.io,kelonye/mist.io,afivos/mist.io,afivos/mist.io,munkiat/mist.io,munkiat...
32b8a5d9f18a673c621c8543848f5163dfe24393
cobs2/__init__.py
cobs2/__init__.py
""" Consistent Overhead Byte Stuffing (COBS) encoding and decoding. Functions are provided for encoding and decoding according to the basic COBS method. The COBS variant "Zero Pair Elimination" (ZPE) is not implemented. A C extension implementation only is provided. References: http://www.stuartcheshire.org/pap...
""" Consistent Overhead Byte Stuffing (COBS) encoding and decoding. Functions are provided for encoding and decoding according to the basic COBS method. The COBS variant "Zero Pair Elimination" (ZPE) is not implemented. A pure Python implementation and a C extension implementation are provided. If the C extension is...
Change Python 2.x import to fall-back to pure Python code if it can't load the C extension.
Change Python 2.x import to fall-back to pure Python code if it can't load the C extension.
Python
mit
cmcqueen/cobs-python,cmcqueen/cobs-python
326e7ba1378b691ad6323c2559686f0c4d97b45f
flowgen/core.py
flowgen/core.py
# -*- coding: utf-8 -*- from flowgen.graph import Graph from flowgen.language import Code from flowgen.options import parser from pypeg2 import parse from pypeg2.xmlast import thing2xml class FlowGen(object): def __init__(self, args): self.args = parser.parse_args(args) def any_output(self): ...
# -*- coding: utf-8 -*- from __future__ import print_function from flowgen.graph import Graph from flowgen.language import Code from flowgen.options import parser from pypeg2 import parse from pypeg2.xmlast import thing2xml class FlowGen(object): def __init__(self, args): self.args = parser.parse_args(arg...
Update py27 compatibility in print function
Update py27 compatibility in print function
Python
mit
ad-m/flowgen
2c56045f95f8efd8ff52e5151b24cfaa275660e8
forum/models.py
forum/models.py
from django.db import models import django.contrib.auth.models as auth class User(auth.User): """Model for representing users. It has few fields that aren't in the standard authentication user table, and are needed for the forum to work, like footers. """ display_name = models.CharField(max_length...
from django.db import models import django.contrib.auth.models as auth class User(auth.User): """Model for representing users. It has few fields that aren't in the standard authentication user table, and are needed for the forum to work, like footers. """ display_name = models.CharField(max_length...
Create model for post revisions.
Create model for post revisions.
Python
mit
xfix/NextBoard
cc8fab220bfeb94c94682912fbb63f4755dfa64f
oa_pmc.py
oa_pmc.py
#!/usr/bin/python # -*- coding: utf-8 -*- from time import sleep from cachetools import LRUCache from kids.cache import cache from http_cache import http_get # examples # https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=PMC3039489&resulttype=core&format=json&tool=oadoi # https://www.ebi.ac.uk/europepm...
#!/usr/bin/python # -*- coding: utf-8 -*- from cachetools import LRUCache from kids.cache import cache from http_cache import http_get # examples # https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=PMC3039489&resulttype=core&format=json&tool=oadoi # https://www.ebi.ac.uk/europepmc/webservices/rest/searc...
Revert "apply caveman rate limiting to europe pmc api calls"
Revert "apply caveman rate limiting to europe pmc api calls" This reverts commit f2d0b4ab961325dfffaf3a54603b56e848f46da0.
Python
mit
Impactstory/sherlockoa,Impactstory/sherlockoa
e9198579b3ff10c78df816fec204e36e502233d5
tests/test_channel_handler.py
tests/test_channel_handler.py
import json from tornado import testing, httpserver from qotr.server import make_application from qotr.channels import Channels class TestChannelHandler(testing.AsyncHTTPTestCase): ''' Test the channel creation handler. ''' port = None application = None def get_app(self): Channels.r...
import json from tornado import testing from qotr.server import make_application from qotr.channels import Channels class TestChannelHandler(testing.AsyncHTTPTestCase): ''' Test the channel creation handler. ''' port = None application = None def get_app(self): Channels.reset() ...
Make sure that the channel creation and storage works
Make sure that the channel creation and storage works Signed-off-by: Rohan Jain <f3a935f2cb7c3d75d1446a19169b923809d6e623@gmail.com>
Python
agpl-3.0
rmoorman/qotr,rmoorman/qotr,crodjer/qotr,sbuss/qotr,sbuss/qotr,rmoorman/qotr,crodjer/qotr,curtiszimmerman/qotr,crodjer/qotr,curtiszimmerman/qotr,rmoorman/qotr,sbuss/qotr,curtiszimmerman/qotr,crodjer/qotr,curtiszimmerman/qotr,sbuss/qotr
b7d63d1aab571eeab3dfc26674039b481398f7e5
sidecar/themes/light/__init__.py
sidecar/themes/light/__init__.py
from pyramid_frontend.theme import Theme from pyramid_frontend.images import FilterChain class LightTheme(Theme): key = 'light' require_config_path = '/_light/js/require_config.js' require_base_url = '/_light/js/vendor/' image_filters = ( FilterChain( 'thumb', width=330, height=22...
from pyramid_frontend.theme import Theme from pyramid_frontend.images import FilterChain from pyramid_frontend.assets.less import LessAsset from pyramid_frontend.assets.requirejs import RequireJSAsset class LightTheme(Theme): key = 'light' image_filters = ( FilterChain( 'thumb', width=330...
Update theme configuration to latest pyramid_frontend API
Update theme configuration to latest pyramid_frontend API
Python
mit
storborg/sidecar,storborg/sidecar
cbb1384757e54252a9a333828e535ca5596eaca1
wafer/schedule/admin.py
wafer/schedule/admin.py
from django.contrib import admin from django import forms from wafer.schedule.models import Venue, Slot, ScheduleItem from wafer.talks.models import Talk, ACCEPTED class ScheduleItemAdminForm(forms.ModelForm): class Meta: model = ScheduleItem def __init__(self, *args, **kwargs): super(Schedul...
from django.contrib import admin from django import forms from wafer.schedule.models import Venue, Slot, ScheduleItem from wafer.talks.models import Talk, ACCEPTED class ScheduleItemAdminForm(forms.ModelForm): class Meta: model = ScheduleItem def __init__(self, *args, **kwargs): super(Schedul...
Add end_time as editable on the slot list view to make tweaking times easier
Add end_time as editable on the slot list view to make tweaking times easier
Python
isc
CTPUG/wafer,CarlFK/wafer,CTPUG/wafer,CarlFK/wafer,CTPUG/wafer,CarlFK/wafer,CTPUG/wafer,CarlFK/wafer
8d3160f15b3c328ba86d6348a278c6825fcfa6c2
wcontrol/src/results.py
wcontrol/src/results.py
from wcontrol.conf.config import BMI, BFP class results(object): def __init__(self, control, gender): self.bmi = self.get_bmi(control.bmi) self.fat = self.get_fat(control.fat, gender) def get_bmi(self, bmi): for limit, msg in BMI: if bmi <= limit: return ms...
from wcontrol.conf.config import BMI, BFP, MUSCLE class results(object): def __init__(self, control, gender): self.bmi = self.get_bmi(control.bmi) self.fat = self.get_fat(control.fat, gender) self.muscle = self.get_muscle(control.muscle, gender) def get_bmi(self, bmi): for lim...
Add function to get the skeletal muscle result
Add function to get the skeletal muscle result
Python
mit
pahumadad/weight-control,pahumadad/weight-control,pahumadad/weight-control,pahumadad/weight-control
00009fe9627b947e3bb0674a3a70c61f4be59fb6
skimage/viewer/qt/__init__.py
skimage/viewer/qt/__init__.py
import os import warnings qt_api = os.environ.get('QT_API') if qt_api is None: try: import PySide qt_api = 'pyside' except ImportError: try: import PyQt4 qt_api = 'pyqt' except ImportError: qt_api = None # Note that we don't want ...
import os import warnings qt_api = os.environ.get('QT_API') if qt_api is None: try: import PyQt4 qt_api = 'pyqt' except ImportError: try: import PySide qt_api = 'pyside' except ImportError: qt_api = None # Note that we don't want ...
Use same order as matplotlib for PySize/PyQT
Use same order as matplotlib for PySize/PyQT
Python
bsd-3-clause
pratapvardhan/scikit-image,oew1v07/scikit-image,rjeli/scikit-image,jwiggins/scikit-image,warmspringwinds/scikit-image,youprofit/scikit-image,newville/scikit-image,warmspringwinds/scikit-image,keflavich/scikit-image,michaelpacer/scikit-image,WarrenWeckesser/scikits-image,ofgulban/scikit-image,juliusbierk/scikit-image,pa...
11dbea120cf035f0af4fec5285187cfd4ea03182
project/urls.py
project/urls.py
from django.conf.urls import patterns, include, url from django.contrib.flatpages import urls from search.views import CustomSearchView from haystack.views import search_view_factory from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url('', include('...
from django.conf.urls import patterns, include, url from django.contrib.flatpages import urls from search.views import CustomSearchView from haystack.views import search_view_factory from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url('', include('...
Remove font serving from app
Remove font serving from app
Python
mit
AxisPhilly/lobbying.ph-django,AxisPhilly/lobbying.ph-django,AxisPhilly/lobbying.ph-django
bfe5c6a16bf8515ae6ba49f4633f1a301e445092
redcliff/cli.py
redcliff/cli.py
from sys import exit import argparse from .commands import dispatch, choices from .config import get_config from .utils import merge def main(): parser = argparse.ArgumentParser() parser.add_argument('-u', '--base-url', metavar='https://redmine.example.com', h...
from sys import exit import argparse from .commands import dispatch, choices from .config import get_config from .utils import merge, error def main(): parser = argparse.ArgumentParser() parser.add_argument('-u', '--base-url', dest='url', metavar='https://redm...
Fix exception when required options are missing
Fix exception when required options are missing Options can be on command line and in config file, so we check in merged dictionary after getting from both sources.
Python
mit
dmedvinsky/redcliff
53fd251e22cf71c1f1f9a705d91ef91a9130129f
backend/django/apps/accounts/tests.py
backend/django/apps/accounts/tests.py
from django.core.urlresolvers import reverse from rest_framework.test import APITestCase from rest_framework import status import factory from .models import BaseAccount class UserFactory(factory.Factory): class Meta: model = BaseAccount first_name = 'John' last_name = 'Doe' email = '{}.{}@e...
from django.core.urlresolvers import reverse from rest_framework.test import APITestCase from rest_framework import status import factory import json from .models import BaseAccount from .serializers import WholeAccountSerializer class UserFactory(factory.django.DjangoModelFactory): class Meta: model = B...
Create a test for user creation through `FactoryBoy`
Create a test for user creation through `FactoryBoy` Add a test for user creation
Python
mit
slavpetroff/sweetshop,slavpetroff/sweetshop
8496ba409b9a340858e4473157aab87593868db7
pytask/views.py
pytask/views.py
from django.shortcuts import render_to_response def show_msg(user, message, redirect_url=None, url_desc=None): """ simply redirect to homepage """ return render_to_response('show_msg.html',{'user': user, 'message': message, ...
from django.shortcuts import render_to_response from pytask.profile import models as profile_models def show_msg(user, message, redirect_url=None, url_desc=None): """ simply redirect to homepage """ return render_to_response('show_msg.html',{'user': user, 'mess...
Use the right name for the profile role's values.
Use the right name for the profile role's values.
Python
agpl-3.0
madhusudancs/pytask,madhusudancs/pytask,madhusudancs/pytask
3cb25e903ad0fd342509d32dca2d3c507f001b5a
devilry/devilry_autoset_empty_email_by_username/models.py
devilry/devilry_autoset_empty_email_by_username/models.py
from django.db.models.signals import post_save from devilry.devilry_account.models import User from django.conf import settings def set_email_by_username(sender, **kwargs): """ Signal handler which is invoked when a User is saved. """ user = kwargs['instance'] if not user.email: user.email...
from django.conf import settings def set_email_by_username(sender, **kwargs): """ Signal handler which is invoked when a User is saved. """ user = kwargs['instance'] if not user.email: user.email = '{0}@{1}'.format(user.username, settings.DEVILRY_DEFAULT_EMAIL_SUFFIX) # post_save.connect(...
Comment out the post_save connect line.
devilry_autoset_empty_email_by_username: Comment out the post_save connect line.
Python
bsd-3-clause
devilry/devilry-django,devilry/devilry-django,devilry/devilry-django,devilry/devilry-django
04fbd56e647de937ceae426acb6762f1cbbcf616
cryptography/__about__.py
cryptography/__about__.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the...
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the...
Fix spelling of my name
Fix spelling of my name
Python
bsd-3-clause
bwhmather/cryptography,dstufft/cryptography,glyph/cryptography,kimvais/cryptography,dstufft/cryptography,bwhmather/cryptography,Lukasa/cryptography,sholsapp/cryptography,bwhmather/cryptography,skeuomorf/cryptography,kimvais/cryptography,Ayrx/cryptography,sholsapp/cryptography,skeuomorf/cryptography,glyph/cryptography,H...
092c58bbd0a8105e80e35c9c83833a62b510104f
similarities.py
similarities.py
#!/usr/bin/env python from signal import signal, SIGPIPE, SIG_DFL signal(SIGPIPE, SIG_DFL) import argparse import sys from gensim.models.word2vec import Word2Vec import csv parser = argparse.ArgumentParser() parser.add_argument('--sim', nargs='?', type=float, default=.3) parser.add_argument('w2v') args = vars(parser...
#!/usr/bin/env python from signal import signal, SIGPIPE, SIG_DFL signal(SIGPIPE, SIG_DFL) import argparse import sys from gensim.models.word2vec import Word2Vec import csv parser = argparse.ArgumentParser() parser.add_argument('--sim', nargs='?', type=float, default=.3) parser.add_argument('w2v') args = vars(parser...
Add a negative similarity crutch
Add a negative similarity crutch
Python
mit
dustalov/watset,dustalov/watset
78154a63e86774fb8952f42883f7788e94d0c8d2
lib/spack/spack/operating_systems/linux_distro.py
lib/spack/spack/operating_systems/linux_distro.py
import re from external.distro import linux_distribution from spack.architecture import OperatingSystem class LinuxDistro(OperatingSystem): """ This class will represent the autodetected operating system for a Linux System. Since there are many different flavors of Linux, this class will attempt t...
import re from spack.architecture import OperatingSystem class LinuxDistro(OperatingSystem): """ This class will represent the autodetected operating system for a Linux System. Since there are many different flavors of Linux, this class will attempt to encompass them all through autodetect...
Fix bug in distribution detection on unsupported platforms.
Fix bug in distribution detection on unsupported platforms.
Python
lgpl-2.1
EmreAtes/spack,TheTimmy/spack,mfherbst/spack,tmerrick1/spack,iulian787/spack,skosukhin/spack,matthiasdiener/spack,mfherbst/spack,lgarren/spack,EmreAtes/spack,iulian787/spack,EmreAtes/spack,matthiasdiener/spack,mfherbst/spack,LLNL/spack,TheTimmy/spack,skosukhin/spack,skosukhin/spack,LLNL/spack,krafczyk/spack,krafczyk/sp...
aae36c00e6dbea1ed68d2a921021d586d5ff723e
openquake/baselib/safeprint.py
openquake/baselib/safeprint.py
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2017 GEM Foundation # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, o...
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2017 GEM Foundation # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, o...
Fix out redirection in python2
Fix out redirection in python2
Python
agpl-3.0
gem/oq-engine,gem/oq-engine,gem/oq-hazardlib,gem/oq-hazardlib,gem/oq-hazardlib,gem/oq-engine,gem/oq-engine,gem/oq-engine
d7f43a15a2e4535728e7ec5d3cb550af3eed1590
h2o-py/h2o/tree/__init__.py
h2o-py/h2o/tree/__init__.py
from .tree import H2OTree from .tree import H2ONode __all__ = ["H2OTree", "H2ONode"]
from .tree import H2OTree from .tree import H2ONode from .tree import H2OSplitNode from .tree import H2OLeafNode __all__ = ["H2OTree", "H2ONode", "H2OSplitNode", "H2OLeafNode"]
Include H2OSplitNode & H2OLeafNode in __all__
Include H2OSplitNode & H2OLeafNode in __all__
Python
apache-2.0
michalkurka/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,h2oai/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,h2oai/h2o-3
b652da4dda3ed5c0a37f2d32a07b9afaf6267e53
organization/network/migrations/0118_team_slug.py
organization/network/migrations/0118_team_slug.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2018-12-19 11:53 from __future__ import unicode_literals from django.db import migrations, models from organization.network.models import Team def generate_slugs(apps, schema_editor): teams = Team.objects.all() for team in teams: team.save() c...
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2018-12-19 11:53 from __future__ import unicode_literals from django.db import migrations, models from organization.network.models import Team # def generate_slugs(apps, schema_editor): # teams = Team.objects.all() # for team in teams: # team.sa...
Fix migration when no existing team.user field at fresh start
Fix migration when no existing team.user field at fresh start
Python
agpl-3.0
Ircam-Web/mezzanine-organization,Ircam-Web/mezzanine-organization
7e0de7c98be293bd3f48f00138c997292696ee6f
Lib/importlib/test/regrtest.py
Lib/importlib/test/regrtest.py
"""Run Python's standard test suite using importlib.__import__. Tests known to fail because of assumptions that importlib (properly) invalidates are automatically skipped if the entire test suite is run. Otherwise all command-line options valid for test.regrtest are also valid for this script. XXX FAILING test_im...
"""Run Python's standard test suite using importlib.__import__. Tests known to fail because of assumptions that importlib (properly) invalidates are automatically skipped if the entire test suite is run. Otherwise all command-line options valid for test.regrtest are also valid for this script. XXX FAILING test_im...
Clarify why test_import is failing under importlib.
Clarify why test_import is failing under importlib.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
33ad684b4b8efab81d82e575d97184dc004d0386
phy/conftest.py
phy/conftest.py
# -*- coding: utf-8 -*- """py.test utilities.""" #------------------------------------------------------------------------------ # Imports #------------------------------------------------------------------------------ import logging import numpy as np import warnings import matplotlib from phylib import add_defau...
# -*- coding: utf-8 -*- """py.test utilities.""" #------------------------------------------------------------------------------ # Imports #------------------------------------------------------------------------------ import logging import numpy as np import warnings import matplotlib from phylib import add_defau...
Remove repeat option from coverage
Remove repeat option from coverage
Python
bsd-3-clause
kwikteam/phy,kwikteam/phy,kwikteam/phy
d0b25766a6e36294ae2c8083664fa36be6be292f
signage/urls.py
signage/urls.py
from django.conf.urls import url from .views import DisplayCreate from .views import DisplayDelete from .views import DisplayDetail from .views import DisplayList from .views import DisplayUpdate from .views import SlideCreate from .views import SlideDelete from .views import SlideList from .views import SlideUpdate ...
from django.conf.urls import url from . import views app_name = 'signage' urlpatterns = [ url(r'^display/(?P<pk>\d+)/$', views.DisplayDetail.as_view(), name='display'), url(r'^display/create/$', views.DisplayCreate.as_view(), name='display_create'), url(r'^display/(?P<pk>\d+)/delete/$', views.DisplayDel...
Refactor URL imports and paths
Refactor URL imports and paths
Python
bsd-3-clause
jbittel/django-signage,jbittel/django-signage,jbittel/django-signage
e42d34e2e3163488daff15c5b584d5f3757d162f
unit_test/memory_unit_test.py
unit_test/memory_unit_test.py
import memory import head # import write_heads from keras import backend as K number_of_memory_locations = 6 memory_vector_size = 3 memory_t = memory.initial(number_of_memory_locations, memory_vector_size) weight_t = K.random_binomial((number_of_memory_locations, 1), 0.2) read_vector = head.reading(memory_t, weigh...
from keras import backend as K import theano.tensor as T import theano import memory import head # # number_of_memory_locations = 6 # memory_vector_size = 3 # # memory_t = memory.initial(number_of_memory_locations, memory_vector_size) # # weight_t = K.random_binomial((number_of_memory_locations, 1), 0.2) # # read_vecto...
Update code of NTM based on Keras.
Update code of NTM based on Keras.
Python
mit
SigmaQuan/NTM-Keras
55098fa6ce3a6d55849f08ddcfb95cc5c241abb5
examples/IPLoM_example.py
examples/IPLoM_example.py
# for local run, before pygraphc packaging import sys sys.path.insert(0, '../pygraphc/misc') from IPLoM import * sys.path.insert(0, '../pygraphc/evaluation') from ExternalEvaluation import * # set path ip_address = '161.166.232.17' standard_path = '/home/hudan/Git/labeled-authlog/dataset/' + ip_address standard_file =...
from pygraphc.misc.IPLoM import * from pygraphc.evaluation.ExternalEvaluation import * # set input path ip_address = '161.166.232.17' standard_path = '/home/hudan/Git/labeled-authlog/dataset/Hofstede2014/dataset1/' + ip_address standard_file = standard_path + 'auth.log.anon.labeled' analyzed_file = 'auth.log.anon' pre...
Edit import module. pygraphc is now ready to be packaged
Edit import module. pygraphc is now ready to be packaged
Python
mit
studiawan/pygraphc
2a3fc1b82e47d23e3de8820343ab7d39c72aa35b
luispedro/urls.py
luispedro/urls.py
from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^luispedro/', include('luispedro.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admin...
from django.conf.urls.defaults import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^luispedro/', include('luispedro.foo.urls')), (r'^admin/', include(admin.site.urls)), )
Make this usable (at least testable)
Make this usable (at least testable)
Python
agpl-3.0
luispedro/django-gitcms,luispedro/django-gitcms
e923a56f21fd6dc8d7e16005792d473788cb1925
markups/common.py
markups/common.py
# This file is part of python-markups module # License: 3-clause BSD, see LICENSE file # Copyright: (C) Dmitry Shachnev, 2012-2018 import os.path # Some common constants and functions (LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3) CONFIGURATION_DIR = (os.getenv('XDG_CONFIG_HOME') or os.getenv...
# This file is part of python-markups module # License: 3-clause BSD, see LICENSE file # Copyright: (C) Dmitry Shachnev, 2012-2018 import os.path # Some common constants and functions (LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3) CONFIGURATION_DIR = (os.getenv('XDG_CONFIG_HOME') or os.getenv...
Add support for Arch Linux mathjax package
Add support for Arch Linux mathjax package Fixes #4.
Python
bsd-3-clause
mitya57/pymarkups,retext-project/pymarkups
b3850c475e449c0c6182629aa7521f335e86b1e1
scrapy_local.py
scrapy_local.py
# Local dev settings for scrapy # This is not the same # Local config for testing import os # use this for running scrapy directly # PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) # FILES_STORE = os.path.join(PROJECT_ROOT, 'datafiles') # Use this for deploying to scrapyd, as it would be in stage/productio...
# Local dev settings for scrapy # This is not the same # Local config for testing import os # use this for running scrapy directly PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) FILES_STORE = os.path.join(PROJECT_ROOT, 'datafiles')
Fix issue with scrapy local settings
Fix issue with scrapy local settings
Python
mit
comsaint/legco-watch,comsaint/legco-watch,comsaint/legco-watch,legco-watch/legco-watch,legco-watch/legco-watch,legco-watch/legco-watch,legco-watch/legco-watch,comsaint/legco-watch
b1504dac6d33b4f0774cabceeb219653b9b6201f
ui.py
ui.py
from terminaltables import SingleTable def render(object, **kw): if object == 'gallows': render_gallows(**kw) if object == 'bank': render_bank(**kw) if object == 'game_state': render_game_state(**kw) def render_gallows(parts=0, **kw): print(""" ______ | | ...
from terminaltables import SingleTable def render(object, **kw): if object == 'gallows': render_gallows(**kw) if object == 'bank': render_bank(**kw) if object == 'game_state': render_game_state(**kw) def render_gallows(parts=0, **kw): print(""" ______ | | ...
Change the way we get a clean, blank line before rendering letter bank
Change the way we get a clean, blank line before rendering letter bank
Python
mit
tml/python-hangman-2017-summer
cf2af4a006d2545bbe0ec9fc92d087d8ff6805f1
cah.py
cah.py
STA_F= "/home/ormiret/cah/statements.txt" ANS_F= "/home/ormiret/cah/answers.txt" import random def rand_line(filename): with open(filename) as f: lines = f.readlines() return random.choice(lines).strip() def statement(): return rand_line(STA_F) def answer(): return rand_line(ANS_F) def fill_...
STA_F= "statements.txt" ANS_F= "answers.txt" import random def rand_line(filename): with open(filename) as f: lines = f.readlines() return random.choice(lines).strip() def statement(): return rand_line(STA_F) def answer(): return rand_line(ANS_F) def fill_statement(): statement = rand_li...
Fix path to statements and answers files.
Fix path to statements and answers files.
Python
mit
ormiret/cards-against-hackspace,ormiret/cards-against-hackspace
7dfd89b22c66eb4cfc38218b9430adc38e8ad073
oonib/__init__.py
oonib/__init__.py
""" In here we shall keep track of all variables and objects that should be instantiated only once and be common to pieces of GLBackend code. """ __version__ = '1.0.0' __all__ = ['Storage', 'randomStr'] import string import random class Storage(dict): """ A Storage object is like a dictionary except `obj.f...
""" In here we shall keep track of all variables and objects that should be instantiated only once and be common to pieces of GLBackend code. """ __version__ = '1.0.0' __all__ = ['Storage', 'randomStr'] import string from random import SystemRandom random = SystemRandom() class Storage(dict): """ A Storage...
Use SystemRandom instead of insecure RNG
Use SystemRandom instead of insecure RNG
Python
bsd-2-clause
dstufft/ooni-backend,dstufft/ooni-backend
09c4cacfd5aeb5740c2c741a74043938fd0d1b0f
tests/test_reporters.py
tests/test_reporters.py
import pytest from seqeval.reporters import DictReporter @pytest.mark.parametrize( 'rows, expected', [ ([], {}), ( [['PERSON', 0.82, 0.79, 0.81, 24]], { 'PERSON': { 'precision': 0.82, 'recall': 0.79, ...
import pytest from seqeval.reporters import DictReporter, StringReporter class TestDictReporter: def test_write_empty(self): reporter = DictReporter() reporter.write_blank() assert reporter.report_dict == {} @pytest.mark.parametrize( 'rows, expected', [ ([...
Add test cases for reporters.py
Add test cases for reporters.py
Python
mit
chakki-works/seqeval,chakki-works/seqeval
4f1f0b9d1643a6ff4934070472973e60b1eb6c26
tests/rules_tests/isValid_tests/NongrammarEntitiesTest.py
tests/rules_tests/isValid_tests/NongrammarEntitiesTest.py
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy """ from unittest import main, TestCase from grammpy import Rule from .grammar import * class NongrammarEntitiesTest(TestCase): pass if __name__ == '__main__': main()
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy """ from unittest import main, TestCase from grammpy import Rule, Nonterminal as _N from grammpy.exceptions import TerminalDoesNotExistsException, NonterminalDoesNotExistsException from .grammar import * class...
Add tests of terminals and nonterminals that are not in grammar
Add tests of terminals and nonterminals that are not in grammar
Python
mit
PatrikValkovic/grammpy
e435592d64dbd4f75a7cc9d1ac8bb17ab4177a2b
erpnext/patches/v4_2/default_website_style.py
erpnext/patches/v4_2/default_website_style.py
import frappe from frappe.templates.pages.style_settings import default_properties def execute(): style_settings = frappe.get_doc("Style Settings", "Style Settings") if not style_settings.apply_style: style_settings.update(default_properties) style_settings.apply_style = 1 style_settings.save()
import frappe from frappe.templates.pages.style_settings import default_properties def execute(): frappe.reload_doc('website', 'doctype', 'style_settings') style_settings = frappe.get_doc("Style Settings", "Style Settings") if not style_settings.apply_style: style_settings.update(default_properties) style_setti...
Fix default website style patch (reload doc)
[minor] Fix default website style patch (reload doc)
Python
agpl-3.0
gangadharkadam/saloon_erp,hatwar/buyback-erpnext,gangadharkadam/v6_erp,indictranstech/Das_Erpnext,gangadharkadam/vlinkerp,shft117/SteckerApp,sheafferusa/erpnext,mahabuber/erpnext,hernad/erpnext,suyashphadtare/gd-erp,gangadharkadam/letzerp,indictranstech/internal-erpnext,indictranstech/buyback-erp,4commerce-technologies...
9ff346834a39605a707d66d4a2c6e3dc20dcdd78
markov_chain.py
markov_chain.py
from random import choice class MarkovChain(object): """ An interface for signle-word states Markov Chains """ def __init__(self, text=None): self._states_map = {} if text is not None: self.add_text(text) def add_text(self, text, separator=" "): """ Adds text ...
from random import choice class MarkovChain(object): """ An interface for signle-word states Markov Chains """ def __init__(self, text=None): self._states_map = {} if text is not None: self.add_text(text) def add_text(self, text, separator=" "): """ Adds text to the ma...
Add Markov Chain representation class
Add Markov Chain representation class
Python
mit
iluxonchik/lyricist
28afc9f6f81e1e7ed94e2ec561ef321bff8bb56a
sphinxdoc/urls.py
sphinxdoc/urls.py
# encoding: utf-8 """ URL conf for django-sphinxdoc. """ from django.conf.urls.defaults import patterns, url from django.views.generic import list_detail from sphinxdoc import models from sphinxdoc.views import ProjectSearchView project_info = { 'queryset': models.Project.objects.all().order_by('name'), 'te...
# encoding: utf-8 """ URL conf for django-sphinxdoc. """ from django.conf.urls.defaults import patterns, url from django.views.generic import list_detail from sphinxdoc import models from sphinxdoc.views import ProjectSearchView project_info = { 'queryset': models.Project.objects.all().order_by('name'), 'te...
Support more general documentation path names.
Support more general documentation path names.
Python
bsd-3-clause
30loops/django-sphinxdoc,kamni/django-sphinxdoc
dbce975bcb348e0f878f39557d911e99ba08294c
corehq/apps/hqcase/management/commands/ptop_reindexer_v2.py
corehq/apps/hqcase/management/commands/ptop_reindexer_v2.py
from django.core.management import BaseCommand, CommandError from corehq.pillows.case import get_couch_case_reindexer, get_sql_case_reindexer from corehq.pillows.xform import get_couch_form_reindexer, get_sql_form_reindexer class Command(BaseCommand): args = 'index' help = 'Reindex a pillowtop index' def...
from django.core.management import BaseCommand, CommandError from corehq.pillows.case import get_couch_case_reindexer, get_sql_case_reindexer from corehq.pillows.case_search import get_couch_case_search_reindexer from corehq.pillows.xform import get_couch_form_reindexer, get_sql_form_reindexer class Command(BaseComma...
Enable reindexing with v2 reindexer
Enable reindexing with v2 reindexer
Python
bsd-3-clause
dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq
cc5028b58736ca7e06083d733d2e0a16a7ec8696
src/vrun/cli.py
src/vrun/cli.py
from __future__ import print_function import os import sys def main(): prefix = sys.prefix binpath = os.path.join(prefix, 'bin') PATH = os.environ.get('PATH', []) PATH = binpath + os.pathsep + PATH os.putenv('PATH', PATH) os.putenv('VRUN_ACTIVATED', '1') os.putenv('VIRTUAL_ENV', sys.prefi...
from __future__ import print_function import os import sys def main(): prefix = sys.prefix binpath = os.path.join(prefix, 'bin') PATH = os.environ.get('PATH', '') if PATH: PATH = binpath + os.pathsep + PATH else: PATH = binpath os.putenv('PATH', PATH) os.putenv('VRUN_ACTI...
Add protection against empty PATH
Add protection against empty PATH
Python
isc
bertjwregeer/vrun
0dfea440014b4e1701fd42a20c45f4d8992c00bb
misp_modules/modules/import_mod/stiximport.py
misp_modules/modules/import_mod/stiximport.py
import json import re import base64 import hashlib import tempfile import os from pymisp.tools import stix misperrors = {'error': 'Error'} userConfig = {} inputSource = ['file'] moduleinfo = {'version': '0.2', 'author': 'Hannah Ward', 'description': 'Import some stix stuff', 'module-type'...
import json import re import base64 import hashlib from pymisp.tools import stix misperrors = {'error': 'Error'} userConfig = {} inputSource = ['file'] moduleinfo = {'version': '0.2', 'author': 'Hannah Ward', 'description': 'Import some stix stuff', 'module-type': ['import']} moduleconfi...
Use SpooledTemp, not NamedTemp file
Use SpooledTemp, not NamedTemp file
Python
agpl-3.0
VirusTotal/misp-modules,MISP/misp-modules,amuehlem/misp-modules,MISP/misp-modules,VirusTotal/misp-modules,Rafiot/misp-modules,amuehlem/misp-modules,MISP/misp-modules,Rafiot/misp-modules,Rafiot/misp-modules,VirusTotal/misp-modules,amuehlem/misp-modules
153025aaa585e70d09509248ab18b214194759ae
tasks/static.py
tasks/static.py
# Copyright 2013 Donald Stufft # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, so...
# Copyright 2013 Donald Stufft # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, so...
Deal with the compass.rb -> config.rb change
Deal with the compass.rb -> config.rb change
Python
apache-2.0
techtonik/warehouse,techtonik/warehouse
f1ed7dd603ace84b1b8015c2d7d57515d9de3947
src/detector.py
src/detector.py
#!/usr/bin/python from sys import argv import numpy as np import cv2 import cv2.cv as cv def detectCircle(imagePath): image = cv2.imread(imagePath) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.Canny(gray, 32, 2) cv2.imwrite("canny.jpg", gray) circles = cv2.HoughCircles(gray, cv.CV_HOUG...
#!/usr/bin/python from sys import argv import numpy as np import cv2 import cv2.cv as cv def detectCircle(imagePath): image = cv2.imread(imagePath) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.Canny(gray, 32, 2) cv2.imwrite("canny.jpg", gray) circles = cv2.HoughCircles(gray, cv.CV_HOUG...
Fix error in RaspberryPi environment <numpy type error>.
Fix error in RaspberryPi environment <numpy type error>.
Python
apache-2.0
Jarrey/BotEyePi,Jarrey/BotEyePi
1b7e4ae56a5e56823f7639ab6940d63ed11f18ae
dataproperty/logger/_logger.py
dataproperty/logger/_logger.py
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import, unicode_literals from ._null_logger import NullLogger try: import logbook logger = logbook.Logger("DataProperty") logger.disable() except ImportError: logger = NullLogg...
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import, unicode_literals from ._null_logger import NullLogger try: import logbook logger = logbook.Logger("DataProperty") logger.disable() LOGBOOK_INSTALLED = True except Impor...
Fix logger functions failures when an optional package not installed
Fix logger functions failures when an optional package not installed
Python
mit
thombashi/DataProperty
efe30ee01d3b1eb46cd7d986beba09ec47a51e14
app/api/cruds/weekday_crud.py
app/api/cruds/weekday_crud.py
from django.core.exceptions import ValidationError import graphene from graphene_django import DjangoObjectType from app.timetables.models import Weekday from .utils import get_errors class WeekdayNode(DjangoObjectType): original_id = graphene.Int() class Meta: model = Weekday filter_fields...
from django.core.exceptions import ValidationError import graphene from graphene_django import DjangoObjectType from app.timetables.models import Weekday from .utils import get_errors class WeekdayNode(DjangoObjectType): original_id = graphene.Int() class Meta: model = Weekday filter_fields...
Fix errors on create weekday
Fix errors on create weekday
Python
mit
teamtaverna/core
807e1315c2abb6c493eca575f478ce7b69173d6f
pajbot/eventloop.py
pajbot/eventloop.py
import logging from irc.schedule import IScheduler from tempora import schedule from tempora.schedule import Scheduler log = logging.getLogger(__name__) # same as InvokeScheduler from the original implementation, # but with the extra try-catch class SafeInvokeScheduler(Scheduler): """ Command targets are fu...
import logging from irc.schedule import IScheduler from tempora import schedule from tempora.schedule import Scheduler log = logging.getLogger(__name__) # same as InvokeScheduler from the original implementation, # but with the extra try-catch class SafeInvokeScheduler(Scheduler): """ Command targets are fu...
Update comment to be a bit more helpful
Update comment to be a bit more helpful
Python
mit
pajlada/tyggbot,pajlada/tyggbot,pajlada/pajbot,pajlada/pajbot,pajlada/pajbot,pajlada/tyggbot,pajlada/tyggbot,pajlada/pajbot
530a26c4a857ee35d841ef1d716021fb2c91524a
notesapi/v1/migrations/0001_initial.py
notesapi/v1/migrations/0001_initial.py
# -*- coding: utf-8 -*- """ Initial migration file for creating Note model """ from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): """ Initial migration file for creating Note model """ dependencies = [ ] operations = [ mig...
# -*- coding: utf-8 -*- """ Initial migration file for creating Note model """ from __future__ import unicode_literals import django.contrib.auth.models import django.contrib.auth.validators from django.db import migrations, models class Migration(migrations.Migration): """ Initial migration file for creating No...
Add auth models and validators to initial db migration.
Add auth models and validators to initial db migration.
Python
agpl-3.0
edx/edx-notes-api,edx/edx-notes-api
71166b445eb5b4aec407b743f8167842e21ed28f
dataedit/templatetags/dataedit/taghandler.py
dataedit/templatetags/dataedit/taghandler.py
from django import template from dataedit import models import webcolors register = template.Library() @register.assignment_tag def get_tags(): return models.Tag.objects.all()[:10] @register.simple_tag() def readable_text_color(color_hex): r,g,b = webcolors.hex_to_rgb(color_hex) L = 0.2126 * r + 0.7152 ...
from django import template from dataedit import models import webcolors register = template.Library() @register.assignment_tag def get_tags(): return models.Tag.objects.all()[:10] @register.simple_tag() def readable_text_color(color_hex): r, g, b = webcolors.hex_to_rgb(color_hex) # Calculate brightnes...
Remove unnecessary variable assignment and print
Remove unnecessary variable assignment and print
Python
agpl-3.0
openego/oeplatform,tom-heimbrodt/oeplatform,tom-heimbrodt/oeplatform,openego/oeplatform,openego/oeplatform,openego/oeplatform,tom-heimbrodt/oeplatform
93dac2902ff11e8198c2c58f48b2aa15f2c01f6e
apps/submission/views.py
apps/submission/views.py
from pathlib import PurePath from tempfile import mkdtemp from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponse from django.views.generic import TemplateView, View from .io.xlsx import generate_template class DownloadXLSXTemplateView(LoginRequiredMixin, TemplateView): te...
from pathlib import PurePath from tempfile import mkdtemp from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponse from django.views.generic import TemplateView, View from .io.xlsx import generate_template class DownloadXLSXTemplateView(LoginRequiredMixin, TemplateView): te...
Update pixel's template file name to meta.xlsx
Update pixel's template file name to meta.xlsx
Python
bsd-3-clause
Candihub/pixel,Candihub/pixel,Candihub/pixel,Candihub/pixel,Candihub/pixel
64fdfe1dc072c3684255f8ecf1895d6350f979b6
nova/policies/image_size.py
nova/policies/image_size.py
# Copyright 2016 Cloudbase Solutions Srl # All Rights Reserved. # # 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 r...
# Copyright 2016 Cloudbase Solutions Srl # All Rights Reserved. # # 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 r...
Add policy description for image size
Add policy description for image size This commit adds policy doc for image size policies. Partial implement blueprint policy-docs Change-Id: I0de4aaa47e21c4e156569eebcb495412ab364417
Python
apache-2.0
gooddata/openstack-nova,jianghuaw/nova,Juniper/nova,mahak/nova,rahulunair/nova,gooddata/openstack-nova,openstack/nova,mikalstill/nova,openstack/nova,rajalokan/nova,vmturbo/nova,Juniper/nova,rajalokan/nova,mahak/nova,jianghuaw/nova,mikalstill/nova,phenoxim/nova,gooddata/openstack-nova,jianghuaw/nova,Juniper/nova,klmitch...
06db6c3823ae480d0180b747ac475f149b2f8976
try_telethon.py
try_telethon.py
#!/usr/bin/env python3 import traceback from telethon.interactive_telegram_client import (InteractiveTelegramClient, print_title) def load_settings(path='api/settings'): """Loads the user settings located under `api/`""" result = {} with open(path, 'r', e...
#!/usr/bin/env python3 import traceback from telethon.interactive_telegram_client import (InteractiveTelegramClient, print_title) def load_settings(path='api/settings'): """Loads the user settings located under `api/`""" result = {} with open(path, 'r', e...
Allow integer-only session name and hash for the example
Allow integer-only session name and hash for the example
Python
mit
expectocode/Telethon,LonamiWebs/Telethon,LonamiWebs/Telethon,LonamiWebs/Telethon,andr-04/Telethon,LonamiWebs/Telethon,kyasabu/Telethon
12e35b703f548df5e57e44446ddd8739f96aef95
tartpy/tools.py
tartpy/tools.py
import time from .runtime import behavior, Actor, exception_message, Runtime from .eventloop import EventLoop class Wait(object): """A synchronizing object. Convenience object to wait for results outside actors. Use as:: w = Wait() wait = runtime.create(w.wait_beh) # now use `w...
from collections.abc import Mapping, Sequence import time from .runtime import behavior, Actor, exception_message, Runtime from .eventloop import EventLoop class Wait(object): """A synchronizing object. Convenience object to wait for results outside actors. Use as:: w = Wait() wait = r...
Add a map function over messages
Add a map function over messages
Python
mit
waltermoreira/tartpy
d37dc009f1c4f6e8855657dd6dbf17df9332f765
test/os_win7.py
test/os_win7.py
#!/usr/bin/env python """ mbed SDK Copyright (c) 2011-2015 ARM Limited 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 ...
#!/usr/bin/env python """ mbed SDK Copyright (c) 2011-2015 ARM Limited 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 ...
Add test for mbed parsing
Add test for mbed parsing
Python
apache-2.0
jupe/mbed-ls,jupe/mbed-ls,mazimkhan/mbed-ls,mtmtech/mbed-ls,mazimkhan/mbed-ls,mtmtech/mbed-ls
55fface07089b32a4d39d2e9a6d7deeb9ef0a23e
mefdas.py
mefdas.py
#!/usr/bin/env python """mefdas.py: Description of what foobar does.""" __author__ = "Philip Chase(pbc@ufl.edu, Chris Barnes(cpb@ufl.edu), Roy Keyes (keyes@ufl.edu), Alex Loiacono (atloiaco@ufl.edu)" __copyright__ = "Copyright 2015, CTS-IT University of Florida" class fuzzyMeasure: '''A class to produce...
#!/usr/bin/env python """mefdas.py: Description of what foobar does.""" __author__ = "Philip Chase(pbc@ufl.edu, Chris Barnes(cpb@ufl.edu), Roy Keyes (keyes@ufl.edu), Alex Loiacono (atloiaco@ufl.edu)" __copyright__ = "Copyright 2015, CTS-IT University of Florida" class fuzzyMeasure: '''A class to produce...
Add pseudocode for set_fm_for_complex_sets and set_fm_for_trivial_cases
Add pseudocode for set_fm_for_complex_sets and set_fm_for_trivial_cases
Python
apache-2.0
ctsit/mdat,indera/mdat
d561796c812bfdde822380851a0583db8726b798
hooks/post_gen_project.py
hooks/post_gen_project.py
import os src = '{{cookiecutter.repo_name}}/src/utils/prepare-commit-msg.py' dst = '{{cookiecutter.repo_name}}/.git/hooks/prepare-commit-msg' os.mkdir('{{cookiecutter.repo_name}}/.git/hooks') os.symlink(src, dst)
import os import subprocess project_dir = '{{cookiecutter.repo_name}}' hooks_dir = os.path.join(project_dir, '.git/hooks') src = os.path.join(project_dir, 'src/utils/prepare-commit-msg.py') dst = os.path.join(hooks_dir, 'prepare-commit-msg') process = subprocess.Popen('git', 'init', project_dir) process.wait() os.m...
Add git init to post generate hook
Add git init to post generate hook
Python
mit
Empiria/matador-cookiecutter
347853290ebc4f5c47430ffce7d603eb4fead2d9
cpt/test/integration/update_python_reqs_test.py
cpt/test/integration/update_python_reqs_test.py
import unittest from conans.test.utils.tools import TestClient from cpt.test.test_client.tools import get_patched_multipackager class PythonRequiresTest(unittest.TestCase): def test_python_requires(self): base_conanfile = """from conans import ConanFile myvar = 123 def myfunct(): return 234 class ...
import unittest from conans.test.utils.tools import TestClient from cpt.test.test_client.tools import get_patched_multipackager class PythonRequiresTest(unittest.TestCase): def test_python_requires(self): base_conanfile = """from conans import ConanFile myvar = 123 def myfunct(): return 234 class ...
Fix pyreq test on Windows
Fix pyreq test on Windows Signed-off-by: Uilian Ries <d4bad57018205bdda203549c36d3feb0bfe416a7@gmail.com>
Python
mit
conan-io/conan-package-tools
5aa54a94929354910d190b9b37f895d0416d7361
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Clifton Kaznocha # Copyright (c) 2014 Clifton Kaznocha # # License: MIT # """This module exports the WriteGood plugin class.""" import SublimeLinter from SublimeLinter.lint import NodeLinter if getattr(SublimeLinter...
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Clifton Kaznocha # Copyright (c) 2014 Clifton Kaznocha # # License: MIT # """This module exports the WriteGood plugin class.""" import SublimeLinter from SublimeLinter.lint import NodeLinter if getattr(SublimeLinter...
Update for SublimeLinter 4 API.
Update for SublimeLinter 4 API. github.com/ckaznocha/SublimeLinter-contrib-write-good/issues/14 github.com/ckaznocha/SublimeLinter-contrib-write-good/issues/11
Python
mit
ckaznocha/SublimeLinter-contrib-write-good
e7bfa4bc9bc8c1caf7ef5f4618943543bed99f0a
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jack Cherng # Copyright (c) 2015 jfcherng # # License: MIT # from SublimeLinter.lint import Linter, util import platform class Iverilog (Linter): syntax = ('verilog') cmd = 'iverilog -t null' tempfile_s...
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jack Cherng # Copyright (c) 2015 jfcherng # # License: MIT # import sublime, sublime_plugin from SublimeLinter.lint import Linter, util class Iverilog (Linter): syntax = ('verilog') cmd = 'iverilog -t null'...
Use the platform() in sublime.py rather than importing platform.
Use the platform() in sublime.py rather than importing platform.
Python
mit
jfcherng/SublimeLinter-contrib-iverilog,jfcherng/SublimeLinter-contrib-iverilog
87438b9dcdbd397d754b4317bd7724e5b663f5b1
dedupsqlfs/lib/cache/simple.py
dedupsqlfs/lib/cache/simple.py
# -*- coding: utf8 -*- from time import time __author__ = 'sergey' class CacheTTLseconds(object): """ Simple cache storage { key (int | str) : [ timestamp (float), - then added, updated, set to 0 if expired values (int | str) - some data ], ... }...
# -*- coding: utf8 -*- from time import time __author__ = 'sergey' class CacheTTLseconds(object): """ Simple cache storage { key (int | str) : [ timestamp (float), - then added, updated, set to 0 if expired values (int | str) - some data ], ... }...
Fix value get - use offset
Fix value get - use offset
Python
mit
sergey-dryabzhinsky/dedupsqlfs,sergey-dryabzhinsky/dedupsqlfs,sergey-dryabzhinsky/dedupsqlfs,sergey-dryabzhinsky/dedupsqlfs
cb3f208e2727cd1adea20c529ece5bd766f5e43d
users/models.py
users/models.py
from django.db import models from django.contrib.auth.models import User from django.contrib import admin from settings.models import VotingSystem # Create your models here. class Admin(models.Model): user = models.ForeignKey(User) system = models.ForeignKey(VotingSystem) def __unicode__(self): return u'[%s] %...
from django.db import models from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.contrib import admin from settings.models import VotingSystem import json # Create your models here. class Admin(models.Model): user = models.ForeignKey(User) system = models.Fo...
Make sure that user details are valid JSON
Make sure that user details are valid JSON
Python
mit
kuboschek/jay,OpenJUB/jay,OpenJUB/jay,OpenJUB/jay,kuboschek/jay,kuboschek/jay
9eb09783d1317c77d65239e1d4c5aceb6eb1bb4b
pysyte/net/hosts.py
pysyte/net/hosts.py
"""Simplified hosts for pysyte""" import getpass import socket from dataclasses import dataclass @dataclass class Host: hostname: str aliases: list addresses: list users: list localhost = Host( *(list(socket.gethostbyname_ex(socket.gethostname())) + [getpass.getuser()]) )
"""Simplified hosts for pysyte""" import getpass import socket from dataclasses import dataclass from typing import List @dataclass class Host: hostname: str aliases: List[str] addresses: List[str] users: List[str] def _read_localhost() -> Host: """Read host values for localhost""" host, al...
Add method to clarify localhost data
Add method to clarify localhost data
Python
mit
jalanb/dotsite