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 |
|---|---|---|---|---|---|---|---|
cc1000824237cd74dec3e0ff210ee08020c2cd92 | add config ini to ament_mypy site package (#182) | ament_mypy/setup.py | ament_mypy/setup.py | from setuptools import find_packages
from setuptools import setup
setup(
name='ament_mypy',
version='0.7.3',
packages=find_packages(exclude=['test']),
install_requires=['setuptools'],
package_data={'': [
'configuration/ament_mypy.ini',
]},
zip_safe=False,
author='Ted Kern',
... | from setuptools import find_packages
from setuptools import setup
setup(
name='ament_mypy',
version='0.7.3',
packages=find_packages(exclude=['test']),
install_requires=['setuptools'],
zip_safe=False,
author='Ted Kern',
author_email='ted.kern@canonical.com',
maintainer='Ted Kern',
ma... | Python | 0 |
d2eb8bd9588bdda2e05967d10ffc6da786f0e82b | fix LinearFA_Agent batch mode learn method. self.laststate is not defined, use self.lastobs instead | pybrain/rl/agents/linearfa.py | pybrain/rl/agents/linearfa.py | from __future__ import print_function
__author__ = 'Tom Schaul, tom@idsia.ch'
from pybrain.rl.agents.logging import LoggingAgent
from pybrain.utilities import drawIndex
from scipy import array
class LinearFA_Agent(LoggingAgent):
""" Agent class for using linear-FA RL algorithms. """
init_explor... | from __future__ import print_function
__author__ = 'Tom Schaul, tom@idsia.ch'
from pybrain.rl.agents.logging import LoggingAgent
from pybrain.utilities import drawIndex
from scipy import array
class LinearFA_Agent(LoggingAgent):
""" Agent class for using linear-FA RL algorithms. """
init_explor... | Python | 0 |
1ec0b7bf12b8d0ea452caa9aad17535a2fd745d8 | Optimise for readability | scell/core.py | scell/core.py | """
scell.core
~~~~~~~~~~
Provides abstractions over lower level APIs and
file objects and their interests.
"""
from select import select as _select
from collections import namedtuple
def select(rl, wl, timeout=None):
"""
Returns the file objects ready for reading/writing
from the read-... | """
scell.core
~~~~~~~~~~
Provides abstractions over lower level APIs and
file objects and their interests.
"""
from select import select as _select
from collections import namedtuple
def select(rl, wl, timeout=None):
"""
Returns the file objects ready for reading/writing
from the read-... | Python | 0.672366 |
9f0837d387c7303d5c8c925a9989ca77a1a96e3e | Bump version after keras model fix | fancyimpute/__init__.py | fancyimpute/__init__.py | from __future__ import absolute_import, print_function, division
from .solver import Solver
from .nuclear_norm_minimization import NuclearNormMinimization
from .iterative_imputer import IterativeImputer
from .matrix_factorization import MatrixFactorization
from .iterative_svd import IterativeSVD
from .simple_fill impo... | from __future__ import absolute_import, print_function, division
from .solver import Solver
from .nuclear_norm_minimization import NuclearNormMinimization
from .iterative_imputer import IterativeImputer
from .matrix_factorization import MatrixFactorization
from .iterative_svd import IterativeSVD
from .simple_fill impo... | Python | 0 |
5b7abc62a541622b007da367e52488eab72f2b5a | Fix font usage. | graph-deps.py | graph-deps.py | #!/usr/bin/env python3
# file: graph-deps.py
# vim:fileencoding=utf-8:fdm=marker:ft=python
#
# Author: R.F. Smith <rsmith@xs4all.nl>
# Created: 2017-04-27 13:50:28 +0200
# Last modified: 2018-03-10 22:50:33 +0100
#
# To the extent possible under law, R.F. Smith has waived all copyright and
# related or neighboring righ... | #!/usr/bin/env python3
# file: graph-deps.py
# vim:fileencoding=utf-8:fdm=marker:ft=python
#
# Author: R.F. Smith <rsmith@xs4all.nl>
# Created: 2017-04-27 13:50:28 +0200
# Last modified: 2017-06-04 13:38:06 +0200
#
# To the extent possible under law, R.F. Smith has waived all copyright and
# related or neighboring righ... | Python | 0.000002 |
8408f5431e56309d95076db16c86b0aa2ef044ba | Decrease number of messages from MoveToFort worker | pokemongo_bot/event_manager.py | pokemongo_bot/event_manager.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from sys import stdout
class EventNotRegisteredException(Exception):
pass
class EventMalformedException(Exception):
pass
class EventHandler(object):
def __init__(self):
pass
def handle_event(self, event, kwargs):
rai... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
class EventNotRegisteredException(Exception):
pass
class EventMalformedException(Exception):
pass
class EventHandler(object):
def __init__(self):
pass
def handle_event(self, event, kwargs):
raise NotImplementedError(... | Python | 0.000001 |
05835304797c9486d0c715d5a07d02fffd676b67 | Fix test to account for new composition | karld/tests/test_run_together.py | karld/tests/test_run_together.py | from itertools import islice
import string
import unittest
from mock import patch, Mock
from ..run_together import csv_file_to_file
class TestCSVFileToFile(unittest.TestCase):
def setUp(self):
self.csv_contents = iter([
'a,b',
'c,d',
'e,f',
])
self.csv_... | from itertools import islice
import string
import unittest
from mock import patch, Mock
from ..run_together import csv_file_to_file
class TestCSVFileToFile(unittest.TestCase):
def setUp(self):
self.csv_contents = iter([
['a', 'b'],
['c', 'd'],
['e', 'f'],
])
... | Python | 0 |
cb202e49d2b96dd46d322bb2c9ef21eb3cce05f7 | Update Google OAuth to user requests_oauthlib | api/init/security/oauth/google.py | api/init/security/oauth/google.py | import json
import os
from flask import redirect, request, session
from flask_restplus import Namespace, Resource
from requests_oauthlib import OAuth2Session
from security.token import get_jwt_token, TokenType, get_token_redirect_response
# OAuth endpoints given in the Google API documentation
AUTHORIZATION_URI = 'ht... | import os
import json
import requests
from flask import redirect, request
from flask_restplus import Namespace, Resource
from google_auth_oauthlib.flow import Flow
from security.token import get_jwt_token, TokenType, get_token_redirect_response
# pylint: disable=unused-variable
google_redirect_url = os.environ['GOOG... | Python | 0 |
25e7574b6d58444ba81b3ad9321662e3a1a6b7e8 | Apply some PEP8 cleanup | product_variant_sale_price/models/product_product.py | product_variant_sale_price/models/product_product.py | # -*- coding: utf-8 -*-
# © 2016 Sergio Teruel <sergio.teruel@tecnativa.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from openerp import models, fields, api
class ProductTemplate(models.Model):
_inherit = "product.template"
@api.multi
def write(self, vals):
res = super(P... | # -*- coding: utf-8 -*-
# © 2016 Sergio Teruel <sergio.teruel@tecnativa.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from openerp import models, fields, api
class ProductTemplate(models.Model):
_inherit = "product.template"
@api.multi
def write(self, vals):
res = super(P... | Python | 0.000001 |
93181a9a8df89c9ed1ff1e06672cc592a2b689dc | Fix deadcode | polyphony/compiler/deadcode.py | polyphony/compiler/deadcode.py | from .env import env
from .ir import *
from logging import getLogger
logger = getLogger(__name__)
class DeadCodeEliminator(object):
def process(self, scope):
if scope.is_namespace() or scope.is_class():
return
usedef = scope.usedef
for blk in scope.traverse_blocks():
... | from .env import env
from .ir import *
from logging import getLogger
logger = getLogger(__name__)
class DeadCodeEliminator(object):
def process(self, scope):
if scope.is_namespace() or scope.is_class() or scope.is_method():
return
usedef = scope.usedef
for blk in scope.traverse... | Python | 0.999094 |
e1e4d36096fe2c8cea92b77feabc60d94ac4310a | Break class now inherits behaviour from KitchenTimer. | pomodoro_evolved/rest_break.py | pomodoro_evolved/rest_break.py | from kitchen_timer import KitchenTimer, AlreadyRunningError, TimeAlreadyUp, NotRunningError
from math import ceil
class BreakAlreadySkipped(Exception): pass
class BreakCannotBeSkippedOnceStarted(Exception): pass
class BreakAlreadyStarted(Exception): pass
class BreakNotStarted(Exception): pass
class BreakAlreadyTermina... | from kitchen_timer import KitchenTimer, AlreadyRunningError, TimeAlreadyUp, NotRunningError
from math import ceil
class BreakAlreadySkipped(Exception): pass
class BreakCannotBeSkippedOnceStarted(Exception): pass
class BreakAlreadyStarted(Exception): pass
class BreakNotStarted(Exception): pass
class BreakAlreadyTermina... | Python | 0 |
ca15e6523bd34e551528dce6c6ee3dcb70cf7806 | Use sed inline (unsure why mv was used originally). | pyinfra/modules/util/files.py | pyinfra/modules/util/files.py | # pyinfra
# File: pyinfra/modules/util/files.py
# Desc: common functions for handling the filesystem
from types import NoneType
def ensure_mode_int(mode):
# Already an int (/None)?
if isinstance(mode, (int, NoneType)):
return mode
try:
# Try making an int ('700' -> 700)
return in... | # pyinfra
# File: pyinfra/modules/util/files.py
# Desc: common functions for handling the filesystem
from types import NoneType
def ensure_mode_int(mode):
# Already an int (/None)?
if isinstance(mode, (int, NoneType)):
return mode
try:
# Try making an int ('700' -> 700)
return in... | Python | 0 |
f015c3e5973c9424734ff6181563ee7905c73428 | fix version pattern | sdcm/utils.py | sdcm/utils.py | # This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be usefu... | # This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be usefu... | Python | 0.000003 |
c1a263107cac6f55ce01ea5f260c005d307398e7 | add env vars to ping.json | laalaa/apps/healthcheck/views.py | laalaa/apps/healthcheck/views.py | import os
import requests
from django.http import JsonResponse
from django.conf import settings
def ping(request):
res = {
"version_number": os.environ.get('APPVERSION'),
"build_date": os.environ.get('APP_BUILD_DATE'),
"commit_id": os.environ.get('APP_GIT_COMMIT'),
"build_tag": os... | import requests
from django.http import JsonResponse
from django.conf import settings
def ping(request):
res = {
"version_number": None,
"build_date": None,
"commit_id": None,
"build_tag": None
}
# Get version details
try:
res['version_number'] = str(open("{0}... | Python | 0.000001 |
5a4d9255c59be0d5dda8272e0e7ced71822f4d40 | Fix memory issues by just trying every number | prime-factors/prime_factors.py | prime-factors/prime_factors.py | def prime_factors(n):
factors = []
factor = 2
while n != 1:
while n % factor == 0:
factors += [factor]
n //= factor
factor += 1
return factors
| import sieve
def prime_factors(n):
primes = sieve.sieve(n)
factors = []
for p in primes:
while n % p == 0:
factors += [p]
n //= p
return factors
| Python | 0.000002 |
f0e68095cd0afc0b1d960d726e0e64de9dec14f1 | remove unused variable | hack.py | hack.py | import time
import json
import smbus
import logging
BUS = None
address = 0x42
gpsReadInterval = 0.1
LOG = logging.getLogger()
# GUIDE
# http://ava.upuaut.net/?p=768
GPSDAT = {
'strType': None,
'fixTime': None,
'lat': None,
'latDir': None,
'lon': None,
'lonDir': None,
'fixQual': None,
... | import time
import json
import smbus
import logging
BUS = None
address = 0x42
gpsReadInterval = 0.1
LOG = logging.getLogger()
# GUIDE
# http://ava.upuaut.net/?p=768
GPSDAT = {
'strType': None,
'fixTime': None,
'lat': None,
'latDir': None,
'lon': None,
'lonDir': None,
'fixQual': None,
... | Python | 0.00003 |
8ea3350c6944946b60732308c912dc240952237c | Revert "Set the right recalbox.log path" | project/settings_production.py | project/settings_production.py | from .settings import *
# Update SITE infos to use the common port 80 to publish the webapp
SITE_FIXED = {
'name': "Recalbox Manager",
'ip': None, # If 'None' find the ip automatically. Use a string to define another ip/hostname
'port': None, # If 'None' no port is added to hostname, so the server have to ... | from .settings import *
# Update SITE infos to use the common port 80 to publish the webapp
SITE_FIXED = {
'name': "Recalbox Manager",
'ip': None, # If 'None' find the ip automatically. Use a string to define another ip/hostname
'port': None, # If 'None' no port is added to hostname, so the server have to ... | Python | 0 |
812efd4b5addeee879e91c6c660ac2a1a2adfe5d | mueve logica de avance de un paso a una funcion | heat.py | heat.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Este script resuelve un problema simple de diffusion en 1D.
La ecuación a resover es:
dT/dt = d2T/dx2; T(0,x) = sin(pi * x); T(t, 0) = T(t, 1) = 0
'''
from __future__ import division
import numpy as np
def inicializa_T(T, N_steps, h):
'''
Rellena T con ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Este script resuelve un problema simple de diffusion en 1D.
La ecuación a resover es:
dT/dt = d2T/dx2; T(0,x) = sin(pi * x); T(t, 0) = T(t, 1) = 0
'''
from __future__ import division
import numpy as np
def inicializa_T(T, N_steps, h):
'''
Rellena T con ... | Python | 0.000001 |
eb66cae55dee3b401cd84a71f9906cdb42a217bc | Update __init__.py | pytorch_lightning/__init__.py | pytorch_lightning/__init__.py | """Root package info."""
__version__ = '0.9.0rc4'
__author__ = 'William Falcon et al.'
__author_email__ = 'waf2107@columbia.edu'
__license__ = 'Apache-2.0'
__copyright__ = 'Copyright (c) 2018-2020, %s.' % __author__
__homepage__ = 'https://github.com/PyTorchLightning/pytorch-lightning'
# this has to be simple string, ... | """Root package info."""
__version__ = '0.9.0rc3'
__author__ = 'William Falcon et al.'
__author_email__ = 'waf2107@columbia.edu'
__license__ = 'Apache-2.0'
__copyright__ = 'Copyright (c) 2018-2020, %s.' % __author__
__homepage__ = 'https://github.com/PyTorchLightning/pytorch-lightning'
# this has to be simple string, ... | Python | 0.000072 |
a5f274b5a3dbb72e109184b7a3c56b2a1dac13b4 | Enable WebForm page | frappe/website/serve.py | frappe/website/serve.py | import frappe
from frappe import _
from frappe.utils import cstr
from frappe.website.page_controllers.document_page import DocumentPage
from frappe.website.page_controllers.list_page import ListPage
from frappe.website.page_controllers.not_permitted_page import NotPermittedPage
from frappe.website.page_controllers.pri... | import frappe
from frappe import _
from frappe.utils import cstr
from frappe.website.page_controllers.document_page import DocumentPage
from frappe.website.page_controllers.list_page import ListPage
from frappe.website.page_controllers.not_permitted_page import NotPermittedPage
from frappe.website.page_controllers.pri... | Python | 0.000008 |
fccc9c14a46e529bd8af0da83f5efc2d4e675769 | Add a device to back the non-existant floppy drive controller. | src/dev/x86/Pc.py | src/dev/x86/Pc.py | # Copyright (c) 2008 The Regents of The University of Michigan
# 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
# notice, this list ... | # Copyright (c) 2008 The Regents of The University of Michigan
# 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
# notice, this list ... | Python | 0 |
fd4688cc899b08253cc50b345bb7e836081783d8 | Add Beta and Binomial to automatically imported nodes | bayespy/inference/vmp/nodes/__init__.py | bayespy/inference/vmp/nodes/__init__.py | ######################################################################
# Copyright (C) 2011,2012 Jaakko Luttinen
#
# This file is licensed under Version 3.0 of the GNU General Public
# License. See LICENSE for a text of the license.
######################################################################
###############... | ######################################################################
# Copyright (C) 2011,2012 Jaakko Luttinen
#
# This file is licensed under Version 3.0 of the GNU General Public
# License. See LICENSE for a text of the license.
######################################################################
###############... | Python | 0 |
769a334675cc451c6de07ed21e23ffd4480088df | Add time/space complexity | lc0041_first_missing_positive.py | lc0041_first_missing_positive.py | """Leetcode 41. First Missing Positive
Hard
URL: https://leetcode.com/problems/first-missing-positive/
Given an unsorted integer array, find the smallest missing positive integer.
Example 1:
Input: [1,2,0]
Output: 3
Example 2:
Input: [3,4,-1,1]
Output: 2
Example 3:
Input: [7,8,9,11,12]
Output: 1
Note:
Your algori... | """Leetcode 41. First Missing Positive
Hard
URL: https://leetcode.com/problems/first-missing-positive/
Given an unsorted integer array, find the smallest missing positive integer.
Example 1:
Input: [1,2,0]
Output: 3
Example 2:
Input: [3,4,-1,1]
Output: 2
Example 3:
Input: [7,8,9,11,12]
Output: 1
Note:
Your algori... | Python | 0.002369 |
f33b294d60ffbfb5351d4579e38ea197e2c3787a | Complete reverse iter sol | lc0482_license_key_formatting.py | lc0482_license_key_formatting.py | """Leecode 482. License Key Formatting
Easy
URL: https://leetcode.com/problems/license-key-formatting/
You are given a license key represented as a string S which consists only
alphanumeric character and dashes. The string is separated into N+1 groups
by N dashes.
Given a number K, we would want to reformat the stri... | """Leecode 482. License Key Formatting
Easy
URL: https://leetcode.com/problems/license-key-formatting/
You are given a license key represented as a string S which consists only
alphanumeric character and dashes. The string is separated into N+1 groups
by N dashes.
Given a number K, we would want to reformat the stri... | Python | 0.999999 |
9a1aec04549ed03cb8e0d8e4e59f29c08bce7716 | set absolute uri script path | middleware.py | middleware.py | __license__ = "Apache 2.0"
__copyright__ = "Copyright 2008 nb.io"
__author__ = "Randy Reddig - ydnar@nb.io"
import sys
import logging
import re
from time import sleep
from random import randint
from django.conf import settings
from django.http import HttpResponsePermanentRedirect, Http404
from django.core.urlresolver... | __license__ = "Apache 2.0"
__copyright__ = "Copyright 2008 nb.io"
__author__ = "Randy Reddig - ydnar@nb.io"
import sys
import logging
import re
from time import sleep
from random import randint
from django.conf import settings
from django.http import HttpResponsePermanentRedirect, Http404
from django.core.urlresolver... | Python | 0 |
dc95d6766d305f2126c158f50417e29d0c47ce3f | Change doc route | backoffice_operateurs/__init__.py | backoffice_operateurs/__init__.py | # -*- coding: utf8 -*-
VERSION = (0, 1, 0)
__author__ = 'Vincent Lara'
__contact__ = "vincent.lara@data.gouv.fr"
__homepage__ = "https://github.com/"
__version__ = ".".join(map(str, VERSION))
from flask import Flask, make_response
from flask.ext.security import Security, SQLAlchemyUserDatastore
from flask.ext.script ... | # -*- coding: utf8 -*-
VERSION = (0, 1, 0)
__author__ = 'Vincent Lara'
__contact__ = "vincent.lara@data.gouv.fr"
__homepage__ = "https://github.com/"
__version__ = ".".join(map(str, VERSION))
from flask import Flask, make_response
from flask.ext.security import Security, SQLAlchemyUserDatastore
from flask.ext.script ... | Python | 0 |
aa4061887fc750dd63cd226e3fa45f0b56ec2462 | Update server.py | site/server.py | site/server.py | #Import flask libraries
import json, re, os, datetime, logging;#Import general libraries
from flask import Flask, jsonify, request, render_template, send_from_directory;
from flask_socketio import SocketIO, send, emit, join_room, leave_room, close_room;
from flask_mail import Mail, Message;
from flask_socketio imp... | #Import flask libraries
import json, re, os, datetime, logging;#Import general libraries
from flask import Flask, jsonify, request, render_template, send_from_directory;
from flask_socketio import SocketIO, send, emit, join_room, leave_room, close_room;
from flask_mail import Mail, Message;
from flask_socketio imp... | Python | 0.000001 |
184ac486740cfca13b3fdb42d3965017c93c6fb5 | remove streamcloud filter | flashget/pages/ddlme.py | flashget/pages/ddlme.py | # -*- coding: utf-8 -*-
from flashget.page import Page, log
from flashget.url import UrlMgr
from flashget.helper import textextract
import json
class DdlMe(Page):
eregex = r'.*ddl.me.*'
ename = 'ddl.me'
name = 'ddl me'
url = 'http://de.ddl.me'
def get(self):
link = self.link
# th... | # -*- coding: utf-8 -*-
from flashget.page import Page, log
from flashget.url import UrlMgr
from flashget.helper import textextract
import json
class DdlMe(Page):
eregex = r'.*ddl.me.*'
ename = 'ddl.me'
name = 'ddl me'
url = 'http://de.ddl.me'
def get(self):
link = self.link
# th... | Python | 0.000001 |
ec149e2e6b56f201ed154eaeecab2f651fe70351 | Update docstrings. | dyfunconn/graphs/laplacian_energy.py | dyfunconn/graphs/laplacian_energy.py | # -*- coding: utf-8 -*-
""" Laplcian Energy
The Laplcian energy (LE) for a graph :math:`G` is computed as
.. math::
LE(G) = \\sum_{i=1}^n | { \\mu_{i} - \\frac{2m}{n} } |
ξ(A_1, A_2 ; t) = ‖exp(-tL_1 ) - exp(-tL_2 )‖_F^2
Where :math:`\mu_i` denote the eigenvalue associated with the node of the Laplcian
mat... | # -*- coding: utf-8 -*-
""" Laplcian Energy
The Laplcian energy (LE) for a graph :math:`G` is computed as
.. math::
LE(G) = \sum_{i=1}^n | {\mu_i - \frac{2m}{n}} |
ξ(A_1, A_2 ; t) = ‖exp(-tL_1 ) - exp(-tL_2 )‖_F^2
Where :math:``\mu_i` denote the eigenvalue associated with the node of the Laplcian
matrix of... | Python | 0 |
cd3e129c1951dbb1d2d99d454b1e07d96d1d5497 | Support multi or non-multi mappers for bowtie alignments | bcbio/ngsalign/bowtie.py | bcbio/ngsalign/bowtie.py | """Next gen sequence alignments with Bowtie (http://bowtie-bio.sourceforge.net).
"""
import os
import subprocess
from bcbio.utils import file_transaction
galaxy_location_file = "bowtie_indices.loc"
def align(fastq_file, pair_file, ref_file, out_base, align_dir, config):
"""Before a standard or paired end alignme... | """Next gen sequence alignments with Bowtie (http://bowtie-bio.sourceforge.net).
"""
import os
import subprocess
from bcbio.utils import file_transaction
galaxy_location_file = "bowtie_indices.loc"
def align(fastq_file, pair_file, ref_file, out_base, align_dir, config):
"""Before a standard or paired end alignme... | Python | 0 |
49e86f8f0f16ac5fe20cb9f91893f5aa5eee2237 | Remove tests for old api | games/tests/test_api.py | games/tests/test_api.py | from django.test import TestCase
from django.core.urlresolvers import reverse
from . import factories
import json
class TestGameApi(TestCase):
def setUp(self):
self.num_games = 10
self.games = []
for n in range(self.num_games):
self.games.append(
factories.GameF... | from django.test import TestCase
from django.core.urlresolvers import reverse
from . import factories
import json
class TestOldApi(TestCase):
def setUp(self):
game = factories.GameFactory
games = [game() for i in range(5)]
self.library = factories.GameLibraryFactory(games=games)
ot... | Python | 0 |
a6283772b07a29faa54a8c141947e19005bef61e | append max and min to entire dataset | minMaxCalc.py | minMaxCalc.py | import pandas as pd
# read in dataset
xl = pd.ExcelFile("data/130N_Cycles_1-47.xlsx")
df = xl.parse("Specimen_RawData_1")
df
"""
This is what the dataset currently looks like - it has 170,101 rows and two columns.
The dataset contains data from 47 cycles following an experiment.
The output of these experiments form... | import pandas as pd
# read in dataset
xl = pd.ExcelFile("data/130N_Cycles_1-47.xlsx")
df = xl.parse("Specimen_RawData_1")
df
"""
This is what the dataset currently looks like - it has 170,101 rows and two columns.
The dataset contains data from 47 cycles following an experiment.
The output of these experiments form... | Python | 0.000294 |
fff56b52afb40ee0a69c9a84b847f7ccc0836bd6 | Update some admin list parameters. | greenmine/scrum/admin.py | greenmine/scrum/admin.py | # -*- coding: utf-8 -*-
from django.contrib import admin
from guardian.admin import GuardedModelAdmin
from greenmine.scrum import models
import reversion
class MilestoneInline(admin.TabularInline):
model = models.Milestone
fields = ('name', 'owner', 'estimated_start', 'estimated_finish', 'closed', 'disponibi... | # -*- coding: utf-8 -*-
from django.contrib import admin
from guardian.admin import GuardedModelAdmin
from greenmine.scrum import models
import reversion
class MilestoneInline(admin.TabularInline):
model = models.Milestone
fields = ('name', 'owner', 'estimated_start', 'estimated_finish', 'closed', 'disponibi... | Python | 0 |
f66a679a1ca8f78a12567a1d8acfe04ca2778ce3 | allow removal of genomes and fragments in admin | src/edge/admin.py | src/edge/admin.py | from django.contrib import admin
from edge.models import Genome, Fragment
class Genome_Admin(admin.ModelAdmin):
list_display = ('id', 'name', 'notes', 'parent', 'created_on')
search_fields = ('name',)
fields = ('name', 'notes', 'active')
actions = None
def has_add_permission(self, request):
... | from django.contrib import admin
from edge.models import Genome, Fragment
class Genome_Admin(admin.ModelAdmin):
list_display = ('id', 'name', 'notes', 'parent', 'created_on')
search_fields = ('name',)
fields = ('name', 'notes', 'active')
actions = None
def has_add_permission(self, request):
... | Python | 0 |
ed21e865f346b700c48458f22e3d3f1841f63451 | Fix JSON encoder to work with Decimal fields | api/swd6/api/app.py | api/swd6/api/app.py | import flask
import flask_cors
from sqlalchemy_jsonapi import flaskext as flask_jsonapi
import logging
from swd6.config import CONF
from swd6.db.models import db
logging.basicConfig(level=logging.DEBUG)
app = flask.Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.con... | import flask
import flask_cors
from sqlalchemy_jsonapi import flaskext as flask_jsonapi
import logging
from swd6.config import CONF
from swd6.db.models import db
logging.basicConfig(level=logging.DEBUG)
app = flask.Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.con... | Python | 0 |
efe79ebfa2b023e6971244b7f3c803a09dd6d2c7 | change check to skipp | tools/pcdo.py | tools/pcdo.py | import glob
from joblib import Parallel, delayed
import os
import click
def cdo_command(ifile, opath, command, ext, skip):
if opath != 'no':
ofile = os.path.join(opath, '{}_{}.nc'.format(os.path.basename(ifile)[:-3], ext))
else:
ofile = ' '
if skip:
if os.path.isfile(ofile):
... | import glob
from joblib import Parallel, delayed
import os
import click
def cdo_comand(ifile, opath, command, ext, checko):
if opath != 'no':
ofile = os.path.join(opath, '{}_tm.nc'.format(os.path.basename(ifile)[:-3]))
else:
ofile = ' '
if checko:
if os.path.isfile(ofile):
... | Python | 0 |
ad1d33f1a4051a3440c60e4a8a655f167fcee1b6 | Rewrite result handling | src/result.py | src/result.py | """
The MIT License (MIT)
Copyright (c) 2017 Stefan Graupner
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, mer... | """
The MIT License (MIT)
Copyright (c) 2017 Stefan Graupner
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, mer... | Python | 0.000009 |
dc4ec816f3afc586a8f513d3ef2b6e26f0020410 | add new route '/projects/{id}' | vyi/projects/service.py | vyi/projects/service.py | from lovely.pyrest.rest import RestService, rpcmethod_route
from lovely.pyrest.validation import validate
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
from vyi.users.model import User
from vyi.projects.model import Project
from ..model import DB_SESSION, refresher
import transaction
PROJECTS_... | from lovely.pyrest.rest import RestService, rpcmethod_route
from lovely.pyrest.validation import validate
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
from vyi.users.model import User
from vyi.projects.model import Project
from ..model import DB_SESSION, refresher
import transaction
PROJECT_S... | Python | 0.000007 |
eb368c11b7d0e481c6539130c34cb0b04c8f57a6 | add prompt number | tpl/prompt.py | tpl/prompt.py | # -*- coding:utf-8 -*-
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
import prompt_toolkit
from prompt_toolkit.history import FileHistory
from prompt_toolkit.completion import Completion, Completer
from tpl import path
class WordMatchType(object):
CONTAINS = 'CONTAINES'
... | # -*- coding:utf-8 -*-
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
import prompt_toolkit
from prompt_toolkit.history import FileHistory
from prompt_toolkit.completion import Completion, Completer
from tpl import path
class WordMatchType(object):
CONTAINS = 'CONTAINES'
... | Python | 0.000007 |
fc301544022c00403cc9ba86c8be7dbe3eee3e47 | Fix formatting | benchbuild/source/git.py | benchbuild/source/git.py | """
Declare a git source.
"""
import typing as tp
import attr
import plumbum as pb
from plumbum import local
from benchbuild.utils.cmd import git, mkdir
from benchbuild.utils.path import flocked
from . import base
Command = pb.commands.base.BaseCommand
VarRemotes = tp.Union[str, tp.Dict[str, str]]
Remotes = tp.Dict... | """
Declare a git source.
"""
import typing as tp
import attr
import plumbum as pb
from plumbum import local
from benchbuild.utils.cmd import git, mkdir
from benchbuild.utils.path import flocked
from . import base
Command = pb.commands.base.BaseCommand
VarRemotes = tp.Union[str, tp.Dict[str, str]]
Remotes = tp.Dict... | Python | 0 |
63fddd07e3b110c06c7369fa9d815e79384ef27e | update try_pandas.py | try_pandas.py | try_pandas.py | # I'm using Spark Cloud Community Edition, sicne my own machine cannot have the right numpy for pandas...
# So, in this code, so features could only be used in Spark Cloud Python Notebook
# Try pandas :)
# cell 1 - load the data (I upload the .csv into Spark Cloud first)
import pandas as pd
import numpy as np
## The ... | # I'm using Spark Cloud Community Edition, sicne my own machine cannot have the right numpy for pandas...
# So, in this code, so features could only be used in Spark Cloud Python Notebook
# Try pandas :)
# cell 1 - load the data (I upload the .csv into Spark Cloud first)
import pandas as pd
import numpy as np
## The ... | Python | 0.000002 |
31caf3d6366cdc3669eb72007a1a6a45bffe2ce3 | Update at 2017-07-23 11-30-32 | plot.py | plot.py | from sys import argv
from pathlib import Path
import matplotlib as mpl
mpl.use('Agg')
import seaborn as sns
sns.set_style("darkgrid")
import matplotlib.pyplot as plt
import pandas as pd
# from keras.utils import plot_model
# plot_model(model, to_file='model.png', show_shapes=True, show_layer_names=False)
def plot_s... | from sys import argv
from pathlib import Path
import matplotlib as mpl
mpl.use('Agg')
import seaborn as sns
sns.set_style("darkgrid")
import matplotlib.pyplot as plt
import pandas as pd
# from keras.utils import plot_model
# plot_model(model, to_file='model.png', show_shapes=True, show_layer_names=False)
def plot_s... | Python | 0 |
c78f864c41d85762a307ced808d6a220a0893805 | [middleware] convert path to unicode | webnotes/middlewares.py | webnotes/middlewares.py | from __future__ import unicode_literals
import webnotes
import os
from werkzeug.wsgi import SharedDataMiddleware
from webnotes.utils import get_site_name, get_site_path, get_site_base_path, get_path, cstr
class StaticDataMiddleware(SharedDataMiddleware):
def __call__(self, environ, start_response):
self.environ =... | from __future__ import unicode_literals
import webnotes
import os
from werkzeug.wsgi import SharedDataMiddleware
from webnotes.utils import get_site_name, get_site_path, get_site_base_path, get_path
class StaticDataMiddleware(SharedDataMiddleware):
def __call__(self, environ, start_response):
self.environ = envir... | Python | 0.999999 |
e2330caffae04bc31376a2e0f66f0e86ebf92532 | Add my own K-nearest-neighbor algorithm | kNearestNeighbors/howItWorksKNearestNeighbors.py | kNearestNeighbors/howItWorksKNearestNeighbors.py | # -*- coding: utf-8 -*-
"""K Nearest Neighbors classification for machine learning.
This file demonstrate knowledge of K Nearest Neighbors classification. By
building the algorithm from scratch.
The idea of K Nearest Neighbors classification is to best divide and separate
the data based on clustering the data and clas... | Python | 0.000008 | |
43bbf64879ad0567805b0bab2fac123cfbc9c5f2 | Add scenario image endpoint | cea/interfaces/dashboard/api/project.py | cea/interfaces/dashboard/api/project.py | import os
import geopandas
from flask_restplus import Namespace, Resource, fields, abort
from staticmap import StaticMap, Polygon
import cea.config
import cea.inputlocator
from cea.utilities.standardize_coordinates import get_geographic_coordinate_system
api = Namespace('Project', description='Current project for CE... | from flask_restplus import Namespace, Resource, fields, abort
import cea.config
import os
import re
api = Namespace('Project', description='Current project for CEA')
# PATH_REGEX = r'(^[a-zA-Z]:\\[\\\S|*\S]?.*$)|(^(/[^/ ]*)+/?$)'
PROJECT_PATH_MODEL = api.model('Project Path', {
'path': fields.String(descriptio... | Python | 0.000042 |
72a633793b30a87b6affa528459185d46fc37007 | Update getJob signature | shared/api.py | shared/api.py | from __future__ import print_function
import boto3
import json
import os
import btr3baseball
jobTable = os.environ['JOB_TABLE']
jobQueue = os.environ['JOB_QUEUE']
repo = btr3baseball.JobRepository(jobTable)
queue = boto3.resource('sqs').get_queue_by_name(QueueName=jobQueue)
def submitJob(event, context):
# Put i... | from __future__ import print_function
import boto3
import json
import os
import btr3baseball
jobTable = os.environ['JOB_TABLE']
jobQueue = os.environ['JOB_QUEUE']
repo = btr3baseball.JobRepository(jobTable)
queue = boto3.resource('sqs').get_queue_by_name(QueueName=jobQueue)
def submitJob(event, context):
# Put i... | Python | 0 |
5692bb1c893182e5aac7271161e64fa9d1a03f2f | Remove test for backend.is_successful | celery/tests/test_backends/test_base.py | celery/tests/test_backends/test_base.py | import sys
import types
import unittest2 as unittest
from celery.serialization import subclass_exception
from celery.serialization import find_nearest_pickleable_exception as fnpe
from celery.serialization import UnpickleableExceptionWrapper
from celery.serialization import get_pickleable_exception as gpe
from celery... | import sys
import types
import unittest2 as unittest
from celery.serialization import subclass_exception
from celery.serialization import find_nearest_pickleable_exception as fnpe
from celery.serialization import UnpickleableExceptionWrapper
from celery.serialization import get_pickleable_exception as gpe
from celery... | Python | 0.000152 |
06d0287a8fef0679b281296e6ed76e0b6c803acb | Improve management command to clear or clean kvstore | sorl/thumbnail/management/commands/thumbnail.py | sorl/thumbnail/management/commands/thumbnail.py | import sys
from django.core.management.base import BaseCommand, CommandError
from sorl.thumbnail import default
class Command(BaseCommand):
help = (
u'Handles thumbnails and key value store'
)
args = '[cleanup, clear]'
option_list = BaseCommand.option_list
def handle(self, *labels, **opti... | from django.core.management.base import BaseCommand, CommandError
from sorl.thumbnail.conf import settings
from sorl.thumbnail import default
class Command(BaseCommand):
help = (
u'Handles thumbnails and key value store'
)
args = '[cleanup, clear]'
option_list = BaseCommand.option_list
de... | Python | 0 |
a8805982ff5b92a59d25a28e2acd63af3c210f65 | Add brute force sol | lc0945_minimum_increment_to_make_array_unique.py | lc0945_minimum_increment_to_make_array_unique.py | """Leetcode 945. Minimum Increment to Make Array Unique
Medium
URL: https://leetcode.com/problems/minimum-increment-to-make-array-unique/
Given an array of integers A, a move consists of choosing any A[i], and
incrementing it by 1.
Return the least number of moves to make every value in A unique.
Example 1:
Input: ... | """Leetcode 945. Minimum Increment to Make Array Unique
Medium
URL: https://leetcode.com/problems/minimum-increment-to-make-array-unique/
Given an array of integers A, a move consists of choosing any A[i], and
incrementing it by 1.
Return the least number of moves to make every value in A unique.
Example 1:
Input: ... | Python | 0.99996 |
ca3b1c09705d65307851711dca71714915e4525a | Fix the formatting of log message | ipaqe_provision_hosts/__main__.py | ipaqe_provision_hosts/__main__.py | #!/usr/bin/env python
from __future__ import print_function
import argparse
import logging
import sys
from ipaqe_provision_hosts.runner import create, delete
from ipaqe_provision_hosts.errors import IPAQEProvisionerError
CONFIG_HELP_MSG = (
'Configuration file for the topology. Must contain core configuration ... | #!/usr/bin/env python
from __future__ import print_function
import argparse
import logging
import sys
from ipaqe_provision_hosts.runner import create, delete
from ipaqe_provision_hosts.errors import IPAQEProvisionerError
CONFIG_HELP_MSG = (
'Configuration file for the topology. Must contain core configuration ... | Python | 0.999999 |
d3c068ea7e240326235f3ac567354708246881de | Remove UnicodeWriter. | pybossa/exporter/csv_export.py | pybossa/exporter/csv_export.py | # -*- coding: utf8 -*-
# This file is part of PYBOSSA.
#
# Copyright (C) 2015 Scifabric LTD.
#
# PYBOSSA is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your op... | # -*- coding: utf8 -*-
# This file is part of PYBOSSA.
#
# Copyright (C) 2015 Scifabric LTD.
#
# PYBOSSA is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your op... | Python | 0.000001 |
01afa5bdbdf1900b5d67ffb6b0bb880d257a1869 | Update server.py | src/server.py | src/server.py | """Server for http-server echo assignment."""
import socket # pragma: no cover
import sys # pragma: no cover
from email.utils import formatdate
def server(): # pragma: no cover
"""
Open the server, waits for input from client.
Closes connection on completed message.
Closes server with Ctrl-C
"... | """Server for http-server echo assignment."""
import socket # pragma: no cover
import sys # pragma: no cover
from email.utils import formatdate
def server(): # pragma: no cover
"""
Open the server, waits for input from client.
Closes connection on completed message.
Closes server with Ctrl-C
"... | Python | 0.000001 |
5c97b9911a2dafde5fd1e4c40cda4e84974eb855 | Allow keys to be set (in anticipation of write commands). Better object __repr__() for spaces and tickets. | assembla/lib.py | assembla/lib.py | from functools import wraps
class AssemblaObject(object):
"""
Proxies getitem calls (eg: `instance['id']`) to a dictionary `instance.data['id']`.
"""
def __init__(self, data):
self.data = data
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value)... | from functools import wraps
class AssemblaObject(object):
"""
Proxies getitem calls (eg: `instance['id']`) to a dictionary `instance.data['id']`.
"""
def __init__(self, data):
self.data = data
def __getitem__(self, key):
return self.data[key]
def keys(self):
return se... | Python | 0 |
2f72db5ddbb9852cbae71b818e6bd40864486331 | Replace OpenGL 2.0 GLSL functions with their ARB counterparts, to accomodate shader-capable pre 2.0 cards/drivers. | src/shader.py | src/shader.py |
from pyglet.gl import *
import pyglet
import euclid
class Shader:
def __init__(self, vert = [], frag = []):
self.Handle = glCreateProgramObjectARB()
# print 'program: ', self.Handle
self.Linked = False
self.createShader(vert, GL_VERTEX_SHADER_ARB)
self.createShader(frag, GL_FRAGMENT_SHADER_ARB)
sel... |
from pyglet.gl import *
import pyglet
import euclid
class Shader:
def __init__(self, vert = [], frag = []):
self.Handle = glCreateProgram()
# print 'program: ', self.Handle
self.Linked = False
self.createShader(vert, GL_VERTEX_SHADER)
self.createShader(frag, GL_FRAGMENT_SHADER)
self.link()
def c... | Python | 0 |
d013f50b92e968258b14b67ebea9e70b4c35dcb0 | Fix completion | pylibs/ropemode/environment.py | pylibs/ropemode/environment.py | class Environment(object):
def ask(self, prompt, default=None, starting=None):
pass
def ask_values(self, prompt, values, default=None, starting=None):
pass
def ask_directory(self, prompt, default=None, starting=None):
pass
def ask_completion(self, prompt, values, starting=Non... | class Environment(object):
def ask(self, prompt, default=None, starting=None):
pass
def ask_values(self, prompt, values, default=None, starting=None):
pass
def ask_directory(self, prompt, default=None, starting=None):
pass
def ask_completion(self, prompt, values, starting=Non... | Python | 0.00144 |
1563c35f10ac4419d6c732e0e25c3d2d62fcd3fd | send all available output to client if are multiple lines available | hey/server.py | hey/server.py | from twisted.internet import protocol, reactor
from twisted.internet.endpoints import TCP4ServerEndpoint
try:
from Queue import Queue, Empty
except ImportError:
# python 3.x
from queue import Queue, Empty
class HeyQueueFactory(protocol.Factory, object):
def __init__(self, outQueue, *args, **kwargs):
... | from twisted.internet import protocol, reactor
from twisted.internet.endpoints import TCP4ServerEndpoint
try:
from Queue import Queue, Empty
except ImportError:
# python 3.x
from queue import Queue, Empty
class HeyQueueFactory(protocol.Factory, object):
def __init__(self, outQueue, *args, **kwargs):
... | Python | 0 |
0dce50c77963ef0d2cdb168f85c2588d62f43220 | Remove duplicate import | yunity/stores/models.py | yunity/stores/models.py | from config import settings
from yunity.base.base_models import BaseModel
from django.db import models
class PickupDate(BaseModel):
date = models.DateTimeField()
collectors = models.ManyToManyField(settings.AUTH_USER_MODEL)
store = models.ForeignKey('stores.store', related_name='pickupdates', on_delete=mo... | from django.db import models
from config import settings
from yunity.base.base_models import BaseModel
from django.db import models
class PickupDate(BaseModel):
date = models.DateTimeField()
collectors = models.ManyToManyField(settings.AUTH_USER_MODEL)
store = models.ForeignKey('stores.store', related_nam... | Python | 0.000008 |
f55182fc2b3e05b154e82ae904cc1a6079b1c4a0 | Add (empty) unit tests for the OmicsUnitType model | apps/core/tests/test_models.py | apps/core/tests/test_models.py | import datetime
from django.core.exceptions import ValidationError
from django.db import IntegrityError, transaction
from django.test import TestCase
from apps.data.factories import EntryFactory
from .. import models
class SpeciesTestCase(TestCase):
def test_can_create_species(self):
name = 'Saccharom... | import datetime
from django.core.exceptions import ValidationError
from django.db import IntegrityError, transaction
from django.test import TestCase
from apps.data.factories import EntryFactory
from .. import models
class SpeciesTestCase(TestCase):
def test_can_create_species(self):
name = 'Saccharom... | Python | 0 |
bc63b8f19742277ad96c2427405f1430687430d1 | expire jwt in 1 day | hbapi/settings/heroku.py | hbapi/settings/heroku.py | import dj_database_url
import os
from .base import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = [('znotdead', 'zhirafchik@gmail.com')]
DATABASES['default'] = dj_database_url.config()
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STAT... | import dj_database_url
import os
from .base import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = [('znotdead', 'zhirafchik@gmail.com')]
DATABASES['default'] = dj_database_url.config()
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STAT... | Python | 0.000001 |
0d7cab10d66fb13d5ea9ddd4fd048ff29def5ba2 | Fix F811 redefinition of unused '_ast_py3' | astroid/_ast.py | astroid/_ast.py | import ast
import sys
from collections import namedtuple
from functools import partial
from typing import Optional
import astroid
try:
import typed_ast.ast3 as _ast_py3
except ImportError:
_ast_py3 = None
PY38 = sys.version_info[:2] >= (3, 8)
if PY38:
# On Python 3.8, typed_ast was merged back into `ast... | import ast
import sys
from collections import namedtuple
from functools import partial
from typing import Optional
import astroid
_ast_py3 = None
try:
import typed_ast.ast3 as _ast_py3
except ImportError:
pass
PY38 = sys.version_info[:2] >= (3, 8)
if PY38:
# On Python 3.8, typed_ast was merged back into... | Python | 0.000008 |
cee2368dac250ef9655a3df9af3188b8abd095dc | Disable slow test. Not intended to run. | spec/puzzle/examples/gph/a_basic_puzzle_spec.py | spec/puzzle/examples/gph/a_basic_puzzle_spec.py | from data import warehouse
from puzzle.examples.gph import a_basic_puzzle
from puzzle.problems import number_problem
from puzzle.puzzlepedia import prod_config
from spec.mamba import *
with _description('a_basic_puzzle'):
with before.all:
warehouse.save()
prod_config.init()
self.subject = a_basic_puzzle.... | from data import warehouse
from puzzle.examples.gph import a_basic_puzzle
from puzzle.problems import number_problem
from puzzle.puzzlepedia import prod_config
from spec.mamba import *
with description('a_basic_puzzle'):
with before.all:
warehouse.save()
prod_config.init()
self.subject = a_basic_puzzle.g... | Python | 0 |
3066f8f64f185624fe95a696d7fcef102dc61921 | add galery models | helena/content/models.py | helena/content/models.py | from django.db import models
from helpers.service import image_path
class ImgWithDescr(models.Model):
""" class with genres model """
directory = None
def get_image_path(instace, filename):
return image_path(instace, filename, directory=self.directory)
title = models.CharField(verbose_nam... | from django.db import models
from helpers.service import image_path
class Genres(models.Model):
""" class with genres model """
def get_image_path(instace, filename):
return image_path(instace, filename, directory='genres')
title = models.CharField(verbose_name='Заголовок', max_length=200)
... | Python | 0.000001 |
a1d3304f993702460077d7f6c70607131aff874b | add fix keyword | libs/player.py | libs/player.py | # @Time : 2016/11/11 11:01
# @Author : lixintong
from keywords import keyword, var_cache
@keyword('current_activity')
def current_activity(acticity_desc):
"""
:param acticity_desc:video_player or topic_player or live or vr_live or pic_player or local_player
:return:
"""
return var_cache['proxy... | # @Time : 2016/11/11 11:01
# @Author : lixintong
from keywords import keyword, var_cache
@keyword('current_activity')
def current_activity(acticity_desc):
"""
:param acticity_desc:video_player or topic_player or live or vr_live or pic_player or local_player
:return:
"""
return var_cache['proxy... | Python | 0 |
04d0bb5a32b3e1b66c6ac1e27df656aed607c3cb | Test suite: Fix re_util doctest on PyPy | python/phonenumbers/re_util.py | python/phonenumbers/re_util.py | """Additional regular expression utilities, to make it easier to sync up
with Java regular expression code.
>>> import re
>>> from .re_util import fullmatch
>>> from .util import u
>>> string = 'abcd'
>>> r1 = re.compile('abcd')
>>> r2 = re.compile('bc')
>>> r3 = re.compile('abc')
>>> fullmatch(r1, string) # doctest:... | """Additional regular expression utilities, to make it easier to sync up
with Java regular expression code.
>>> import re
>>> from .re_util import fullmatch
>>> from .util import u
>>> string = 'abcd'
>>> r1 = re.compile('abcd')
>>> r2 = re.compile('bc')
>>> r3 = re.compile('abc')
>>> fullmatch(r1, string) # doctest:... | Python | 0 |
f44b5758f2320021fa607891e97a6f4e438b47a2 | Add command line flag for tail end cutoff for specificity score experiments | train_bert_keras_model.py | train_bert_keras_model.py | """
Copyright 2020 Google LLC.
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
dis... | """
Copyright 2020 Google LLC.
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
dis... | Python | 0 |
7fcfe4ece5d7b792b2f38b9b0115f590d3fe0e60 | Fix glu.py for windows | autoconf/glu.py | autoconf/glu.py | from _external import *
from gl import *
if windows:
glu = LibWithHeaderChecker('GLU32', ['windows.h','GL/glu.h'], 'c', dependencies=[gl])
elif macos:
glu = LibWithHeaderChecker('OpenGL', ['OpenGL/glu.h'], 'c', name='glu')
else :
glu = LibWithHeaderChecker('GLU', ['GL/glu.h'], 'c', dependencies=[gl])
| from _external import *
from gl import *
if windows:
glu = LibWithHeaderChecker('GLU32', ['windows.h','GL/glu.h'], 'c', dependencies=[gl])
if macos:
glu = LibWithHeaderChecker('OpenGL', ['OpenGL/glu.h'], 'c', name='glu')
else :
glu = LibWithHeaderChecker('GLU', ['GL/glu.h'], 'c', dependencies=[gl])
| Python | 0.000002 |
33017d1266b36635a5f29db5ae6883e1bf97e76e | Add fullPath to folders in box metadata | waterbutler/providers/box/metadata.py | waterbutler/providers/box/metadata.py | import os
from waterbutler.core import metadata
class BaseBoxMetadata(metadata.BaseMetadata):
def __init__(self, raw, folder):
super().__init__(raw)
self.folder = folder
@property
def provider(self):
return 'box'
@property
def full_path(self):
if 'path_collectio... | import os
from waterbutler.core import metadata
class BaseBoxMetadata(metadata.BaseMetadata):
def __init__(self, raw, folder):
super().__init__(raw)
self.folder = folder
@property
def provider(self):
return 'box'
class BoxFolderMetadata(BaseBoxMetadata, metadata.BaseFolderMeta... | Python | 0.000001 |
cde4a3d1a2ae9d6108eafcd8eb5a21d56ebaae70 | Include working directory in build | avalon/build.py | avalon/build.py | """Project Builder API
Usage:
$ cd project
$ python -m avalon.build
"""
import os
import sys
import json
import shutil
import tempfile
import subprocess
from avalon import lib, session
AVALON_DEBUG = bool(os.getenv("AVALON_DEBUG"))
def run(src, fname, session):
tempdir = tempfile.mkdtemp()
with ... | import os
import sys
import json
import shutil
import tempfile
import subprocess
from avalon import lib, _session
CREATE_NO_WINDOW = 0x08000000
IS_WIN32 = sys.platform == "win32"
DEBUG = os.getenv("AVALON_DEBUG", False)
def run(src, fname, session):
tempdir = tempfile.mkdtemp()
with tempfile.NamedTemporaryF... | Python | 0 |
2e3d31dd20936574d238fc61c1d43983d8b9ff1c | Add out_path input. | qipipe/interfaces/fix_dicom.py | qipipe/interfaces/fix_dicom.py | from nipype.interfaces.base import (BaseInterface,
BaseInterfaceInputSpec, traits, Directory, TraitedSpec)
import os
from qipipe.staging.fix_dicom import fix_dicom_headers
class FixDicomInputSpec(BaseInterfaceInputSpec):
source = Directory(exists=True, desc='The input patient directory', mandatory=True)
de... | from nipype.interfaces.base import (BaseInterface,
BaseInterfaceInputSpec, traits, Directory, TraitedSpec)
import os
from qipipe.staging.fix_dicom import fix_dicom_headers
class FixDicomInputSpec(BaseInterfaceInputSpec):
source = Directory(exists=True, desc='The input patient directory', mandatory=True)
de... | Python | 0 |
9d3d541faaf993665040d39a5cacb52d7a096cde | Add in a model concept for settings | drupdates/utils.py | drupdates/utils.py | import datetime
import requests
import os
from os.path import expanduser
import yaml
def nextFriday():
# Get the data string for the following Friday
today = datetime.date.today()
if datetime.datetime.today().weekday() == 4:
friday = str(today + datetime.timedelta( (3-today.weekday())%7+1 ))
else:
frid... | import datetime
import requests
import os
from os.path import expanduser
import yaml
def nextFriday():
# Get the data string for the following Friday
today = datetime.date.today()
if datetime.datetime.today().weekday() == 4:
friday = str(today + datetime.timedelta( (3-today.weekday())%7+1 ))
else:
frid... | Python | 0.000001 |
3972594787f4ed33d656ff0c097fdb3633a96b14 | add testcase for #1 | tsstats/tests/test_log.py | tsstats/tests/test_log.py | from time import sleep
import pytest
from tsstats.exceptions import InvalidLog
from tsstats.log import parse_log, parse_logs
@pytest.fixture
def clients():
return parse_log('tsstats/tests/res/test.log')
def test_log_client_count(clients):
assert len(clients) == 3
def test_log_onlinetime(clients):
as... | import pytest
from tsstats.exceptions import InvalidLog
from tsstats.log import parse_log, parse_logs
@pytest.fixture
def clients():
return parse_log('tsstats/tests/res/test.log')
def test_log_client_count(clients):
assert len(clients) == 3
def test_log_onlinetime(clients):
assert clients['1'].online... | Python | 0.000001 |
07f86c47c58d6266bd4b42c81521001aca072ff1 | Add some more rubbish to example string | jsonconfigparser/test/__init__.py | jsonconfigparser/test/__init__.py | import unittest
from jsonconfigparser import JSONConfigParser
class JSONConfigTestCase(unittest.TestCase):
def test_init(self):
JSONConfigParser()
def test_read_string(self):
string = '[section]\n' + \
'# comment comment\n' + \
'foo = "bar"\n' + \
... | import unittest
from jsonconfigparser import JSONConfigParser
class JSONConfigTestCase(unittest.TestCase):
def test_init(self):
JSONConfigParser()
def test_read_string(self):
string = '[section]\n' + \
'foo = "bar"\n'
cf = JSONConfigParser()
cf.read_string(s... | Python | 0.000173 |
39da3725f9b8e6842f06954c562873d0a8ff731a | fix silly request header error | dvc/remote/http.py | dvc/remote/http.py | from __future__ import unicode_literals
from dvc.scheme import Schemes
from dvc.utils import LARGE_FILE_SIZE
from dvc.utils.compat import open
import requests
import logging
from dvc.progress import Tqdm
from dvc.exceptions import DvcException
from dvc.config import Config
from dvc.remote.base import RemoteBASE
log... | from __future__ import unicode_literals
from dvc.scheme import Schemes
from dvc.utils import LARGE_FILE_SIZE
from dvc.utils.compat import open
import requests
import logging
from dvc.progress import Tqdm
from dvc.exceptions import DvcException
from dvc.config import Config
from dvc.remote.base import RemoteBASE
log... | Python | 0.000004 |
546368705e132fcc462f63e40f89eb431c54ec65 | Remove XMLField (removed from django 1.4) | dynamo/settings.py | dynamo/settings.py |
# django imports
from django.conf import settings
# Delete database column after field has been deleted
DYNAMO_DELETE_COLUMNS = getattr(settings,'DYNAMO_DELETE_COLUMNS',True)
# Delete database table after model has been deleted
DYNAMO_DELETE_TABLES = getattr(settings,'DYNAMO_DELETE_TABLES',True)
# Default app to ... |
# django imports
from django.conf import settings
# Delete database column after field has been deleted
DYNAMO_DELETE_COLUMNS = getattr(settings,'DYNAMO_DELETE_COLUMNS',True)
# Delete database table after model has been deleted
DYNAMO_DELETE_TABLES = getattr(settings,'DYNAMO_DELETE_TABLES',True)
# Default app to ... | Python | 0 |
49ff951100b35c63d6b04f4c18f8123240fabec1 | Check for datetime present in event start and end date. | economicpy/gcal.py | economicpy/gcal.py | import gflags
import httplib2
from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run
class Calendar(object):
def __init__(self, client_id, client_secret, ignore_events, src_path):
self.user_agent =... | import gflags
import httplib2
from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run
class Calendar(object):
def __init__(self, client_id, client_secret, ignore_events, src_path):
self.user_agent =... | Python | 0 |
60039cd74693982ef38808a63366aa1454b50bd1 | Bump version to 13.3.2 | recipe_scrapers/__version__.py | recipe_scrapers/__version__.py | __version__ = "13.3.2"
| __version__ = "13.3.1"
| Python | 0 |
6c293419d490f217a520e6c9fc696b39a46a172c | Fix excludes | froide_campaign/providers/amenity.py | froide_campaign/providers/amenity.py | from django.db.models import Q
from django.template.defaultfilters import slugify
from django_amenities.models import Amenity
from froide.publicbody.models import PublicBody
from froide.georegion.models import GeoRegion
from ..models import InformationObject
from .base import BaseProvider, first
class AmenityProv... | from django.template.defaultfilters import slugify
from django_amenities.models import Amenity
from froide.publicbody.models import PublicBody
from froide.georegion.models import GeoRegion
from ..models import InformationObject
from .base import BaseProvider, first
class AmenityProvider(BaseProvider):
CREATE_... | Python | 0.000006 |
d0625e452a3cf01535468d6908d9b4c2ae354f62 | Implement announce with verify host | st-ddns.py | st-ddns.py | #!/usr/bin/env python3
import ssl
from hashlib import sha256
import requests
from deviceID import get_device_id
# fingerprint pinning to host
pinning = (
(
'discovery-v4-1.syncthing.net',
'SR7AARM-TCBUZ5O-VFAXY4D-CECGSDE-3Q6IZ4G-XG7AH75-OBIXJQV-QJ6NLQA',
),
(
'discovery-v4-2.syncth... | #!/usr/bin/env python3
import requests
import ssl
from hashlib import sha256
from deviceID import get_device_id
# ID pinning to host
pinning = (
(
'discovery-v4-1.syncthing.net',
'SR7AARM-TCBUZ5O-VFAXY4D-CECGSDE-3Q6IZ4G-XG7AH75-OBIXJQV-QJ6NLQA',
),
)
def verify_host(host):
cert = ssl.get... | Python | 0 |
87a720dc526efe9732fd1b4633e773ef4a11352a | Use earliest consultation if legal date is unavailable | mainapp/management/commands/fix-sort-date.py | mainapp/management/commands/fix-sort-date.py | import datetime
from dateutil import tz
from django.core.management.base import BaseCommand
from django.db.models import F, Subquery, OuterRef, Q
from mainapp.models import Paper, File, Consultation
class Command(BaseCommand):
help = "After the initial import, this command guesses the sort_date-Attribute of pap... | import datetime
from django.core.management.base import BaseCommand
from django.db.models import F
from mainapp.models import Paper, File
class Command(BaseCommand):
help = "After the initial import, this command guesses the sort_date-Attribute of papers and files"
def add_arguments(self, parser):
... | Python | 0 |
5320f9bd74aeab70849cf288d5da4a94bd98cccd | store labels in a separate text field | load_corpus.py | load_corpus.py | #!/usr/bin/env python
from elasticsearch import Elasticsearch
from elasticsearch.client import IndicesClient
import os
es = Elasticsearch()
index = IndicesClient(es)
if index.exists('yso'):
index.delete('yso')
indexconf = {
'mappings': {
'concept': {
'properties': {
'labe... | #!/usr/bin/env python
from elasticsearch import Elasticsearch
from elasticsearch.client import IndicesClient
import os
es = Elasticsearch()
index = IndicesClient(es)
if index.exists('yso'):
index.delete('yso')
indexconf = {
'mappings': {
'concept': {
'properties': {
'text... | Python | 0.000001 |
0c5310374e7eaeb39fcc3c184b60afa096abf364 | Add missing methods from ItemWrapper | gaphor/core/modeling/presentation.py | gaphor/core/modeling/presentation.py | """
Base code for presentation elements
"""
from __future__ import annotations
from typing import (
TYPE_CHECKING,
Callable,
Dict,
Generator,
Generic,
List,
Optional,
Sequence,
TypeVar,
)
from gaphor.core.modeling import Element
from gaphor.core.modeling.properties import associat... | """
Base code for presentation elements
"""
from __future__ import annotations
from typing import (
TYPE_CHECKING,
Callable,
Dict,
Generator,
Generic,
List,
Optional,
TypeVar,
)
from gaphor.core.modeling import Element
from gaphor.core.modeling.properties import association, attribute... | Python | 0 |
4a719e275c3639b2a2186711d9d616ce9435d614 | Update agent for environment | reinforcement-learning/play.py | reinforcement-learning/play.py | """This is the agent which currently takes the action with highest immediate reward."""
import env
env.make("text")
for episode in range(10):
env.reset()
episode_reward = 0
for t in range(100):
episode_reward += env.actual_reward
if env.done:
print(
"Episode %d ... | """This is the agent which currently takes the action with highest immediate reward."""
import pandas as pd
import numpy as np
import env
actions = ["left", "right", "stay"]
left = {x: [0]*(env.screen_width - 1) for x in range(2)}
right = {x: [0]*(env.screen_width - 1) for x in range(2)}
table = pd.DataFrame(left)
... | Python | 0 |
2a2ab3f758facfafe3604325ecec08cfcfa2b6e9 | Update tests.py | image_space_app/tests.py | image_space_app/tests.py | import datetime
import unittest
from django.utils import timezone
from django.test import TestCase
class ImageSpaceTests(unittest.TestCase):
def setUp(self):
self.url="http://localhost:8000"
self.email="John@doe.com"
self.password="password"
def tearDown(self):
del self.ur... | import datetime
import unittest
from django.utils import timezone
from django.test import TestCase
class ImageSpaceTests(unittest.TestCase):
def setUp(self):
self.url="http://localhost:8000"
self.email="John@doe.com"
self.password="password"
def tearDown(self):
del self.ur... | Python | 0.000001 |
7fb829cf17b8274ca67f98356e2d47abedc2df5b | Add type information to component registry | gaphor/services/componentregistry.py | gaphor/services/componentregistry.py | """
A registry for components (e.g. services) and event handling.
"""
from typing import Iterator, Set, Tuple, Type, TypeVar
from gaphor.abc import Service
from gaphor.application import ComponentLookupError
T = TypeVar("T", bound=Service)
class ComponentRegistry(Service):
"""
The ComponentRegistry provide... | """
A registry for components (e.g. services) and event handling.
"""
from typing import Set, Tuple
from gaphor.abc import Service
from gaphor.application import ComponentLookupError
class ComponentRegistry(Service):
"""
The ComponentRegistry provides a home for application wide components.
"""
def ... | Python | 0 |
907165cf323d2492ee2fc2f837a0aff2fec8ef77 | Update utils.py | banpei/utils.py | banpei/utils.py | import numpy as np
def power_method(A, iter_num=1):
"""
Calculate the first singular vector/value of a target matrix based on the power method.
Parameters
----------
A : numpy array
Target matrix
iter_num : int
Number of iterations
Returns
-------
u : numpy ... | import numpy as np
def power_method(A, iter_num=1):
"""
Calculate the first singular vector/value of a target matrix based on the power method.
Parameters
----------
A : numpy array
Target matrix
iter_num : int
Number of iterations
Returns
-------
u : numpy ... | Python | 0 |
c793401befa1efed0b5ad1eb77809c23f6855372 | Fix ES thread mapping. | inbox/search/mappings.py | inbox/search/mappings.py | # TODO[k]: participants as nested, tags too.
# first/last_message_timestamp as {'type': 'date', 'format': 'dateOptionalTime'}
# for range filters and such?
THREAD_MAPPING = {
'properties': {
'namespace_id': {'type': 'string'},
'tags': {'type': 'string'},
'last_message_timestamp': {'type': 's... | # TODO[k]: participants as nested, tags too.
THREAD_MAPPING = {
'properties': {
'namespace_id': {'type': 'string'},
'tags': {'type': 'string'},
'last_message_timestamp': {'type': 'date', 'format': 'dateOptionalTime'},
'object': {'type': 'string'},
'message_ids': {'type': 'str... | Python | 0 |
e0dac0a621cbeed615553e5c3544f9c49de96eb2 | Subtract 1 from model end_year | metadata/FrostNumberModel/hooks/pre-stage.py | metadata/FrostNumberModel/hooks/pre-stage.py | """A hook for modifying parameter values read from the WMT client."""
import os
import shutil
from wmt.utils.hook import find_simulation_input_file, yaml_dump
from topoflow_utils.hook import assign_parameters
file_list = []
def execute(env):
"""Perform pre-stage tasks for running a component.
Parameters
... | """A hook for modifying parameter values read from the WMT client."""
import os
import shutil
from wmt.utils.hook import find_simulation_input_file
from topoflow_utils.hook import assign_parameters
file_list = []
def execute(env):
"""Perform pre-stage tasks for running a component.
Parameters
-------... | Python | 0 |
be7ee0ba4cdfab1ef03b0d58913cddb00c572c0f | Revise descriptive comments | lc0131_palindrome_partitioning.py | lc0131_palindrome_partitioning.py | """Leetcode 131. Palindrome Partitioning
Medium
URL: https://leetcode.com/problems/palindrome-partitioning/
Given a string s, partition s such that
every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example:
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]
"""... | """Leetcode 131. Palindrome Partitioning
Medium
URL: https://leetcode.com/problems/palindrome-partitioning/
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example:
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]
"""
... | Python | 0.000001 |
9d29061f8520506d798ad75aa296be8dc838aaf7 | Remove leftover print call in paginator | resolwe/elastic/pagination.py | resolwe/elastic/pagination.py | """.. Ignore pydocstyle D400.
==================
Elastic Paginators
==================
Paginator classes used in Elastic app.
.. autoclass:: resolwe.elastic.pagination.LimitOffsetPostPagination
"""
from __future__ import absolute_import, division, print_function, unicode_literals
from rest_framework.pagination im... | """.. Ignore pydocstyle D400.
==================
Elastic Paginators
==================
Paginator classes used in Elastic app.
.. autoclass:: resolwe.elastic.pagination.LimitOffsetPostPagination
"""
from __future__ import absolute_import, division, print_function, unicode_literals
from rest_framework.pagination im... | Python | 0 |
7e42c10472dd8c97649d523bb00c13f952698c46 | Fix versions | myvcs/main.py | myvcs/main.py | #!/usr/bin/env python
import os
from os.path import basename, exists, isdir, join
import shutil
import string
import sys
META_DIR = '.myvcs'
def backup(path):
backup_dir = join(path, META_DIR)
if exists(backup_dir):
shutil.rmtree(backup_dir)
def is_backup_dir(src, names):
if src == path:
... | #!/usr/bin/env python
import os
from os.path import exists, isdir, join
import shutil
import sys
META_DIR = '.myvcs'
def backup(path):
backup_dir = join(path, META_DIR)
if exists(backup_dir):
shutil.rmtree(backup_dir)
def is_backup_dir(src, names):
if src == path:
return [META... | Python | 0.000001 |
ee1effb3a91bca7fcf1c590955f45e5b631a0598 | Revise documentation | hanlp/pretrained/ner.py | hanlp/pretrained/ner.py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-30 20:07
from hanlp_common.constant import HANLP_URL
MSRA_NER_BERT_BASE_ZH = HANLP_URL + 'ner/ner_bert_base_msra_20200104_185735.zip'
'BERT model (:cite:`devlin-etal-2019-bert`) trained on MSRA with 3 entity types.'
MSRA_NER_ALBERT_BASE_ZH = HANLP_URL + 'ner/ner_... | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-30 20:07
from hanlp_common.constant import HANLP_URL
MSRA_NER_BERT_BASE_ZH = HANLP_URL + 'ner/ner_bert_base_msra_20200104_185735.zip'
'BERT model (:cite:`devlin-etal-2019-bert`) trained on MSRA with 3 entity types.'
MSRA_NER_ALBERT_BASE_ZH = HANLP_URL + 'ner/ner_... | Python | 0.000001 |
6df071a84e4c1c75e93c33e6e8676cf4b618e2a6 | Add __version__ and remove testing hack | bes/__init__.py | bes/__init__.py | """
Log actions to Elastic Search (via UDP)
"""
import datetime as _datetime
import json as _json
import logging as _logging
import socket as _socket
__version__ = '0.1'
LOG = _logging.getLogger(__name__)
DEFAULT = {
'host': 'localhost',
'port': 9700,
'protocol': 'UDP',
'index': 'log',
'datest... | """
Log actions to Elastic Search (via UDP)
"""
import datetime as _datetime
import json as _json
import logging as _logging
import socket as _socket
LOG = _logging.getLogger(__name__)
DEFAULT = {
'host': 'localhost',
'port': 9700,
'protocol': 'UDP',
'index': 'log',
'datestamp_index': False,
... | Python | 0.000017 |
a5d3c78295d951fd29f00fc8d8480c2a518fd615 | set srid explicit | utm_zone_info/viewsets.py | utm_zone_info/viewsets.py | from rest_framework import status, viewsets
from rest_framework.response import Response
from utm_zone_info.coordinate_reference_system import utm_zones_for_representing
from utm_zone_info.serializers import GeometrySerializer
class UTMZoneInfoViewSet(viewsets.ViewSet):
"""
A simple ViewSet for posting Point... | from rest_framework import status, viewsets
from rest_framework.response import Response
from utm_zone_info.coordinate_reference_system import utm_zones_for_representing
from utm_zone_info.serializers import GeometrySerializer
class UTMZoneInfoViewSet(viewsets.ViewSet):
"""
A simple ViewSet for posting Point... | Python | 0.000002 |
b62423f6ccb47a6f4074ec8e95d9861a3bb06874 | Change error message | ckanext/requestdata/logic/validators.py | ckanext/requestdata/logic/validators.py | from email_validator import validate_email
from ckan.plugins.toolkit import _
from ckan.plugins.toolkit import get_action
def email_validator(key, data, errors, context):
email = data[key]
try:
validate_email(email)
except Exception:
message = _('Please provide a valid email address.')
... | from email_validator import validate_email
from ckan.plugins.toolkit import _
from ckan.plugins.toolkit import get_action
def email_validator(key, data, errors, context):
email = data[key]
try:
validate_email(email)
except Exception:
message = _('Please provide a valid email address.')
... | Python | 0.000001 |
cd1e6ddbf8038c7f65357ec42eaa31b9ddf3f1d6 | add statistics module | statistics.py | statistics.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from PySide.QtSql import *
from db import *
class Statistics:
meta_table = MetaTable()
class SequenceStatistics(Statistics):
def __init__(self, unit='Mb', letter='ATCG'):
self.table = FastaTable()
self.unit = unit
self.letter = letter
self._bases = {'A':0,'G':0... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from PySide.QtSql import *
from db import *
class Statistics:
meta_table = MetaTable()
class SequenceStatistics(Statistics):
def __init__(self):
self.table = FastaTable()
self._bases = {'A':0,'G':0,'C':0,'T':0}
self._total_sequences = 0
self._total_bases = 0
... | Python | 0.000001 |
09e8dd8ed521105aedeb9d35234998d7fa82bb4d | Format max line length to 79. | sqlcop/cli.py | sqlcop/cli.py | from __future__ import print_function
import sys
import sqlparse
import optparse
from sqlcop.checks.cross_join import CrossJoinCheck
from sqlcop.checks.order_by_count import OrderByCountCheck
def parse_file(filename):
try:
return open(filename, 'r').readlines()
except UnicodeDecodeError:
# It'... | from __future__ import print_function
import sys
import sqlparse
import optparse
from sqlcop.checks.cross_join import CrossJoinCheck
from sqlcop.checks.order_by_count import OrderByCountCheck
def parse_file(filename):
try:
return open(filename, 'r').readlines()
except UnicodeDecodeError:
# It'... | Python | 0.000351 |
51257ca1ebb61d48b8c8dd5b1562fdc73e4ecc99 | Load .solv file from testdata | bindings/python/tests/relation.py | bindings/python/tests/relation.py | #
# test Relation
#
# Relations are the primary means to specify dependencies.
# Relations combine names and version through an operator.
# Relations can be compared (<=> operator) or matched (=~ operator)
#
# The following operators are defined:
# REL_GT: greater than
# REL_EQ: equals
# REL_GE: greater equal
# ... | #
# test Relation
#
# Relations are the primary means to specify dependencies.
# Relations combine names and version through an operator.
# Relations can be compared (<=> operator) or matched (=~ operator)
#
# The following operators are defined:
# REL_GT: greater than
# REL_EQ: equals
# REL_GE: greater equal
# ... | Python | 0 |
e64d922a7e7c64921c90d81c44014f7287ba83fa | disable logging in travis | .travis/localsettings.py | .travis/localsettings.py | import os
####### Configuration for CommCareHQ Running on Travis-CI #####
from docker.dockersettings import *
USE_PARTITIONED_DATABASE = os.environ.get('USE_PARTITIONED_DATABASE', 'no') == 'yes'
PARTITION_DATABASE_CONFIG = get_partitioned_database_config(USE_PARTITIONED_DATABASE)
BASE_ADDRESS = '{}:8000'.format(os.... | import os
####### Configuration for CommCareHQ Running on Travis-CI #####
from docker.dockersettings import *
USE_PARTITIONED_DATABASE = os.environ.get('USE_PARTITIONED_DATABASE', 'no') == 'yes'
PARTITION_DATABASE_CONFIG = get_partitioned_database_config(USE_PARTITIONED_DATABASE)
BASE_ADDRESS = '{}:8000'.format(os.... | Python | 0 |
a150520c9fd49a3e6cb6b4396694371797de8440 | make plot tool skip invalid files | modules/tools/plot_trace/plot_planning_result.py | modules/tools/plot_trace/plot_planning_result.py | #!/usr/bin/env python
###############################################################################
# Copyright 2017 The Apollo 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 ... | #!/usr/bin/env python
###############################################################################
# Copyright 2017 The Apollo 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 ... | Python | 0.000001 |
6f69a770ef3b55a7d846abfc306e41025131d8a6 | Fix FeedEntry custom model admin | apps/feeds/admin.py | apps/feeds/admin.py | from django.contrib import admin
from .models import Feed, FeedEntry
class FeedAdmin(admin.ModelAdmin):
list_display = ('feed_url', 'created_by')
class FeedEntryAdmin(admin.ModelAdmin):
list_display = ('title', 'link', 'feed',
'feed_created_by', 'added_to_kippt')
def feed_created_b... | from django.contrib import admin
from .models import Feed, FeedEntry
class FeedEntryAdmin(admin.ModelAdmin):
list_display = ('title', 'link', 'feed',
'feed__created_by', 'added_to_kippt')
admin.site.register(Feed)
admin.site.register(FeedEntry, FeedEntryAdmin)
| Python | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.