commit stringlengths 40 40 | subject stringlengths 4 1.73k | repos stringlengths 5 127k | old_file stringlengths 2 751 | new_file stringlengths 2 751 | new_contents stringlengths 1 8.98k | old_contents stringlengths 0 6.59k | license stringclasses 13
values | lang stringclasses 23
values |
|---|---|---|---|---|---|---|---|---|
15dfc6d1da9d8af2ed9a6f519744fab11a68367e | Fix `xml_sax_parser.py` good/bad naming | github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql | python/ql/test/experimental/query-tests/Security/CWE-611/xml_sax_make_parser.py | python/ql/test/experimental/query-tests/Security/CWE-611/xml_sax_make_parser.py | from flask import request, Flask
from io import StringIO
import xml.sax
# xml_content = '<?xml version="1.0"?><!DOCTYPE dt [<!ENTITY xxe SYSTEM "file:///etc/passwd">]><test>&xxe;</test>'
app = Flask(__name__)
class MainHandler(xml.sax.ContentHandler):
def __init__(self):
self._result = []
def chara... | from flask import request, Flask
from io import StringIO
import xml.sax
# xml_content = '<?xml version="1.0"?><!DOCTYPE dt [<!ENTITY xxe SYSTEM "file:///etc/passwd">]><test>&xxe;</test>'
app = Flask(__name__)
class MainHandler(xml.sax.ContentHandler):
def __init__(self):
self._result = []
def chara... | mit | Python |
fdd66e3f5859e8cbec0c6bb7d3d337ea5c30845d | remove unused import statements | arjunkrishnababu96/jekpost | jekpost/jekpost_create.py | jekpost/jekpost_create.py | #!/usr/bin/env python3
import argparse
import datetime
def generate_post_file(title, location, disqus_name=None):
title_line = "title: {}".format(title)
filename = make_filename(title, get_date_formatted(datetime.date.today()))
with open(filename, mode='x', encoding='utf-8') as actual_file:
print... | #!/usr/bin/env python3
import argparse
import shutil
import os
import datetime
def generate_post_file(title, location, disqus_name=None):
title_line = "title: {}".format(title)
filename = make_filename(title, get_date_formatted(datetime.date.today()))
with open(filename, mode='x', encoding='utf-8') as ac... | mit | Python |
9e7eae0e2f3ec5e818f70a537ee740cd5375f7c3 | make cfitsio explicitly depend on curl (#12016) | iulian787/spack,LLNL/spack,iulian787/spack,iulian787/spack,iulian787/spack,iulian787/spack,LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack | var/spack/repos/builtin/packages/cfitsio/package.py | var/spack/repos/builtin/packages/cfitsio/package.py | # Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Cfitsio(AutotoolsPackage):
"""CFITSIO is a library of C and Fortran subroutines for readin... | # Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Cfitsio(AutotoolsPackage):
"""CFITSIO is a library of C and Fortran subroutines for readin... | lgpl-2.1 | Python |
a028ee702583deeb07b3bee38e200bd843479320 | Load default watermark from the environment | jacebrowning/memegen,jacebrowning/memegen | app/settings.py | app/settings.py | import os
from pathlib import Path
ROOT = Path(__file__).parent.parent.resolve()
# Server configuration
PORT = int(os.environ.get("PORT", 5000))
WORKERS = int(os.environ.get("WEB_CONCURRENCY", 1))
if "DOMAIN" in os.environ: # staging / production
SERVER_NAME = os.environ["DOMAIN"]
RELEASE_STAGE = "staging"... | import os
from pathlib import Path
ROOT = Path(__file__).parent.parent.resolve()
# Server configuration
PORT = int(os.environ.get("PORT", 5000))
WORKERS = int(os.environ.get("WEB_CONCURRENCY", 1))
if "DOMAIN" in os.environ: # staging / production
SERVER_NAME = os.environ["DOMAIN"]
RELEASE_STAGE = "staging"... | mit | Python |
1283d02beb8f633e2c31ba29fd43c8eef45b7cdb | Bump micro version number. | laijingtao/landlab,landlab/landlab,cmshobe/landlab,RondaStrauch/landlab,landlab/landlab,landlab/landlab,decvalts/landlab,csherwood-usgs/landlab,SiccarPoint/landlab,cmshobe/landlab,RondaStrauch/landlab,SiccarPoint/landlab,ManuSchmi88/landlab,Carralex/landlab,ManuSchmi88/landlab,decvalts/landlab,csherwood-usgs/landlab,am... | landlab/__init__.py | landlab/__init__.py | #! /usr/bin/env python
"""
The Landlab
:Package name: TheLandlab
:Version: 0.1.0
:Release date: 2013-03-24
:Authors:
Greg Tucker,
Nicole Gasparini,
Erkan Istanbulluoglu,
Daniel Hobley,
Sai Nudurupati,
Jordan Adams,
Eric Hutton
:URL: http://csdms.colorado.edu/trac/landlab
:License: MIT
"""
from __futur... | #! /usr/bin/env python
"""
The Landlab
:Package name: TheLandlab
:Version: 0.1.0
:Release date: 2013-03-24
:Authors:
Greg Tucker,
Nicole Gasparini,
Erkan Istanbulluoglu,
Daniel Hobley,
Sai Nudurupati,
Jordan Adams,
Eric Hutton
:URL: http://csdms.colorado.edu/trac/landlab
:License: MIT
"""
from __futur... | mit | Python |
eea8d0364609a53e215e3f056e6315a6dbc3d50d | call the decorator | Endika/OpenUpgrade,Endika/OpenUpgrade,pedrobaeza/OpenUpgrade,hifly/OpenUpgrade,grap/OpenUpgrade,damdam-s/OpenUpgrade,Endika/OpenUpgrade,hifly/OpenUpgrade,blaggacao/OpenUpgrade,blaggacao/OpenUpgrade,sebalix/OpenUpgrade,hifly/OpenUpgrade,damdam-s/OpenUpgrade,hifly/OpenUpgrade,blaggacao/OpenUpgrade,sebalix/OpenUpgrade,Ope... | addons/account_analytic_analysis/migrations/8.0.1.1/pre-migration.py | addons/account_analytic_analysis/migrations/8.0.1.1/pre-migration.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2015 Therp BV (<http://therp.nl>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of ... | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2015 Therp BV (<http://therp.nl>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of ... | agpl-3.0 | Python |
a368bf67522711d8c9ad31f231af95c307612ca2 | add a getters to exceptions | missionpinball/mpf,missionpinball/mpf | mpf/exceptions/base_error.py | mpf/exceptions/base_error.py | """Error in MPF or MPF-MC."""
from mpf._version import log_url
class BaseError(AssertionError):
"""Error in a config file found."""
# pylint: disable-msg=too-many-arguments
def __init__(self, message, error_no, logger_name, context=None, url_name=None):
"""Initialise exception."""
self._... | """Error in MPF or MPF-MC."""
from mpf._version import log_url
class BaseError(AssertionError):
"""Error in a config file found."""
# pylint: disable-msg=too-many-arguments
def __init__(self, message, error_no, logger_name, context=None, url_name=None):
"""Initialise exception."""
self._... | mit | Python |
a651b979ca869be932a6ad8f9686436ab6a16a6e | Update the py-lxml package (#4090) | iulian787/spack,tmerrick1/spack,lgarren/spack,matthiasdiener/spack,iulian787/spack,LLNL/spack,LLNL/spack,skosukhin/spack,matthiasdiener/spack,krafczyk/spack,tmerrick1/spack,iulian787/spack,tmerrick1/spack,tmerrick1/spack,krafczyk/spack,mfherbst/spack,mfherbst/spack,skosukhin/spack,EmreAtes/spack,lgarren/spack,EmreAtes/... | var/spack/repos/builtin/packages/py-lxml/package.py | var/spack/repos/builtin/packages/py-lxml/package.py | ##############################################################################
# Copyright (c) 2013-2016, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | ##############################################################################
# Copyright (c) 2013-2016, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | lgpl-2.1 | Python |
40625f2b38525c738486c25d10223fa1b24ce7ec | Use unicode in to_string | translationexchange/tml-python,translationexchange/tml-python | tml/strings.py | tml/strings.py | # encoding: UTF-8
def to_string(text):
""" Safe string conversion
Args:
text (string|unicode): input string
Returns:
str
"""
if type(text) is unicode:
return text
return unicode(text.decode('utf-8'))
| # encoding: UTF-8
def to_string(text):
""" Safe string conversion
Args:
text (string|unicode): input string
Returns:
str
"""
if text is unicode:
return text.encode('utf-8')
return text
| mit | Python |
9660f44a5d17521109397b14c32db71a2fba18ff | Update Conda Version to match MT build number | Esri/military-tools-geoprocessing-toolbox | tools/setup.py | tools/setup.py | # coding: utf-8
'''
------------------------------------------------------------------------------
Copyright 2018 Esri
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/lic... | # coding: utf-8
'''
------------------------------------------------------------------------------
Copyright 2018 Esri
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/lic... | apache-2.0 | Python |
b50f72c1aa77e91f4cfcecbcf4dedd7095f1c71e | improve comments for placeholder replacing | b-mueller/mythril,b-mueller/mythril,b-mueller/mythril,b-mueller/mythril | mythril/ether/ethcontract.py | mythril/ether/ethcontract.py | from mythril.disassembler.disassembly import Disassembly
from ethereum import utils
import persistent
import re
class ETHContract(persistent.Persistent):
def __init__(self, code, creation_code="", name="Unknown", enable_online_lookup=True):
# Workaround: We currently do not support compile-time ... | from mythril.disassembler.disassembly import Disassembly
from ethereum import utils
import persistent
import re
class ETHContract(persistent.Persistent):
def __init__(self, code, creation_code="", name="Unknown", enable_online_lookup=True):
creation_code = re.sub(r'(_+.*_+)', 'aa' * 20, creation... | mit | Python |
09d7f74ad51f468c9e74db0fcce9c5d65ebc919c | Fix import | projectweekend/Pi-Camera-Time-Lapse,projectweekend/Pi-Camera-Time-Lapse | camera/__init__.py | camera/__init__.py | from .camera import ConfigurableCamera
| from .camera import TimeLapseCamera
| mit | Python |
c941414c6ff18d6f3ad46b20cfa431549d8fde20 | Bump version to 0.8.0.rc2 | christiansandberg/canopen,christiansandberg/canopen | canopen/version.py | canopen/version.py |
__version__ = "0.8.0.rc2"
|
__version__ = "0.8.0.rc1"
| mit | Python |
7d22d48e14cdcc24e9f4d1308be4a9bfb443f5df | disable the discussion cache update signal until we get solution for pickling | J861449197/edx-platform,shashank971/edx-platform,bigdatauniversity/edx-platform,eestay/edx-platform,EduPepperPDTesting/pepper2013-testing,pdehaye/theming-edx-platform,jazztpt/edx-platform,leansoft/edx-platform,vismartltd/edx-platform,longmen21/edx-platform,mbareta/edx-platform-ft,vasyarv/edx-platform,devs1991/test_edx_... | common/djangoapps/cache_toolbox/discussion_cache.py | common/djangoapps/cache_toolbox/discussion_cache.py | import logging
from django.core.cache import cache, get_cache
from datetime import datetime
def _get_discussion_cache():
return get_cache('mongo_metadata_inheritance')
def get_discussion_cache_key(course_id):
return 'discussion_items_{0}'.format(course_id)
def get_discussion_cache_entry(modulestore, course... | import logging
from django.core.cache import cache, get_cache
from datetime import datetime
def _get_discussion_cache():
return get_cache('mongo_metadata_inheritance')
def get_discussion_cache_key(course_id):
return 'discussion_items_{0}'.format(course_id)
def get_discussion_cache_entry(modulestore, course... | agpl-3.0 | Python |
aa9f15af76e67a529be345850e7913755cba8b21 | Fix typo | github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql | python/ql/test/experimental/library-tests/frameworks/django-v1/response_test.py | python/ql/test/experimental/library-tests/frameworks/django-v1/response_test.py | from django.http.response import HttpResponse, HttpResponseRedirect, JsonResponse, HttpResponseNotFound
# Not an XSS sink, since the Content-Type is not "text/html"
# FP reported in https://github.com/github/codeql-python-team/issues/38
def fp_json_response(request):
# implicitly sets Content-Type to "application/... | from django.http.response import HttpResponse, HttpResponseRedirect, JsonResponse, HttpResponseNotFound
# Not an XSS sink, since the Content-Type is not "text/html"
# FP reported in https://github.com/github/codeql-python-team/issues/38
def fp_json_response(request):
# implicitly sets Content-Type to "application/... | mit | Python |
8748de555f3cd939ecc39cf3bdae50a8677359d7 | Bump to v1.9.0 | Cal-CS-61A-Staff/ok-client | client/__init__.py | client/__init__.py | __version__ = 'v1.9.0'
FILE_NAME = 'ok'
import os
import sys
sys.path.insert(0, '')
# Add directory in which the ok.zip is stored to sys.path.
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
| __version__ = 'v1.8.2'
FILE_NAME = 'ok'
import os
import sys
sys.path.insert(0, '')
# Add directory in which the ok.zip is stored to sys.path.
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
| apache-2.0 | Python |
8ae4be4fea8af1d560f713338de36cdd651d6e2a | bump to 1.6.6. for auth changes | Cal-CS-61A-Staff/ok-client | client/__init__.py | client/__init__.py | __version__ = 'v1.6.6'
FILE_NAME = 'ok'
import os
import sys
sys.path.insert(0, '')
# Add directory in which the ok.zip is stored to sys.path.
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
| __version__ = 'v1.6.5'
FILE_NAME = 'ok'
import os
import sys
sys.path.insert(0, '')
# Add directory in which the ok.zip is stored to sys.path.
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
| apache-2.0 | Python |
0bb418c72d858322a8fc7ad515f36a045d9dd0de | update to v1.3.29 | jathak/ok-client,Cal-CS-61A-Staff/ok-client,jackzhao-mj/ok-client | client/__init__.py | client/__init__.py | __version__ = 'v1.3.29'
import os
import sys
sys.path.insert(0, '')
# Add directory in which the ok.zip is stored to sys.path.
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
| __version__ = 'v1.3.28'
import os
import sys
sys.path.insert(0, '')
# Add directory in which the ok.zip is stored to sys.path.
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
| apache-2.0 | Python |
4f3234433b97e7f243d54e9e95399f5cabecd315 | Change broken course_modes migration to not touch the database. | antoviaque/edx-platform,pepeportela/edx-platform,edx/edx-platform,teltek/edx-platform,ahmedaljazzar/edx-platform,mitocw/edx-platform,edx-solutions/edx-platform,hastexo/edx-platform,IndonesiaX/edx-platform,pepeportela/edx-platform,Lektorium-LLC/edx-platform,mitocw/edx-platform,marcore/edx-platform,romain-li/edx-platform... | common/djangoapps/course_modes/migrations/0005_auto_20151217_0958.py | common/djangoapps/course_modes/migrations/0005_auto_20151217_0958.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('course_modes', '0004_auto_20151113_1457'),
]
operations = [
migrations.SeparateDatabaseAndState(
database_operat... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('course_modes', '0004_auto_20151113_1457'),
]
operations = [
migrations.RemoveField(
model_name='coursemode',
... | agpl-3.0 | Python |
0c9c9f4f86ccc2c7328309569e0ebba44de3b1de | make stages class more subclassable | olebole/astrometry.net,olebole/astrometry.net,olebole/astrometry.net,olebole/astrometry.net,olebole/astrometry.net,olebole/astrometry.net,olebole/astrometry.net,olebole/astrometry.net | util/stages.py | util/stages.py | from astrometry.util.file import *
class CallGlobal(object):
def __init__(self, pattern, globals, *args, **kwargs):
self.pat = pattern
self.args = args
self.kwargs = kwargs
self.globals = globals
def getfunc(self, stage):
func = self.pat % stage
func = eval(func, self.globals)
return func
def getkwarg... | from astrometry.util.file import *
class CallGlobal(object):
def __init__(self, pattern, globals, *args, **kwargs):
self.pat = pattern
self.args = args
self.kwargs = kwargs
self.globals = globals
def getfunc(self, stage):
func = self.pat % stage
func = eval(func, self.globals)
return func
def __call__... | bsd-3-clause | Python |
b1e2face6015afc560de6928141a85bb99eaf0da | bump version | getweber/weber-cli | cob/__version__.py | cob/__version__.py | __version__ = "0.0.4"
| __version__ = "0.0.3"
| bsd-3-clause | Python |
efd617d4a5835fc345e6044c604d1ec492ad7bf7 | Handle empty choices | Didero/DideRobot | commands/Choice.py | commands/Choice.py | import random
from CommandTemplate import CommandTemplate
class Command(CommandTemplate):
triggers = ['choice', 'choose']
helptext = "Helps you make a choice between options in a comma-separated list"
possibleReplies = ["{}", "Hmm, I'd go with {}", "Out of those, {} sounds the least bad", "{}, obviously",
... | import random
from CommandTemplate import CommandTemplate
class Command(CommandTemplate):
triggers = ['choice', 'choose']
helptext = "Helps you make a choice between options in a comma-separated list"
possibleReplies = ["{}", "Hmm, I'd go with {}", "Out of those, {} sounds the least bad", "{}, obviously",
... | mit | Python |
a6f95c70aaf9049465438c68080a09603c54628f | Add detail view for Build model | SchrodingersGat/InvenTree,inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree | InvenTree/build/api.py | InvenTree/build/api.py | """
JSON API for the Build app
"""
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
from rest_framework import generics, permissions
from django.conf.urls import url, include
from .models import Build, Bu... | """
JSON API for the Build app
"""
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
from rest_framework import generics, permissions
from django.conf.urls import url, include
from .models import Build, Bu... | mit | Python |
e7a48fc19e965475c2d3c32e3c084a056c2927aa | Update pyyaml usage | QuteBits/resume_42 | resume_tex.py | resume_tex.py | # Converts my Resume from YAML to TeX.
# Just don't forget to drop pdflatex on the output :)
# ------------------------------------------------------------------------------
# @contributor Aleksandr Mattal <https://github.com/qutebits>
# inspired by work of Brandon Amos <https://github.com/bamos/cv>
import re
import y... | # Converts my Resume from YAML to TeX.
# Just don't forget to drop pdflatex on the output :)
# ------------------------------------------------------------------------------
# @contributor Aleksandr Mattal <https://github.com/qutebits>
# inspired by work of Brandon Amos <https://github.com/bamos/cv>
import re
import y... | mit | Python |
b6937405a9b85026f3e9cffc94fa65c87ee793c0 | Add possibility to debug csv streamer views. | jlaunonen/kirppu,jlaunonen/kirppu,jlaunonen/kirppu,jlaunonen/kirppu | kirppu/views/csv_utils.py | kirppu/views/csv_utils.py | # -*- coding: utf-8 -*-
import functools
import html
import io
from urllib.parse import quote
from django.conf import settings
from django.http import HttpResponse, StreamingHttpResponse
def strip_generator(fn):
@functools.wraps(fn)
def inner(output, event, generator=False):
if generator:
... | # -*- coding: utf-8 -*-
import functools
import io
from urllib.parse import quote
from django.http import StreamingHttpResponse
def strip_generator(fn):
@functools.wraps(fn)
def inner(output, event, generator=False):
if generator:
# Return the generator object only when using StringIO.
... | mit | Python |
acb787e677a76311172942ad0e0cf033d6b0b3a9 | Remove version printing | simpeg/discretize,simpeg/discretize,simpeg/discretize | docs/examples/plot_streamThickness.py | docs/examples/plot_streamThickness.py | """
Simple example to vary streamline thickness based on the vector amplitudes
=================================
"""
import numpy as np
import matplotlib.pyplot as plt
from discretize import TensorMesh
###############################################################################
# Create mesh
# -----
#
# Minimum ce... | """
Simple example to vary streamline thickness based on the vector amplitudes
=================================
"""
import numpy as np
import matplotlib.pyplot as plt
from discretize import TensorMesh
###############################################################################
# Create mesh
# -----
#
# Minimum ce... | mit | Python |
1abc730b053ba5de43983f22560267c6e790ec7c | Make main file importable. | AntonHerrNilsson/the-dungeon | the_dungeon.py | the_dungeon.py | import sys
import world
from creatures import Player
from player_ai import PlayerAI
import display
def run(world, steps=None, slp=0.5, show=True, player=None):
if steps is None:
steps = sys.maxsize
display.initialize()
for i in range(steps):
if show:
to_display = [world]
... | import sys
import world
from creatures import Player
from player_ai import PlayerAI
import display
def run(world, steps=None, slp=0.5, show=True, player=None):
if steps is None:
steps = sys.maxsize
display.initialize()
for i in range(steps):
if show:
to_display = [world]
... | mit | Python |
faba2bc98f08cddea51d2e0093aa5c2981c8bf15 | Add update interval constant. Add detail to constructor. | babycaseny/gdrive-linux,jimlawton/gdrive-linux-googlecode,jimlawton/gdrive-linux,jmfield2/gdrive-linux | gdrived.py | gdrived.py | #!/usr/bin/env python
#
# Copyright 2012 Jim Lawton. 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 requir... | #!/usr/bin/env python
#
# Copyright 2012 Jim Lawton. 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 requir... | apache-2.0 | Python |
e3e8dea40503944e1983f20ab18edd67163f384f | Bump version 0.19.0rc1 --> 0.19.0rc2 | lbryio/lbry,lbryio/lbry,lbryio/lbry | lbrynet/__init__.py | lbrynet/__init__.py | import logging
__version__ = "0.19.0rc2"
version = tuple(__version__.split('.'))
logging.getLogger(__name__).addHandler(logging.NullHandler())
| import logging
__version__ = "0.19.0rc1"
version = tuple(__version__.split('.'))
logging.getLogger(__name__).addHandler(logging.NullHandler())
| mit | Python |
82a8b7ac80fd7758a9a5e41c7751d4138577f85e | update logger in client test | h2020-endeavour/iSDX,h2020-endeavour/iSDX,h2020-endeavour/iSDX,h2020-endeavour/iSDX,h2020-endeavour/iSDX,h2020-endeavour/iSDX,h2020-endeavour/iSDX | pctrl/client_test.py | pctrl/client_test.py | #!/usr/bin/env python
# Author:
# Florian Kaufmann (DE-CIX)
import argparse
import atexit
import json
from multiprocessing.connection import Listener, Client
import os
from signal import signal, SIGTERM
from sys import exit
from threading import RLock, Thread
from lib import PConfig
import util.log
class XRS_Client... | #!/usr/bin/env python
# Author:
# Florian Kaufmann (DE-CIX)
import argparse
import atexit
import json
from multiprocessing.connection import Listener, Client
import os
from signal import signal, SIGTERM
from sys import exit
from threading import RLock, Thread
from lib import PConfig
class XRS_Client(object):
d... | apache-2.0 | Python |
f07331b8bfe3c43e694501b44ffadfae2dc262c6 | fix null hypothesis bug in hypergeom | kellieotto/permute,statlab/permute,jarrodmillman/permute,kellieotto/permute | permute/hypergeom.py | permute/hypergeom.py | """
Hypergeometric Test
"""
import numpy as np
from .utils import get_prng
def hypergeometric(x, N, n, G, reps=10**5, alternative='greater', keep_dist=False, seed=None):
"""
Parameters
----------
x : int
number of `good` elements observed in the sample
N : int
population size
... | """
Hypergeometric Test
"""
import scipy
import numpy as np
from scipy.special import comb
from .utils import get_prng
def hypergeom(population, n, g, reps=10**5, alternative='greater', keep_dist=False, seed=None):
"""
Parameters
----------
population : array-like
list of elements consisting of x in {0, 1} w... | bsd-2-clause | Python |
ea2a56d7e4c45a3c760e3b9e5bb1e7e9e760f853 | Bump version to 0.0.6 | portfoliome/pgawedge | pgawedge/_version.py | pgawedge/_version.py | version_info = (0, 0, 6)
__version__ = '.'.join(map(str, version_info))
| version_info = (0, 0, 5)
__version__ = '.'.join(map(str, version_info))
| mit | Python |
850222c22e46806157d3081c70d2852a866b3351 | change links() to global | lewangbtcc/anti-XSS,lewangbtcc/anti-XSS | getLink.py | getLink.py | #encoding: utf8
# links ia a global set that stroe all of the links in the particular domain.
links = set()
# Return a set of url links in src page
def getLink(src):
source = src.lower()
# links = set()
head = 0
length = len(source)
flag = True
while ((flag) and (head < length)):
flag ... | #encoding: utf8
# Return a set of url links in src page
def getLink(src):
source = src.lower()
links = set()
head = 0
length = len(source)
flag = True
while ((flag) and (head < length)):
flag = False
pos1 = source[head:].find('href="') + head
pos2 = source[pos1 + 7:].fin... | mit | Python |
d88b7876570cc2bd66a19a508f22f8e7e0501243 | use the default value of getattr.. | pivotal-energy-solutions/django-company-registration,pivotal-energy-solutions/django-company-registration | company_registration/tasks.py | company_registration/tasks.py | # -*- coding: utf-8 -*-
"""tasks.py: Django company_registration"""
import logging
from celery.schedules import crontab
from celery.task.base import periodic_task
from company_registration.models import RegistrationProfile
import settings
__author__ = 'Steven Klass'
__date__ = '1/9/13 2:56 PM'
__copyright__ = 'Copyr... | # -*- coding: utf-8 -*-
"""tasks.py: Django company_registration"""
import logging
from celery.schedules import crontab
from celery.task.base import periodic_task
from company_registration.models import RegistrationProfile
import settings
__author__ = 'Steven Klass'
__date__ = '1/9/13 2:56 PM'
__copyright__ = 'Copyr... | apache-2.0 | Python |
9c8af5537e9371bd4843dad066a0186fe4bb7ea3 | Revert "ignoring ball_lost_time" | bit-bots/bitbots_behaviour | bitbots_body_behavior/src/bitbots_body_behavior/decisions/goal_seen.py | bitbots_body_behavior/src/bitbots_body_behavior/decisions/goal_seen.py | import rospy
from dynamic_stack_decider.abstract_decision_element import AbstractDecisionElement
class GoalSeen(AbstractDecisionElement):
def __init__(self, blackboard, dsd, parameters=None):
super(GoalSeen, self).__init__(blackboard, dsd, parameters)
self.goal_lost_time = rospy.Duration(self.bla... | import rospy
from dynamic_stack_decider.abstract_decision_element import AbstractDecisionElement
class GoalSeen(AbstractDecisionElement):
def __init__(self, blackboard, dsd, parameters=None):
super(GoalSeen, self).__init__(blackboard, dsd, parameters)
self.goal_lost_time = rospy.Duration(self.bla... | bsd-3-clause | Python |
8759a164c82026e4dcb386fd9803da28e2c1c242 | Update Chapter07/PracticeQuestions/Question2.py added docstrings | JoseALermaIII/python-tutorials,JoseALermaIII/python-tutorials | books/CrackingCodesWithPython/Chapter07/PracticeQuestions/Question2.py | books/CrackingCodesWithPython/Chapter07/PracticeQuestions/Question2.py | """Chapter 7 Practice Question 2
Is each spam a global or local variable?
"""
spam = 42 # global/local
def foo() -> None:
"""Prints spam.
Prints the contents of the spam variable.
Returns:
Prints spam variable.
"""
global spam
spam = 99 # global/local
print(spam)
def main()... | # Is each spam a global or local variable?
spam = 42 # global/local
def foo():
global spam
spam = 99 # global/local
print(spam)
def main():
foo() # mind == blown
# If Question2.py is run (instead of imported as a module), call
# the main() function:
if __name__ == '__main__':
main()
| mit | Python |
2a024236ff6f50689d99e9cf327a7145ae08e0f6 | add portal db config | Cepave/dashboard,Cepave/dashboard,Cepave/dashboard,Cepave/dashboard | rrd/config.py | rrd/config.py | #-*-coding:utf8-*-
import os
import json
#-- dashboard db config --
DASHBOARD_DB_HOST = "127.0.0.1"
DASHBOARD_DB_PORT = 3306
DASHBOARD_DB_USER = "root"
DASHBOARD_DB_PASSWD = ""
DASHBOARD_DB_NAME = "dashboard"
#-- graph db config --
GRAPH_DB_HOST = "127.0.0.1"
GRAPH_DB_PORT = 3306
GRAPH_DB_USER = "root"
GRAPH_DB_PASSW... | #-*-coding:utf8-*-
import os
import json
#-- dashboard db config --
DASHBOARD_DB_HOST = "127.0.0.1"
DASHBOARD_DB_PORT = 3306
DASHBOARD_DB_USER = "root"
DASHBOARD_DB_PASSWD = ""
DASHBOARD_DB_NAME = "dashboard"
#-- graph db config --
GRAPH_DB_HOST = "127.0.0.1"
GRAPH_DB_PORT = 3306
GRAPH_DB_USER = "root"
GRAPH_DB_PASSW... | apache-2.0 | Python |
9b5975f92db327fe9fb5698ed9f512a03f0932c3 | Add instructions for running image analysis | tokee/juxta,tokee/juxta,tokee/juxta | gridify.py | gridify.py | # Prerequisites
#git clone git@github.com:ml4a/ml4a-ofx.git
#cd mla-ofx
#pip3 install keras
#pip3 install numpy
#pip3 install prime
# https://github.com/Quasimondo/RasterFairy
#pip3 install rasterfairy
# Run instructions
# put 300+ images in the folder 'images'
#python3 .scripts/tSNE-images.py --images_path images --... | import rasterfairy
import json
import numpy as np
import math
# Expects output from tSNE-images.py and runs rasterfairy on the input,
# writing the image paths layed out to a grid as the output
with open('/home/te/projects/ml4a-ofx/points.json') as json_file:
data = json.load(json_file)
arr = []
for tup in data:... | apache-2.0 | Python |
67bdac10aa9f38643339d73b437e43d5ae34be75 | Add StepFormSet inlineformset to forms.py | livingsilver94/getaride,livingsilver94/getaride,livingsilver94/getaride | planner/forms.py | planner/forms.py | from django.contrib.auth.forms import AuthenticationForm
from django import forms
from django.core.validators import MinLengthValidator
from .models import PoolingUser, Trip, Step
from users.forms import UserCreationForm
class LoginForm(AuthenticationForm):
username = forms.CharField(widget=forms.EmailInput(attrs... | from django.contrib.auth.forms import AuthenticationForm
from django import forms
from django.core.validators import MinLengthValidator
from .models import PoolingUser, Trip, Step
from users.forms import UserCreationForm
class LoginForm(AuthenticationForm):
username = forms.CharField(widget=forms.EmailInput(attrs... | mit | Python |
375e214d6cea559e94a6f0de2ce2fc05c3dea424 | add country to the feed | qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | corehq/apps/change_feed/management/commands/run_form_websocket_feed.py | corehq/apps/change_feed/management/commands/run_form_websocket_feed.py | from optparse import make_option
from django.core.management import BaseCommand
from django_countries.data import COUNTRIES
from corehq.apps.change_feed import topics
from corehq.apps.change_feed.consumer.feed import KafkaChangeFeed
from ws4redis.publisher import RedisPublisher
from ws4redis.redis_store import RedisMes... | from optparse import make_option
from django.core.management import BaseCommand
from corehq.apps.change_feed import topics
from corehq.apps.change_feed.consumer.feed import KafkaChangeFeed
from ws4redis.publisher import RedisPublisher
from ws4redis.redis_store import RedisMessage
import json
import time
class Command... | bsd-3-clause | Python |
12b8a94266411fc85f9566e25a4da2a9ca59a83d | Add setup sh scripts to handler.py | andreMonkey/camera_processing,andreMonkey/camera_processing,andreMonkey/camera_processing,andreMonkey/camera_processing | handler.py | handler.py | #!/usr/bin/env python
print("""
This example shows how you can monitor an analog input by attaching a function to its changed event.
You should see the analog value being printed out as it changes.
Try connecting up a rotary potentiometer or analog sensor to input one.
""")
from subprocess import call
import time
... | #!/usr/bin/env python
print("""
This example shows how you can monitor an analog input by attaching a function to its changed event.
You should see the analog value being printed out as it changes.
Try connecting up a rotary potentiometer or analog sensor to input one.
""")
from subprocess import call
import time
... | bsd-2-clause | Python |
9909064d4dfcf9c1ae72b906318cda7b736ad9d2 | correct log file location | PhillyDSA/phillydsa-com,PhillyDSA/phillydsa-com,PhillyDSA/phillydsa-com,PhillyDSA/phillydsa-com | config/settings/production.py | config/settings/production.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import os
import configparser
from django.core.exceptions import ImproperlyConfigured
from .base import * # noqa
DEBUG = False
ALLOWED_HOSTS = ['127.0.0.1']
config = configparser.ConfigParser()
try:
config.read(os.path.join(BASE_... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import os
import configparser
from django.core.exceptions import ImproperlyConfigured
from .base import * # noqa
DEBUG = False
ALLOWED_HOSTS = ['127.0.0.1']
config = configparser.ConfigParser()
try:
config.read(os.path.join(BASE_... | agpl-3.0 | Python |
5722942e8c2898967d1ebc97e31c0cda5d39df3d | Improve security settings | FlowFX/reggae-cdmx,FlowFX/reggae-cdmx | config/settings/production.py | config/settings/production.py | from .common import *
ENVIRONMENT = 'production'
DEBUG = False
# Core settings
ALLOWED_HOSTS = ['.reggae-cdmx.com', ]
INTERNAL_IPS: list = []
# Security
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
# CSRF_USE_SESSIONS = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_SSL_REDIRECT = True # Force HTTPS
# St... | from .common import *
ENVIRONMENT = 'production'
DEBUG = False
# Core settings
ALLOWED_HOSTS = ['.reggae-cdmx.com', ]
INTERNAL_IPS: list = []
# Security
# CSRF_COOKIE_SECURE = True
# CSRF_USE_SESSIONS = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_SSL_REDIRECT = True # Force HTTPS
# Static files
STATIC_URL = '/s... | mit | Python |
5d46b0c7516451241037d6b46c66aa153b962b83 | update outip match | wangdiwen/ip2geo | ip2geo.py | ip2geo.py | #!/usr/bin/env python
# encoding=utf-8
import sys
import argparse
import requests
import urllib
import re
# parse the console params
parser = argparse.ArgumentParser()
parser.add_argument('domain', help='a domain like baidu.com | a ipv4 addr', type=str)
parser.add_argument('-v', help='show request detail info', actio... | #!/usr/bin/env python
# encoding=utf-8
import sys
import argparse
import requests
import urllib
import re
# parse the console params
parser = argparse.ArgumentParser()
parser.add_argument('domain', help='a domain like baidu.com | a ipv4 addr', type=str)
parser.add_argument('-v', help='show request detail info', actio... | mit | Python |
e818de96908e4ec6801d42e54c29036b3cc373b3 | Update denormalization command | barberscore/barberscore-api,dbinetti/barberscore-django,dbinetti/barberscore-django,barberscore/barberscore-api,dbinetti/barberscore,dbinetti/barberscore,barberscore/barberscore-api,barberscore/barberscore-api | project/apps/api/management/commands/denormalize.py | project/apps/api/management/commands/denormalize.py | from django.core.management.base import (
BaseCommand,
)
from apps.api.models import (
Convention,
Contest,
Award,
Contestant,
Entrant,
Session,
Performance,
Song,
Singer,
Director,
Panelist,
)
class Command(BaseCommand):
help = "Command to denormailze data."
... | from django.core.management.base import (
BaseCommand,
)
from apps.api.models import (
Convention,
Contest,
Contestant,
Performance,
Song,
Group,
Singer,
Director,
Panelist,
)
class Command(BaseCommand):
help = "Command to denormailze data."
def handle(self, *args, **... | bsd-2-clause | Python |
1dcee2da40eec36f049d501048b33be1208ef90b | fix a bug with import in DBFileSystemGC | yliu120/dbsystem,yliu120/dbsystem,yliu120/dbsystem | HW3/dbsys-hw3/DBFileSystemGC.py | HW3/dbsys-hw3/DBFileSystemGC.py | import os;
class DBFileSystemGC:
defaultDBPath = './data';
# close all the files in that directory.
def list_files(path):
# returns a list of names (with extension, without full path) of all files
# in folder path
files = []
for name in os.listdir(path):
if os.path.isfile(os.path.joi... | from Database import Database
from Catalog.Schema import DBSchema
import os;
class DBFileSystemGC:
defaultDBPath = './data';
# close all the files in that directory.
def list_files(path):
# returns a list of names (with extension, without full path) of all files
# in folder path
files = []
... | apache-2.0 | Python |
51ea9b839c1ef4b9150da3fb35d4a0be4799674b | Update denormalization command | dbinetti/barberscore,barberscore/barberscore-api,barberscore/barberscore-api,dbinetti/barberscore,barberscore/barberscore-api,dbinetti/barberscore-django,barberscore/barberscore-api,dbinetti/barberscore-django | project/apps/api/management/commands/denormalize.py | project/apps/api/management/commands/denormalize.py | from django.core.management.base import (
BaseCommand,
)
from apps.api.models import (
Award,
Certification,
Chapter,
Chart,
Contest,
Contestant,
Convention,
Group,
Judge,
Member,
Organization,
Performance,
Performer,
Person,
Role,
Round,
Score,
... | from django.core.management.base import (
BaseCommand,
)
from apps.api.models import (
Award,
Certification,
Chapter,
Chart,
Contest,
Contestant,
Convention,
Group,
Judge,
Member,
Organization,
Performance,
Performer,
Person,
Role,
Round,
Score,
... | bsd-2-clause | Python |
86c213ab74853aaad620f31d0fabd45f9e61a7df | Remove messaging - it's too noisy. | FreddieSanchez/RunnitAutoMod | runnit-bot.py | runnit-bot.py | """
This script is used to helpout AutoMod on some things it can't do.
"""
import datetime
import os,sys
import praw
import logging
import re
import sched, time
USERNAME=os.environ['USER']
PASSWORD=os.environ['PASSWORD']
AUTHOR=os.environ['AUTHOR']
CommentsRemoved = set();
def login():
r = praw.Reddit('RunnitAuto... | """
This script is used to helpout AutoMod on some things it can't do.
"""
import datetime
import os,sys
import praw
import logging
import re
import sched, time
USERNAME=os.environ['USER']
PASSWORD=os.environ['PASSWORD']
AUTHOR=os.environ['AUTHOR']
CommentsRemoved = set();
def login():
r = praw.Reddit('RunnitAuto... | mit | Python |
ee3941e2c3a0355314b270c04de6a623f5a0730c | Add statistics about general speaking | thomasleese/smartbot-old,Cyanogenoid/smartbot,tomleese/smartbot,Muzer/smartbot | plugins/stats.py | plugins/stats.py | import operator
class Plugin:
def __call__(self, bot):
bot.on_hear(r".*", self.on_hear_anything)
bot.on_hear(r"(lol|:D|:P)", self.on_hear)
bot.on_respond(r"stats", self.on_respond)
bot.on_help("stats", self.on_help)
def on_hear_anything(self, bot, msg, reply):
stats = b... | import operator
class Plugin:
def __call__(self, bot):
bot.on_hear(r"(lol|:D|:P)", self.on_hear)
bot.on_respond(r"stats", self.on_respond)
bot.on_help("stats", self.on_help)
def on_hear(self, bot, msg, reply):
stats = bot.storage.get("stats", {})
for word in msg["match... | mit | Python |
02f157652f5b93a5f8c7af8ad6e4caf31f038192 | bump version and fix logging issues | mistermatti/plugz,mistermatti/plugz | plugz/loading.py | plugz/loading.py | import os
import sys
import inspect
from collections import defaultdict
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
from plugz import PluginTypeBase
import errors
""" Main storage of the plugins."""
_loaded_plugins = defaultdict(list)
def register_plugin(f):
"""... | import os
import sys
import inspect
from collections import defaultdict
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
from plugz import PluginTypeBase
import errors
""" Main storage of the plugins."""
_loaded_plugins = defaultdict(list)
def register_plugin(f):
"""... | bsd-3-clause | Python |
d34f8e7a68b3c3b8023ac298f31a2ff52595ed80 | Fix some encoding problems | sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer | documents/management/commands/clean_old_versions.py | documents/management/commands/clean_old_versions.py | import shutil, tempfile, os, csv
from optparse import make_option
from daisyproducer.documents.models import Document
from django.core.management.base import BaseCommand
from django.utils.encoding import smart_str
class Command(BaseCommand):
args = ''
help = 'Clean out old versions from the database and the f... | import shutil, tempfile, os, csv
from optparse import make_option
from daisyproducer.documents.models import Document
from django.core.management.base import BaseCommand
class Command(BaseCommand):
args = ''
help = 'Clean out old versions from the database and the file system'
option_list = BaseCommand.o... | agpl-3.0 | Python |
517f9062be966c4374f2efbdfb636872f45024bd | remove https from redirect middleware | blcook223/bencook.info,blcook223/bencook.info,blcook223/bencook.info,blcook223/bencook.info | core/middleware.py | core/middleware.py | """
Middleware for core app.
"""
from django.contrib.sites.models import Site
from django.http import HttpResponsePermanentRedirect
from django.core.urlresolvers import resolve
from django.core import urlresolvers
from django.utils.http import urlquote
# http://eikke.com/django-domain-redirect-middleware/
class Doma... | """
Middleware for core app.
"""
from django.contrib.sites.models import Site
from django.http import HttpResponsePermanentRedirect
from django.core.urlresolvers import resolve
from django.core import urlresolvers
from django.utils.http import urlquote
# http://eikke.com/django-domain-redirect-middleware/
class Doma... | isc | Python |
d9b3f20eba5a18cffc9ae2022a22c06be5880bf5 | Update admin.py | ulule/django-courriers,ulule/django-courriers | courriers/admin.py | courriers/admin.py | from django.contrib import admin
from django.conf.urls.defaults import patterns, url
from django.shortcuts import get_object_or_404
from django.utils.translation import ugettext as _
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from .models import Newsletter, NewsletterItem... | from django.contrib import admin
from django.conf.urls.defaults import patterns, url
from django.shortcuts import get_object_or_404
from django.utils.translation import ugettext as _
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from .models import Newsletter, NewsletterItem... | mit | Python |
2d4cce26f8b6c45b0c92783475285273e6a0722c | Allow hardcoded error headers per #10 | nullism/pycnic,nullism/pycnic | pycnic/errors.py | pycnic/errors.py | from .data import STATUSES
class PycnicError(Exception):
pass
class HTTPError(PycnicError):
status_code = 0
status = None
message = None
data = None
headers = None
def __init__(self, status_code, message, data=None, headers=[]):
if self.status_code:
status_code = self.... | from .data import STATUSES
class PycnicError(Exception):
pass
class HTTPError(PycnicError):
status_code = 0
status = None
message = None
data = None
headers = None
def __init__(self, status_code, message, data=None, headers=[]):
if self.status_code:
status_code = self.... | mit | Python |
f6ff634bc532585fefb7c30d33709857f6b6d336 | add kepsff to init | gully/PyKE,christinahedges/PyKE | pyke/__init__.py | pyke/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
PACKAGEDIR = os.path.abspath(os.path.dirname(__file__))
from .version import __version__
from .keparray import *
from .kepbls import *
from .kepclip import *
from .kepconvert import *
from .kepcotrend import *
from .kepdetre... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
PACKAGEDIR = os.path.abspath(os.path.dirname(__file__))
from .version import __version__
from .keparray import *
from .kepbls import *
from .kepclip import *
from .kepconvert import *
from .kepcotrend import *
from .kepdetre... | mit | Python |
5260a603965dbe5a36d6b1737692c5fd093b7944 | Make kmer positions 1-offset. | drtconway/pykmer | pykmer/basics.py | pykmer/basics.py | from pykmer.bits import ffs, rev, popcnt, m1
nuc = { 'A':0, 'a':0, 'C':1, 'c':1, 'G':2, 'g':2, 'T':3, 't':3 }
def kmer(seq):
"Turn a string in to an integer k-mer"
r = 0
for c in seq:
if c not in nuc:
return None
r = (r << 2) | nuc[c]
return r
def render(k, x):
"Turn a... | from pykmer.bits import ffs, rev, popcnt, m1
nuc = { 'A':0, 'a':0, 'C':1, 'c':1, 'G':2, 'g':2, 'T':3, 't':3 }
def kmer(seq):
"Turn a string in to an integer k-mer"
r = 0
for c in seq:
if c not in nuc:
return None
r = (r << 2) | nuc[c]
return r
def render(k, x):
"Turn a... | apache-2.0 | Python |
cf0223f6a725641431fa9f704cab47d96d4783a2 | Add method for parsing articles from archive | HIIT/mediacollection | sites/ksml.py | sites/ksml.py | # -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
import processor
from datetime import datetime
def parse( url ):
r = requests.get( url )
if r.status_code == 404:
return processor.create_dictionary('', url, r.status_code, [u''], [u''], u'', u'', u'', u'', [u''], [u''])
r.encoding = 'UTF-8'... | # -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
import processor
from datetime import datetime
def parse( url ):
r = requests.get( url )
if r.status_code == 404:
return processor.create_dictionary('', url, r.status_code, [u''], [u''], u'', u'', u'', u'', [u''], [u''])
r.encoding = 'UTF-8'... | mit | Python |
25904df895e495570d8fab05619809c84b7d45e1 | Comment B Combinator | esehara/skiski | skiski/bfc.py | skiski/bfc.py | from ski import S, K, I
from helper import Typename
class B(metaclass=Typename("B")):
"""
which composes two function
>>> B(lambda x: x).dot(lambda x: x + 5).dot(5).b()
10
"""
is_class = True
def __init__(self, x):
self.x = x
self.is_class = False
def dot(self, y):
... | from ski import S, K, I
from helper import Typename
class B(metaclass=Typename("B")):
is_class = True
def __init__(self, x):
self.x = x
self.is_class = False
def dot(self, y):
return B2(self.x, y)
def __str__(self):
return "(B " + str(self.x) + ")"
def __repr__(... | mit | Python |
13981e78604234a0f736d52e5d1dacc92e95882b | update system encoding | antoine-tran/Wikisearch-example | python/search.py | python/search.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interface to ElasticSearch for serving search requests
#
# Tuan Tran (ttran@l3s.de)
#
import sys
from sys import argv
from conn import connect,close as es_close
QUERY = { "query":{ "multi_match" : {"query": "%s", "fields": [ "text", "title", "contributor" ]}}}
def si... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interface to ElasticSearch for serving search requests
#
# Tuan Tran (ttran@l3s.de)
#
import sys
from sys import argv
from conn import connect,close as es_close
QUERY = { "query":{ "multi_match" : {"query": "%s", "fields": [ "text", "title", "contributor" ]}}}
def si... | apache-2.0 | Python |
6333ccb825b026bdb805672ff14f99123d8a381e | remove gen | connyay/speed,connyay/speed | python/server.py | python/server.py | import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
application = tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.current().start()
| import tornado.ioloop
import tornado.web
from tornado import gen
class MainHandler(tornado.web.RequestHandler):
@gen.coroutine
def get(self):
self.write("Hello, world")
application = tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
application.listen(8888)
tor... | mit | Python |
2ac0509e6a6e1a92ee04def45cf502664b1bd101 | Fix storemagic test for new alias API | ipython/ipython,ipython/ipython | IPython/extensions/tests/test_storemagic.py | IPython/extensions/tests/test_storemagic.py | import tempfile, os
from IPython.config.loader import Config
import nose.tools as nt
ip = get_ipython()
ip.magic('load_ext storemagic')
def test_store_restore():
ip.user_ns['foo'] = 78
ip.magic('alias bar echo "hello"')
tmpd = tempfile.mkdtemp()
ip.magic('cd ' + tmpd)
ip.magic('store foo')
ip... | import tempfile, os
from IPython.config.loader import Config
import nose.tools as nt
ip = get_ipython()
ip.magic('load_ext storemagic')
def test_store_restore():
ip.user_ns['foo'] = 78
ip.magic('alias bar echo "hello"')
tmpd = tempfile.mkdtemp()
ip.magic('cd ' + tmpd)
ip.magic('store foo')
ip... | bsd-3-clause | Python |
18a6b18f6668a059dcc337c7ab175497f1448a29 | Update honeypot.py | FabioChiodini/HoneypotCF | honeypot.py | honeypot.py | from flask import Flask, jsonify, request
import os
import requests
from pprint import pprint
import json
import logging
import logstash
#added this K
#from cfenv import AppEnv
#added this K
#env = AppEnv()
#env.LOG_HOST # 'test-app'
#env.LOG_PORT # 5000
if 'LOG_HOST' not in os.environ or 'LOG_PORT' not in os.envi... | from flask import Flask, jsonify, request
import os
import requests
from pprint import pprint
import json
import logging
import logstash
#added this K
#from cfenv import AppEnv
#added this K
#env = AppEnv()
#env.LOG_HOST # 'test-app'
#env.LOG_PORT # 5000
if 'LOG_HOST' not in os.environ or 'LOG_PORT' not in os.envi... | mit | Python |
e40736c1055747cab45adb8ce6a511b9889000fd | test case for quotation | Aptitudetech/ERPNext,indictranstech/erpnext,gsnbng/erpnext,njmube/erpnext,anandpdoshi/erpnext,geekroot/erpnext,anandpdoshi/erpnext,njmube/erpnext,gsnbng/erpnext,geekroot/erpnext,geekroot/erpnext,anandpdoshi/erpnext,geekroot/erpnext,gsnbng/erpnext,indictranstech/erpnext,anandpdoshi/erpnext,njmube/erpnext,njmube/erpnext,... | erpnext/selling/doctype/quotation/test_quotation.py | erpnext/selling/doctype/quotation/test_quotation.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe, json
from frappe.utils import flt
import unittest
test_dependencies = ["Product Bundle"]
class TestQuotation(unittest.TestCase):
def t... | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe, json
from frappe.utils import flt
import unittest
test_dependencies = ["Product Bundle"]
class TestQuotation(unittest.TestCase):
def t... | agpl-3.0 | Python |
5efca5a3e8fb978cb47e986b1bd7296fe2cae3ce | Add some spaces to get_list_as_english | hawkrives/gobbldygook,hawkrives/gobbldygook,hawkrives/gobbldygook | helpers.py | helpers.py | def get_readable_list(passed_list, sep=', '):
output = ""
for i, item in enumerate(passed_list):
if len(passed_list) is 1:
output += str(item)
else:
if i is not (len(passed_list) - 1):
output += str(item) + sep
else:
output += str(item)
return output
def get_list_as_english(passed_list):
ou... | def get_readable_list(passed_list, sep=', '):
output = ""
for i, item in enumerate(passed_list):
if len(passed_list) is 1:
output += str(item)
else:
if i is not (len(passed_list) - 1):
output += str(item) + sep
else:
output += str(item)
return output
def get_list_as_english(passed_list):
ou... | agpl-3.0 | Python |
05de768e2b62cec0808f9bd6530f82984e9ad438 | Define resource, send the transport to the resource as a parameter | harrissoerja/vumi,harrissoerja/vumi,vishwaprakashmishra/xmatrix,TouK/vumi,harrissoerja/vumi,TouK/vumi,vishwaprakashmishra/xmatrix,vishwaprakashmishra/xmatrix,TouK/vumi | vumi/transports/mtn_rwanda/mtn_rwanda_ussd.py | vumi/transports/mtn_rwanda/mtn_rwanda_ussd.py | from twisted.internet import reactor
from twisted.web import xmlrpc, server
from twisted.internet.defer import inlineCallbacks
from vumi import log
from vumi.transports.base import Transport
from vumi.config import ConfigText
class MTNRwandaUSSDTransportConfig(Transport.CONFIG_CLASS):
"""
MTN Rwanda USSD tra... | from twisted.internet import reactor
from twisted.web import xmlrpc, server
from vumi import log
from vumi.transports.base import Transport
from vumi.config import ConfigText
class MTNRwandaUSSDTransportConfig(Transport.CONFIG_CLASS):
"""
MTN Rwanda USSD transport configuration.
"""
# TODO: Configure... | bsd-3-clause | Python |
9ebd20e98bc196885885fd8cdfc121f170fd0fa2 | make command_line.py actually work as a standalone wrapper | MatthewCox/colour-valgrind | colourvalgrind/command_line.py | colourvalgrind/command_line.py | #!/usr/bin/env python
from colourvalgrind import colour_valgrind
import argparse
import subprocess
import sys
def main():
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("-t", "--test",
help="valgrind log file to run through colour filters",
... | #!/usr/bin/env python
from colourvalgrind import colour_valgrind
def main():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input",
help="valgrind log file to run through colour filters",
required=True)
args = parser.pars... | mit | Python |
f081cddddc4bc92775afb152aba22b2b5245a164 | fix errors reported by http://validator.w3.org/ | ellson/graphviz-web-static,MjAbuz/graphviz-web-static,ellson/graphviz-web-static,MjAbuz/graphviz-web-static,MjAbuz/graphviz-web-static,ellson/graphviz-web-static | ht2html.py | ht2html.py | #!/usr/bin/python
import sys
if len(sys.argv) < 2:
exit
pageset = sys.argv[1].split()
source = sys.argv[2]
basename = source.split('.')[0]
fout = open(basename + '.html', 'w')
fout.write('''<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!--
This is a generated document. Please edit "''' + ... | #!/usr/bin/python
import sys
if len(sys.argv) < 2:
exit
pageset = sys.argv[1].split()
source = sys.argv[2]
basename = source.split('.')[0]
fout = open(basename + '.html', 'w')
fout.write('''<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!--
This is a generated document. Please edit "''' + ... | epl-1.0 | Python |
590e27f30cb58da535b8cd6bc0e9e48011409a18 | Add reference to actual bug | tmobile/jazz-installer,tmobile/jazz-installer,tmobile/jazz-installer,tmobile/jazz-installer | feature-extensions/apigee/terraformBugWorkaround.py | feature-extensions/apigee/terraformBugWorkaround.py | import json
import subprocess
# Exists because of:
# https://github.com/terraform-providers/terraform-provider-aws/issues/5742
# and can be nuked if that is ever fixed.
terraformNewGatewayRoleOutput = "apigee-lambda-gateway-role-arn"
terraformPreviousRoleOutput = "previous-role-arn"
# Replaces function's role with ... | import json
import subprocess
terraformNewGatewayRoleOutput = "apigee-lambda-gateway-role-arn"
terraformPreviousRoleOutput = "previous-role-arn"
# Replaces function's role with one created by Terraform
def linkNewRoleToExistingFunctionWithCLI(functionName):
updateFunctionRole(functionName, getRoleArnFromTerrafo... | apache-2.0 | Python |
fd237a2208c419ade371640f947dcc9c70af344c | add get parameters function | shl198/Projects,shl198/Projects,shl198/Projects,shl198/Pipeline,shl198/Pipeline,shl198/Projects,shl198/Pipeline,shl198/Pipeline | Modules/FileProcess.py | Modules/FileProcess.py | import subprocess
def remove(files):
"""
this function can remove files provided
"""
if isinstance(files,str):
subprocess.call('rm {file}'.format(file=files),shell=True)
if isinstance(files,list):
cmd = ''
for f in files:
cmd = cmd + 'rm {file} & '.format(file=f)
... | import subprocess
def remove(files):
"""
this function can remove files provided
"""
if isinstance(files,str):
subprocess.call('rm {file}'.format(file=files),shell=True)
if isinstance(files,list):
cmd = ''
for f in files:
cmd = cmd + 'rm {file} & '.format(file=f)
... | mit | Python |
f431943bf8f94f8fe5229c8c55e9d341bb417015 | fix for issue #11 | arq5x/poretools,arq5x/poretools | poretools/formats.py | poretools/formats.py | class Fastq(object):
def __init__(self, s):
self.s = s
self.parse()
def parse(self):
(self.name, self.seq, self.sep, self.qual) = self.s.strip().split('\n')
def __repr__(self):
return '\n'.join([self.name, self.seq, self.sep, self.qual])
class Fasta(object):
def __init__(self, s):
self.s = s
self.pa... | class Fastq(object):
def __init__(self, s):
self.s = s
self.parse()
def parse(self):
(self.name, self.seq, self.sep, self.qual) = self.s.strip().split('\n')
def __repr__(self):
return '\n'.join([self.name, self.seq, self.sep, self.qual])
class Fasta(object):
def __init__(self, s):
self.s = s
self.pa... | mit | Python |
f591fa8d337db4487d4485f943aef67c97e49b30 | Fix about.py | Akuli/the-simple-noteprogram,Akuli/the-simple-noteprogram | install-prefix/lib/the-simple-noteprogram/the_simple_noteprogram/about.py | install-prefix/lib/the-simple-noteprogram/the_simple_noteprogram/about.py | """An about dialog and information about this program"""
from gettext import gettext as _
# Information about authors, add your name here if you've helped with
# making this program but your name is not here yet
AUTHORS = ["Akuli"]
TRANSLATORS = {
_("Finnish"): "Akuli",
}
# General information
SHORT_DESCRIPTION =... | """An about dialog and information about this program"""
from gettext import gettext as _
# Information about authors, add your name here if you've helped with
# making this program but your name is not here yet
AUTHORS = ["Akuli"]
TRANSLATORS = {
_("Finnish"): "Akuli",
}
# General information
SHORT_DESCRIPTION =... | mit | Python |
2d92120b292f23bcd3c927e50d2be4bf27616722 | fix mistake in template tag | saippuakauppias/django-simple-open-graph | simple_open_graph/templatetags/simple_open_graph.py | simple_open_graph/templatetags/simple_open_graph.py | from django import template
from ..utils import string_to_dict
register = template.Library()
@register.tag
def opengraph_meta(parser, token):
try:
tag_name, properties = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError(
"%r tag requires two arguments"... | from django import template
from ..utils import string_to_dict
register = template.Library()
@register.tag
def opengraph_meta(parser, token):
try:
tag_name, properties = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError(
"%r tag requires two arguments"... | isc | Python |
f2fd7fa693b5be7ae37445fc185611e80aacddf3 | Fix bug to actually find the sdk | pebble/libpebble,pebble/libpebble,pebble/libpebble,pebble/libpebble | pebble/PblBuildCommand.py | pebble/PblBuildCommand.py | import sh, os
from PblCommand import PblCommand
class PblBuildCommand(PblCommand):
name = 'build'
help = 'Build your Pebble project'
def configure_subparser(self, parser):
parser.add_argument('--sdk', help='Path to Pebble SDK (ie: ~/pebble-dev/PebbleSDK-2.X/)')
def run(self, args):
waf_path = os.path... | import sh, os
from PblCommand import PblCommand
class PblBuildCommand(PblCommand):
name = 'build'
help = 'Build your Pebble project'
def configure_subparser(self, parser):
parser.add_argument('--sdk', help='Path to Pebble SDK (ie: ~/pebble-dev/PebbleSDK-2.X/)')
def run(self, args):
waf_path = os.path... | mit | Python |
09450c14e4d3cdfb645e1284eaf80350204a6f9e | fix warning | galaxy-genome-annotation/python-apollo,erasche/python-apollo,galaxy-genome-annotation/python-apollo | arrow/config.py | arrow/config.py | from __future__ import absolute_import
import os
import yaml
DEFAULT_CONFIG = {
}
def global_config_path():
config_path = os.environ.get(
"ARROW_GLOBAL_CONFIG_PATH",
"~/.apollo-arrow.yml"
)
config_path = os.path.expanduser(config_path)
return config_path
def read_global_config():
... | from __future__ import absolute_import
import os
import yaml
DEFAULT_CONFIG = {
}
def global_config_path():
config_path = os.environ.get(
"ARROW_GLOBAL_CONFIG_PATH",
"~/.apollo-arrow.yml"
)
config_path = os.path.expanduser(config_path)
return config_path
def read_global_config():
... | mit | Python |
ade326e47be07abb634c61632aa913b641780a59 | fix the field names in serializers | jonboiser/content-curation,jayoshih/content-curation,DXCanas/content-curation,fle-internal/content-curation,jayoshih/content-curation,fle-internal/content-curation,DXCanas/content-curation,aronasorman/content-curation,jonboiser/content-curation,fle-internal/content-curation,DXCanas/content-curation,jonboiser/content-cu... | contentcuration/contentcuration/serializers.py | contentcuration/contentcuration/serializers.py | from contentcuration.models import * # TODO: Change this later?
from rest_framework import serializers
from rest_framework_bulk import BulkListSerializer, BulkSerializerMixin
class LicenseSerializer(serializers.ModelSerializer):
class Meta:
model = License
fields = ('license_name', 'exists', 'i... | from contentcuration.models import * # TODO: Change this later?
from rest_framework import serializers
from rest_framework_bulk import BulkListSerializer, BulkSerializerMixin
class LicenseSerializer(serializers.ModelSerializer):
class Meta:
model = License
fields = ('license_name', 'exists', 'i... | mit | Python |
c961b2bde6f5ca13888d2eeae2ba0bdaf8e494f9 | Fix homepage migration | ljean/coop_cms,ljean/coop_cms,ljean/coop_cms | coop_cms/migrations/0004_auto_20160620_1310.py | coop_cms/migrations/0004_auto_20160620_1310.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.core.urlresolvers import reverse
def set_homepage(apps, schema_editor):
# Move from homepage_for_site to SiteSettings
site_class = apps.get_model("sites", "Site")
for site in site_class.obj... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
def set_homepage(apps, schema_editor):
# We can't import the Person model directly as it may be a newer
# version than this migration expects. We use the historical version.
site_class = apps.get_mode... | bsd-3-clause | Python |
e8a28f4bda8092e8b8ad3ee8ee0bfaac200e3334 | Update plot_regress_continuous.py | cjayb/mne-python,olafhauk/mne-python,antiface/mne-python,cjayb/mne-python,larsoner/mne-python,larsoner/mne-python,bloyl/mne-python,alexandrebarachant/mne-python,drammock/mne-python,mne-tools/mne-python,wmvanvliet/mne-python,drammock/mne-python,mne-tools/mne-python,adykstra/mne-python,olafhauk/mne-python,leggitta/mne-py... | examples/stats/plot_regress_continuous.py | examples/stats/plot_regress_continuous.py | """
=========================================
Regression on continuous data (rER[P/F])
=========================================
This demonstrates how rERPs/regressing the continuous data is a
generalisation of traditional averaging. If all preprocessing steps
are the same and if no overlap between epochs exists and if... | """
=========================================
Regression on continuous data (rER[P/F])
=========================================
This demonstrates how rERPs/regressing the continuous data is a
generalisation of traditional averaging. If all preprocessing steps
are the same and if no overlap between epochs exists and if... | bsd-3-clause | Python |
b3f9583047c93aa0c07529a53c1bec6ec3820196 | Make image.Image class abstract | alvarolopez/atrope | atrope/image.py | atrope/image.py | # -*- coding: utf-8 -*-
# Copyright 2014 Alvaro Lopez Garcia
#
# 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 ... | # -*- coding: utf-8 -*-
# Copyright 2014 Alvaro Lopez Garcia
#
# 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 ... | apache-2.0 | Python |
173ec0e1488cc4697ec8ca949433d7f49a216344 | fix bug | spencerpomme/coconuts-on-fire,spencerpomme/coconuts-on-fire,spencerpomme/coconuts-on-fire,spencerpomme/coconuts-on-fire,spencerpomme/coconuts-on-fire,spencerpomme/coconuts-on-fire | auto_upgrade.py | auto_upgrade.py | #! /usr/local/bin/python3
# can not be used on windows due to line end difference.
import pip
from subprocess import call
for dist in pip.get_installed_distributions():
call("pip3 install --upgrade --no-cache-dir " + dist.project_name, shell=True)
| #! /usr/local/bin/python3
# can not be used on windows due to line end difference.
import pip
from subprocess import call
for dist in pip.get_installed_distributions():
call("pip3 install --upgrade --no-cache-dir" + dist.project_name, shell=True)
| apache-2.0 | Python |
9d401d7f68c3b145f73bd7ec029361e1e85d6483 | Fix import order | thinkopensolutions/server-tools,thinkopensolutions/server-tools | external_file_location/models/__init__.py | external_file_location/models/__init__.py | # -*- coding: utf-8 -*-
from . import task
from . import attachment
from . import location
| # -*- coding: utf-8 -*-
from . import attachment
from . import location
from . import task
| agpl-3.0 | Python |
3309450ca3cc410626c98e7c599817c54f8d30b3 | Remove unused import | faide/py3o.template,faide/py3o.template | py3o/template/tests/test_templates.py | py3o/template/tests/test_templates.py | __author__ = 'faide'
import unittest
from py3o.template.main import Template
import lxml.etree
import pkg_resources
from pyjon.utils import get_secure_filename
import zipfile
from io import BytesIO
import os
from lxml.etree import XMLSyntaxError
class TestTemplate(unittest.TestCase):
def tearDown(self):
... | __author__ = 'faide'
import unittest
from py3o.template.main import move_siblings
from py3o.template.main import Template
import lxml.etree
import pkg_resources
from pyjon.utils import get_secure_filename
import zipfile
from io import BytesIO
import os
from lxml.etree import XMLSyntaxError
class TestTemplate(unittes... | mit | Python |
d133913d11e5384eddc472bda63ca781d3adc532 | Handle basic ISBN | rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism | python/isbn-verifier/isbn_verifier.py | python/isbn-verifier/isbn_verifier.py | class IsbnVerifier(object):
def __init__(self, string):
self.string = string
def is_valid(self):
sum_so_far = 0
for i, c in enumerate(IsbnVerifier.remove_slashes(self.string)):
sum_so_far += IsbnVerifier.convert_char_to_int(c) * (10 - i)
return sum_so_far % 11 == 0
... | class IsbnVerifier(object):
def __init__(self, string):
self.string = string
def is_valid(self):
return True
def verify(isbn):
return IsbnVerifier(isbn).is_valid()
| mit | Python |
7a116c18ae8d63a18d646aed899b3f21893501c6 | Update Python 2 deprecation error message | JohnSnowLabs/spark-nlp,JohnSnowLabs/spark-nlp,JohnSnowLabs/spark-nlp,JohnSnowLabs/spark-nlp | python/sparknlp/annotator/__init__.py | python/sparknlp/annotator/__init__.py | # Copyright 2017-2022 John Snow Labs
#
# 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... | # Copyright 2017-2022 John Snow Labs
#
# 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... | apache-2.0 | Python |
e19b93477ab8d8d7def9561076e69eff43bf2ca6 | Sort the archive box so most recent year is at the top. | grundleborg/mesosphere | mesoblog/boxes.py | mesoblog/boxes.py | # This file contains the functions for MesoBoxes
# See mesobox/boxes.py for the enabling code.
from mesoblog.models import Article, Category
import calendar
import functools
BOX_INCLUDES = (
'categories',
'dates',
)
def categories(request):
result = {}
if request.resolver_match.app_name is "m... | # This file contains the functions for MesoBoxes
# See mesobox/boxes.py for the enabling code.
from mesoblog.models import Article, Category
import calendar
BOX_INCLUDES = (
'categories',
'dates',
)
def categories(request):
result = {}
if request.resolver_match.app_name is "mesoblog":
... | mit | Python |
a5753a6665bcddf71a892f47bc393da322e21cce | Remove ugettext import | otto-torino/django-baton,otto-torino/django-baton,otto-torino/django-baton | baton/config.py | baton/config.py | # -*- coding: utf-8 -*-
from django.conf import settings
from django.utils.html import mark_safe
from django.utils.translation import gettext as _
default_config = {
'SITE_TITLE': 'Baton',
'SITE_HEADER': '<img src="%sbaton/img/logo.png" />' % settings.STATIC_URL,
'INDEX_TITLE': _('Site administration'),
... | # -*- coding: utf-8 -*-
from django.conf import settings
from django.utils.html import mark_safe
from django.utils.translation import ugettext as _
default_config = {
'SITE_TITLE': 'Baton',
'SITE_HEADER': '<img src="%sbaton/img/logo.png" />' % settings.STATIC_URL,
'INDEX_TITLE': _('Site administration'),
... | mit | Python |
6ccdada25f8b6c0e38955e955efb235aea9945ee | Refactor testing console exporter (#2877) | open-telemetry/opentelemetry-python,open-telemetry/opentelemetry-python | opentelemetry-sdk/tests/metrics/integration_test/test_console_exporter.py | opentelemetry-sdk/tests/metrics/integration_test/test_console_exporter.py | # Copyright The OpenTelemetry 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 agreed to in ... | # Copyright The OpenTelemetry 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 agreed to in ... | apache-2.0 | Python |
f39006397687ba071e89c3ab6dd16cce33235ca4 | fix the css rules conversion for if-config='' | huubbouma/diazo,huubbouma/diazo,ebrehault/diazo,ebrehault/diazo,huubbouma/diazo,ebrehault/diazo | lib/xdv/cssrules.py | lib/xdv/cssrules.py | #!/usr/bin/env python
"""\
Usage: %prog RULES
RULES is a file defining a set of xdv rules in css syntax, e.g:
<rules xmlns="http://namespaces.plone.org/xdv"
xmlns:css="http://namespaces.plone.org/xdv+css">
<copy css:content="#content-wrapper" css:theme="#page-content"/>
</rules>\
"""
usage = __doc__
fr... | #!/usr/bin/env python
"""\
Usage: %prog RULES
RULES is a file defining a set of xdv rules in css syntax, e.g:
<rules xmlns="http://namespaces.plone.org/xdv"
xmlns:css="http://namespaces.plone.org/xdv+css">
<copy css:content="#content-wrapper" css:theme="#page-content"/>
</rules>\
"""
usage = __doc__
fr... | bsd-3-clause | Python |
e03b3d35858fc70ffbc1441321acd1166470c542 | Format code using black | tensorflow/cloud,tensorflow/cloud | src/python/tensorflow_cloud/core/tests/examples/multi_file_example/scale_model.py | src/python/tensorflow_cloud/core/tests/examples/multi_file_example/scale_model.py | # Copyright 2020 Google LLC. 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 applicable ... | # Copyright 2020 Google LLC. 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 applicable ... | apache-2.0 | Python |
7ebee43c0461c79d97d3023c0e404298c641c896 | update notebooks | sdpython/pyrsslocal,sdpython/pyrsslocal,sdpython/pyrsslocal | _unittests/ut_module/test_convert_notebooks.py | _unittests/ut_module/test_convert_notebooks.py | """
@brief test log(time=0s)
"""
import sys
import os
import unittest
try:
import src
except ImportError:
path = os.path.normpath(
os.path.abspath(
os.path.join(
os.path.split(__file__)[0],
"..",
"..")))
if path not in sys.path:
... | """
@brief test log(time=0s)
"""
import sys
import os
import unittest
try:
import src
except ImportError:
path = os.path.normpath(
os.path.abspath(
os.path.join(
os.path.split(__file__)[0],
"..",
"..")))
if path not in sys.path:
... | mit | Python |
4f8cf6c7349f7596a19d35e30af3c21491b00d03 | Add docstring | NUinfolab/context,NUinfolab/context,Pantsworth/political-pundits,NUinfolab/context,Pantsworth/political-pundits,Pantsworth/political-pundits,Pantsworth/political-pundits,NUinfolab/context | web/session.py | web/session.py | """
Flask session utilities
"""
import flask
def session_get(key):
return flask.session.get(key)
def session_set(key, value):
flask.session.permanent = True # Safari seems to need this
flask.session[key] = value
def session_pop(key):
if key in flask.session:
flask.session.pop(key)
de... | #
# per-app session management
#
import flask
def session_get(key):
return flask.session.get(key)
def session_set(key, value):
flask.session.permanent = True # Safari seems to need this
flask.session[key] = value
def session_pop(key):
if key in flask.session:
flask.session.pop(key)
... | mit | Python |
5a21917049397e3414d55a739aa295a9d15322a7 | add comments | pranavj1001/LearnLanguages,pranavj1001/LearnLanguages,pranavj1001/LearnLanguages,pranavj1001/LearnLanguages,pranavj1001/LearnLanguages,pranavj1001/LearnLanguages,pranavj1001/LearnLanguages | python/SearchAlgorithms/SequentialSearch/Sequential.py | python/SearchAlgorithms/SequentialSearch/Sequential.py | # method to search for an element in an unordered list
def sequential_search_unordered_list(array, element):
pos = 0
found = False
while pos < len(array) and not found:
if array[pos] == element:
found = True
else:
pos += 1
return found
unordered_list = [1, 65... | def sequential_search_unordered_list(array, element):
pos = 0
found = False
while pos < len(array) and not found:
if array[pos] == element:
found = True
else:
pos += 1
return found
unordered_list = [1, 65, 37, 49, 52]
print(sequential_search_unordered_list(un... | mit | Python |
eb9b540d97d1538668ccc198717c73fd1f806719 | Fix registration command to comply with virtualenvs. | dgnorth/drift,dgnorth/drift,dgnorth/drift | drift/management/commands/register.py | drift/management/commands/register.py | """
Register or update a deploable.
"""
import sys
import subprocess
from driftconfig.config import TSTransaction
from drift.utils import pretty
from driftconfig.util import register_this_deployable
def get_options(parser):
parser.add_argument(
"--preview", help="Only preview the changes, do not commit... | """
Register or update a deploable.
"""
import subprocess
from driftconfig.config import TSTransaction
from drift.utils import pretty
from driftconfig.util import register_this_deployable
def get_options(parser):
parser.add_argument(
"--preview", help="Only preview the changes, do not commit to origin.... | mit | Python |
b0a4a6e4fdd46c7c11e1ad7358fb211e68563d7c | update docstring. (#33) | rm-hull/pcd8544,rm-hull/luma.lcd | luma/lcd/__init__.py | luma/lcd/__init__.py | # -*- coding: utf-8 -*-
# Copyright (c) 2013-17 Richard Hull and contributors
# See LICENSE.rst for details.
"""
LCD display drivers.
"""
| # -*- coding: utf-8 -*-
# Copyright (c) 2013-17 Richard Hull and contributors
# See LICENSE.rst for details.
"""
LCD display driver for PCD8544 devices.
"""
| mit | Python |
051422346bc0d55bb7f2261b9bd23dce5afc48ca | test for dm | ooici/coi-services,ooici/coi-services,ooici/coi-services,ooici/coi-services,ooici/coi-services | ion/services/dm/utility/test/test_coverage_craft.py | ion/services/dm/utility/test/test_coverage_craft.py | #!/usr/bin/env python
'''
@author Luke Campbell <LCampbell@ASAScience.com>
@file ion/services/dm/utility/test/test_coverage_craft.py
@date Thu Jul 19 16:44:05 EDT 2012
@description Utilities for crafting granules into a coverage
'''
from pyon.util.unit_test import PyonTestCase
from ion.services.dm.utility.granule_util... | #!/usr/bin/env python
'''
@author Luke Campbell <LCampbell@ASAScience.com>
@file ion/services/dm/utility/test/test_coverage_craft.py
@date Thu Jul 19 16:44:05 EDT 2012
@description Utilities for crafting granules into a coverage
'''
from pyon.util.unit_test import PyonTestCase
class CoverageCraftUnitTest(PyonTestCase... | bsd-2-clause | Python |
c43e46a71f99e2fa7d5836260ac05519ac0c0329 | Remove dotenv from wsgi | kyleconroy/speakers,kyleconroy/speakers,kyleconroy/speakers | calltospeakers/wsgi.py | calltospeakers/wsgi.py | """
WSGI config for calltospeakers project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os
ENVIRONMENT = os.getenv('ENVIRONMENT')
if ENVIRONMENT == 'PRODUCTION':
settin... | """
WSGI config for calltospeakers project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os
import dotenv
try:
dotenv.read_dotenv(
os.path.join(os.path.dirname(o... | mit | Python |
3f72b358d3c8cbf0d063f2dfc0dfd94fa4e4393c | Add support for WTF fields in r16 headers | njvack/pfile-tools | pfile_tools/anonymizer.py | pfile_tools/anonymizer.py | # Part of the pfile-tools package
# Copyright (c) 2012, Board of Regents of the University of Wisconsin
# Written by Nathan Vack <njvack@wisc.edu>
# A library for performing anonymization of GE p-file headers.
from collections import namedtuple
import struct_utils
import logging
logger = logging.getLogger(__name__)
... | # Part of the pfile-tools package
# Copyright (c) 2012, Board of Regents of the University of Wisconsin
# Written by Nathan Vack <njvack@wisc.edu>
# A library for performing anonymization of GE p-file headers.
from collections import namedtuple
import struct_utils
import logging
logger = logging.getLogger(__name__)
... | bsd-3-clause | Python |
87172c2f23bed0b6a3566052624416a8c4a6e29b | Fix double typedef | lazka/pgi,lazka/pgi | pgi/cffilib/glib/_cdef.py | pgi/cffilib/glib/_cdef.py | # Copyright 2013 Christoph Reiter
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
GLIB_CDEF = """
typedef c... | # Copyright 2013 Christoph Reiter
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
GLIB_CDEF = """
typedef c... | lgpl-2.1 | Python |
cbf47d00da391f8799485b1b8c5bb449496b4604 | Use stable MADAM API. | eseifert/madam-rest | madam_rest/api_v1.py | madam_rest/api_v1.py | from datetime import datetime
from fractions import Fraction
from flask import Blueprint, jsonify, send_file, url_for
from frozendict import frozendict
from madam_rest import asset_storage
api = Blueprint('v1', __name__, url_prefix='/v1')
def _serializable(value):
"""
Utility function to convert data stru... | from datetime import datetime
from fractions import Fraction
from flask import Blueprint, jsonify, send_file, url_for
from frozendict import frozendict
from madam_rest import asset_storage
api = Blueprint('v1', __name__, url_prefix='/v1')
def _serializable(value):
"""
Utility function to convert data stru... | agpl-3.0 | Python |
898028dea2e04d52c32854752bda34d331c7696f | Move on if email exists | DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative | ynr/apps/candidatebot/management/commands/candidatebot_import_email_from_csv.py | ynr/apps/candidatebot/management/commands/candidatebot_import_email_from_csv.py | from __future__ import unicode_literals
import csv
from django.core.management.base import BaseCommand
from candidatebot.helpers import CandidateBot
from popolo.models import Person
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
'filename',
hel... | from __future__ import unicode_literals
import csv
from django.core.management.base import BaseCommand
from candidatebot.helpers import CandidateBot
from popolo.models import Person
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
'filename',
hel... | agpl-3.0 | Python |
00a87b50596e4b81ea103c895c3b764e39b5c8ea | Stop to use the __future__ module. | openstack/oslo.serialization | oslo_serialization/base64.py | oslo_serialization/base64.py | # Copyright 2015 Red Hat
# 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 appli... | # Copyright 2015 Red Hat
# 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 appli... | apache-2.0 | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.