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
15941639134d4360753607bd488d3c80d15ca825
second/blog/models.py
second/blog/models.py
from __future__ import unicode_literals from django.db import models from django.utils import timezone # Create your models here. class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(de...
from __future__ import unicode_literals from django.db import models from django.utils import timezone # Create your models here. class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(de...
Add comments model to blog
Add comments model to blog
Python
mit
ugaliguy/Django-Tutorial-Projects,ugaliguy/Django-Tutorial-Projects
b5a71f2142c16b8523da483a6879578522cfd9bb
semesterpage/forms.py
semesterpage/forms.py
from django import forms from django.utils.translation import ugettext_lazy as _ from dal import autocomplete from .models import Course, Options class OptionsForm(forms.ModelForm): """ A form solely used for autocompleting Courses in the admin, using django-autocomplete-light, """ self_chosen_c...
from django import forms from django.utils.translation import ugettext_lazy as _ from dal import autocomplete from .models import Course, Options class OptionsForm(forms.ModelForm): """ A form solely used for autocompleting Courses in the admin, using django-autocomplete-light, """ self_chosen_c...
Clarify that self_chosen_courses == enrolled
Clarify that self_chosen_courses == enrolled Fixes #75.
Python
mit
afriestad/WikiLinks,afriestad/WikiLinks,afriestad/WikiLinks
5f688e5a99c2e4ec476f28306c2cca375934bba7
nvidia_commands_layer.py
nvidia_commands_layer.py
#!/usr/bin/env python3.5 import subprocess class NvidiaCommandsLayerException(Exception): pass class NvidiaCommandsLayer(object): @staticmethod def set_fan_percentage( value: int ) -> None: if value < 0 or value > 100: raise NvidiaCommandsLayerException('Cannot set a...
#!/usr/bin/env python3 import subprocess class NvidiaCommandsLayerException(Exception): pass class NvidiaCommandsLayer(object): @staticmethod def set_fan_percentage( value: int ) -> None: if value < 0 or value > 100: raise NvidiaCommandsLayerException('Cannot set a v...
Fix script not working from bash
Fix script not working from bash
Python
mit
radu-nedelcu/nvidia-fan-controller,radu-nedelcu/nvidia-fan-controller
1e9fb28b1263bb543191d3c44ba39d8311ad7cae
quantecon/__init__.py
quantecon/__init__.py
""" Import the main names to top level. """ from . import models as models from .compute_fp import compute_fixed_point from .discrete_rv import DiscreteRV from .ecdf import ECDF from .estspec import smooth, periodogram, ar_periodogram from .graph_tools import DiGraph from .gridtools import cartesian, mlinspace from .k...
""" Import the main names to top level. """ from .compute_fp import compute_fixed_point from .discrete_rv import DiscreteRV from .ecdf import ECDF from .estspec import smooth, periodogram, ar_periodogram from .graph_tools import DiGraph from .gridtools import cartesian, mlinspace from .kalman import Kalman from .lae i...
Remove models/ subpackage from api due to migration to QuantEcon.applications
Remove models/ subpackage from api due to migration to QuantEcon.applications
Python
bsd-3-clause
QuantEcon/QuantEcon.py,oyamad/QuantEcon.py,QuantEcon/QuantEcon.py,oyamad/QuantEcon.py
ff9fc6e6036ea99af4db6a5760d05a33cf7336e1
solidity/python/constants/PrintLn2ScalingFactors.py
solidity/python/constants/PrintLn2ScalingFactors.py
import os import sys sys.path.append(os.path.join(os.path.dirname(__file__),'..')) from decimal import Decimal from decimal import getcontext from FormulaSolidityPort import fixedLog2 MIN_PRECISION = 32 MAX_PRECISION = 127 getcontext().prec = MAX_PRECISION ln2 = Decimal(2).ln() fixedLog2MaxInput = ((1<<(256-MA...
from decimal import Decimal from decimal import getcontext from decimal import ROUND_FLOOR from decimal import ROUND_CEILING MIN_PRECISION = 32 MAX_PRECISION = 127 def ln(n): return Decimal(n).ln() def log2(n): return ln(n)/ln(2) def floor(d): return int(d.to_integral_exact(rounding=ROUND_FLOOR)) ...
Make this constant-generating script independent of the solidity emulation module.
Make this constant-generating script independent of the solidity emulation module.
Python
apache-2.0
enjin/contracts
6e4fcfeb6da8f4d61731ec2cb77c14b09fe35d31
aurorawatchuk/snapshot.py
aurorawatchuk/snapshot.py
import aurorawatchuk as aw class AuroraWatchUK(object): """Take a snapshot of the AuroraWatch UK status. This class mimics the behaviour of the aurorawatchuk.AuroraWatchUK class but its fields are evaluated just once, at the time first requested. Thus the values it returns are snapshots of the status. Th...
from aurorawatchuk import AuroraWatchUK __author__ = 'Steve Marple' __version__ = '0.0.8' __license__ = 'MIT' class AuroraWatchUK_SS(object): """Take a snapshot of the AuroraWatch UK status. This class mimics the behaviour of the :class:`.aurorawatchuk.AuroraWatchUK` class but its fields are evaluated ...
Rename class to AuroraWatchUK_SS and add documentation
Rename class to AuroraWatchUK_SS and add documentation
Python
mit
stevemarple/python-aurorawatchuk
17d9c84b01a6b9adc264164041d4c226355a6943
loadimpact/utils.py
loadimpact/utils.py
# coding=utf-8 __all__ = ['UTC'] from datetime import timedelta, tzinfo _ZERO = timedelta(0) def is_dict_different(d1, d2, epsilon=0.00000000001): s1 = set(d1.keys()) s2 = set(d2.keys()) intersect = s1.intersection(s2) added = s1 - intersect removed = s2 - intersect changed = [] for o ...
# coding=utf-8 __all__ = ['UTC'] from datetime import timedelta, tzinfo _ZERO = timedelta(0) def is_dict_different(d1, d2, epsilon=0.00000000001): s1 = set(d1.keys()) s2 = set(d2.keys()) intersect = s1.intersection(s2) added = s1 - intersect removed = s2 - intersect changed = [] for o ...
Fix float diff comparison in dict differ function.
Fix float diff comparison in dict differ function.
Python
apache-2.0
loadimpact/loadimpact-sdk-python
2dec3e5810ef9ba532eaa735d0eac149c240aa2f
pyxrf/api.py
pyxrf/api.py
# from .model.fileio import (stitch_fitted_results, spec_to_hdf, create_movie, # combine_data_to_recon, h5file_for_recon, export_to_view) # from .model.load_data_from_db import make_hdf, make_hdf_stitched, export1d # from .model.command_tools import fit_pixel_data_and_save, pyxrf_batch impo...
from .model.fileio import (stitch_fitted_results, spec_to_hdf, create_movie, # noqa: F401 combine_data_to_recon, h5file_for_recon, export_to_view, # noqa: F401 make_hdf_stitched) # noqa: F401 from .model.load_data_from_db import make_hdf, export1d # noqa: F401 ...
Set flake8 to ignore F401 violations
Set flake8 to ignore F401 violations
Python
bsd-3-clause
NSLS-II/PyXRF,NSLS-II-HXN/PyXRF,NSLS-II-HXN/PyXRF
dcb8678b8f460ce1b5d5d86e14d567a3bcbaa0d1
riak/util.py
riak/util.py
import collections def quacks_like_dict(object): """Check if object is dict-like""" return isinstance(object, collections.Mapping) def deep_merge(a, b): """Merge two deep dicts non-destructively Uses a stack to avoid maximum recursion depth exceptions >>> a = {'a': 1, 'b': {1: 1, 2: ...
try: from collections import Mapping except ImportError: # compatibility with Python 2.5 Mapping = dict def quacks_like_dict(object): """Check if object is dict-like""" return isinstance(object, Mapping) def deep_merge(a, b): """Merge two deep dicts non-destructively Uses a stack ...
Adjust for compatibility with Python 2.5
Adjust for compatibility with Python 2.5
Python
apache-2.0
basho/riak-python-client,bmess/riak-python-client,GabrielNicolasAvellaneda/riak-python-client,basho/riak-python-client,bmess/riak-python-client,GabrielNicolasAvellaneda/riak-python-client,basho/riak-python-client
96855ef5baee62f63887d942854c065ad6943f87
micropress/forms.py
micropress/forms.py
from django import forms from micropress.models import Article, Section, Press class ArticleForm(forms.ModelForm): section = forms.ModelChoiceField(Section.objects.all(), empty_label=None) class Meta: model = Article fields = ('title', 'slug', 'byline', 'section', 'body', 'markup_type') cla...
from django import forms from micropress.models import Article, Section, Press class ArticleForm(forms.ModelForm): section = forms.ModelChoiceField(Section.objects.all(), empty_label=None) class Meta: model = Article fields = ('title', 'slug', 'byline', 'section', 'body', 'markup_type') ...
Validate that Article.slug and press are unique_together.
Validate that Article.slug and press are unique_together.
Python
mit
jbradberry/django-micro-press,jbradberry/django-micro-press
31a8d7377d46abef6eec6f7eb5b154f948c3388a
spam/ansiInventory.py
spam/ansiInventory.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ AnsibleInventory: INTRO: USAGE: """ import os import ansible.inventory class AnsibleInventory(object): ''' Ansible Inventory wrapper class. ''' def __init__(self, inventory_filename): ''' Initialize Inventory ''' if...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ AnsibleInventory: INTRO: USAGE: """ import os import ansible.inventory class AnsibleInventory(object): ''' Ansible Inventory wrapper class. ''' def __init__(self, inventory_filename): ''' Initialize Inventory ''' se...
Fix get_host() to return host list
Fix get_host() to return host list
Python
apache-2.0
bdastur/spam,bdastur/spam
25121b9bdceda0b0a252e2bdec0e76a4eb733a4c
dotsecrets/textsub.py
dotsecrets/textsub.py
# Original algorithm by Xavier Defrang. # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330 # This implementation by alane@sourceforge.net. import re import UserDict class Textsub(UserDict.UserDict): def __init__(self, dict=None): self.re = None self.regex = None UserDict.User...
# Original algorithm by Xavier Defrang. # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330 # This implementation by alane@sourceforge.net. import re try: from UserDict import UserDict except ImportError: from collections import UserDict class Textsub(UserDict): def __init__(self, dict=None)...
Make UserDict usage compatible with Python3
Make UserDict usage compatible with Python3
Python
bsd-3-clause
oohlaf/dotsecrets
40ac5bc5f8c3f68c0c5b2b6debe19b487893d6f5
ecal_users.py
ecal_users.py
from google.appengine.ext import db import uuid class EmailUser(db.Model): # the email address that the user sends events to: email_address = db.StringProperty(default=str(uuid.uuid4())) # the AuthSub token used to authenticate the user to gcal: auth_token = db.StringProperty() date_added = db.Date...
from google.appengine.ext import db import random import string def make_address(): """ Returns a random alphanumeric string of 10 digits. Since there are 62 choices per digit, this gives: 62 ** 10 = 8.39299366 x 10 ** 17 possible results. When there are a million accounts active, we need: ...
Use a slightly friendlier string than UUID for email addresses.
Use a slightly friendlier string than UUID for email addresses.
Python
mit
eentzel/myeventbot,eentzel/myeventbot,eentzel/myeventbot,eentzel/myeventbot,eentzel/myeventbot
9310be1429109f5324502f7e66318e23f5ea489d
test/test_terminate_handler.py
test/test_terminate_handler.py
import uuid from handler_fixture import StationHandlerTestCase from groundstation.transfer.request_handlers import handle_fetchobject from groundstation.transfer.response_handlers import handle_terminate class TestHandlerTerminate(StationHandlerTestCase): def test_handle_terminate(self): # Write an objec...
import uuid from handler_fixture import StationHandlerTestCase from groundstation.transfer.request_handlers import handle_fetchobject from groundstation.transfer.response_handlers import handle_terminate class TestHandlerTerminate(StationHandlerTestCase): def test_handle_terminate(self): # Write an objec...
Test that teardown methods are actually called
Test that teardown methods are actually called
Python
mit
richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation
0b99bf43e02c22f0aa136ca02717521b1f4f2414
salt/runner.py
salt/runner.py
''' Execute salt convenience routines ''' # Import python modules import sys # Import salt modules import salt.loader class Runner(object): ''' Execute the salt runner interface ''' def __init__(self, opts): self.opts = opts self.functions = salt.loader.runner(opts) def _verify_f...
''' Execute salt convenience routines ''' # Import python modules import sys # Import salt modules import salt.loader class Runner(object): ''' Execute the salt runner interface ''' def __init__(self, opts): self.opts = opts self.functions = salt.loader.runner(opts) def _verify_f...
Add doc printing for salt-run
Add doc printing for salt-run
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
33fd4bba1f2c44e871051862db8071fadb0e9825
core-plugins/shared/1/dss/reporting-plugins/shared_create_metaproject/shared_create_metaproject.py
core-plugins/shared/1/dss/reporting-plugins/shared_create_metaproject/shared_create_metaproject.py
# -*- coding: utf-8 -*- # Ingestion service: create a metaproject (tag) with user-defined name in given space def process(transaction, parameters, tableBuilder): """Create a project with user-defined name in given space. """ # Prepare the return table tableBuilder.addHeader("success") tableBuilde...
# -*- coding: utf-8 -*- # Ingestion service: create a metaproject (tag) with user-defined name in given space def process(transaction, parameters, tableBuilder): """Create a project with user-defined name in given space. """ # Prepare the return table tableBuilder.addHeader("success") tableBuilde...
Create metaproject with user-provided description.
Create metaproject with user-provided description.
Python
apache-2.0
aarpon/obit_shared_core_technology,aarpon/obit_shared_core_technology,aarpon/obit_shared_core_technology
b345c00b41ade2e12449566f7cb013a7bb8d078f
democracy/migrations/0032_add_language_code_to_comment.py
democracy/migrations/0032_add_language_code_to_comment.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.10 on 2016-12-16 15:03 from __future__ import unicode_literals from django.db import migrations, models from democracy.models import SectionComment def forwards_func(apps, schema_editor): for comment in SectionComment.objects.all(): comment._detect_lang(...
# -*- coding: utf-8 -*- # Generated by Django 1.9.10 on 2016-12-16 15:03 from __future__ import unicode_literals from django.db import migrations, models from democracy.models import SectionComment def forwards_func(apps, schema_editor): for comment in SectionComment.objects.all(): comment._detect_lang(...
Add literal dependency so migration 0031 won't fail if run in the wrong order
Add literal dependency so migration 0031 won't fail if run in the wrong order
Python
mit
City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi
423e4cc4b73e7c13d0796069733ee37aaad4c2e4
taar/recommenders/__init__.py
taar/recommenders/__init__.py
from .collaborative_recommender import CollaborativeRecommender from .locale_recommender import LocaleRecommender from .legacy_recommender import LegacyRecommender from .recommendation_manager import RecommendationManager __all__ = [ 'CollaborativeRecommender', 'LegacyRecommender', 'LocaleRecommender', ...
from .collaborative_recommender import CollaborativeRecommender from .locale_recommender import LocaleRecommender from .legacy_recommender import LegacyRecommender from .similarity_recommender import SimilarityRecommender from .recommendation_manager import RecommendationManager __all__ = [ 'CollaborativeRecommen...
Add SimilarityRecommender to init file
Add SimilarityRecommender to init file
Python
mpl-2.0
maurodoglio/taar
a80f5bad5369ae9a7ae3ab6914d3e9e642062ec3
odl/contrib/param_opt/test/test_param_opt.py
odl/contrib/param_opt/test/test_param_opt.py
import pytest import odl import odl.contrib.fom import odl.contrib.param_opt from odl.util.testutils import simple_fixture space = simple_fixture('space', [odl.rn(3), odl.uniform_discr([0, 0], [1, 1], [9, 11]), odl.uniform_discr(0, 1, 10)]) def te...
import pytest import odl import odl.contrib.fom import odl.contrib.param_opt from odl.util.testutils import simple_fixture space = simple_fixture('space', [odl.rn(3), odl.uniform_discr([0, 0], [1, 1], [9, 11]), odl.uniform_discr(0, 1, 10)]) fom = ...
Add fixture for FOM for test_optimal_parameters
TST: Add fixture for FOM for test_optimal_parameters
Python
mpl-2.0
odlgroup/odl,odlgroup/odl,kohr-h/odl,kohr-h/odl
44fe9bc37b05987c4c323d3be56f69c6f5990b82
enigma.py
enigma.py
import string class Steckerbrett: def __init__(self): pass class Umkehrwalze: def __init__(self, wiring): self.wiring = wiring def encode(self, letter): return self.wiring[string.ascii_uppercase.index(letter)] class Walzen: def __init__(self, notch, wiring): assert...
import string class Steckerbrett: def __init__(self): pass class Umkehrwalze: def __init__(self, wiring): self.wiring = wiring def encode(self, letter): return self.wiring[string.ascii_uppercase.index(letter)] class Walzen: def __init__(self, notch, wiring): assert...
Initialize the machine assignments and assertions
Initialize the machine assignments and assertions
Python
mit
ranisalt/enigma
722c3dad6d0a0cc34955ab4a5cfafb90a7cf0e64
scaffold/twork_app/twork_app/web/action/not_found.py
scaffold/twork_app/twork_app/web/action/not_found.py
#!/usr/bin/env python # -*- coding: utf-8 -*- '''NotFoundHandler ''' from tornado.web import HTTPError from twork_app.web.action.base import BaseHandler class NotFoundHandler(BaseHandler): '''NotFoundHandler, RESTFUL SUPPORTED. ''' ST_ITEM = 'NOT_FOUND' def post(self, *args, **kwargs): r...
#!/usr/bin/env python # -*- coding: utf-8 -*- '''NotFoundHandler ''' from tornado.web import HTTPError from twork_app.web.action.base import BaseHandler class NotFoundHandler(BaseHandler): '''NotFoundHandler, RESTFUL SUPPORTED. ''' ST_ITEM = 'NOT_FOUND' def post(self, *args, **kwargs): r...
Rewrite put method for not found handler
Rewrite put method for not found handler
Python
apache-2.0
bufferx/twork,bufferx/twork
a7946f996d618ad2491f36655f000c513017193c
permamodel/tests/test_package_directories.py
permamodel/tests/test_package_directories.py
"""Tests directories set in the permamodel package definition file.""" import os from nose.tools import assert_true from .. import (permamodel_directory, data_directory, examples_directory, tests_directory) def test_permamodel_directory_is_set(): assert(permamodel_directory is not None) def tes...
"""Tests directories set in the permamodel package definition file.""" import os from .. import data_directory, examples_directory, permamodel_directory, tests_directory def test_permamodel_directory_is_set(): assert permamodel_directory is not None def test_data_directory_is_set(): assert data_directory ...
Remove assert_ functions from nose.
Remove assert_ functions from nose.
Python
mit
permamodel/permamodel,permamodel/permamodel
8061b8dd4e836e6af16dd93b332f8cea6b55433c
exgrep.py
exgrep.py
#!/usr/bin/env python3 # -*- coding: utf8 -*- """ Usage: exgrep TERM [options] EXCEL_FILE... Options: TERM The term to grep for. Can be any valid (python) regular expression. EXCEL_FILE The list of files to search through -o Only output the matched part """ import re from docopt import docopt import ...
#!/usr/bin/env python3 # -*- coding: utf8 -*- """ Usage: exgrep TERM [options] EXCEL_FILE... Options: TERM The term to grep for. Can be any valid (python) regular expression. EXCEL_FILE The list of files to search through -c COL Only search in the column specified by COL. -o Only output the match...
Add support for only searching specified column
Add support for only searching specified column
Python
mit
Sakartu/excel-toolkit
5d91948e11400253f161be489bb8c9bf13b7ee35
source/main.py
source/main.py
"""updates subreddit css with compiled sass""" import subprocess import praw def css() -> str: """compiles sass and returns css""" res: subprocess.CompletedProcess = subprocess.run( "sass index.scss --style compressed --quiet", stdout=subprocess.PIPE ) return res.stdout def update(reddit: ...
"""updates subreddit css with compiled sass""" import subprocess import time import praw def css() -> str: """compiles sass and returns css""" res: subprocess.CompletedProcess = subprocess.run( "sass index.scss --style compressed --quiet", stdout=subprocess.PIPE ) return res.stdout def ui...
Use direct subreddit stylesheet update function
Use direct subreddit stylesheet update function Instead of updating the wiki, uses the praw-defined function. Also adds an UID function for subreddit reason
Python
mit
neoliberal/css-updater
38b2bccc4146226d698f5abd1bed1107fe3bbe68
canon.py
canon.py
from melopy import * m = Melopy('canon', 50) melody = [] for start in ['d4', 'a3', 'b3m', 'f#3m', 'g3', 'd3', 'g3', 'a3']: if start.endswith('m'): scale = generate_minor_triad(start[:-1]) else: scale = generate_major_triad(start) for note in scale: melody.append(note) m.add_melody(melody, 0.2) m.add_not...
from melopy import * m = Melopy('canon', 50) melody = [] for start in ['d4', 'a3', 'bm3', 'f#m3', 'g3', 'd3', 'g3', 'a3']: if start.endswith('m'): scale = m.generate_minor_triad(start[:-1]) else: scale = m.generate_major_triad(start) for note in scale: melody.append(note) m.add_melody(melody, 0.2) m.add_n...
Revert "Added "add_rest(length)" method. Changed iterate and generate functions to be outside of the class."
Revert "Added "add_rest(length)" method. Changed iterate and generate functions to be outside of the class." This reverts commit 672069e8f8f7ded4537362707378f32cccde1ae6.
Python
mit
juliowaissman/Melopy,jdan/Melopy
6bd7891e0cfcedc1a5d0813b644b5d6bb941045a
gaphor/abc.py
gaphor/abc.py
from __future__ import annotations import abc from typing import TYPE_CHECKING if TYPE_CHECKING: from gaphor.core.modeling import Element from gaphor.diagram.diagramtoolbox import ToolboxDefinition class Service(metaclass=abc.ABCMeta): """Base interface for all services in Gaphor.""" @abc.abstractm...
from __future__ import annotations from abc import ABCMeta, abstractmethod from typing import TYPE_CHECKING if TYPE_CHECKING: from gaphor.core.modeling import Element from gaphor.diagram.diagramtoolbox import ToolboxDefinition class Service(metaclass=ABCMeta): """Base interface for all services in Gapho...
Remove use of deprecated abstractproperty
Remove use of deprecated abstractproperty Signed-off-by: Dan Yeaw <2591e5f46f28d303f9dc027d475a5c60d8dea17a@yeaw.me>
Python
lgpl-2.1
amolenaar/gaphor,amolenaar/gaphor
880b00a92ac86bb9a5d30392bafb2c019dab7b74
test/unit/test_api_objects.py
test/unit/test_api_objects.py
""" Test api_objects.py """ import unittest from fmcapi import api_objects class TestApiObjects(unittest.TestCase): def test_ip_host_required_for_put(self): self.assertEqual(api_objects.IPHost.REQUIRED_FOR_PUT, ['id', 'name', 'value'])
""" Test api_objects.py """ import mock import unittest from fmcapi import api_objects class TestApiObjects(unittest.TestCase): def test_ip_host_required_for_put(self): self.assertEqual(api_objects.IPHost.REQUIRED_FOR_PUT, ['id', 'name', 'value']) @mock.patch('fmcapi.api_objects.APIClassTemplate.pa...
Add unit test to test for bad response on api delete
Add unit test to test for bad response on api delete
Python
bsd-3-clause
daxm/fmcapi,daxm/fmcapi
d6ed0e5925e0793bf4fc84b09e709b3a0d907f58
lc0525_contiguous_array.py
lc0525_contiguous_array.py
"""Leetcode 525. Contiguous Array Medium URL: https://leetcode.com/problems/contiguous-array/ Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. Example 1: Input: [0,1] Output: 2 Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1. Ex...
"""Leetcode 525. Contiguous Array Medium URL: https://leetcode.com/problems/contiguous-array/ Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. Example 1: Input: [0,1] Output: 2 Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1. Ex...
Complete diffsum idx dict sol w/ time/space complexity
Complete diffsum idx dict sol w/ time/space complexity
Python
bsd-2-clause
bowen0701/algorithms_data_structures
7b798d923c5a5af37e9f4c2d92881e907f2c0c74
python/testData/inspections/PyUnresolvedReferencesInspection/ignoredUnresolvedReferenceInUnionType.py
python/testData/inspections/PyUnresolvedReferencesInspection/ignoredUnresolvedReferenceInUnionType.py
class A: pass a = A() print(a.f<caret>oo) x = A() or None print(x.foo)
class A: pass a = A() print(a.f<caret>oo) def func(c): x = A() if c else None return x.foo
Use more reliable test data as pointed in IDEA-COMMUNITY-CR-936
Use more reliable test data as pointed in IDEA-COMMUNITY-CR-936
Python
apache-2.0
asedunov/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,caot/intellij-community,diorcety/intellij-community,asedunov/intellij-community,supersven/intellij-community,signed/intel...
218aab63d87d6537c6705f6228a5f49e61d27f8f
protocols/models.py
protocols/models.py
from datetime import datetime from django.db import models class Topic(models.Model): name = models.CharField(max_length=100) description = models.TextField() attachment = models.ManyToManyField(Attachment) def __unicode__(self): return self.name class Protocol(models.Model): date = mo...
from datetime import datetime from django.db import models class Topic(models.Model): name = models.CharField(max_length=100) description = models.TextField() attachment = models.ManyToManyField('attachments.Attachment') def __unicode__(self): return self.name class Protocol(models.Model):...
Make migration to fix Topic's attachments
Make migration to fix Topic's attachments
Python
mit
Hackfmi/Diaphanum,Hackfmi/Diaphanum
6cd3e11f6ec84cffc0ea71d15d2e164f499529cf
gidget/util/tumorTypeConfig.py
gidget/util/tumorTypeConfig.py
#!/usr/bin/env python import os.path as path import sys import csv TUMOR_CONFIG_DIALECT = "tumor-type-config" csv.register_dialect(TUMOR_CONFIG_DIALECT, delimiter=',', lineterminator='\n') _relpath_configfile = path.join('config', 'tumorTypesConfig.csv') _configfile = path.expandvars(path.join('${GIDGET_SOURCE_ROOT...
#!/usr/bin/env python import os.path as path import sys import csv TUMOR_CONFIG_DIALECT = "tumor-type-config" csv.register_dialect(TUMOR_CONFIG_DIALECT, delimiter=',', lineterminator='\n', skipinitialspace=True) _relpath_configfile = path.join('config', 'tumorTypesConfig.csv') _configfile = path.expandvars(path.joi...
Make sure tumor-type config ignores spaces
Make sure tumor-type config ignores spaces
Python
mit
cancerregulome/gidget,cancerregulome/gidget,cancerregulome/gidget
25064a26fcb674c6cd0165945f5e07cc0b4d2136
medical_prescription_sale_stock_us/__openerp__.py
medical_prescription_sale_stock_us/__openerp__.py
# -*- coding: utf-8 -*- # © 2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { 'name': 'Medical Prescription Sale Stock - US', 'summary': 'Provides US Locale to Medical Prescription Sale Stock', 'version': '9.0.1.0.0', 'author': "LasLabs, Odoo Community Associatio...
# -*- coding: utf-8 -*- # © 2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { 'name': 'Medical Prescription Sale Stock - US', 'summary': 'Provides US Locale to Medical Prescription Sale Stock', 'version': '9.0.1.0.0', 'author': "LasLabs, Odoo Community Associatio...
Add dependency * Add dependency on medical_prescription_us to manifest file. This is needed for successful installation.
[FIX] medical_prescription_sale_stock_us: Add dependency * Add dependency on medical_prescription_us to manifest file. This is needed for successful installation.
Python
agpl-3.0
laslabs/vertical-medical,laslabs/vertical-medical
7341cc7a9049d3650cf8512e6ea32fefd4bf3cee
tensorflow_text/python/keras/layers/__init__.py
tensorflow_text/python/keras/layers/__init__.py
# coding=utf-8 # Copyright 2021 TF.Text Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
# coding=utf-8 # Copyright 2021 TF.Text Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
Add missing symbols for tokenization layers
Add missing symbols for tokenization layers Tokenization layers are now exposed by adding them to the list of allowed symbols. Cheers
Python
apache-2.0
tensorflow/text,tensorflow/text,tensorflow/text
e4cfbe6a60a15041a449fd7717166849136cb48b
stormtracks/settings/default_stormtracks_settings.py
stormtracks/settings/default_stormtracks_settings.py
# *** DON'T MODIFY THIS FILE! *** # # Instead copy it to stormtracks_settings.py # # Default settings for project # This will get copied to $HOME/.stormtracks/ # on install. import os SETTINGS_DIR = os.path.abspath(os.path.dirname(__file__)) # expandvars expands e.g. $HOME DATA_DIR = os.path.expandvars('$HOME/stormtra...
# *** DON'T MODIFY THIS FILE! *** # # Instead copy it to stormtracks_settings.py # # Default settings for project # This will get copied to $HOME/.stormtracks/ # on install. import os SETTINGS_DIR = os.path.abspath(os.path.dirname(__file__)) # expandvars expands e.g. $HOME DATA_DIR = os.path.expandvars('$HOME/stormtra...
Remove no longer used setting.
Remove no longer used setting.
Python
mit
markmuetz/stormtracks,markmuetz/stormtracks
2329886a57a25db56079ff615188b744877f3070
scot/backend_builtin.py
scot/backend_builtin.py
# Released under The MIT License (MIT) # http://opensource.org/licenses/MIT # Copyright (c) 2013-2016 SCoT Development Team """Use internally implemented functions as backend.""" from __future__ import absolute_import import scipy as sp from . import backend from . import datatools, pca, csp from .var import VAR fro...
# Released under The MIT License (MIT) # http://opensource.org/licenses/MIT # Copyright (c) 2013-2016 SCoT Development Team """Use internally implemented functions as backend.""" from __future__ import absolute_import import scipy as sp from . import backend from . import datatools, pca, csp from .var import VAR fro...
Change ICA default to extended Infomax
Change ICA default to extended Infomax
Python
mit
mbillingr/SCoT,scot-dev/scot,scot-dev/scot,cle1109/scot,cbrnr/scot,cle1109/scot,mbillingr/SCoT,cbrnr/scot
91bf68e26c0fdf7de4209622192f9d57be2d60f8
feincms/views/cbv/views.py
feincms/views/cbv/views.py
from __future__ import absolute_import, unicode_literals from django.http import Http404 from feincms import settings from feincms._internal import get_model from feincms.module.mixins import ContentView class Handler(ContentView): page_model_path = 'page.Page' context_object_name = 'feincms_page' @pro...
from __future__ import absolute_import, unicode_literals from django.http import Http404 from django.utils.functional import cached_property from feincms import settings from feincms._internal import get_model from feincms.module.mixins import ContentView class Handler(ContentView): page_model_path = None c...
Stop invoking get_model for each request
Stop invoking get_model for each request
Python
bsd-3-clause
joshuajonah/feincms,mjl/feincms,matthiask/django-content-editor,michaelkuty/feincms,matthiask/django-content-editor,nickburlett/feincms,feincms/feincms,michaelkuty/feincms,mjl/feincms,mjl/feincms,joshuajonah/feincms,joshuajonah/feincms,nickburlett/feincms,matthiask/django-content-editor,joshuajonah/feincms,feincms/fein...
be33ae4e800619e0c50ef9dd7ce5e135e2ebb54b
telethon/errors/__init__.py
telethon/errors/__init__.py
import re from .common import ( ReadCancelledError, InvalidParameterError, TypeNotFoundError, InvalidChecksumError ) from .rpc_errors import ( RPCError, InvalidDCError, BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, FloodError, ServerError, BadMessageError ) from .rpc_errors_303 i...
import re from .common import ( ReadCancelledError, InvalidParameterError, TypeNotFoundError, InvalidChecksumError ) from .rpc_errors import ( RPCError, InvalidDCError, BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, FloodError, ServerError, BadMessageError ) from .rpc_errors_303 i...
Fix rpc_message_to_error failing to construct them
Fix rpc_message_to_error failing to construct them
Python
mit
LonamiWebs/Telethon,LonamiWebs/Telethon,LonamiWebs/Telethon,LonamiWebs/Telethon,kyasabu/Telethon,expectocode/Telethon,andr-04/Telethon
b12b1245a5a77f2d9373a4878fe07c01335624f7
froide/publicbody/forms.py
froide/publicbody/forms.py
from django import forms from django.utils.translation import ugettext as _ from helper.widgets import EmailInput class PublicBodyForm(forms.Form): name = forms.CharField(label=_("Name of Public Body")) description = forms.CharField(label=_("Short description"), widget=forms.Textarea, required=False) ema...
from django import forms from django.utils.translation import ugettext as _ from haystack.forms import SearchForm from helper.widgets import EmailInput class PublicBodyForm(forms.Form): name = forms.CharField(label=_("Name of Public Body")) description = forms.CharField(label=_("Short description"), widget=...
Add a topic search form (currently not used)
Add a topic search form (currently not used)
Python
mit
stefanw/froide,CodeforHawaii/froide,catcosmo/froide,LilithWittmann/froide,LilithWittmann/froide,ryankanno/froide,okfse/froide,fin/froide,LilithWittmann/froide,CodeforHawaii/froide,LilithWittmann/froide,ryankanno/froide,okfse/froide,fin/froide,stefanw/froide,stefanw/froide,catcosmo/froide,ryankanno/froide,catcosmo/froid...
076a129a8468a6c85c8b55a752aca87a60f90d79
ehrcorral/compressions.py
ehrcorral/compressions.py
from __future__ import print_function from __future__ import division from __future__ import absolute_import from __future__ import unicode_literals from jellyfish import soundex, nysiis, metaphone from metaphone import doublemetaphone as dmetaphone def first_letter(name): """A simple name compression that retur...
from __future__ import print_function from __future__ import division from __future__ import absolute_import from __future__ import unicode_literals from jellyfish import soundex, nysiis, metaphone from metaphone import doublemetaphone as dmetaphone def first_letter(name): """A simple name compression that retur...
Add if/else to first_letter compression to handle empty names
Add if/else to first_letter compression to handle empty names
Python
isc
nsh87/ehrcorral
bd7c0a9ac2d357ab635bf2948824256f1e6ddbec
src/carreralib/serial.py
src/carreralib/serial.py
from serial import serial_for_url from .connection import BufferTooShort, Connection, TimeoutError class SerialConnection(Connection): def __init__(self, url, timeout=None): self.__serial = serial_for_url(url, baudrate=19200, timeout=timeout) def close(self): self.__serial.close() def r...
from serial import serial_for_url from .connection import BufferTooShort, Connection, TimeoutError class SerialConnection(Connection): __serial = None def __init__(self, url, timeout=None): self.__serial = serial_for_url(url, baudrate=19200, timeout=timeout) def close(self): if self.__...
Fix SerialConnection.close() with invalid device.
Fix SerialConnection.close() with invalid device.
Python
mit
tkem/carreralib
b8c724cb141f6b0757d38b826b5cfd841284a37e
kuryr_libnetwork/server.py
kuryr_libnetwork/server.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 t...
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
Fix no log in /var/log/kuryr/kuryr.log
Fix no log in /var/log/kuryr/kuryr.log code misuse "Kuryr" in log.setup, it should be "kuryr". Change-Id: If36c9e03a01dae710ca12cf340abbb0c5647b47f Closes-bug: #1617863
Python
apache-2.0
celebdor/kuryr-libnetwork,celebdor/kuryr-libnetwork,celebdor/kuryr-libnetwork
0d59cf159d9c5f6c64c49cc7ef3cef8feaf5452d
templatetags/coltrane.py
templatetags/coltrane.py
from django.db.models import get_model from django import template from django.contrib.comments.models import Comment, FreeComment from coltrane.models import Entry, Link register = template.Library() class LatestFeaturedNode(template.Node): def __init__(self, varname): self.varname = varname d...
from django.db.models import get_model from django import template from django.contrib.comments.models import Comment, FreeComment from template_utils.templatetags.generic_content import GenericContentNode from coltrane.models import Entry, Link register = template.Library() class LatestFeaturedNode(GenericContent...
Refactor LatestFeaturedNode to use GenericContentNode and accept a configurable number of entries to fetch
Refactor LatestFeaturedNode to use GenericContentNode and accept a configurable number of entries to fetch git-svn-id: 9770886a22906f523ce26b0ad22db0fc46e41232@54 5f8205a5-902a-0410-8b63-8f478ce83d95
Python
bsd-3-clause
clones/django-coltrane,mafix/coltrane-blog
7321ed72469ad4b9eaf7b1feda370472c294fa97
django_backend_test/noras_menu/forms.py
django_backend_test/noras_menu/forms.py
# -*- encoding: utf-8 -*- #STDLIB importa #Core Django Imports from django import forms #Third Party apps imports #Imports local apps from .models import Menu, MenuItems
# -*- encoding: utf-8 -*- #STDLIB importa from datetime import date #Core Django Imports from django import forms from django.forms.models import inlineformset_factory #Third Party apps imports #Imports local apps from .models import Menu, MenuItems, UserSelectedLunch, Subscribers class MenuForm(forms.ModelForm): ...
Add ModelForm of Menu, MenuItems and Subscriber
Add ModelForm of Menu, MenuItems and Subscriber
Python
mit
semorale/backend-test,semorale/backend-test,semorale/backend-test
e103ac2a6df36d4236640d36da1a92b6da90e7c5
masters/master.chromium.webrtc/master_builders_cfg.py
masters/master.chromium.webrtc/master_builders_cfg.py
# Copyright (c) 2015 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 buildbot.changes.filter import ChangeFilter from buildbot.schedulers.basic import SingleBranchScheduler from master.factory import annotator_factor...
# Copyright (c) 2015 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 buildbot.changes.filter import ChangeFilter from buildbot.schedulers.basic import SingleBranchScheduler from master.factory import annotator_factor...
Switch chromium.webrtc Linux builders to chromium recipe.
WebRTC: Switch chromium.webrtc Linux builders to chromium recipe. With https://codereview.chromium.org/1406253003/ landed this is the first CL in a series of careful rollout to the new recipe. BUG=538259 TBR=phajdan.jr@chromium.org Review URL: https://codereview.chromium.org/1508933002 git-svn-id: 239fca9b83025a0b6...
Python
bsd-3-clause
eunchong/build,eunchong/build,eunchong/build,eunchong/build
f83011c7b5fdb7c1865d04b03e44660851fc8dcd
test/handler_fixture.py
test/handler_fixture.py
import unittest import tempfile import shutil import uuid import groundstation.node import groundstation.transfer.response import groundstation.transfer.request from groundstation.station import Station class MockStream(list): def enqueue(self, *args, **kwargs): self.append(*args, **kwargs) def MockTER...
import unittest import tempfile import shutil import uuid import groundstation.node import groundstation.transfer.response import groundstation.transfer.request from groundstation.station import Station class MockStream(list): def enqueue(self, *args, **kwargs): self.append(*args, **kwargs) def MockTER...
Implement teardown on Station mock
Implement teardown on Station mock
Python
mit
richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation
d8c0f7cd89ec52d9ad7553a27421c899b3a94417
dbaas/workflow/workflow.py
dbaas/workflow/workflow.py
# -*- coding: utf-8 -*- from django.utils.module_loading import import_by_path from notification.models import TaskHistory import logging LOG = logging.getLogger(__name__) def start_workflow(workflow_dict, task=None): try : if not 'steps' in workflow_dict: return False workflow_dict['step_counter'] = 0 ...
# -*- coding: utf-8 -*- from django.utils.module_loading import import_by_path import logging LOG = logging.getLogger(__name__) def start_workflow(workflow_dict, task=None): try: if not 'steps' in workflow_dict: return False workflow_dict['step_counter'] = 0 for step in workf...
Improve logs and refactor to pep8
Improve logs and refactor to pep8
Python
bsd-3-clause
globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service
adc78d6c23b15bc06d16c7365b1875ebe39dc328
jukebox/scanner.py
jukebox/scanner.py
import os import zope.interface import mutagen import jukebox.song class IScanner(zope.interface.Interface): def scan(): """ Start the scanning process. It is expected to be called at startup and can block. """ def watch(): """ Starts an async watcher that can...
import os import zope.interface import mutagen import jukebox.song class IScanner(zope.interface.Interface): def scan(): """ Start the scanning process. It is expected to be called at startup and can block. """ def watch(): """ Starts an async watcher that can...
Support more than on path when building a DirScanner
Support more than on path when building a DirScanner
Python
mit
armooo/jukebox,armooo/jukebox
949f629b349707c2f4caf0a288969b5a6143a730
kyokai/response.py
kyokai/response.py
""" Module for a Response object. A Response is returned by Routes when the underlying coroutine is done. """ from http_parser.util import IOrderedDict from .util import HTTP_CODES class Response(object): """ A response is responsible (no pun intended) for delivering data to the client, again. The meth...
""" Module for a Response object. A Response is returned by Routes when the underlying coroutine is done. """ from http_parser.util import IOrderedDict from .util import HTTP_CODES class Response(object): """ A response is responsible (no pun intended) for delivering data to the client, again. The meth...
Add \r\n to the end of each header too
Add \r\n to the end of each header too
Python
mit
SunDwarf/Kyoukai
e08a382e215569b2ad147ea82d7ede1319722724
configurator/__init__.py
configurator/__init__.py
"""Adaptive configuration dialogs. Attributes: __version__: The current version string. """ import os import subprocess def _get_version(version=None): # overwritten by setup.py if version is None: pkg_dir = os.path.dirname(__file__) src_dir = os.path.abspath(os.path.join(pkg_dir, os.pardir...
"""Adaptive configuration dialogs. Attributes: __version__: The current version string. """ import os import subprocess def _get_version(version=None): # overwritten by setup.py if version is None: pkg_dir = os.path.dirname(__file__) src_dir = os.path.abspath(os.path.join(pkg_dir, os.pardir...
Use git describe --always in _get_version()
Use git describe --always in _get_version() Travis CI does a truncated clone and causes 'git describe' to fail if the version tag is not part of the truncated history.
Python
apache-2.0
yasserglez/configurator,yasserglez/configurator
749181ac27583900af94feca848f3039d7c69bcc
app/backend/gwells/views/api.py
app/backend/gwells/views/api.py
from rest_framework.response import Response from rest_framework.views import APIView from gwells.settings.base import get_env_variable class KeycloakConfig(APIView): """ serves keycloak config """ def get(self, request): config = { "realm": get_env_variable("SSO_REALM"), "au...
from rest_framework.response import Response from rest_framework.views import APIView from gwells.settings.base import get_env_variable class KeycloakConfig(APIView): """ serves keycloak config """ def get(self, request): config = { "realm": get_env_variable("SSO_REALM"), "au...
Add "idir" as default value.
Add "idir" as default value.
Python
apache-2.0
bcgov/gwells,bcgov/gwells,bcgov/gwells,bcgov/gwells
e4564e790dca3079e76540f452836353b902f5b6
flexbe_core/src/flexbe_core/core/loopback_state.py
flexbe_core/src/flexbe_core/core/loopback_state.py
#!/usr/bin/env python import rospy from flexbe_core.core.lockable_state import LockableState class LoopbackState(LockableState): """ A state that can refer back to itself. It periodically transitions to itself while no other outcome is fulfilled. """ _loopback_name = 'loopback' def __init...
#!/usr/bin/env python import rospy from flexbe_core.core.lockable_state import LockableState class LoopbackState(LockableState): """ A state that can refer back to itself. It periodically transitions to itself while no other outcome is fulfilled. """ _loopback_name = 'loopback' def __init...
Add method to set a custom execute rate for states
[flexbe_core] Add method to set a custom execute rate for states
Python
bsd-3-clause
team-vigir/flexbe_behavior_engine,team-vigir/flexbe_behavior_engine
f1fedff9247b78120df7335b64cdf46c8f60ef03
test/test_fixtures.py
test/test_fixtures.py
import pytest from tornado import gen _used_fixture = False @gen.coroutine def dummy(io_loop): yield gen.Task(io_loop.add_callback) raise gen.Return(True) @pytest.fixture(scope='module') def preparations(): global _used_fixture _used_fixture = True pytestmark = pytest.mark.usefixtures('preparatio...
import pytest from tornado import gen _used_fixture = False @gen.coroutine def dummy(io_loop): yield gen.Task(io_loop.add_callback) raise gen.Return(True) @pytest.fixture(scope='module') def preparations(): global _used_fixture _used_fixture = True pytestmark = pytest.mark.usefixtures('preparatio...
Add some test for method signature inspection
Add some test for method signature inspection
Python
apache-2.0
eugeniy/pytest-tornado
03e864845d0b06cfa4b6cec1adf9b08152a49f0b
forms_builder/example_project/manage.py
forms_builder/example_project/manage.py
#!/usr/bin/env python from django.core.management import execute_manager import imp try: imp.find_module('settings') # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized t...
#!/usr/bin/env python import sys import os sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../..')) from django.core.management import execute_manager import imp try: imp.find_module('settings') # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can'...
Allow tests to be run from example_project
Allow tests to be run from example_project
Python
bsd-2-clause
iddqd1/django-forms-builder,ixc/django-forms-builder,frontendr/django-forms-builder,vinnyrose/django-forms-builder,GetHappie/django-forms-builder,Afnarel/django-forms-builder,JostCrow/django-forms-builder,GetHappie/django-forms-builder,nimbis/django-forms-builder,Afnarel/django-forms-builder,simas/django-forms-builder,...
3e9a90890f122090be027a3af3d6cbd8a713963c
test/test_issue655.py
test/test_issue655.py
from rdflib import Graph, Namespace, URIRef, Literal from rdflib.compare import to_isomorphic import unittest class TestIssue655(unittest.TestCase): def test_issue655(self): PROV = Namespace('http://www.w3.org/ns/prov#') bob = URIRef("http://example.org/object/Bob") value = Literal(float...
from rdflib import Graph, Namespace, URIRef, Literal from rdflib.compare import to_isomorphic import unittest class TestIssue655(unittest.TestCase): def test_issue655(self): PROV = Namespace('http://www.w3.org/ns/prov#') bob = URIRef("http://example.org/object/Bob") value = Literal(float...
Add tests requested by @joernhees
Add tests requested by @joernhees
Python
bsd-3-clause
RDFLib/rdflib,RDFLib/rdflib,RDFLib/rdflib,RDFLib/rdflib
a66f0227946984702fe6247f64b65152774c5d06
test/test_packages.py
test/test_packages.py
import pytest @pytest.mark.parametrize("name", [ ("bash-completion"), ("bind-utils"), ("bridge-utils"), ("docker"), ("epel-release"), ("git"), ("iptables-services"), ("libnfsidmap"), ("net-tools"), ("nfs-utils"), ("pyOpenSSL"), ("screen"), ("strace"), ("tcpdump"), ("wget"), ]) def test_p...
import pytest @pytest.mark.parametrize("name", [ ("bash-completion"), ("bind-utils"), ("bridge-utils"), ("docker"), ("epel-release"), ("git"), ("iptables-services"), ("libnfsidmap"), ("net-tools"), ("nfs-utils"), ("pyOpenSSL"), ("screen"), ("strace"), ("tcpdump"), ("wget"), ]) def test_p...
Rework based on examples in docs
Rework based on examples in docs
Python
mit
wicksy/vagrant-openshift,wicksy/vagrant-openshift,wicksy/vagrant-openshift
e6d483c867687188ad89dae9ea00b0d651598605
tw_begins.py
tw_begins.py
#!/usr/bin/env python import begin import twitterlib @begin.subcommand def timeline(): "Display recent tweets from users timeline" for status in begin.context.api.timeline: print u"%s: %s" % (status.user.screen_name, status.text) @begin.subcommand def mentions(): "Display recent tweets mentionin...
#!/usr/bin/env python import begin import twitterlib @begin.subcommand def timeline(): "Display recent tweets from users timeline" for status in begin.context.api.timeline: print u"%s: %s" % (status.user.screen_name, status.text) @begin.subcommand def mentions(): "Display recent tweets mentionin...
Use only long form arguments
Use only long form arguments Do not use any short (single character) arguments for command line options.
Python
mit
aliles/cmdline_examples
2ac4bca0db8609bc92c9de8b1c272b2a607f6c15
tests/resource_tests.py
tests/resource_tests.py
# # Project: retdec-python # Copyright: (c) 2015 by Petr Zemek <s3rvac@gmail.com> and contributors # License: MIT, see the LICENSE file for more details # """Tests for the :mod:`retdec.resource` module.""" import unittest from unittest import mock from retdec.conn import APIConnection from retdec.resource import...
# # Project: retdec-python # Copyright: (c) 2015 by Petr Zemek <s3rvac@gmail.com> and contributors # License: MIT, see the LICENSE file for more details # """Tests for the :mod:`retdec.resource` module.""" import unittest from unittest import mock from retdec.conn import APIConnection from retdec.resource import...
Move tests for Resource.wait_until_finished() into a separate class.
Move tests for Resource.wait_until_finished() into a separate class.
Python
mit
s3rvac/retdec-python
95eb2c11a4f35e594eda25c10bdf85a25b2f4392
src/ConfigLoader.py
src/ConfigLoader.py
import json import sys def load_config_file(out=sys.stdout): default_filepath = "../resources/config/default-config.json" user_filepath = "../resources/config/user-config.json" try: default_json = read_json(default_filepath) user_json = read_json(user_filepath) for property in use...
import json import sys def load_config_file(out=sys.stdout): if sys.argv[0].endswith('nosetests'): default_filepath = "./resources/config/default-config.json" user_filepath = "./resources/config/user-config.json" else: default_filepath = "../resources/config/default-config.json" ...
Fix nosetests for config file loading
Fix nosetests for config file loading
Python
bsd-3-clause
sky-uk/bslint
7d8283b2d233a8fbee97de122f0b4ba293cf788d
app/emails.py
app/emails.py
# -*- coding: utf-8 -*- from flask import render_template,g from flask.ext.mail import Message from app import mail, db from .models import User from config import MAIL_SENDER # Wrapper function for sending mails using flask-mail plugin def send_email(subject, sender, recipients, text_body): msg = Message(subject...
# -*- coding: utf-8 -*- from flask import render_template,g from flask.ext.mail import Message from app import mail, db from .models import User from config import MAIL_SENDER from threading import Thread from app import app # Send mail into a dedicated thread in order to avoir the web app to wait def send_async_emai...
Send email notifications in asynchronous mode
Send email notifications in asynchronous mode Each mail notification is done on a thread in order to not block the main thread of the web app.
Python
mit
ptitoliv/cineapp,ptitoliv/cineapp,ptitoliv/cineapp
57db4140237b79cc8b6958ac503bc087f57ddad2
ibmcnx/doc/DataSources.py
ibmcnx/doc/DataSources.py
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Appli...
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Appli...
Create script to save documentation to a file
4: Create script to save documentation to a file Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/4
Python
apache-2.0
stoeps13/ibmcnx2,stoeps13/ibmcnx2
30e1e82573437cfaf8b75ec9f42c520a5f4f60d5
ibmcnx/doc/DataSources.py
ibmcnx/doc/DataSources.py
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Appli...
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Appli...
Create documentation of DataSource Settings
8: Create documentation of DataSource Settings Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8
Python
apache-2.0
stoeps13/ibmcnx2,stoeps13/ibmcnx2
4d2a2b3e5b9f734e688c104845d33b90dda2c159
commands/say.py
commands/say.py
from CommandTemplate import CommandTemplate class Command(CommandTemplate): triggers = ['say'] helptext = "Makes the bot say the provided text in the provided channel (format 'say [channel/user] text')" adminOnly = True showInCommandList = False def execute(self, bot, user, target, triggerInMsg, msg, msgWithout...
from CommandTemplate import CommandTemplate class Command(CommandTemplate): triggers = ['say'] helptext = "Makes the bot say the provided text in the provided channel (format 'say [channel/user] text')" adminOnly = True showInCommandList = False def execute(self, bot, user, target, triggerInMsg, msg, msgWithout...
Add a check to see if the bot's in the channel the message should go to
Add a check to see if the bot's in the channel the message should go to
Python
mit
Didero/DideRobot
236816340df75e1ef4fc3f6ee4540a02c44fc279
tests/helpers/helpers.py
tests/helpers/helpers.py
from inspect import getdoc import pytest class CodeCollector(object): def __init__(self): self.collected = [] def __call__(self, f): self.collected.append(f) return f def __iter__(self): return iter(self.collected) def parametrize(self, test_func): retu...
from inspect import getdoc import pytest class CodeCollector(object): def __init__(self, name='code'): self.name = name self.collected = [] def __call__(self, f): self.collected.append(f) return f def __iter__(self): return iter(self.collected) def param...
Support argument name in the CodeCollector helper.
Support argument name in the CodeCollector helper.
Python
bsd-2-clause
proofit404/dependencies,proofit404/dependencies,proofit404/dependencies,proofit404/dependencies
e822ee6fe844c18b2a459ed188f4fbae26c617e5
lingcod/bookmarks/forms.py
lingcod/bookmarks/forms.py
from lingcod.features.forms import FeatureForm from lingcod.bookmarks.models import Bookmark from django import forms class BookmarkForm(FeatureForm): name = forms.CharField(label='Bookmark Name') latitude = forms.FloatField(widget=forms.HiddenInput()) longitude = forms.FloatField(widget=forms.HiddenInput(...
from lingcod.features.forms import FeatureForm from lingcod.bookmarks.models import Bookmark from django import forms class BookmarkForm(FeatureForm): name = forms.CharField(label='Bookmark Name') latitude = forms.FloatField(widget=forms.HiddenInput()) longitude = forms.FloatField(widget=forms.HiddenInput(...
Hide IP from input form
Hide IP from input form --HG-- branch : bookmarks
Python
bsd-3-clause
underbluewaters/marinemap,underbluewaters/marinemap,underbluewaters/marinemap
184e726d44d113a46ddb9cf3a5762f453ed7b512
myuw/management/commands/clear_expired_sessions.py
myuw/management/commands/clear_expired_sessions.py
""" The django clearsessions commend internally calls: cls.get_model_class().objects.filter( expire_date__lt=timezone.now()).delete() which could lock the DB table for a long time when having a large number of records to delete. To prevent the job running forever, we only delete a limit number of expired dja...
""" The django clearsessions commend internally calls: cls.get_model_class().objects.filter( expire_date__lt=timezone.now()).delete() which could lock the DB table for a long time when having a large number of records to delete. To prevent the job running forever, we only delete a limit number of expired dja...
Add a 5 second pause
Add a 5 second pause
Python
apache-2.0
uw-it-aca/myuw,uw-it-aca/myuw,uw-it-aca/myuw,uw-it-aca/myuw
f00c7f3a976ba4790963a5701c5ce13f6dcd84fa
tests/test_funcmakers.py
tests/test_funcmakers.py
import inspect from collections import defaultdict import pytest from funcy.funcmakers import * def test_callable(): assert make_func(lambda x: x + 42)(0) == 42 def test_int(): assert make_func(0)('abc') == 'a' assert make_func(2)([1,2,3]) == 3 assert make_func(1)({1: 'a'}) == 'a' with pytest.r...
from collections import defaultdict import pytest from funcy.funcmakers import * def test_callable(): assert make_func(lambda x: x + 42)(0) == 42 def test_int(): assert make_func(0)('abc') == 'a' assert make_func(2)([1,2,3]) == 3 assert make_func(1)({1: 'a'}) == 'a' with pytest.raises(IndexErro...
Remove unused import from tests
Remove unused import from tests
Python
bsd-3-clause
Suor/funcy
b602e732ae091b78c1a0e7258bec878a12cf063f
tests/test_account.py
tests/test_account.py
# coding: utf-8 import unittest from lastpass.account import Account class AccountTestCase(unittest.TestCase): def setUp(self): self.id = 'id' self.name = 'name' self.username = 'username' self.password = 'password' self.url = 'url' self.group = 'group' self...
# coding: utf-8 import unittest from lastpass.account import Account class AccountTestCase(unittest.TestCase): def setUp(self): self.id = 'id' self.name = 'name' self.username = 'username' self.password = 'password' self.url = 'url' self.group = 'group' self...
Add a test for `notes` attribute
Add a test for `notes` attribute
Python
mit
konomae/lastpass-python
55d4b7b939fc218d47a920761350aee7bee91eb9
opps/article/views.py
opps/article/views.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.views.generic.detail import DetailView from django.views.generic.list import ListView from opps.article.models import Post class OppsList(ListView): context_object_name = "context" @property def template_name(self): return 'channel/{0}....
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.views.generic.detail import DetailView from django.views.generic.list import ListView from opps.article.models import Post class OppsList(ListView): context_object_name = "context" @property def template_name(self): long_slug = self.kwa...
Fix template name on entry home page (/) on list page
Fix template name on entry home page (/) on list page
Python
mit
opps/opps,williamroot/opps,williamroot/opps,opps/opps,opps/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,opps/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,YACOWS/opps,williamroot/opps
1f5403108a25257dfa63d235c8faf4e02f69c6bf
opps/sitemaps/urls.py
opps/sitemaps/urls.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.conf.urls import patterns, url from django.contrib.sitemaps import views as sitemap_views from opps.sitemaps.sitemaps import GenericSitemap, InfoDisct sitemaps = { 'articles': GenericSitemap(InfoDisct(), priority=0.6), } sitemaps_googlenews = { 'arti...
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.conf.urls import patterns, url from django.views.decorators.cache import cache_page from django.contrib.sitemaps import views as sitemap_views from opps.sitemaps.sitemaps import GenericSitemap, InfoDisct sitemaps = { 'articles': GenericSitemap(InfoDisct()...
Add cache page on sitemap fixed
Add cache page on sitemap fixed
Python
mit
jeanmask/opps,williamroot/opps,YACOWS/opps,opps/opps,YACOWS/opps,opps/opps,opps/opps,jeanmask/opps,opps/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,williamroot/opps,williamroot/opps,YACOWS/opps
99b1e11542c7e102e9fe739ea355b84d22b913d3
src/experiments/forms.py
src/experiments/forms.py
from crispy_forms.bootstrap import FormActions from crispy_forms.helper import FormHelper from crispy_forms.layout import Fieldset, Layout, Submit from django import forms from django.utils.functional import cached_property from django.utils.translation import ugettext_lazy as _ from core.widgets import SimpleMDEWidge...
from crispy_forms.bootstrap import FormActions from crispy_forms.helper import FormHelper from crispy_forms.layout import Fieldset, Layout, Submit, Div from django import forms from django.utils.functional import cached_property from django.utils.translation import ugettext_lazy as _ from core.widgets import SimpleMDE...
Disable form submit for now
Disable form submit for now
Python
mit
ccwang002/biocloud-server-kai,ccwang002/biocloud-server-kai,ccwang002/biocloud-server-kai
0b632368b4991621696a7f7a396afecf61e6ccc3
tools/examples/geturl.py
tools/examples/geturl.py
#!/usr/bin/env python2 # # USAGE: geturl.py FILE_OR_DIR1 FILE_OR_DIR2 ... # # prints out the URL associated with each item # import sys import svn._wc import svn.util def main(pool, files): for f in files: entry = svn._wc.svn_wc_entry(f, 0, pool) print svn._wc.svn_wc_entry_t_url_get(entry) if __name__ == '...
#!/usr/bin/env python2 # # USAGE: geturl.py FILE_OR_DIR1 FILE_OR_DIR2 ... # # prints out the URL associated with each item # import os import sys import svn.wc import svn.util def main(pool, files): for f in files: dirpath = fullpath = os.path.abspath(f) if not os.path.isdir(dirpath): dirpath = os.pa...
Update the example to use the new access baton stuff.
Update the example to use the new access baton stuff.
Python
apache-2.0
jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion
7148264a374301cb6cf9d35f3b17f3a02652600f
manage.py
manage.py
#!/usr/bin/env python import os from app import create_app, db from app.models import User, Role, Permission from flask.ext.script import Manager, Shell from flask.ext.migrate import Migrate, MigrateCommand app = create_app(os.getenv('FLASK_CONFIG') or 'default') manager = Manager(app) migrate = Migrate(app, db) def...
#!/usr/bin/env python import os from app import create_app, db from app.models import User, Role, Permission from flask.ext.script import Manager, Shell from flask.ext.migrate import Migrate, MigrateCommand app = create_app(os.getenv('FLASK_CONFIG') or 'default') manager = Manager(app) migrate = Migrate(app, db) def...
Add command to seed database
Add command to seed database
Python
mit
richgieg/flask-now,richgieg/flask-now
c1a8d0e1fdc0d2ebd822a041874ba6de8ed6d9ac
mod/default/mod_default.py
mod/default/mod_default.py
#! /usr/bin/env python # coding:utf-8 from mod import Mod import random import os class ModDefault(Mod): def __init__( self, filename=None, logger=None ): Mod.__init__(self, logger) text_path = filename or os.path.join( os.path.abspath(os.path.dirname(__fi...
#! /usr/bin/env python # coding:utf-8 from mod import Mod import random import os class ModDefault(Mod): def __init__( self, filename=None, logger=None ): Mod.__init__(self, logger) text_path = filename or os.path.join( os.path.abspath(os.path.dirname(__fi...
Use uniform instead of random
Use uniform instead of random
Python
mit
kenkov/kovot,kenkov/kovot
a6017e692ee8d602a228a91ad76b344459292bbf
src/hatchit/urls.py
src/hatchit/urls.py
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', 'event_manager.views.home', name='home'), url(r'^admin/', include(admin.site.urls)), )
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', 'event_manager.views.home', name='home'), url(r'^s/$', 'event_manager.views.my_suggestions', name='suggestions'), url(r'^e/$', 'event_manager.views.my_events', na...
Add routes for new views
Add routes for new views
Python
agpl-3.0
DavidJFelix/hatchit,DavidJFelix/hatchit,DavidJFelix/hatchit
3ceb39e4bbc4c5de7cbcce9c1ecfe94daa57266e
zhihudaily/models.py
zhihudaily/models.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from peewee import Model, IntegerField, CharField from zhihudaily.configs import Config class BaseModel(Model): class Meta: database = Config.database class Zhihudaily(BaseModel): date = Integer...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from peewee import Model, IntegerField, CharField from zhihudaily.configs import Config class BaseModel(Model): class Meta: database = Config.database class Zhihudaily(BaseModel): date = Integer...
Fix bug when create the datebase table
Fix bug when create the datebase table
Python
mit
lord63/zhihudaily,lord63/zhihudaily,lord63/zhihudaily
ba3009d1d19243c703743070df68ad1ea11d454e
addons/hr_contract/__terp__.py
addons/hr_contract/__terp__.py
{ "name" : "Human Resources Contracts", "version" : "1.0", "author" : "Tiny", "category" : "Generic Modules/Human Resources", "website" : "http://tinyerp.com/module_hr.html", "depends" : ["hr"], "module": "", "description": """ Add all information on the employee form to manage contracts: * Martial status, *...
{ "name" : "Human Resources Contracts", "version" : "1.0", "author" : "Tiny", "category" : "Generic Modules/Human Resources", "website" : "http://tinyerp.com/module_hr.html", "depends" : ["hr"], "module": "", "description": """ Add all information on the employee form to manage contracts: * Martial status, *...
Add hr_contract_security.xml file entry in update_xml section
Add hr_contract_security.xml file entry in update_xml section bzr revid: mga@tinyerp.com-cceb329e8e30908ba1f6594b9502506150d105b2
Python
agpl-3.0
ygol/odoo,fossoult/odoo,leoliujie/odoo,hoatle/odoo,vrenaville/ngo-addons-backport,matrixise/odoo,cedk/odoo,chiragjogi/odoo,lsinfo/odoo,Nick-OpusVL/odoo,ihsanudin/odoo,dfang/odoo,gsmartway/odoo,ojengwa/odoo,windedge/odoo,tangyiyong/odoo,agrista/odoo-saas,mlaitinen/odoo,Daniel-CA/odoo,incaser/odoo-odoo,VitalPet/odoo,xujb...
7461666cde3c0206058d10f2341e0a57bf33e504
src/renderers/status.py
src/renderers/status.py
from flask import Blueprint from models import db, Status import json status_renderer = Blueprint('status', __name__) @status_renderer.route('/status/<int:user_id>') def get_tweet(user_id): status = db.session.query(Status).order_by(Status.id.desc()).one() return json.dumps({'type' : 'text', 'stat...
from flask import Blueprint from models import db, Status import json status_renderer = Blueprint('status', __name__) @status_renderer.route('/status') def get_status(): status = db.session.query(Status).order_by(Status.id.desc()).one() return json.dumps({'type' : 'text', 'status_text' : status.st...
Remove user_id requirement for FB endpoint
Remove user_id requirement for FB endpoint
Python
mit
ndm25/notifyable
7d9c7133de36d2fd7587d7be361cd0ff964d4e94
deflect/urls.py
deflect/urls.py
from django.conf.urls import patterns from django.conf.urls import url from .views import redirect urlpatterns = patterns('', url(r'^(?P<key>[a-zA-Z0-9]+)$', redirect, name='deflect-redirect'), )
from django.conf import settings from django.conf.urls import patterns from django.conf.urls import url from .views import alias from .views import redirect urlpatterns = patterns('', url(r'^(?P<key>[a-zA-Z0-9]+)$', redirect, name='deflect-redirect'), ) alias_prefix = getattr(settings, 'DEFLECT_ALIAS_PREFIX', '...
Add custom URL alias paths to URLconf
Add custom URL alias paths to URLconf
Python
bsd-3-clause
jbittel/django-deflect
403ad86bde44c1a015d8d35ac2826221ef98f9da
drftest/shop/api/views.py
drftest/shop/api/views.py
from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework.permissions import IsAuthenticated class ShopAPIView(APIView): permission_classes = (IsAuthenticated,) class OrdersView(ShopAPIView): ...
from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework.permissions import IsAuthenticated from django.db import transaction class ShopAPIView(APIView): permission_classes = (IsAuthenticated,) c...
Add transaction support to the orders view
Add transaction support to the orders view
Python
mit
andreagrandi/drf3-test,andreagrandi/drf3-test,andreagrandi/drf3-test
fbbe6b46b93274567e031d2ba7874fe3231b1557
openacademy/model/openacademy_course.py
openacademy/model/openacademy_course.py
# -*- coding: utf-8 -*- from openerp import models, fields, api ''' This module create model of Course ''' class Course(models.Model): ''' This class create model of Course ''' _name = 'openacademy.course' # model odoo name name = fields.Char(string="Title", required=True) description = fiel...
# -*- coding: utf-8 -*- from openerp import models, fields, api ''' This module create model of Course ''' class Course(models.Model): ''' This class create model of Course ''' _name = 'openacademy.course' # model odoo name name = fields.Char(string="Title", required=True) description = fiel...
Modify copy method into inherit
[REF] openacademy: Modify copy method into inherit
Python
apache-2.0
lescobarvx/curso-tecnico-odoo
979d1b8ce4567432a6816b55fe5c29ef7c190459
aospy_user/calcs/tendencies.py
aospy_user/calcs/tendencies.py
"""Calculations involved in mass and energy budgets.""" import numpy as np from aospy.utils import coord_to_new_dataarray from .. import TIME_STR def first_to_last_vals_dur(arr, freq='1M'): """Time elapsed between 1st and last values in each given time period.""" time = coord_to_new_dataarray(arr, TIME_STR) ...
"""Calculations involved in mass and energy budgets.""" import numpy as np from aospy.utils import coord_to_new_dataarray from .. import TIME_STR def first_to_last_vals_dur(arr, freq='1M'): """Time elapsed between 1st and last values in each given time period.""" time = coord_to_new_dataarray(arr, TIME_STR) ...
Add experimental every-timestep tendency function
Add experimental every-timestep tendency function
Python
apache-2.0
spencerahill/aospy-obj-lib
7d76b44c371d74cb8c7b272fd9bf8021db6c6702
qa/rpc-tests/test_framework/cashlib/__init__.py
qa/rpc-tests/test_framework/cashlib/__init__.py
# Copyright (c) 2018 The Bitcoin Unlimited developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.cashlib.cashlib import init, bin2hex, signTxInput, randombytes, pubkey, spendscript, addrbin, txid, SIGHASH_...
# Copyright (c) 2018 The Bitcoin Unlimited developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from .cashlib import init, bin2hex, signTxInput, randombytes, pubkey, spendscript, addrbin, txid, SIGHASH_ALL, SIGHASH_NONE, SIG...
Use relative import for cashlib
Use relative import for cashlib
Python
mit
BitcoinUnlimited/BitcoinUnlimited,Justaphf/BitcoinUnlimited,BitcoinUnlimited/BitcoinUnlimited,BitcoinUnlimited/BitcoinUnlimited,BitcoinUnlimited/BitcoinUnlimited,Justaphf/BitcoinUnlimited,Justaphf/BitcoinUnlimited,Justaphf/BitcoinUnlimited,BitcoinUnlimited/BitcoinUnlimited,BitcoinUnlimited/BitcoinUnlimited,Justaphf/Bit...
ad5da54795ac1329c683e069d3148120470b6451
brainhack/covariance/pearson.py
brainhack/covariance/pearson.py
import numpy as np from scipy.sparse import coo_matrix from sklearn.base import BaseEstimator class PearsonCorrelation(BaseEstimator): """Pearson correlation estimator """ def __init__(self, assume_centered=False): self.assume_centered = assume_centered def fit(self, X, y=None, connectivity=...
import numpy as np from scipy.sparse import coo_matrix from sklearn.base import BaseEstimator import scipy as sp class PearsonCorrelation(BaseEstimator): """Pearson correlation estimator """ def __init__(self, assume_centered=False, spatial=False): self.assume_centered = assume_centered s...
Add option for spatial correlation
Add option for spatial correlation
Python
bsd-3-clause
AlexandreAbraham/brainhack2013
6d44672ab0689f6d000001749e0e81b4a9b375f7
reporting_scripts/user_info.py
reporting_scripts/user_info.py
''' This module will retrieve info about students registered in the course Usage: python user_info.py ''' from collections import defaultdict from base_edx import EdXConnection from generate_csv_report import CSV connection = EdXConnection('certificates_generatedcertificate', 'auth_userprofile') collection = con...
''' This module will retrieve info about students registered in the course Usage: python user_info.py ''' from base_edx import EdXConnection from generate_csv_report import CSV connection = EdXConnection('certificates_generatedcertificate', 'auth_userprofile') collection = connection.get_access_to_collection() d...
Update to handle users with no final grade
Update to handle users with no final grade
Python
mit
McGillX/edx_data_research,andyzsf/edx_data_research,McGillX/edx_data_research,andyzsf/edx_data_research,McGillX/edx_data_research
40a59efec51661d4325e97f2e307963811336b94
calaccess_processed/__init__.py
calaccess_processed/__init__.py
from __future__ import absolute_import default_app_config = 'calaccess_processed.apps.CalAccessProcessedConfig'
#!/usr/bin/env python # -*- coding: utf-8 -*- import os default_app_config = 'calaccess_processed.apps.CalAccessProcessedConfig' def get_model_list(): """ Returns a model list of """ from django.apps import apps model_list = apps.get_app_config("calaccess_processed").models.values() return [ ...
Add get_model_list and archive_directory_path functions
Add get_model_list and archive_directory_path functions
Python
mit
california-civic-data-coalition/django-calaccess-processed-data,california-civic-data-coalition/django-calaccess-processed-data
df2bce1dc4542615a61b5346d2f7e89029e80de9
caniusepython3/test/__init__.py
caniusepython3/test/__init__.py
try: import unittest2 as unittest except ImportError: import unittest try: from unittest import mock except ImportError: import mock try: import xmlrpc.client as xmlrpc_client except ImportError: import xmlrpclib as xmlrpc_client import functools def skip_pypi_timeouts(method): @functool...
import requests try: import unittest2 as unittest except ImportError: import unittest try: from unittest import mock except ImportError: import mock import functools def skip_pypi_timeouts(method): @functools.wraps(method) def closure(*args, **kwargs): try: method(*args, ...
Update test skipping based on requests
Update test skipping based on requests
Python
apache-2.0
brettcannon/caniusepython3
18d2c4be27b58a142145f0726e6be21c358064cd
src/rnaseq_lib/docker/__init__.py
src/rnaseq_lib/docker/__init__.py
import os from subprocess import call def base_docker_call(mount): return ['docker', 'run', '--rm', '-v', '{}:/data'.format(mount)] def fix_directory_ownership(output_dir, tool): """ Uses a Docker container to change ownership recursively of a directory :param str output_dir: Directory to change ow...
import os from subprocess import call def base_docker_call(mount): """ Returns the boilerplate array used for Docker calls :param str mount: Directory to mount :return: Docker run parameters :rtype: list(str) """ return ['docker', 'run', '--rm', '-v', '{}:/data'.format(os.path.abspath(mou...
Use abspath for docker mount
Use abspath for docker mount
Python
mit
jvivian/rnaseq-lib,jvivian/rnaseq-lib
76f77023095b068402553b878a65f0566d8add81
runapp.py
runapp.py
import os from paste.deploy import loadapp from waitress import serve if __name__ == "__main__": port = int(os.environ.get("PORT", 5000)) app = loadapp('config:production.ini', relative_to='.') serve(app, host='0.0.0.0', port=port)
import os from paste.deploy import loadapp from pyramid.paster import setup_logging from waitress import serve if __name__ == "__main__": port = int(os.environ.get("PORT", 5000)) setup_logging('production.ini') app = loadapp('config:production.ini', relative_to='.') serve(app, host='0.0.0.0', port=po...
Enable logs when run in Heroku
Enable logs when run in Heroku
Python
agpl-3.0
Yaco-Sistemas/yith-library-server,lorenzogil/yith-library-server,Yaco-Sistemas/yith-library-server,lorenzogil/yith-library-server,Yaco-Sistemas/yith-library-server,lorenzogil/yith-library-server
2c965c0a75be129f429e40ade34ef608f8ceea27
micropress/urls.py
micropress/urls.py
from django.conf.urls.defaults import * urlpatterns = patterns('micropress.views', (r'^$', 'article_list'), (r'^issue/(?P<issue>\d+)/$', 'issue_list'), (r'^article/(?P<slug>[-\w]+)/$', 'article_detail'), #(r'^new/$', 'article_create'), )
from django.conf.urls.defaults import * urlpatterns = patterns('micropress.views', (r'^$', 'article_list'), url(r'^issue/(?P<issue>\d+)/$', 'article_list', name='issue_list'), (r'^article/(?P<slug>[-\w]+)/$', 'article_detail'), #(r'^new/$', 'article_create'), )
Fix url spec for article list by issue.
Fix url spec for article list by issue.
Python
mit
jbradberry/django-micro-press,jbradberry/django-micro-press
794f3d7e229f94b71a7cb3aaefd4640b185e2572
feder/letters/management/commands/reimport_mailbox.py
feder/letters/management/commands/reimport_mailbox.py
from __future__ import unicode_literals from django.core.management.base import BaseCommand from django_mailbox.models import Message from feder.letters.signals import MessageParser class Command(BaseCommand): help = "Reimport mailbox archived emails as letter." def handle(self, *args, **options): ...
from __future__ import unicode_literals from django.core.management.base import BaseCommand from django_mailbox.models import Message from feder.letters.signals import MessageParser class Command(BaseCommand): help = "Reimport mailbox archived emails as letter." def handle(self, *args, **options): ...
Disable delete message on IO error
Disable delete message on IO error
Python
mit
watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder
673d96c8845a69f567ffe4475d5eb9f110b9995c
cloudenvy/commands/envy_list.py
cloudenvy/commands/envy_list.py
from cloudenvy.envy import Envy class EnvyList(object): def __init__(self, argparser): self._build_subparser(argparser) def _build_subparser(self, subparsers): help_str = 'List all ENVys in your current project.' subparser = subparsers.add_parser('list', help=help_str, ...
from cloudenvy.envy import Envy class EnvyList(object): def __init__(self, argparser): self._build_subparser(argparser) def _build_subparser(self, subparsers): help_str = 'List all ENVys in your current project.' subparser = subparsers.add_parser('list', help=help_str, ...
Remove --name from 'envy list'
Remove --name from 'envy list'
Python
apache-2.0
cloudenvy/cloudenvy
a0b4476d08c59da74eb64cbcc92621cad160fbce
scipy_distutils/setup.py
scipy_distutils/setup.py
import sys sys.path.insert(0,'..') import os d = os.path.basename(os.path.dirname(os.path.abspath(__file__))) if d == 'scipy_distutils': execfile('setup_scipy_distutils.py') else: os.system('cd .. && ln -s %s scipy_distutils' % (d)) execfile('setup_scipy_distutils.py') os.system('cd .. && rm -f scipy_di...
import sys sys.path.insert(0,'..') import os d = os.path.basename(os.path.dirname(os.path.abspath(__file__))) if d == 'scipy_distutils': import scipy_distutils del sys.path[0] execfile('setup_scipy_distutils.py') else: os.system('cd .. && ln -s %s scipy_distutils' % (d)) import scipy_distutils d...
Clean up sys.path after scipy_distutils has been imported.
Clean up sys.path after scipy_distutils has been imported.
Python
bsd-3-clause
mattip/numpy,andsor/numpy,naritta/numpy,GaZ3ll3/numpy,jschueller/numpy,felipebetancur/numpy,bertrand-l/numpy,argriffing/numpy,pbrod/numpy,dato-code/numpy,AustereCuriosity/numpy,cjermain/numpy,argriffing/numpy,astrofrog/numpy,seberg/numpy,jankoslavic/numpy,rmcgibbo/numpy,Yusa95/numpy,cjermain/numpy,nguyentu1602/numpy,gi...
8d63079647d37b3d479dab13efacd1eafeac9629
.travis/run_all_tests.py
.travis/run_all_tests.py
#!/usr/bin/python import sys, os, os.path from subprocess import call cur_dir = os.path.dirname(os.path.realpath(__file__)) parent_dir = os.path.dirname(cur_dir) statuses = [ call(["echo", "Running python unit tests via nose..."]), call(["/usr/bin/env", "nosetests", parent_dir], env=os.environ.copy()), c...
#!/usr/bin/python import sys, os, os.path from subprocess import call cur_dir = os.path.dirname(os.path.realpath(__file__)) parent_dir = os.path.dirname(cur_dir) statuses = [ call(["echo", "Running python unit tests via nose..."]), call([os.path.join(parent_dir, "manage.py"), "test", "harmony.apps.lab.tests"...
Update test harness configuration for Travis CI.
Update test harness configuration for Travis CI.
Python
bsd-3-clause
Harvard-ATG/HarmonyLab,Harvard-ATG/HarmonyLab,Harvard-ATG/HarmonyLab,Harvard-ATG/HarmonyLab
1b73399006c6dbd972814f680eb1d2e582699ad7
examples/xor-classfier.py
examples/xor-classfier.py
#!/usr/bin/env python # -*- coding: utf-8 -*- '''Example using the theanets package for learning the XOR relation.''' import climate import numpy as np import theanets climate.enable_default_logging() X = np.array([[0.0, 0.0], [0.0, 1.0], [1.0, 0.0], [1.0, 1.0]]) Y = np.array([0, 1, 1, 0, ]) Xi = np.random.randint...
#!/usr/bin/env python # -*- coding: utf-8 -*- '''Example using the theanets package for learning the XOR relation.''' import climate import numpy as np import theanets climate.enable_default_logging() X = np.array([[0.0, 0.0], [0.0, 1.0], [1.0, 0.0], [1.0, 1.0]]) Y = np.array([0, 1, 1, 0, ]) Xi = np.random.randint...
Adjust default parameters for xor classifier.
Adjust default parameters for xor classifier.
Python
mit
lmjohns3/theanets,chrinide/theanets,devdoer/theanets
72cb23aeffb2ec9ec29ad063fb4d586f00b67b57
openpassword/pkcs_utils.py
openpassword/pkcs_utils.py
from math import fmod def byte_pad(input_bytes, length=8): if length > 256: raise ValueError("Maximum padding length is 256") # Modulo input bytes length with padding length to see how many bytes to pad with bytes_to_pad = int(fmod(len(input_bytes), length)) # Pad input bytes with a sequence...
from math import fmod def byte_pad(input_bytes, length=8): if length > 256: raise ValueError("Maximum padding length is 256") # Modulo input bytes length with padding length to see how many bytes to pad with bytes_to_pad = int(fmod(len(input_bytes), length)) # Pad input bytes with a sequence...
Convert byte to string before using it with ord()
Convert byte to string before using it with ord()
Python
mit
openpassword/blimey,openpassword/blimey
f3fa16aeee901f7ee1438bbc5b12170f82a184bc
project/api/management/commands/song_titles.py
project/api/management/commands/song_titles.py
# Django from django.core.management.base import BaseCommand from django.core.mail import EmailMessage from openpyxl import Workbook # First-Party from api.models import Chart class Command(BaseCommand): help = "Command to sync database with BHS ." def handle(self, *args, **options): self.stdout.wri...
# Django from django.core.management.base import BaseCommand from django.core.mail import EmailMessage from openpyxl import Workbook # First-Party from api.models import Chart class Command(BaseCommand): help = "Command to sync database with BHS ." def handle(self, *args, **options): self.stdout.wri...
Remove me from song title report send
Remove me from song title report send
Python
bsd-2-clause
dbinetti/barberscore-django,dbinetti/barberscore,barberscore/barberscore-api,dbinetti/barberscore,barberscore/barberscore-api,barberscore/barberscore-api,dbinetti/barberscore-django,barberscore/barberscore-api
4aa8cd1f2230b5c2b180a097815802ed1bcb4905
Lib/sandbox/pyem/__init__.py
Lib/sandbox/pyem/__init__.py
#! /usr/bin/env python # Last Change: Sat Jun 09 10:00 PM 2007 J from info import __doc__ from gauss_mix import GmParamError, GM from gmm_em import GmmParamError, GMM, EM #from online_em import OnGMM as _OnGMM #import examples as _examples __all__ = filter(lambda s:not s.startswith('_'), dir()) from numpy.testing i...
#! /usr/bin/env python # Last Change: Sun Jul 22 11:00 AM 2007 J raise ImportError( """pyem has been moved to scikits and renamed to em. Please install scikits.learn instead, and change your import to the following: from scickits.learn.machine import em.""") from info import __doc__ from gauss_mix import GmParamErr...
Raise an import error when importing pyem as it has been moved to scikits.
Raise an import error when importing pyem as it has been moved to scikits.
Python
bsd-3-clause
newemailjdm/scipy,mdhaber/scipy,Newman101/scipy,Shaswat27/scipy,ilayn/scipy,haudren/scipy,nmayorov/scipy,pschella/scipy,zxsted/scipy,njwilson23/scipy,jseabold/scipy,anntzer/scipy,Srisai85/scipy,pyramania/scipy,jor-/scipy,jseabold/scipy,lukauskas/scipy,woodscn/scipy,raoulbq/scipy,grlee77/scipy,sargas/scipy,aman-iitj/sci...
732620e2fa9cb9af11136f11751f1255df9aadf6
game/itemsets/__init__.py
game/itemsets/__init__.py
# -*- coding: utf-8 -*- """ Item Sets - ItemSet.dbc """ from .. import * from ..globalstrings import * class ItemSet(Model): pass class ItemSetTooltip(Tooltip): def tooltip(self): self.append("name", ITEM_SET_NAME % (self.obj.getName(), 0, 0), color=YELLOW) items = self.obj.getItems() for item in ite...
# -*- coding: utf-8 -*- """ Item Sets - ItemSet.dbc """ from .. import * from ..globalstrings import * class ItemSet(Model): pass class ItemSetTooltip(Tooltip): def tooltip(self): items = self.obj.getItems() maxItems = len(items) self.append("name", ITEM_SET_NAME % (self.obj.getName(), 0, maxItems), ...
Add maxItems to ItemSet and remove debug output
game/itemsets: Add maxItems to ItemSet and remove debug output
Python
cc0-1.0
jleclanche/pywow,jleclanche/pywow,jleclanche/pywow,jleclanche/pywow,jleclanche/pywow,jleclanche/pywow
2dc90659a7265740bb5821f0f153f00de1b2205a
pydle/features/__init__.py
pydle/features/__init__.py
from . import rfc1459, account, ctcp, tls, isupport, whox, ircv3 from .rfc1459 import RFC1459Support from .account import AccountSupport from .ctcp import CTCPSupport from .tls import TLSSupport from .isupport import ISUPPORTSupport from .whox import WHOXSupport from .ircv3 import IRCv3Support, IRCv3_1Support, IRCv3_2...
from . import rfc1459, account, ctcp, tls, isupport, whox, ircv3 from .rfc1459 import RFC1459Support from .account import AccountSupport from .ctcp import CTCPSupport from .tls import TLSSupport from .isupport import ISUPPORTSupport from .whox import WHOXSupport from .ircv3 import IRCv3Support, IRCv3_1Support, IRCv3_2...
Enable RplWhoisHostSupport implementation (as part of full featured client)
Enable RplWhoisHostSupport implementation (as part of full featured client)
Python
bsd-3-clause
Shizmob/pydle
9a18cd0cb6366d45803c19301843ddda3a362cfb
tests/test_publisher.py
tests/test_publisher.py
from lektor.publisher import Command def test_Command_triggers_no_warnings(recwarn): # This excercises the issue where publishing via rsync resulted # in ResourceWarnings about unclosed streams. # This is essentially how RsyncPublisher runs rsync. with Command(["echo"]) as client: for _ in cl...
import gc import warnings import weakref import pytest from lektor.publisher import Command def test_Command_triggers_no_warnings(): # This excercises the issue where publishing via rsync resulted # in ResourceWarnings about unclosed streams. with pytest.warns(None) as record: # This is essenti...
Reword comment, add check that Command is actually garbage collected
Reword comment, add check that Command is actually garbage collected
Python
bsd-3-clause
lektor/lektor,lektor/lektor,lektor/lektor,lektor/lektor