commit
stringlengths
40
40
subject
stringlengths
1
1.49k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
new_contents
stringlengths
1
29.8k
old_contents
stringlengths
0
9.9k
lang
stringclasses
3 values
proba
float64
0
1
82bc502cf7bb64236feba6e140d98bb9e555f4ca
Fix assert_raises for catching parents of exceptions.
tests/backport_assert_raises.py
tests/backport_assert_raises.py
from __future__ import unicode_literals """ Patch courtesy of: https://marmida.com/blog/index.php/2012/08/08/monkey-patching-assert_raises/ """ # code for monkey-patching import nose.tools # let's fix nose.tools.assert_raises (which is really unittest.assertRaises) # so that it always supports context management # i...
from __future__ import unicode_literals """ Patch courtesy of: https://marmida.com/blog/index.php/2012/08/08/monkey-patching-assert_raises/ """ # code for monkey-patching import nose.tools # let's fix nose.tools.assert_raises (which is really unittest.assertRaises) # so that it always supports context management # i...
Python
0
bea4752dea1e7f01257b38faef9e21ba0e946983
Implement psutil within blackbox tests
tests/blackbox/testlib/utils.py
tests/blackbox/testlib/utils.py
# Copyright 2019 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
# Copyright 2019 Red Hat, Inc. # # 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...
Python
0.000002
fc94bda4cb840b74fbd1226d69bf0aafc5e16e61
return when not installed (#283)
pwndbg/commands/rop.py
pwndbg/commands/rop.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import re import subprocess import tempfile import gdb import pwndbg.commands import pwndbg.vmmap parser ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import re import subprocess import tempfile import gdb import pwndbg.commands import pwndbg.vmmap parser ...
Python
0
0a5b7c606a711307bdc41179cf94c0a72c15ee92
Make BaseCommandTest automatically instantiate commands using decoration magic.
hypebot/commands/hypetest.py
hypebot/commands/hypetest.py
# Copyright 2019 The Hypebot Authors. 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 required by applicabl...
# Copyright 2019 The Hypebot Authors. 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 required by applicabl...
Python
0
6cef7f841fc34321d68e8c85ff7f78682c59eae2
Add help and version text; check for IO errors
py-chrome-bookmarks.py
py-chrome-bookmarks.py
#!/usr/bin/python # py-chrome-bookmarks # # A script to convert Google Chrome's bookmarks file to the standard HTML-ish # format. # # (c) Benjamin Esham, 2011. See the accompanying README for this file's # license and other information. import json, sys, os, re # html escaping code from http://wiki.python.org/moin...
#!/usr/bin/python # py-chrome-bookmarks # # A script to convert Google Chrome's bookmarks file to the standard HTML-ish # format. # # (c) Benjamin Esham, 2011. See the accompanying README for this file's # license and other information. import json, sys, os, re # html escaping code from http://wiki.python.org/moin...
Python
0
98467f55ef8526d343065da7d6a896b16539fa53
use consistent hash for etag
http_agent/utils/etag.py
http_agent/utils/etag.py
from zlib import adler32 def make_entity_tag(body): checksum = adler32(body.encode()) return '"{checksum}"'.format(checksum=checksum)
def make_entity_tag(body): checksum = hash(body) + (1 << 64) return '"{checksum}"'.format(checksum=checksum)
Python
0.000001
82f6a4cf6e1e5ceef2c48811eceb93e8a7ce13e3
Add handler for demo.
filestore/file_readers.py
filestore/file_readers.py
from __future__ import (absolute_import, division, print_function, unicode_literals) from .retrieve import HandlerBase import six import logging import h5py import numpy as np import os.path logger = logging.getLogger(__name__) class _HDF5HandlerBase(HandlerBase): def open(self): ...
from __future__ import (absolute_import, division, print_function, unicode_literals) from .retrieve import HandlerBase import six import logging import h5py import numpy as np import os.path logger = logging.getLogger(__name__) class _HdfMapsHandlerBase(HandlerBase): """ Reader for X...
Python
0
996e33d1662517ba8a1671d8549fa3d189f3b1d0
reorganize script and allow user provided date ranges
get-challenges.py
get-challenges.py
#!/usr/bin/env python3 from datetime import datetime, timezone from dateutil import parser import click import os.path import os import shutil import praw import sys import re _SITE_NAME = 'dailyprogrammer-bot' _SUBREDDIT = 'dailyprogrammer' _DATE_FORMAT = '%Y-%m-%d' _RATING_PATTERN = r'(?<=\[)(?!psa)[a-z]*(?=\])' _S...
#!/usr/bin/env python3 from datetime import datetime, timezone import click import os.path import os import shutil import praw import pytz import re _SITE_NAME = 'dailyprogrammer-bot' _SUBREDDIT = 'dailyprogrammer' _FIRST_SUBMISSION_DATE = datetime(2012, 2, 9, tzinfo=pytz.timezone('America/Los_Angeles')) _DATE_FORMAT...
Python
0
ec668c693051f70026360ac2f3bc67ced6c01a21
fix little bug
src/fb_messenger/test/test_attachements.py
src/fb_messenger/test/test_attachements.py
import unittest class FirstTest(unittest.TestCase): def test_first(self): self.assertEqual(True, True, 'incorrect types')
import unittest class FirstTest(unittest.TestCase): def test_first(self): self.assertEqual(True, False, 'incorrect types')
Python
0.000001
4979e8e5ee8ac6cb86ab260f44f052b27381eeb6
bump version
giddy/__init__.py
giddy/__init__.py
__version__ = "2.0.0" # __version__ has to be defined in the first line """ :mod:`giddy` --- Spatial Dynamics and Mobility ============================================== """ from . import directional from . import ergodic from . import markov from . import mobility from . import rank from . import util
__version__ = "1.2.0" # __version__ has to be defined in the first line """ :mod:`giddy` --- Spatial Dynamics and Mobility ============================================== """ from . import directional from . import ergodic from . import markov from . import mobility from . import rank from . import util
Python
0
522906d2842d90722776f898015fde060c967401
Update cam.py
pyCam/build_0.3/cam.py
pyCam/build_0.3/cam.py
import cv2 import numpy as np from twilio.rest import TwilioRestClient import time #importing modules ^^ body_cascade = cv2.CascadeClassifier('haarcascade_fullbody.xml') #importing cascade-classfier ^^ vc = cv2.VideoCapture(0) #finding default camera ^^ while -1: ret, img = vc.read() gray = cv2.cvtColor...
import cv2 import numpy as np from twilio.rest import TwilioRestClient import time #importing modules ^^ body_cascade = cv2.CascadeClassifier('haarcascade_fullbody.xml') #importing cascade-classfiers ^^ vc = cv2.VideoCapture(0) #finding default camera ^^ while -1: ret, img = vc.read() gray = cv2.cvtColo...
Python
0.000001
64c08dfc40240c7b1b4b876b12bdb57ace22d675
remove print statement
gippy/__init__.py
gippy/__init__.py
#!/usr/bin/env python ################################################################################ # GIPPY: Geospatial Image Processing library for Python # # AUTHOR: Matthew Hanson # EMAIL: matt.a.hanson@gmail.com # # Copyright (C) 2015 Applied Geosolutions # # Licensed under the Apache License, Ve...
#!/usr/bin/env python ################################################################################ # GIPPY: Geospatial Image Processing library for Python # # AUTHOR: Matthew Hanson # EMAIL: matt.a.hanson@gmail.com # # Copyright (C) 2015 Applied Geosolutions # # Licensed under the Apache License, Ve...
Python
0.999999
30f89eacb428af7091d238d39766d6481735c670
fix for BASH_FUNC_module on qstat output
igf_airflow/hpc/hpc_queue.py
igf_airflow/hpc/hpc_queue.py
import json import subprocess from collections import defaultdict from tempfile import TemporaryFile def get_pbspro_job_count(job_name_prefix=''): ''' A function for fetching running and queued job information from a PBSPro HPC cluster :param job_name_prefix: A text to filter running jobs, default '' :returns...
import json import subprocess from collections import defaultdict from tempfile import TemporaryFile def get_pbspro_job_count(job_name_prefix=''): ''' A function for fetching running and queued job information from a PBSPro HPC cluster :param job_name_prefix: A text to filter running jobs, default '' :returns...
Python
0.000001
8998d0f617791f95b1ed6b4a1fffa0f71752b801
Update docs/params for initialization methods.
pybo/bayesopt/inits.py
pybo/bayesopt/inits.py
""" Implementation of methods for sampling initial points. """ # future imports from __future__ import division from __future__ import absolute_import from __future__ import print_function # global imports import numpy as np # local imports from ..utils import ldsample # exported symbols __all__ = ['init_middle', '...
""" Implementation of methods for sampling initial points. """ # future imports from __future__ import division from __future__ import absolute_import from __future__ import print_function # global imports import numpy as np # local imports from ..utils import ldsample # exported symbols __all__ = ['init_middle', '...
Python
0
cfc13f7e98062a2eb5a9a96298ebc67ee79d9602
Use path for urls
src/clarityv2/deductions/admin.py
src/clarityv2/deductions/admin.py
from django.urls import path from django.contrib import admin from django.db.models import Sum from clarityv2.utils.views.private_media import PrivateMediaView from .models import Deduction class DeductionPrivateMediaView(PrivateMediaView): model = Deduction permission_required = 'invoices.can_view_invoice'...
from django.conf.urls import url from django.contrib import admin from django.db.models import Sum from clarityv2.utils.views.private_media import PrivateMediaView from .models import Deduction class DeductionPrivateMediaView(PrivateMediaView): model = Deduction permission_required = 'invoices.can_view_invo...
Python
0.000002
a8d7afe076c14115f3282114cecad216e46e7353
Update scipy_effects.py
pydub/scipy_effects.py
pydub/scipy_effects.py
""" This module provides scipy versions of high_pass_filter, and low_pass_filter as well as an additional band_pass_filter. Of course, you will need to install scipy for these to work. When this module is imported the high and low pass filters from this module will be used when calling audio_segment.high_pass_filter(...
""" This module provides scipy versions of high_pass_filter, and low_pass_filter as well as an additional band_pass_filter. Of course, you will need to install scipy for these to work. When this module is imported the high and low pass filters are used when calling audio_segment.high_pass_filter() and audio_segment.h...
Python
0.000002
7508d20bd3d6af0b2e5a886c8ea2f895d9e69935
Bump version: 0.2.1 → 0.2.2
pyfilemail/__init__.py
pyfilemail/__init__.py
# -*- coding: utf-8 -*- __title__ = 'pyfilemail' __version__ = '0.2.2' __author__ = 'Daniel Flehner Heen' __license__ = 'MIT' __copyright__ = 'Copyright 2016 Daniel Flehner Heen' import os import logging from functools import wraps import appdirs # Init logger logger = logging.getLogger('pyfilemail') level = os.g...
# -*- coding: utf-8 -*- __title__ = 'pyfilemail' __version__ = '0.2.1' __author__ = 'Daniel Flehner Heen' __license__ = 'MIT' __copyright__ = 'Copyright 2016 Daniel Flehner Heen' import os import logging from functools import wraps import appdirs # Init logger logger = logging.getLogger('pyfilemail') level = os.g...
Python
0.000001
f7066d6bdd4fefbf517cd8ab44951955bb9f3a2a
Fix min/max for None types
gpaw/setup/gcc.py
gpaw/setup/gcc.py
#!/usr/bin/env python3 """Wrapper for the GNU compiler that converts / removes incompatible compiler options and allows for file-specific tailoring.""" import sys from subprocess import call # Default compiler and options compiler = 'gcc' args2change = {} fragile_files = ['c/xc/tpss.c'] # Default optimisation sett...
#!/usr/bin/env python3 """Wrapper for the GNU compiler that converts / removes incompatible compiler options and allows for file-specific tailoring.""" import sys from subprocess import call # Default compiler and options compiler = 'gcc' args2change = {} fragile_files = ['c/xc/tpss.c'] # Default optimisation sett...
Python
0.000072
0b6b7ab518362445f3901f8d3b0d6281e2671c3f
Make code python3 compatible
drivers/python/setup.py
drivers/python/setup.py
# Copyright 2010-2012 RethinkDB, all rights reserved. from setuptools import setup, Extension from distutils.command.build_ext import build_ext from distutils.errors import DistutilsPlatformError, CCompilerError, DistutilsExecError import sys class build_ext_nofail(build_ext): # This class can replace the build_e...
# Copyright 2010-2012 RethinkDB, all rights reserved. from setuptools import setup, Extension from distutils.command.build_ext import build_ext from distutils.errors import DistutilsPlatformError, CCompilerError, DistutilsExecError import sys class build_ext_nofail(build_ext): # This class can replace the build_e...
Python
0.000222
7418379d959cba0e96161c9e61f340541b82d85f
clean up xor a bit
python/examples/xor.py
python/examples/xor.py
# Copyright Hugh Perkins 2016 # # This Source Code Form is subject to the terms of the Mozilla Public License, # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at http://mozilla.org/MPL/2.0/. """ Simple example of xor """ from __future__ import print_function import PyDeepCL imp...
# Copyright Hugh Perkins 2015 # # This Source Code Form is subject to the terms of the Mozilla Public License, # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at http://mozilla.org/MPL/2.0/. from __future__ import print_function # import sys # import array import PyDeepCL imp...
Python
0
9729c3aecccfa8130db7b5942c423c0807726f81
Add feature importance bar chart.
python/gbdt/_forest.py
python/gbdt/_forest.py
from libgbdt import Forest as _Forest class Forest: def __init__(self, forest): if type(forest) is str or type(forest) is unicode: self._forest = _Forest(forest) elif type(forest) is _Forest: self._forest = forest else: raise TypeError, 'Unsupported fores...
from libgbdt import Forest as _Forest class Forest: def __init__(self, forest): if type(forest) is str or type(forest) is unicode: self._forest = _Forest(forest) elif type(forest) is _Forest: self._forest = forest else: raise TypeError, 'Unsupported fores...
Python
0
851fe0dad512dbf9888638566135d1f8cd0dd853
fix #4036
gui/qt/qrtextedit.py
gui/qt/qrtextedit.py
from electrum.i18n import _ from electrum.plugins import run_hook from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import QFileDialog from .util import ButtonsTextEdit, MessageBoxMixin, ColorScheme class ShowQRTextEdit(ButtonsTextEdit): def __init__(self, text=None): ButtonsTex...
from electrum.i18n import _ from electrum.plugins import run_hook from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import QFileDialog from .util import ButtonsTextEdit, MessageBoxMixin, ColorScheme class ShowQRTextEdit(ButtonsTextEdit): def __init__(self, text=None): ButtonsTex...
Python
0.000001
50d44ec25eb102451a495dd645ffb2a6f77012ae
Add a shortcut for imports
queue_util/__init__.py
queue_util/__init__.py
from queue_util.consumer import Consumer from queue_util.producer import Producer
Python
0.000002
325c5a8f407340fa8901f406c301fa8cbdac4ff8
bump version to 0.13.0
gunicorn/__init__.py
gunicorn/__init__.py
# -*- coding: utf-8 - # # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. version_info = (0, 13, 0) __version__ = ".".join(map(str, version_info)) SERVER_SOFTWARE = "gunicorn/%s" % __version__
# -*- coding: utf-8 - # # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. version_info = (0, 12, 2) __version__ = ".".join(map(str, version_info)) SERVER_SOFTWARE = "gunicorn/%s" % __version__
Python
0
dda25cdb808259ec2a91cba74273dc6c929af0aa
Check README.md and CHANGELOG.md.
dscan/plugins/drupal.py
dscan/plugins/drupal.py
from cement.core import handler, controller from dscan.plugins import BasePlugin from dscan.common.update_api import GitRepo import dscan.common.update_api as ua import dscan.common.versions class Drupal(BasePlugin): plugins_base_url = [ "%ssites/all/modules/%s/", "%ssites/default/modules/...
from cement.core import handler, controller from dscan.plugins import BasePlugin from dscan.common.update_api import GitRepo import dscan.common.update_api as ua import dscan.common.versions class Drupal(BasePlugin): plugins_base_url = [ "%ssites/all/modules/%s/", "%ssites/default/modules/...
Python
0
fbb3df846b3b9f4a86d6238cc5605a8d771ff924
add python 3 compatibility
dumper/logging_utils.py
dumper/logging_utils.py
from __future__ import unicode_literals import logging import six class BaseLogger(object): @classmethod def get_logger(cls): logger = logging.getLogger(cls.module) logger.setLevel('DEBUG') return logger @classmethod def _log(cls, message): cls.get_logger().debug(mes...
from __future__ import unicode_literals import logging class BaseLogger(object): @classmethod def get_logger(cls): logger = logging.getLogger(cls.module) logger.setLevel('DEBUG') return logger @classmethod def _log(cls, message): cls.get_logger().debug(message) ...
Python
0.000001
0f4d2b75cde58f6926636563691182fb5896c894
Add docstring to autocorr and ambiguity functions so the axes and peak location of the result is made clear.
echolect/core/coding.py
echolect/core/coding.py
# Copyright 2013 Ryan Volz # This file is part of echolect. # Echolect is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # Echolect is...
# Copyright 2013 Ryan Volz # This file is part of echolect. # Echolect is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # Echolect is...
Python
0
cc6bc2b9af67c064339371b43795c36ed3e5ddcb
use TemplateResponse everywhere
ella_galleries/views.py
ella_galleries/views.py
from django.http import Http404 from django.template.response import TemplateResponse from django.utils.translation import ungettext from django.utils.cache import patch_vary_headers from ella.core.views import get_templates_from_publishable def gallery_item_detail(request, context, item_slug=None): ''' Retur...
from django.http import Http404 from django.shortcuts import render_to_response from django.template import RequestContext from django.utils.translation import ungettext from django.utils.cache import patch_vary_headers from ella.core.views import get_templates_from_publishable def gallery_item_detail(request, contex...
Python
0
63587ab033a0aabd52af6b657600d2d2547f034f
Bump release version
grove/__init__.py
grove/__init__.py
############################################################################## # Copyright 2016-2017 Rigetti Computing # # 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...
############################################################################## # Copyright 2016-2017 Rigetti Computing # # 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...
Python
0
e0de9a865b731f3f24bc7a42909849abc738217f
Increment version
karld/_meta.py
karld/_meta.py
version_info = (0, 2, 1) version = '.'.join(map(str, version_info))
version_info = (0, 2, 0) version = '.'.join(map(str, version_info))
Python
0.000002
c39ce3485af781e8974a70200baa1f51e5c1633b
fix imports
gstat/__init__.py
gstat/__init__.py
from gstat import gstat, gstats, gstat_elapsed, gstat_event
Python
0.000002
cbbe9d50108747b15864436de01947bc2598b1b3
Fix bug
WindAdapter/data_provider.py
WindAdapter/data_provider.py
# -*- coding: utf-8 -*- import pandas as pd try: from WindPy import w except ImportError: pass class WindRunner: def __init__(self): try: w.start() except NameError: pass def __del__(self): try: w.stop() except AttributeError: ...
# -*- coding: utf-8 -*- import pandas as pd try: from WindPy import w except ImportError: pass class WindRunner: def __init__(self): try: w.start() except NameError: pass def __del__(self): try: w.stop() except AttributeError: ...
Python
0.000001
2a0e3fe9c83da1d11b892c7c35e367f414329936
Update teaching_modules.py
src/ensae_teaching_cs/automation/teaching_modules.py
src/ensae_teaching_cs/automation/teaching_modules.py
# -*- coding: utf-8 -*- """ @file @brief List of modules to maintain for the teachings. """ def get_teaching_modules(): """ List of teachings modules to maintain (CI + documentation). .. runpython:: :showcode: from ensae_teaching_cs.automation import get_teaching_modules print('\...
# -*- coding: utf-8 -*- """ @file @brief List of modules to maintain for the teachings. """ def get_teaching_modules(): """ List of teachings modules to maintain (CI + documentation). .. runpython:: :showcode: from ensae_teaching_cs.automation import get_teaching_modules print('\...
Python
0.000001
bc08499fd803278ea502bafdf845dec438f951f3
Update range-sum-query-2d-immutable.py
Python/range-sum-query-2d-immutable.py
Python/range-sum-query-2d-immutable.py
# Time: ctor: O(m * n) # lookup: O(1) # Space: O(m * n) # # Given a 2D matrix matrix, find the sum of the elements inside # the rectangle defined by its upper left corner (row1, col1) # and lower right corner (row2, col2). # # Range Sum Query 2D # The above rectangle (with the red border) is defined by # (row...
# Time: ctor: O(m * n) # lookup: O(1) # Space: O(m * n) # # Given a 2D matrix matrix, find the sum of the elements inside # the rectangle defined by its upper left corner (row1, col1) # and lower right corner (row2, col2). # # Range Sum Query 2D # The above rectangle (with the red border) is defined by # (row...
Python
0.000005
27f8b342e1a4bea9c807b005d16f932880bb7136
Document utils.setup_readline
jedi/utils.py
jedi/utils.py
""" Utilities for end-users. """ import sys from jedi import Interpreter def readline_complete(text, state): """ Function to be passed to :func:`readline.set_completer`. Usage:: import readline readline.set_completer(readline_complete) """ ns = vars(sys.modules['__main__']) ...
""" Utilities for end-users. """ import sys from jedi import Interpreter def readline_complete(text, state): """ Function to be passed to :func:`readline.set_completer`. Usage:: import readline readline.set_completer(readline_complete) """ ns = vars(sys.modules['__main__']) ...
Python
0.000001
c9dceb4dc83490ab0eebcd3efc9590d3275f53df
tidy up messytables-jts integration
ktbh/schema.py
ktbh/schema.py
import unicodecsv from cStringIO import StringIO import messytables import itertools import slugify import jsontableschema from messytables.types import * from messytables_jts import celltype_as_string def censor(dialect): tmp = dict(dialect) censored = [ "doublequote", "lineterminator", ...
import unicodecsv from cStringIO import StringIO import messytables import itertools import slugify import jsontableschema from messytables.types import * from messytables_jts import rowset_as_schema def censor(dialect): tmp = dict(dialect) censored = [ "doublequote", "lineterminator", ...
Python
0
39de531241f987daf2f417fd419c7bd63248dd9d
Bump version number.
kyokai/util.py
kyokai/util.py
""" Misc utilities. """ import os import pathlib VERSION = "1.5.0" VERSIONT = tuple(map(int, VERSION.split('.'))) HTTP_CODES = { 200: "OK", 201: "Created", 202: "Accepted", 203: "Non-Authoritative Information", 204: "No Content", 205: "Reset Content", 301: "Moved Permanently", 302: "Fo...
""" Misc utilities. """ import os import pathlib VERSION = "1.3.8" VERSIONT = tuple(map(int, VERSION.split('.'))) HTTP_CODES = { 200: "OK", 201: "Created", 202: "Accepted", 203: "Non-Authoritative Information", 204: "No Content", 205: "Reset Content", 301: "Moved Permanently", 302: "Fo...
Python
0
34ca71d5db9c1f17d236e5e49471fb6f2a6e1747
Implement Paulo tip about router.
aldryn_search/router.py
aldryn_search/router.py
# -*- coding: utf-8 -*- from django.conf import settings from django.utils.translation import get_language from cms.utils.i18n import alias_from_language from haystack import routers from haystack.constants import DEFAULT_ALIAS class LanguageRouter(routers.BaseRouter): def for_read(self, **hints): langu...
# -*- coding: utf-8 -*- from django.conf import settings from cms.utils.i18n import get_current_language from haystack import routers from haystack.constants import DEFAULT_ALIAS class LanguageRouter(routers.BaseRouter): def for_read(self, **hints): language = get_current_language() if language ...
Python
0
9fa2214b03d3264240b46fe5368b37ffa696f50c
Allow test selection according to tags
baf/src/baf.py
baf/src/baf.py
"""The main module of the Bayesian API Fuzzer.""" import sys from time import time from fastlog import log from csv_reader import read_csv_as_dicts from setup import setup, parse_tags from cliargs import cli_parser from fuzzer import run_test from results import Results from report_generator import generate_reports ...
"""The main module of the Bayesian API Fuzzer.""" import sys from time import time from fastlog import log from csv_reader import read_csv_as_dicts from setup import setup from cliargs import cli_parser from fuzzer import run_test from results import Results from report_generator import generate_reports VERSION_MAJ...
Python
0
e5e523890dd1129402d7a0477468ee47dee3fd91
Fix missing part/block conversion.
inbox/sendmail/smtp/common.py
inbox/sendmail/smtp/common.py
from inbox.sendmail.base import generate_attachments, SendError from inbox.sendmail.smtp.postel import BaseSMTPClient from inbox.sendmail.smtp.message import create_email, create_reply class SMTPClient(BaseSMTPClient): """ SMTPClient for Gmail and other providers. """ def _send_mail(self, db_session, message,...
from inbox.sendmail.base import generate_attachments, SendError from inbox.sendmail.smtp.postel import BaseSMTPClient from inbox.sendmail.smtp.message import create_email, create_reply class SMTPClient(BaseSMTPClient): """ SMTPClient for Gmail and other providers. """ def _send_mail(self, db_session, message,...
Python
0
2808b0dfba0597e09d80eafedfead246779111d9
Clean up verbose looking code
MOAL/data_structures/trees/binary_trees.py
MOAL/data_structures/trees/binary_trees.py
# -*- coding: utf-8 -*- __author__ = """Chris Tabor (dxdstudio@gmail.com)""" if __name__ == '__main__': from os import getcwd from os import sys sys.path.append(getcwd()) from MOAL.helpers.display import Section from MOAL.helpers.display import print_h4 from MOAL.helpers.display import cmd_title from MOA...
# -*- coding: utf-8 -*- __author__ = """Chris Tabor (dxdstudio@gmail.com)""" if __name__ == '__main__': from os import getcwd from os import sys sys.path.append(getcwd()) from MOAL.helpers.display import Section from MOAL.helpers.display import print_h4 from MOAL.helpers.display import cmd_title from MOA...
Python
0.998916
872a96b52061bd9ab3a3178aacf3e3d0be2cc498
Make field filter errors ValidationErrors
nap/dataviews/fields.py
nap/dataviews/fields.py
from django.db.models.fields import NOT_PROVIDED from django.forms import ValidationError from nap.utils import digattr class field(property): '''A base class to compare against.''' def __get__(self, instance, cls=None): if instance is None: return self return self.fget(instance....
from django.db.models.fields import NOT_PROVIDED from nap.utils import digattr class field(property): '''A base class to compare against.''' def __get__(self, instance, cls=None): if instance is None: return self return self.fget(instance._obj) def __set__(self, instance, va...
Python
0.000008
f41bb86dd5263d63172b303a5a3993fc28e612dc
fix spelling of "received"
django-hq/apps/receiver/submitprocessor.py
django-hq/apps/receiver/submitprocessor.py
from models import * import logging import hashlib import settings import traceback import sys import os import string import uuid from django.db import transaction def get_submission_path(): return settings.rapidsms_apps_conf['receiver']['xform_submission_path'] @transaction.com...
from models import * import logging import hashlib import settings import traceback import sys import os import string import uuid from django.db import transaction def get_submission_path(): return settings.rapidsms_apps_conf['receiver']['xform_submission_path'] @transaction.com...
Python
0.999883
bbe263e8bd9bb12ccef681d4f21f6b90c89f059d
Remove some debug logging
flask/test/test_signup.py
flask/test/test_signup.py
from __future__ import unicode_literals from test import TestCase from web import app from db import session, User from nose.tools import eq_ class TestSignup(TestCase): def test_sign_up(self): app.test_client().post('/', data={'email': 'andrew@lorente.name'}) users = session().query(User.email)...
from __future__ import unicode_literals from test import TestCase from web import app from db import session, User from nose.tools import eq_ class TestSignup(TestCase): def test_sign_up(self): app.test_client().post('/', data={'email': 'andrew@lorente.name'}) users = session().query(User.email)...
Python
0.000003
6d9e8e8831cd08fa358f33f155a760de3ec59f3b
document that this file is generated
Lib/fontTools/ttLib/tables/__init__.py
Lib/fontTools/ttLib/tables/__init__.py
# DON'T EDIT! This file is generated by MetaTools/buildTableList.py. def _moduleFinderHint(): """Dummy function to let modulefinder know what tables may be dynamically imported. Generated by MetaTools/buildTableList.py. """ import B_A_S_E_ import C_F_F_ import D_S_I_G_ import G_D_E_F_ import G_P_O_S_ import G_...
def _moduleFinderHint(): """Dummy function to let modulefinder know what tables may be dynamically imported. Generated by MetaTools/buildTableList.py. """ import B_A_S_E_ import C_F_F_ import D_S_I_G_ import G_D_E_F_ import G_P_O_S_ import G_S_U_B_ import J_S_T_F_ import L_T_S_H_ import O_S_2f_2 import T_S...
Python
0.000003
1f977aa5fa28ed1e351f337191291198384abe02
Set auth_encryption_key option to be secret
heat/common/crypt.py
heat/common/crypt.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 # ...
# # 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 # ...
Python
0.000001
57100d99b58263a76f9bf405f7bdc62e8839552e
Fix bug with JSON serialization
model.py
model.py
import datetime import random from google.appengine.api import memcache from google.appengine.ext import db def from_milliseconds(millis): return datetime.datetime.utcfromtimestamp(millis / 1000) def to_milliseconds(date_time): delta = date_time - from_milliseconds(0) return int(round(delta.total_secon...
import datetime import random from google.appengine.api import memcache from google.appengine.ext import db def from_milliseconds(millis): return datetime.datetime.utcfromtimestamp(millis / 1000) def to_milliseconds(date_time): delta = date_time - from_milliseconds(0) return int(round(delta.total_secon...
Python
0.000002
197a0440ddbf31aa87a6a6998b41344be4924076
fix on the rows update
gui/placeslist.py
gui/placeslist.py
# -*- coding: utf8 -*- from PyQt4 import QtGui from PyQt4 import QtCore class placesList(QtGui.QTableWidget): _columns = ('Name', 'Type', 'X', 'Y', 'Locate') _app = None _parent = None def __init__(self, parent, app): """ Initialisation of the window, creates the GUI and displays the window. """ self._...
# -*- coding: utf8 -*- from PyQt4 import QtGui from PyQt4 import QtCore class placesList(QtGui.QTableWidget): _columns = ('Name', 'Type', 'X', 'Y', 'Locate') _app = None _parent = None def __init__(self, parent, app): """ Initialisation of the window, creates the GUI and displays the window. """ self._...
Python
0
29e18edf18c14cd11c8cebd93548eeadbb61b1da
Fix biases by using correct shape
model.py
model.py
import tensorflow as tf def make_weight_variable(name, num_inputs, num_outputs): return tf.get_variable( name, [num_inputs, num_outputs], initializer=tf.contrib.layers.variance_scaling_initializer() ) class Model: def __init__(self, chars, max_steps, lstm_units=250, l1_units=200,...
import tensorflow as tf def make_weight_variable(name, num_inputs, num_outputs): return tf.get_variable( name, [num_inputs, num_outputs], initializer=tf.contrib.layers.variance_scaling_initializer() ) class Model: def __init__(self, chars, max_steps, lstm_units=250, l1_units=200,...
Python
0.0001
5809fc832340e3ee5d798fa347e4933e874bdb8b
Allow older django to find the tests
voting/tests/__init__.py
voting/tests/__init__.py
import django if django.VERSION[0] == 1 and django.VERSION[1] < 6: from .tests import *
Python
0.000003
b33b6c7a5ae8835514389340ff3152f03f619984
prefix number underscore sep
holodeck/settings.py
holodeck/settings.py
LOGICAL_SHARDS = 8 PHYSICAL_SHARDS = [ { 'ENGINE': 'django.db.backends.sqlite3', 'NAME_PREFIX': 'holodeck_1', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', }, { 'ENGINE': 'django.db.backends.sqlite3', 'NAME_PREFIX': 'holodeck_2', ...
LOGICAL_SHARDS = 8 PHYSICAL_SHARDS = [ { 'ENGINE': 'django.db.backends.sqlite3', 'NAME_PREFIX': 'holodeck1', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', }, { 'ENGINE': 'django.db.backends.sqlite3', 'NAME_PREFIX': 'holodeck2', '...
Python
0.998789
9246d33429e1940d5a98c3c16e708159437b88fa
enable header modification
lib/neuroimaging/tools/AnalyzeHeaderTool.py
lib/neuroimaging/tools/AnalyzeHeaderTool.py
import os, sys from optparse import OptionParser, Option from neuroimaging.data import DataSource from neuroimaging.refactoring.analyze import struct_fields, AnalyzeHeader ############################################################################## class AnalyzeHeaderTool (OptionParser): "Command-line tool for...
import os, sys from optparse import OptionParser, Option from neuroimaging.data import DataSource from neuroimaging.refactoring.analyze import struct_fields, AnalyzeHeader ############################################################################## class AnalyzeHeaderTool (OptionParser): "Command-line tool for...
Python
0
1117f6e2d51ed6faf37aa2a6deab8a6ff8fa0e5b
test for compiling simple command
linemode/tests/test_command_list_printer.py
linemode/tests/test_command_list_printer.py
import unittest from linemode.drivers.command_list import compile class TestCommandListPrinter(unittest.TestCase): def test_simple_command(self): program = compile([ "reset" ]) self.assertEqual(program, b'reset')
import unittest from linemode.drivers.command_list import CommandListPrinter class TestCommandListPrinter(unittest.TestCase): pass
Python
0.000001
5662a6cb9cd567b5e08398e4e5394f8049f02741
Update tests to allow for id in content type json
feincms_extensions/tests/test_content_types.py
feincms_extensions/tests/test_content_types.py
import datetime from django.test import TestCase from . import factories from .models import Dummy from .. import content_types class TestJsonRichTextContent(TestCase): model = Dummy.content_type_for(content_types.JsonRichTextContent) def test_json(self): """A JsonRichTextContent can be rendered to...
import datetime from django.test import TestCase from . import factories from .models import Dummy from .. import content_types class TestJsonRichTextContent(TestCase): model = Dummy.content_type_for(content_types.JsonRichTextContent) def test_json(self): """A JsonRichTextContent can be rendered to...
Python
0
3f0b19d153360ee5cf1fda1acfa0e4ad846b6c86
fix admin.py, remove site on AccountAccess and add it on Provider
allaccess/admin.py
allaccess/admin.py
from django.contrib import admin from .models import Provider, AccountAccess class ProviderAdmin(admin.ModelAdmin): "Admin customization for OAuth providers." list_display = ('name', 'enabled', 'site',) list_filter = ('name', 'enabled', 'site', ) class AccountAccessAdmin(admin.ModelAdmin): "Admi...
from django.contrib import admin from .models import Provider, AccountAccess class ProviderAdmin(admin.ModelAdmin): "Admin customization for OAuth providers." list_display = ('name', 'enabled', ) class AccountAccessAdmin(admin.ModelAdmin): "Admin customization for accounts." list_display = ( ...
Python
0
ee6d4f50b4a27e9cc8c3b5f8a821a6d9c0cf4f21
remove unwanted changes
frappe/website/page_renderers/document_page.py
frappe/website/page_renderers/document_page.py
import frappe from frappe.model.document import get_controller from frappe.website.page_renderers.base_template_page import BaseTemplatePage from frappe.website.utils import cache_html from frappe.website.router import (get_doctypes_with_web_view, get_page_info_from_web_page_with_dynamic_routes) class DocumentPage(B...
import frappe from frappe.model.document import get_controller from frappe.website.page_renderers.base_template_page import BaseTemplatePage from frappe.website.utils import build_response from frappe.website.router import (get_doctypes_with_web_view, get_page_info_from_web_page_with_dynamic_routes) class DocumentPa...
Python
0.005417
a5f1ad3e47daf3f8db04b605fb13ff3f9f871e3a
Divide entire loss by n, not just mll component.
gpytorch/mlls/exact_marginal_log_likelihood.py
gpytorch/mlls/exact_marginal_log_likelihood.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import math import torch from .marginal_log_likelihood import MarginalLogLikelihood from ..lazy import LazyVariable, NonLazyVariable from ..likelihoods import GaussianLik...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import math import torch from .marginal_log_likelihood import MarginalLogLikelihood from ..lazy import LazyVariable, NonLazyVariable from ..likelihoods import GaussianLik...
Python
0.000004
16110c627100f5fd6bdaaf859ed71559ea17780a
Fix push/pull tests
jupyterlab_git/tests/test_pushpull.py
jupyterlab_git/tests/test_pushpull.py
from subprocess import PIPE from mock import patch, call, Mock from jupyterlab_git.git import Git @patch('subprocess.Popen') @patch('os.environ', {'TEST': 'test'}) def test_git_pull_fail(mock_subproc_popen): # Given process_mock = Mock() attrs = { 'communicate.return_value': ('output', 'Authenti...
from subprocess import PIPE from mock import patch, call, Mock from jupyterlab_git.git import Git @patch('subprocess.Popen') @patch('os.environ', {'TEST': 'test'}) def test_git_pull_fail(mock_subproc_popen): # Given process_mock = Mock() attrs = { 'communicate.return_value': ('output', 'Authenti...
Python
0.000686
d80878788ddcc1443c54c11b923da23bc295b496
Fix wget -q flag
charmtest/network.py
charmtest/network.py
import io import argparse class Wget(object): name = "wget" def __init__(self, network): self._network = network def __call__(self, proc_args): parser = argparse.ArgumentParser() parser.add_argument("url") parser.add_argument("-O", dest="output") parser.add_argum...
import io import argparse class Wget(object): name = "wget" def __init__(self, network): self._network = network def __call__(self, proc_args): parser = argparse.ArgumentParser() parser.add_argument("url") parser.add_argument("-O", dest="output") parser.add_argum...
Python
0.000002
833395650dc585d1a35e15d8751801988f251388
Use closure to remove globals.
avenue/web.py
avenue/web.py
# -*- coding: utf-8 -*- # Copyright (c) 2012 Michael Babich # See LICENSE.txt or http://opensource.org/licenses/MIT '''Acts as an interface between what Flask serves and what goes on in the rest of the application. ''' from avenue import app, api from flask import render_template, make_response from copy import copy i...
# -*- coding: utf-8 -*- # Copyright (c) 2012 Michael Babich # See LICENSE.txt or http://opensource.org/licenses/MIT '''Acts as an interface between what Flask serves and what goes on in the rest of the application. ''' from avenue import app, api from flask import render_template, make_response from copy import copy i...
Python
0
730e765822932b5b0b00832c41140f39a9ae8d11
Bump version
datetimerange/__version__.py
datetimerange/__version__.py
# encoding: utf-8 from datetime import datetime __author__ = "Tsuyoshi Hombashi" __copyright__ = "Copyright 2016-{}, {}".format(datetime.now().year, __author__) __license__ = "MIT License" __version__ = "0.3.6" __maintainer__ = __author__ __email__ = "tsuyoshi.hombashi@gmail.com"
# encoding: utf-8 from datetime import datetime __author__ = "Tsuyoshi Hombashi" __copyright__ = "Copyright 2016-{}, {}".format(datetime.now().year, __author__) __license__ = "MIT License" __version__ = "0.3.5" __maintainer__ = __author__ __email__ = "tsuyoshi.hombashi@gmail.com"
Python
0
0b9a97a4d6d47bd8f442c3fe3783b1d2cd85ac74
Add tests for widgets
jarbas/dashboard/tests/test_dashboard_admin.py
jarbas/dashboard/tests/test_dashboard_admin.py
from collections import namedtuple from unittest.mock import MagicMock from django.test import TestCase from jarbas.core.models import Reimbursement from jarbas.dashboard.admin import ( ReceiptUrlWidget, ReimbursementModelAdmin, SubquotaWidget, SubuotaListfilter, SuspiciousWidget, ) Request = na...
from collections import namedtuple from unittest.mock import MagicMock from django.test import TestCase from jarbas.core.models import Reimbursement from jarbas.dashboard.admin import ReimbursementModelAdmin, SubuotaListfilter Request = namedtuple('Request', ('method',)) ReimbursementMock = namedtuple('Reimbursemen...
Python
0.000001
35ff017b483bb46b1f942045bd2c9e20ace39483
fix line splitting
Commands/Urban.py
Commands/Urban.py
# -*- coding: utf-8 -*- """ Created on Jan 24, 2014 @author: Tyranic-Moron """ import urllib import json from IRCMessage import IRCMessage from IRCResponse import IRCResponse, ResponseType from CommandInterface import CommandInterface from Utils import WebUtils from twisted.words.protocols.irc import assembleForma...
# -*- coding: utf-8 -*- """ Created on Jan 24, 2014 @author: Tyranic-Moron """ import urllib import json from IRCMessage import IRCMessage from IRCResponse import IRCResponse, ResponseType from CommandInterface import CommandInterface from Utils import WebUtils from twisted.words.protocols.irc import assembleForma...
Python
0.000001
55f3e0e222246bfbc9c1a19f68b06941bac6cd70
Add an option to include spaces on random string generator
base/utils.py
base/utils.py
""" Small methods for generic use """ # standard library import itertools import random import re import string import unicodedata # django from django.utils import timezone def today(): """ This method obtains today's date in local time """ return timezone.localtime(timezone.now()).date() # BROKE...
""" Small methods for generic use """ # standard library import itertools import random import re import string import unicodedata # django from django.utils import timezone def today(): """ This method obtains today's date in local time """ return timezone.localtime(timezone.now()).date() # BROKE...
Python
0.000004
5496bd29c4262c252367d7b305d2a78fd1ad2fa7
move debug call
bcdata/wcs.py
bcdata/wcs.py
import logging import requests import bcdata log = logging.getLogger(__name__) def get_dem( bounds, out_file="dem.tif", src_crs="EPSG:3005", dst_crs="EPSG:3005", resolution=25, interpolation=None ): """Get TRIM DEM for provided bounds, write to GeoTIFF. """ bbox = ",".join([str(b) for b in bounds])...
import logging import requests import bcdata log = logging.getLogger(__name__) def get_dem( bounds, out_file="dem.tif", src_crs="EPSG:3005", dst_crs="EPSG:3005", resolution=25, interpolation=None ): """Get TRIM DEM for provided bounds, write to GeoTIFF. """ bbox = ",".join([str(b) for b in bounds])...
Python
0.000002
c4ad9519c117edfdc59f229380fa0797bc6bfffa
Update BitshareComFolder.py
module/plugins/crypter/BitshareComFolder.py
module/plugins/crypter/BitshareComFolder.py
# -*- coding: utf-8 -*- from module.plugins.internal.SimpleCrypter import SimpleCrypter, create_getInfo class BitshareComFolder(SimpleCrypter): __name__ = "BitshareComFolder" __type__ = "crypter" __version__ = "0.04" __pattern__ = r'http://(?:www\.)?bitshare\.com/\?d=\w+' __config__ = [("...
# -*- coding: utf-8 -*- from module.plugins.internal.SimpleCrypter import SimpleCrypter, create_getInfo class BitshareComFolder(SimpleCrypter): __name__ = "BitshareComFolder" __type__ = "crypter" __version__ = "0.03" __pattern__ = r'http://(?:www\.)?bitshare\.com/\?d=\w+' __config__ = [("...
Python
0
326f0b881d36ed19d0a37495ae34fc24fc1eb707
Load the spotify header file from an absolute path
connect_ffi.py
connect_ffi.py
from cffi import FFI ffi = FFI() print "Loading Spotify library..." #TODO: Use absolute paths for open() and stuff #Header generated with cpp spotify.h > spotify.processed.h && sed -i 's/__extension__//g' spotify.processed.h with open(os.path.join(sys.path[0], "spotify.processed.h")) as file: header = file.read() ...
from cffi import FFI ffi = FFI() print "Loading Spotify library..." #TODO: Use absolute paths for open() and stuff #Header generated with cpp spotify.h > spotify.processed.h && sed -i 's/__extension__//g' spotify.processed.h with open("spotify.processed.h") as file: header = file.read() ffi.cdef(header) ffi.cdef(...
Python
0
278dcb8b2fb3e1f69434ec9c41e566501cdc50bd
Remove unused functionality
organizations/backends/forms.py
organizations/backends/forms.py
# -*- coding: utf-8 -*- # Copyright (c) 2012-2019, Ben Lopatin and contributors # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of source code must retain the above copyright ...
# -*- coding: utf-8 -*- # Copyright (c) 2012-2019, Ben Lopatin and contributors # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of source code must retain the above copyright ...
Python
0
331fb50e6a4dcef99c8a6806d3efd7531859542f
add comments
achievements/templatetags/achievement_tags.py
achievements/templatetags/achievement_tags.py
from django import template from achievements.models import Category, Trophy from achievements import settings register = template.Library() # call single_category.html with the given parameters @register.inclusion_tag('achievements/single_category.html') def render_category(category, user): return { 'ca...
from django import template from achievements.models import Category, Trophy from achievements import settings register = template.Library() @register.inclusion_tag('achievements/single_category.html') def render_category(category, user): return { 'category': category, 'percentage': category.get...
Python
0
66fc121dbe0dbb7a69a62bfdaf98838a4f7a0bf3
Update yeti.py
misp_modules/modules/expansion/yeti.py
misp_modules/modules/expansion/yeti.py
import json import json try: import pyeti except ImportError: print("pyeti module not installed.") misperrors = {'error': 'Error'} mispattributes = {'input': ['ip-src', 'ip-dst', 'hostname', 'domain'], 'output': ['hostname', 'domain', 'ip-src', 'ip-dst', 'url']} # possible module-types: 'e...
import json import json try: import pyeti except ImportError: print("pyeti module not installed.") misperrors = {'error': 'Error'} mispattributes = {'input': ['ip-src', 'ip-dst', 'hostname', 'domain'], 'output': ['hostname', 'domain', 'ip-src', 'ip-dst', 'url']} # possible module-types: 'ex...
Python
0
24124edccd9a822bb300815907c37d6453defed5
Add recursive handling of nested states.
py/statemachines/simple_state_machine_script_test.py
py/statemachines/simple_state_machine_script_test.py
#---------------------------------------------------------------------------------------- # BEGIN: READ_HEXAPOD_CURRENT_POSE # TEMPLATE: ReadTransformState # smach.StateMachine.add('READ_HEXAPOD_CURRENT_POSE', TFListenerState('ur10_1/base', 'hexapod_1/top', 'hexapod_current_pose'), ...
#---------------------------------------------------------------------------------------- # BEGIN: READ_HEXAPOD_CURRENT_POSE # TEMPLATE: ReadTransformState # smach.StateMachine.add('READ_HEXAPOD_CURRENT_POSE', TFListenerState('ur10_1/base', 'hexapod_1/top', 'hexapod_current_pose'), ...
Python
0
c3dffef7869c0ce19801d78393a336b6b6ecbce7
stop littering /tmp with temporary resource files
pynodegl-utils/pynodegl_utils/tests/cmp_resources.py
pynodegl-utils/pynodegl_utils/tests/cmp_resources.py
#!/usr/bin/env python # # Copyright 2020 GoPro Inc. # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache...
#!/usr/bin/env python # # Copyright 2020 GoPro Inc. # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache...
Python
0.000002
deccf656db39ac949f93e562e4f41a32589feb9b
Use a more complex and extendable check for shortcuts in StructuredText
cybox/common/structured_text.py
cybox/common/structured_text.py
# Copyright (c) 2013, The MITRE Corporation. All rights reserved. # See LICENSE.txt for complete terms. import cybox import cybox.bindings.cybox_common as common_binding class StructuredText(cybox.Entity): _binding = common_binding _namespace = 'http://cybox.mitre.org/common-2' def __init__(self, value=...
# Copyright (c) 2013, The MITRE Corporation. All rights reserved. # See LICENSE.txt for complete terms. import cybox import cybox.bindings.cybox_common as common_binding class StructuredText(cybox.Entity): _binding = common_binding _namespace = 'http://cybox.mitre.org/common-2' def __init__(self, value=...
Python
0
1eae87ee4435b4dda35d64295de13756394dbce9
Add GET to 'Allow-Methods' by default. Fixes #12
crossdomain.py
crossdomain.py
#!/usr/bin/env python from datetime import timedelta from flask import make_response, request, current_app from functools import update_wrapper def crossdomain(origin=None, methods=['GET'], headers=None, max_age=21600, attach_to_all=True, automatic_options=True): if methods is not...
#!/usr/bin/env python from datetime import timedelta from flask import make_response, request, current_app from functools import update_wrapper def crossdomain(origin=None, methods=None, headers=None, max_age=21600, attach_to_all=True, automatic_options=True): if methods is not No...
Python
0
9ec25b6a5f8400b68c51ce9c5667c8c0c1648521
Remove unneeded catch
cucco/regex.py
cucco/regex.py
#-*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import re """ Regular expression to match URLs as seen on http://daringfireball.net/2010/07/improved_regex_for_matching_urls """ URL_REGEX = re.compile( r'(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([...
#-*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import re """ Regular expression to match URLs as seen on http://daringfireball.net/2010/07/improved_regex_for_matching_urls """ URL_REGEX = re.compile( r'(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([...
Python
0.000019
1c6f53492fc4cdc132769e4ffcfb076557a45c34
Remove English words from Non-English corpus data
modules/preprocessor/emille_preprocessor.py
modules/preprocessor/emille_preprocessor.py
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- """EMILLE Corpus Preprocessor which inherits from BasePreprocessor.""" import regex as re from base_preprocessor import BasePreprocessor from nltk.tokenize import sent_tokenize from bs4 import BeautifulSoup import sys import unicodedata from collections import defaultdi...
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- """EMILLE Corpus Preprocessor which inherits from BasePreprocessor.""" import regex as re from base_preprocessor import BasePreprocessor from nltk.tokenize import sent_tokenize from bs4 import BeautifulSoup import sys import unicodedata from collections import defaultdi...
Python
0.000083
efd96f03d51c1fce3ef370cae88928e16f0b9f17
Parse the response with json
buffer/api.py
buffer/api.py
import json from rauth import OAuth2Session BASE_URL = 'https://api.bufferapp.com/1/%s' class API(OAuth2Session): ''' Small and clean class that embrace all basic operations with the buffer app ''' def get(self, url): if not self.access_token: raise ValueError('Please set an access token fi...
from rauth import OAuth2Session BASE_URL = 'https://api.bufferapp.com/1/%s' class API(OAuth2Session): ''' Small and clean class that embrace all basic operations with the buffer app ''' def get(self, url): if not self.access_token: raise ValueError('Please set an access token first!') r...
Python
0.999999
0629183a91046b746d04c1a68e190721a156560b
rename id->fileid (id is a builtin)
build/cook.py
build/cook.py
# # Copyright (c) 2004 Specifix, Inc. # All rights reserved # import recipe import time import files import commit import os import util import sha1helper def cook(repos, cfg, recipeFile): classList = recipe.RecipeLoader(recipeFile) built = [] if recipeFile[0] != "/": raise IOError, "recipe file names mu...
# # Copyright (c) 2004 Specifix, Inc. # All rights reserved # import recipe import time import files import commit import os import util import sha1helper def cook(repos, cfg, recipeFile): classList = recipe.RecipeLoader(recipeFile) built = [] if recipeFile[0] != "/": raise IOError, "recipe file names mu...
Python
0
29273b0d7473a1efa955cd35686838780d390106
add more counters
monasca_persister/repositories/persister.py
monasca_persister/repositories/persister.py
# (C) Copyright 2016 Hewlett Packard Enterprise Development Company LP # # 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 ap...
# (C) Copyright 2016 Hewlett Packard Enterprise Development Company LP # # 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 ap...
Python
0
fa1f4a1420f2ea6d66234dae2189a7fb8fdf1f6f
remove debug print
common/lib/xmodule/xmodule/mongo_utils.py
common/lib/xmodule/xmodule/mongo_utils.py
""" Common MongoDB connection functions. """ import logging import pymongo from pymongo import ReadPreference from mongodb_proxy import MongoProxy logger = logging.getLogger(__name__) # pylint: disable=invalid-name # pylint: disable=bad-continuation def connect_to_mongodb( db, host, port=27017, tz_aware=Tr...
""" Common MongoDB connection functions. """ import logging import pymongo from pymongo import ReadPreference from mongodb_proxy import MongoProxy logger = logging.getLogger(__name__) # pylint: disable=invalid-name # pylint: disable=bad-continuation def connect_to_mongodb( db, host, port=27017, tz_aware=Tr...
Python
0.000008
a9ff2da085738770e1b3c03162f79454851df3b8
Fix issue #144, getting wrong field name for harakiri_count
newrelic_plugin_agent/plugins/uwsgi.py
newrelic_plugin_agent/plugins/uwsgi.py
""" uWSGI """ import json import logging from newrelic_plugin_agent.plugins import base LOGGER = logging.getLogger(__name__) class uWSGI(base.SocketStatsPlugin): GUID = 'com.meetme.newrelic_uwsgi_agent' DEFAULT_HOST = 'localhost' DEFAULT_PORT = 1717 def add_datapoints(self, stats): """Ad...
""" uWSGI """ import json import logging from newrelic_plugin_agent.plugins import base LOGGER = logging.getLogger(__name__) class uWSGI(base.SocketStatsPlugin): GUID = 'com.meetme.newrelic_uwsgi_agent' DEFAULT_HOST = 'localhost' DEFAULT_PORT = 1717 def add_datapoints(self, stats): """Ad...
Python
0
2d40d6a9623adb9e91bd1e4d99c5c111d0ff4f8f
Update the New Season service to use MySportsFeeds API v2
nflpool/services/new_season_service.py
nflpool/services/new_season_service.py
from nflpool.data.seasoninfo import SeasonInfo from nflpool.data.dbsession import DbSessionFactory import requests import pendulum import nflpool.data.secret as secret from requests.auth import HTTPBasicAuth class NewSeasonService: @staticmethod def get_install(): return [] '''After first time in...
from nflpool.data.seasoninfo import SeasonInfo from nflpool.data.dbsession import DbSessionFactory import requests import pendulum import nflpool.data.secret as secret from requests.auth import HTTPBasicAuth class NewSeasonService: @staticmethod def get_install(): return [] '''After first time in...
Python
0
4a83439926181f26e4656d2a2b78021209d3b629
fix the dropout to 0.2 because that is what they use
code/nolearntrail.py
code/nolearntrail.py
from nolearn.dbn import DBN from readfacedatabases import * from sklearn import cross_validation from sklearn.metrics import zero_one_score from sklearn.metrics import classification_report import argparse import numpy as np from common import * parser = argparse.ArgumentParser(description='nolearn test') parser.add...
from nolearn.dbn import DBN from readfacedatabases import * from sklearn import cross_validation from sklearn.metrics import zero_one_score from sklearn.metrics import classification_report import argparse import numpy as np from common import * parser = argparse.ArgumentParser(description='nolearn test') parser.add...
Python
0.002569
ddc571f32212a57f725101314878d17df9124bb8
fix loop range
commands/cmd_roll.py
commands/cmd_roll.py
import random from lib.command import Command class RollCommand(Command): name = 'roll' description = 'Roll some dice.' def run(self, message, args): if not args: self.reply(message, 'No roll specification supplied. Try */roll 3d6*.', parse_mode='Markdown') return ...
import random from lib.command import Command class RollCommand(Command): name = 'roll' description = 'Roll some dice.' def run(self, message, args): if not args: self.reply(message, 'No roll specification supplied. Try */roll 3d6*.', parse_mode='Markdown') return ...
Python
0.000001
f92c8c9620524d0414af6f039885c2875a247cd0
add msrest dependency (#7062)
sdk/appconfiguration/azure-appconfiguration/setup.py
sdk/appconfiguration/azure-appconfiguration/setup.py
#!/usr/bin/env python #------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. #----------------------------------------------------------------...
#!/usr/bin/env python #------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. #----------------------------------------------------------------...
Python
0
fe06c3a839bdc13384250924a4a30d9dd3455fc7
fix archive resource unit test
service/test/unit/resources/test_archive_resource.py
service/test/unit/resources/test_archive_resource.py
from twisted.trial import unittest import json from mockito import mock, when, verify from test.unit.resources import DummySite from twisted.web.test.requesthelper import DummyRequest from pixelated.resources.mails_resource import MailsArchiveResource from twisted.internet import defer class TestArchiveResource(unitt...
import unittest import json from mockito import mock, when, verify from test.unit.resources import DummySite from twisted.web.test.requesthelper import DummyRequest from pixelated.resources.mails_resource import MailsArchiveResource from twisted.internet import defer class TestArchiveResource(unittest.TestCase): ...
Python
0
6ecae8f97723b90193bc64e53f8dcee22c3cbf55
add tag to return settings values to django template.
odm2admin/templatetags/admin_extras.py
odm2admin/templatetags/admin_extras.py
# this came from https://djangosnippets.org/snippets/2196/ # adds a collect tag for templates so you can build lists from django import template from django.contrib import admin from django.contrib.gis.geos import GEOSGeometry from django.core.management import settings register = template.Library() @register.tag d...
# this came from https://djangosnippets.org/snippets/2196/ # adds a collect tag for templates so you can build lists from django import template from django.contrib import admin from django.contrib.gis.geos import GEOSGeometry from django.core.management import settings register = template.Library() @register.tag d...
Python
0
b9b7ed8f4ddf139bd031ce7650558f7a0e753718
Fix "compilation" error.
solidity/python/constants/PrintMaxExpPerPrecision.py
solidity/python/constants/PrintMaxExpPerPrecision.py
from math import factorial MIN_PRECISION = 32 MAX_PRECISION = 63 NUM_OF_VALUES_PER_ROW = 4 assert((MAX_PRECISION+1) % NUM_OF_VALUES_PER_ROW == 0) NUM_OF_COEFS = 34 maxFactorial = factorial(NUM_OF_COEFS) coefficients = [maxFactorial/factorial(i) for i in range(NUM_OF_COEFS)] def fixedExpUnsafe(x,precision): ...
from math import factorial MIN_PRECISION = 32 MAX_PRECISION = 63 NUM_OF_VALUES_PER_ROW = 4 assert((MAX_PRECISION+1) % NUM_OF_VALUES_PER_ROW == 0) NUM_OF_COEFS = 34 maxFactorial = factorial(NUM_OF_COEFS) coefficients = [maxFactorial/factorial(i) for i in range(NUM_OF_COEFS)] def fixedExpUnsafe(x,precision): ...
Python
0.000013
283dd9918bd16202bf799c470e8e5b50d2ef1cd6
Increment version number to 0.7.0
datajoint/version.py
datajoint/version.py
__version__ = "0.7.0"
__version__ = "0.6.1"
Python
0.99997
0f5fe279d6b4641b2a2741271da4f021238f00a1
fix import in generator
dataset_generator.py
dataset_generator.py
import csv import os # execfile("C:\\Users\\YONI\\Documents\\Projects\\degree\\attack detection methods\\anomaly_generator\\dataset_generator.py") ROW_NUM = 10 path = "C:\\Users\\YONI\\Documents\\anomally_detector\\data_sets\\example\\" users_num = 100 features_num = 20 directory = "data_sets\\" if not os.path.exi...
import csv # execfile("C:\\Users\\YONI\\Documents\\Projects\\degree\\attack detection methods\\anomaly_generator\\dataset_generator.py") ROW_NUM = 10 path = "C:\\Users\\YONI\\Documents\\anomally_detector\\data_sets\\example\\" users_num = 100 features_num = 20 directory = "data_sets\\" if not os.path.exists(direct...
Python
0
7ccb9cb0d6e3ce6e3c6c09604af5e2bbdfae63ae
update urls.py
openstax/urls.py
openstax/urls.py
from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from wagtail.contrib.wagtailapi import urls as wagtailapi_urls from wagtail.wagtailadmin import urls as wagtailadmin_urls from wagtail.wagtailcore import urls as wagtail...
from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from wagtail.contrib.wagtailapi import urls as wagtailapi_urls from wagtail.wagtailadmin import urls as wagtailadmin_urls from wagtail.wagtailcore import urls as wagtail...
Python
0.000001
853135b61f34ece1363da9b53244e775a2ba16a8
Add docstring for convert_timezone()
datetime/datetime.py
datetime/datetime.py
import datetime # ============================================================================== # TIMESTAMP 2 STR # ============================================================================== def timestamp2str(t, pattern="%Y-%m-%d %H:%M:%S"): """ ...
import datetime # ============================================================================== # TIMESTAMP 2 STR # ============================================================================== def timestamp2str(t, pattern="%Y-%m-%d %H:%M:%S"): """ ...
Python
0
21b668f8f6d75ff56c85f6f21a2565e39a220679
Add more datetime functions
datetime/datetime.py
datetime/datetime.py
import datetime import dateutil import dateutil.tz def gettz(tz): """ Return a timezone object to be used by dateutul given a timezone as a string such as "UTC" or "Australia/Melbourne" """ return dateutil.tz.gettz(tz) def datetime2str(dt, format="%Y-%m-%d %H:%M:%S", tz="Australia/Melbourne"): """...
import datetime import dateutil import dateutil.tz def timestamp2str(t, tz="Australia/Melbourne", format="%Y-%m-%d %H:%M:%S.f %Z"): tzinfo = dateutil.tz.gettz(tz) assert tzinfo is not None, "Could not get timezone data" return datetime.datetime.fromtimestamp(t, tz=tzinfo).strftime(format) def str2datetime...
Python
0.000001
9d2ef02367380c76f39c4bd84ea2f35897d0bebf
Edit school enrollment management command
education/management/commands/create_school_enrollment_script.py
education/management/commands/create_school_enrollment_script.py
''' Created on May 28, 2013 @author: raybesiga ''' import datetime import logging import itertools from logging import handlers from django.core.management.base import BaseCommand from django.contrib.sites.models import Site from django.contrib.auth.models import User from django.core.mail import send_mail from djan...
''' Created on May 28, 2013 @author: raybesiga ''' import datetime import logging import itertools from logging import handlers from django.core.management.base import BaseCommand from django.contrib.sites.models import Site from django.contrib.auth.models import User from django.core.mail import send_mail from djan...
Python
0
900ddf92a1cf65270a7b420a848c0f2611647899
handle &amp;
freelancefinder/remotes/sources/workinstartups/workinstartups.py
freelancefinder/remotes/sources/workinstartups/workinstartups.py
"""Wrapper for the WorkInStartups source.""" import json import bleach import maya import requests from jobs.models import Post ADDITIONAL_TAGS = ['p', 'br'] class WorkInStartups(object): """Wrapper for the WorkInStartups source.""" json_api_address = 'http://workinstartups.com/job-board/api/api.php?acti...
"""Wrapper for the WorkInStartups source.""" import json import bleach import maya import requests from jobs.models import Post ADDITIONAL_TAGS = ['p', 'br'] class WorkInStartups(object): """Wrapper for the WorkInStartups source.""" json_api_address = 'http://workinstartups.com/job-board/api/api.php?acti...
Python
0.000001
2c53bc17f98a3e9fdc71ba77f1ab9c1c06f82509
remove test param on srvy
collection/srvy.py
collection/srvy.py
#!/usr/bin/python import sys import time from time import sleep from datetime import datetime import random import sqlite3 import csv from configparser import ConfigParser from gpiozero import Button import pygame # VARIABLES question_csv_location = '../archive/questions.csv' sqlite_file = '../archive/srvy.db' yes_...
#!/usr/bin/python import sys import time from time import sleep from datetime import datetime import random import sqlite3 import csv from configparser import ConfigParser if __name__ == '__main__': # Check if running on a Raspberry Pi try: from gpiozero import Button except ImportError: ...
Python
0.000001
a2d9edbe8b154858fe89be12ca281a926ad46ac7
Remove double negative
api/init/health/routes.py
api/init/health/routes.py
import os from flask import jsonify from flask_restplus import Resource, Namespace # pylint: disable=unused-variable def register_health(namespace: Namespace): """Method used to register the health check namespace and endpoint.""" @namespace.route('/health') @namespace.doc() class Health(Resource): ...
import os from flask import jsonify from flask_restplus import Resource, Namespace # pylint: disable=unused-variable def register_health(namespace: Namespace): """Method used to register the health check namespace and endpoint.""" @namespace.route('/health') @namespace.doc() class Health(Resource): ...
Python
0.999999
9a2b3477dcfd3e8ba6fac43678713f5213fe87b2
Caugh edge cause for initials of n=0 v. n=None
dedupe/predicates.py
dedupe/predicates.py
#!/usr/bin/python # -*- coding: utf-8 -*- import re def tokenFieldPredicate(field): """returns the tokens""" return tuple(field.split()) def commonIntegerPredicate(field): """"return any integers""" return tuple(re.findall("\d+", field)) def nearIntegersPredicate(field): """return any integers N...
#!/usr/bin/python # -*- coding: utf-8 -*- import re def tokenFieldPredicate(field): """returns the tokens""" return tuple(field.split()) def commonIntegerPredicate(field): """"return any integers""" return tuple(re.findall("\d+", field)) def nearIntegersPredicate(field): """return any integers N...
Python
0.999999
2b0f4345ff1d4f97f8c00bdad3be035bd5478073
Use a temporary file which exists.
libcloud/test/test_init.py
libcloud/test/test_init.py
# -*- coding: utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one or more§ # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "Li...
# -*- coding: utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one or more§ # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "Li...
Python
0
a51a089e90719dfda2e6164b0f4c1aec50c26534
Add ordering
entity/migrations/0006_entity_relationship_unique.py
entity/migrations/0006_entity_relationship_unique.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2016-12-12 18:20 from __future__ import unicode_literals from django.db import migrations, connection from django.db.models import Count, Max def disable_triggers(apps, schema_editor): """ Temporarily disable user triggers on the relationship table. We d...
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2016-12-12 18:20 from __future__ import unicode_literals from django.db import migrations, connection from django.db.models import Count, Max def disable_triggers(apps, schema_editor): """ Temporarily disable user triggers on the relationship table. We d...
Python
0