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 |
|---|---|---|---|---|---|---|---|
a66cba1f1c41ae371c752dc7b4b0f4609c8e8161 | Fix Houzz usufy wrapper | osrframework/wrappers/houzz.py | osrframework/wrappers/houzz.py | # !/usr/bin/python
# -*- coding: cp1252 -*-
#
##################################################################################
#
# Copyright 2016-2018 Félix Brezo and Yaiza Rubio (i3visio, contacto@i3visio.com)
#
# This program is part of OSRFramework. You can redistribute it and/or modify
# it under the ter... | # !/usr/bin/python
# -*- coding: cp1252 -*-
#
##################################################################################
#
# Copyright 2016-2018 Félix Brezo and Yaiza Rubio (i3visio, contacto@i3visio.com)
#
# This program is part of OSRFramework. You can redistribute it and/or modify
# it under the ter... | Python | 0 |
52b1448c6eb91ca9d59c7f2be5fa60f93262d52b | Bump version to 2.2.0 | pip_check_reqs/__init__.py | pip_check_reqs/__init__.py | __version__ = '2.2.0'
| __version__ = '2.1.1'
| Python | 0 |
695ea0a9b9768c713e03f9d3ec3ca4a702de0347 | Update repeaterBotScript.py | script/repeaterBotScript.py | script/repeaterBotScript.py | # For the Repeater Bot
import telepot
# your bot key
bot = telepot.Bot("[YOUR_TOKEN]")
def handle(msg):
chat_id = msg['chat']['id']
chat_msg = msg['text']
bot.sendMessage(chat_id, chat_msg)
bot.message_loop(handle)
| # For the Repeater Bot
import telepot
# your bot key
bot = telepot.Bot("228412441:AAH0hKP-WOlcFGsZRaSCETVKIFBZf7C4gXc")
def handle(msg):
chat_id = msg['chat']['id']
chat_msg = msg['text']
bot.sendMessage(chat_id, chat_msg)
bot.message_loop(handle)
| Python | 0.000001 |
2033166b57ec566c763a9ff70df9a4123243160d | Bump version to 1.17.4 | platformio_api/__init__.py | platformio_api/__init__.py | # Copyright 2014-present Ivan Kravets <me@ikravets.com>
#
# 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... | # Copyright 2014-present Ivan Kravets <me@ikravets.com>
#
# 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... | Python | 0 |
1ce9101f4ac12e400e0ba09a2221c16f3b02f0ab | Add iter_plugins_dirs() test | podoc/tests/test_plugin.py | podoc/tests/test_plugin.py | # -*- coding: utf-8 -*-
"""Test plugin system."""
#------------------------------------------------------------------------------
# Imports
#------------------------------------------------------------------------------
import os.path as op
from ..core import save_text
from ..plugin import (IPluginRegistry, IPlugi... | # -*- coding: utf-8 -*-
"""Test plugin system."""
#------------------------------------------------------------------------------
# Imports
#------------------------------------------------------------------------------
import os.path as op
from ..core import save_text
from ..plugin import IPluginRegistry, IPlugin... | Python | 0.000001 |
ab037d2fc6d91ecbdb17e083b6ae81c235a91411 | Optimize pauses | polyglotdb/corpus/pause.py | polyglotdb/corpus/pause.py | from .importable import ImportContext
class PauseContext(ImportContext):
"""
Class that contains methods for dealing specifically with non-speech elements
"""
@property
def has_pauses(self):
return 'pause' in self.hierarchy.subset_tokens[self.word_name]
def encode_pauses(self, pause_w... | from .importable import ImportContext
class PauseContext(ImportContext):
"""
Class that contains methods for dealing specifically with non-speech elements
"""
@property
def has_pauses(self):
return 'pause' in self.hierarchy.subset_tokens[self.word_name]
def encode_pauses(self, pause_w... | Python | 0.000005 |
9c73bba34609226d065ed75603d15abafc616072 | make a plot too | scripts/make-orbitfit-w0.py | scripts/make-orbitfit-w0.py | # coding: utf-8
""" Make w0.npy files from orbitfit results
Call like:
TODO
python fitorbit.py --output-path=../output/orbitfits/ --potential=barred_mw \
-v --nsteps=256 --nwalkers=64 --mpi --fixtime
"""
from __future__ import division, print_function
__author__ = "adrn <adrn@astro.columbia.edu>"
# Standard libr... | # coding: utf-8
""" Make w0.npy files from orbitfit results
Call like:
TODO
python fitorbit.py --output-path=../output/orbitfits/ --potential=barred_mw \
-v --nsteps=256 --nwalkers=64 --mpi --fixtime
"""
from __future__ import division, print_function
__author__ = "adrn <adrn@astro.columbia.edu>"
# Standard libr... | Python | 0.000026 |
5a865e7f9fd8745006c581519802dfc321acfeea | Fix LZ4 Compression for Python-LZ4 | _lz4.py | _lz4.py | try:
# Try to import the python-lz4 package
import lz4.block
except ImportError:
# If python-lz4 isn't present, fallback to using pure python
from io import BytesIO
try:
from six import byte2int
from six.moves import xrange
except ImportError:
xrange = range
de... | try:
# Try to import the python-lz4 package
import lz4.block
except ImportError:
# If python-lz4 isn't present, fallback to using pure python
from io import BytesIO
try:
from six import byte2int
from six.moves import xrange
except ImportError:
xrange = range
de... | Python | 0.010003 |
7fa19f13df92a3ddea6f69519539ead6cdeab3af | implement list --version option | reno/lister.py | reno/lister.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | Python | 0.000105 |
98edde06a481cc18727a8c030bc670f7ab43b73f | increase timeout | scripts/pyinstaller/sign.py | scripts/pyinstaller/sign.py | import argparse
import os
import pathlib
import sys
from subprocess import STDOUT, check_call
if sys.platform != "darwin":
raise NotImplementedError
parser = argparse.ArgumentParser()
parser.add_argument(
"--application-id",
required=True,
help="Certificate ID (should be added to the keychain).",
)
ar... | import argparse
import os
import pathlib
import sys
from subprocess import STDOUT, check_call
if sys.platform != "darwin":
raise NotImplementedError
parser = argparse.ArgumentParser()
parser.add_argument(
"--application-id",
required=True,
help="Certificate ID (should be added to the keychain).",
)
ar... | Python | 0.999426 |
4020c3dea19ac7624ec15b076224845aa79a2c2c | fix last commit (missing import) | protocols/ircs2s_common.py | protocols/ircs2s_common.py | """
ircs2s_common.py: Common base protocol class with functions shared by TS6 and P10-based protocols.
"""
import time
from pylinkirc.classes import Protocol
from pylinkirc.log import log
class IRCS2SProtocol(Protocol):
def checkCollision(self, nick):
"""
Nick collision checker.
"""
... | """
ircs2s_common.py: Common base protocol class with functions shared by TS6 and P10-based protocols.
"""
from pylinkirc.classes import Protocol
from pylinkirc.log import log
class IRCS2SProtocol(Protocol):
def checkCollision(self, nick):
"""
Nick collision checker.
"""
uid = sel... | Python | 0 |
8284279a5e92679976637bc9f966f4b776636e82 | Use copies of net to avoid cross-talk between tests. | Testing/test_InitialConditions.py | Testing/test_InitialConditions.py | import copy
import unittest
import scipy
from TestNetwork import net
net = copy.deepcopy(net)
net.compile()
net.setInitialVariableValue('A', 1.0)
net.setInitialVariableValue('B', 2.0)
class test_ics(unittest.TestCase):
def test_default_initial_conditions(self):
"""Test that default ICs are handled correc... | import copy
import unittest
import scipy
from TestNetwork import net
net = copy.deepcopy(net)
net.compile()
net.setInitialVariableValue('A', 1.0)
net.setInitialVariableValue('B', 2.0)
class test_ics(unittest.TestCase):
def test_default_initial_conditions(self):
"""Test that default ICs are handled correc... | Python | 0 |
b989bc03278cf1049656f7a91bd95806b6a63580 | Use lockfile to ensure just one process | bdbc.py | bdbc.py | """
Listen to windows focus changes, and close Dropbox Preference window
when opened.
"""
import logging
import ctypes
from sys import exit
from pywinauto import Application, findwindows
from fasteners import InterProcessLock
from tempfile import gettempdir
logger = logging.getLogger()
ch = logging.FileHandler(gettemp... | """
Listen to windows focus changes, and close Dropbox Preference window
when opened.
"""
def only_one():
from tendo import singleton
me = singleton.SingleInstance() # will sys.exit(-1) if other instance is running
def kill_window():
from pywinauto import Application, findwindows
try:
for hand... | Python | 0 |
35b9de04035e8e2d19c7d891ce758e95a5bc4679 | Split bord.py into logical functions. | bord.py | bord.py | #!/usr/bin/python3
"""
bord - The Board for your website
bord is a static site generator written in Python 3.
There are many static site generators like bord.
This one is mine.
Written by Rahul Pisharody.
MIT Licence
"""
import argparse
import os
import re
import markdown
from jinja2 import Fi... | #!/usr/bin/python3
"""
bord - The Board for your website
bord is a static site generator written in Python 3.
There are many static site generators like bord.
This one is mine.
Written by Rahul Pisharody.
MIT Licence
"""
import os
import re
import markdown
from jinja2 import FileSystemLoa... | Python | 0 |
aac855cb0339f87e1046811b9097858201cfe841 | isolate helper functions | grove/alpha/jordan_gradient/gradient_helper.py | grove/alpha/jordan_gradient/gradient_helper.py | import numpy as np
def real_to_binary(number, precision=16):
""" Convert real decimal to precision-bit binary fraction
:param float number: Real decimal over [0, 1).
:param int precision: Number of bits of binary precision.
:return float bf: Binary fraction representation of real decimal.
"""
... | import numpy as np
from jordan_gradient import gradient_estimator
def real_to_binary(number, precision=16):
""" Convert real decimal to precision-bit binary fraction
:param float number: Real decimal over [0, 1).
:param int precision: Number of bits of binary precision.
:return float bf: Binary fr... | Python | 0.000004 |
935a9dda8ffcbef049f62f7df6778be5c502dcfa | Update quick_install.py | bin/quick_install.py | bin/quick_install.py | #!/usr/bin/env python
"""Quickly install Mapbender3 starter using Git.
You can just call it or give the name of a branch (defaults to 'develop' as
well as a the directory where to install/update (defaults to
mapbender3_BRANCH).
The default admin account (root <root@example.com> / root) can also be given
using command... | #!/usr/bin/env python
"""Quickly install Mapbender3 starter using Git.
You can just call it or give the name of a branch (defaults to 'develop' as
well as a the directory where to install/update (defaults to
mapbender3_BRANCH).
The default admin account (root <root@example.com> / root) can also be given
using command... | Python | 0.000001 |
29d209feb2a52c8cffb3f4116d43b2b01053df4b | Create latest and branch folder | deploy_gh_pages.py | deploy_gh_pages.py | import json
import os
import shutil
import tempfile
def copytree(src, dst, symlinks=False, ignore=None):
for item in os.listdir(src):
s = os.path.join(src, item)
d = os.path.join(dst, item)
if os.path.isdir(s):
shutil.copytree(s, d, symlinks, ignore)
else:
s... | import json
import os
import shutil
import tempfile
def copytree(src, dst, symlinks=False, ignore=None):
for item in os.listdir(src):
s = os.path.join(src, item)
d = os.path.join(dst, item)
if os.path.isdir(s):
shutil.copytree(s, d, symlinks, ignore)
else:
s... | Python | 0 |
48e7bc7f8adf13dd4ac89277e086ba007e555810 | Return unicode string if element on preprint provider form doesn't exist. | admin/preprint_providers/forms.py | admin/preprint_providers/forms.py | import bleach
from django import forms
from osf.models import PreprintProvider, Subject
from admin.base.utils import get_subject_rules, get_toplevel_subjects, get_nodelicense_choices
class PreprintProviderForm(forms.ModelForm):
toplevel_subjects = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(),... | import bleach
from django import forms
from osf.models import PreprintProvider, Subject
from admin.base.utils import get_subject_rules, get_toplevel_subjects, get_nodelicense_choices
class PreprintProviderForm(forms.ModelForm):
toplevel_subjects = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(),... | Python | 0.000011 |
4aa1b4d79ef7777f060a05c70ead7a27dc6ed6e9 | Add plot_coef | fft2d/plot.py | fft2d/plot.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import fft2d
import numpy as np
import matplotlib.pyplot as plt
import argparse
def _load_size(prop):
Lx = prop.Lx if prop.Lx > 0 else 1.0
Ly = prop.Ly if prop.Ly > 0 else 1.0
return Lx, Ly
def plot_field(filename, figure_ext):
arr, prop = fft2d.load(f... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import fft2d
import numpy as np
import matplotlib.pyplot as plt
import argparse
def main(args):
arr, prop = fft2d.load(args.filename)
Nx, Ny = arr.shape
Lx = prop.Lx if prop.Lx > 0 else 1.0
Ly = prop.Ly if prop.Ly > 0 else 1.0
X, Y = np.meshgrid(np.l... | Python | 0.000013 |
7ee29cfee740d6096fca8379253073077890a54c | Add more info to the redis example. | examples/util/wordcount_redis.py | examples/util/wordcount_redis.py | """
Usage:
python wordcount_redis.py redis://redis_server:6379:0 redis://redis_server:6379:1
The input is read from db 0 and the output is written to db 1. The inputs
should be of the form (key, list_of_values) (they are read from the server with the
lrange command. See the redis documentation for more info).
The ou... | from disco.schemes.scheme_redis import redis_output_stream
from disco.worker.task_io import task_output_stream
from disco.core import Job, result_iterator
class WordCount(Job):
reduce_output_stream = (task_output_stream, redis_output_stream)
@staticmethod
def map(line, params):
k, v = line
... | Python | 0 |
a52bba727dd83acc129494e764c64714ff2d4e52 | fix typo | sympy/utilities/pytest.py | sympy/utilities/pytest.py | """py.test hacks to support XFAIL/XPASS"""
# XXX this should be integrated into py.test
# XXX but we can't force everyone to install py-lib trunk
# tested with py-lib 0.9.0
from py.__.test.outcome import Outcome, Passed, Failed, Skipped
from py.__.test.terminal.terminal import TerminalSession
from time import time as... | """py.test hacks to support XFAIL/XPASS"""
# XXX this should be integrated into py.tes
# XXX but we can't force everyone to install py-lib trunk
# tested with py-lib 0.9.0
from py.__.test.outcome import Outcome, Passed, Failed, Skipped
from py.__.test.terminal.terminal import TerminalSession
from time import time as ... | Python | 0.999991 |
a08c04151e88eb95ae05484adb8b3f64ef91bd87 | Update example | examples/tools/print_mo_and_dm.py | examples/tools/print_mo_and_dm.py | #!/usr/bin/env python
#
# Author: Qiming Sun <osirpt.sun@gmail.com>
#
import sys
import numpy
from pyscf import gto, scf, tools
'''
Formatted output for 2D array
'''
mol = gto.M(atom='H 0 0 0; F 0 0 1', basis='ccpvdz')
nf = mol.nao_nr()
orb = numpy.random.random((nf,4))
#
# Print orbital coefficients
#
tools.dump_m... | #!/usr/bin/env python
#
# Author: Qiming Sun <osirpt.sun@gmail.com>
#
import sys
import numpy
from pyscf import gto, tools
'''
Formatted output for 2D array
'''
mol = gto.M(atom='H 0 0 0; F 0 0 1', basis='ccpvdz')
nf = mol.nao_nr()
orb = numpy.random.random((nf,4))
#
# Print orbital coefficients
#
tools.dump_mat.du... | Python | 0.000001 |
ad595aae697abbf7c7de79a4a2448f0c47133934 | Make viewer runnable from outer dirs. | execution_trace/viewer/viewer.py | execution_trace/viewer/viewer.py | # Run with `python viewer.py PATH_TO_RECORD_JSON.
import json
import os
import sys
from flask import Flask, jsonify
from flask.helpers import send_from_directory
app = Flask(__name__)
viewer_root = os.path.abspath(os.path.dirname(__file__))
# `main` inits these.
# File containing `record` output.
record_path = No... | # Run with `python viewer.py PATH_TO_RECORD_JSON.
import json
import sys
from flask import Flask, jsonify
from flask.helpers import send_from_directory
app = Flask(__name__)
# `main` inits these.
# File containing `record` output.
record_path = None
# 0 is source, 1:N is state
record_data = []
@app.route("/")
de... | Python | 0 |
385fbdc0401c979a71b0ff326852292bbb6a6ceb | Print coverages and deal with missing files | exp/influence2/ProcessResults.py | exp/influence2/ProcessResults.py |
import numpy
import matplotlib
matplotlib.use("GTK3Agg")
import matplotlib.pyplot as plt
from exp.influence2.ArnetMinerDataset import ArnetMinerDataset
from apgl.util.Latex import Latex
from apgl.util.Util import Util
from apgl.util.Evaluator import Evaluator
ranLSI = False
numpy.set_printoptions(suppress=True,... |
import numpy
import matplotlib
matplotlib.use("GTK3Agg")
import matplotlib.pyplot as plt
from exp.influence2.ArnetMinerDataset import ArnetMinerDataset
from apgl.util.Latex import Latex
from apgl.util.Util import Util
from apgl.util.Evaluator import Evaluator
numpy.set_printoptions(suppress=True, precision=3, l... | Python | 0 |
1c939a99e377ff1dfe037c47dd99f635d3cb0a1f | Remove Cotswold election id (update expected) | polling_stations/apps/data_collection/management/commands/import_cotswold.py | polling_stations/apps/data_collection/management/commands/import_cotswold.py | from data_collection.management.commands import BaseXpressWebLookupCsvImporter
class Command(BaseXpressWebLookupCsvImporter):
council_id = 'E07000079'
addresses_name = 'CotswoldPropertyPostCodePollingStationWebLookup-2017-03-27.TSV'
stations_name = 'CotswoldPropertyPostCodePollingStationWebLookup-2017-03-2... | from data_collection.management.commands import BaseXpressWebLookupCsvImporter
class Command(BaseXpressWebLookupCsvImporter):
council_id = 'E07000079'
addresses_name = 'CotswoldPropertyPostCodePollingStationWebLookup-2017-03-27.TSV'
stations_name = 'CotswoldPropertyPostCodePollingStationWebLookup-2017-03-2... | Python | 0 |
55fd2ec6454df9c62e40c5115be94a00bf944bc4 | Allow list_classes.py to be loaded without side-effects | examples/list_classes.py | examples/list_classes.py | #!/usr/bin/python
"""This script lists classes and optionally attributes from UML model created
with Gaphor.
"""
import optparse
import sys
from gaphor import UML
from gaphor.application import Session
# Setup command line options.
usage = "usage: %prog [options] file.gaphor"
def main():
parser = optparse.Opt... | #!/usr/bin/python
"""This script lists classes and optionally attributes from UML model created
with Gaphor.
"""
import optparse
import sys
from gaphor import UML
from gaphor.application import Session
# Setup command line options.
usage = "usage: %prog [options] file.gaphor"
parser = optparse.OptionParser(usage=u... | Python | 0.000001 |
5ced1112e75a076b253072e7386af0cac994c937 | Address flake8 errors with long strings in actions/lib/get_scan_executions.py, via cleanup | packs/alertlogic/actions/lib/get_scan_executions.py | packs/alertlogic/actions/lib/get_scan_executions.py | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | Python | 0 |
99927b39cdfa47d60d6e045898ad4e0745fb763a | Add the ability to get the queue depth by calling len(queue) where queue is an instance of Queue | rmqid/queue.py | rmqid/queue.py | """
Queue is a class that encompasses and returns the methods of the
Specification.Queue class
"""
import contextlib
import logging
from pamqp import specification
from rmqid import base
LOGGER = logging.getLogger(__name__)
class Queue(base.AMQPClass):
"""Queue class that with methods that return the specifica... | """
Queue is a class that encompasses and returns the methods of the
Specification.Queue class
"""
import contextlib
import logging
from pamqp import specification
from rmqid import base
LOGGER = logging.getLogger(__name__)
class Queue(base.AMQPClass):
"""Queue class that with methods that return the specifica... | Python | 0.000018 |
8a348c30e2381e76f09355f3cf23a9e87e060d80 | Update without_end.py | Python/String_1/without_end.py | Python/String_1/without_end.py | # Given a string, return a version without the first and last char, so "Hello"
# yields "ell". The string length will be at least 2.
# without_end('Hello') --> 'ell'
# without_end('java') --> 'av'
# without_end('coding') --> 'odin'
def without_end(str):
return str[1:len(str) - 1]
print(without_end('Hello'))
print(... | # Given a string, return a version without the first and last char, so "Hello"
# yields "ell". The string length will be at least 2.
# without_end('Hello') -> 'ell'
# without_end('java') -> 'av'
# without_end('coding') -> 'odin'
def without_end(str):
return str[1:len(str) - 1]
print(without_end('Hello'))
print(wit... | Python | 0.000002 |
9259bcd9d4dd745a5f34dff8dd4286eecf4a62f2 | Update verifyAuthenticodePS.py | Python/verifyAuthenticodePS.py | Python/verifyAuthenticodePS.py |
# NOTE: This is Windows Only - tested in Python2.7.1
# https://twitter.com/jgstew/status/1011657455275610112
# https://github.com/jgstew/tools/blob/master/CMD/PS_VerifyFileSig.bat
# https://github.com/jgstew/tools/blob/master/Python/verifyAuthenticode.py
# powershell -ExecutionPolicy Bypass -command "(Get-Authenticod... |
# NOTE: This is Windows Only - tested in Python2.7.1
# https://twitter.com/jgstew/status/1011657455275610112
# https://github.com/jgstew/tools/blob/master/CMD/PS_VerifyFileSig.bat
# https://github.com/jgstew/tools/blob/master/Python/verifyAuthenticode.py
# powershell -ExecutionPolicy Bypass -command "(Get-Authenticod... | Python | 0 |
f1ef248f046c91683df8e6837249cc407a5f1cf2 | Update ngrokwebhook.py | examples/ngrokwebhook.py | examples/ngrokwebhook.py | #sample script that reads ngrok info from localhost:4040 and create Cisco Spark Webhook
#typicall ngrok is called "ngrok http 8080" to redirect localhost:8080 to Internet
#accesible ngrok url
#
#To use script simply launch ngrok, then launch this script. After ngrok is killed, run this
#script a second time to re... | #sample script that reads ngrok info from localhost:4040 and create Cisco Spark Webhook
#typicall ngrok is called "ngrok http 8080" to redirect localhost:8080 to Internet
#accesible ngrok url
#
#To use script simply launch ngrok, then launch this script. After ngrok is killed, run this
#script a second time to re... | Python | 0.000001 |
339459eefa9c2b3daab76f258a4bde576b374c9b | Update create_http_task.py (#2187) | tasks/create_http_task.py | tasks/create_http_task.py | # Copyright 2019 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 law or ag... | # Copyright 2019 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 law or ag... | Python | 0.000001 |
fc8bfc1f2cda0844adbf1d831a1a5e1888f8949b | add regression test for behavior when fallbackfee is disabled | test/functional/wallet_fallbackfee.py | test/functional/wallet_fallbackfee.py | #!/usr/bin/env python3
# Copyright (c) 2017-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test wallet replace-by-fee capabilities in conjunction with the fallbackfee."""
from test_framework.tes... | #!/usr/bin/env python3
# Copyright (c) 2017-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test wallet replace-by-fee capabilities in conjunction with the fallbackfee."""
from test_framework.tes... | Python | 0 |
94c1b54ef1db5180c5f1d07e857bf91d6b6fbf25 | fix for python2.7 on windows | examples/usage_stream.py | examples/usage_stream.py | # -*- coding: utf-8 -*-
from janome.tokenizer import Tokenizer
import sys
from io import open
PY3 = sys.version_info[0] == 3
print(u'Tokenize (stream mode)')
t = Tokenizer(mmap=True)
with open('text_lemon.txt', encoding='utf-8') as f:
text = f.read()
if not PY3:
text = unicode(text)
for token in t... | # -*- coding: utf-8 -*-
from janome.tokenizer import Tokenizer
import sys
from io import open
PY3 = sys.version_info[0] == 3
print(u'Tokenize (stream mode)')
t = Tokenizer(mmap=True)
with open('text_lemon.txt', encoding='utf-8') as f:
text = f.read()
if not PY3:
text = unicode(text, 'utf-8')
for t... | Python | 0.000001 |
331cef286380f3369344dbc9a60e460619c17405 | fix dnn | federatedml/nn/homo_nn/zoo/dnn.py | federatedml/nn/homo_nn/zoo/dnn.py | #
# Copyright 2019 The FATE Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | #
# Copyright 2019 The FATE Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | Python | 0.000032 |
cee0a7a3af8f17c69e4c9701a363f50904321bd1 | fix daemonizer.kill | aquests/lib/daemonize.py | aquests/lib/daemonize.py | import os
import sys
import time
import signal
from . import killtree, processutil
class Daemonizer:
def __init__(self, chdir="/", procname = None, umask=0o22):
self.chdir = chdir
self.procname = procname
self.umask = umask
self.pidfile = os.path.join (chdir, '.pid')
def runAsDaemon(self):
if status (sel... | import os
import sys
import time
import signal
from . import killtree, processutil
class Daemonizer:
def __init__(self, chdir="/", procname = None, umask=0o22):
self.chdir = chdir
self.procname = procname
self.umask = umask
self.pidfile = os.path.join (chdir, '.pid')
def runAsDaemon(self):
if status (sel... | Python | 0.000002 |
f5c5fef9cfdc94ad2d1b7d95f990e288251f57fe | Add search analyzer to search | froide/helper/search/__init__.py | froide/helper/search/__init__.py | import importlib
from django.conf import settings
from elasticsearch_dsl import analyzer, tokenizer
from django_elasticsearch_dsl import Index
from .signal_processor import CelerySignalProcessor
from .queryset import SearchQuerySetWrapper
from .registry import search_registry
__all__ = [
'CelerySignalProcessor... | import importlib
from django.conf import settings
from elasticsearch_dsl import analyzer, tokenizer
from django_elasticsearch_dsl import Index
from .signal_processor import CelerySignalProcessor
from .queryset import SearchQuerySetWrapper
from .registry import search_registry
__all__ = [
'CelerySignalProcessor... | Python | 0 |
56b38e64aeea12269b36d11849e0952377510c16 | Change method of listening to state changes | homeassistant/components/automation/template.py | homeassistant/components/automation/template.py | """
homeassistant.components.automation.template
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Offers template automation rules.
For more details about this automation rule, please refer to the documentation
at https://home-assistant.io/components/automation/#template-trigger
"""
import logging
from homeassistant... | """
homeassistant.components.automation.template
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Offers template automation rules.
For more details about this automation rule, please refer to the documentation
at https://home-assistant.io/components/automation/#template-trigger
"""
import logging
from homeassistant... | Python | 0 |
3f80950f1fa9c5bad018a8cdaa9f6ae70168e4e1 | Update main.py | device/src/main.py | device/src/main.py | #This is the file executing while STM32 MCU bootup, and in this file,
#it will call other functions to fullfill the project.
#Communication module: LoRa.
#Communication method with gateway via LoRa.
#Uart port drive LoRa module.
#Parse JSON between device and gateway via LoRa channel.
#LoRa module: E32-TTL-100
#Pin s... | #This is the file executing while STM32 MCU bootup, and in this file,
#it will call other functions to fullfill the project.
#Communication module: LoRa.
#Communication method with gateway via LoRa.
#Uart port drive LoRa module.
#Parse JSON between device and gateway via LoRa channel.
#LoRa module: E32-TTL-100
#Pin s... | Python | 0.000001 |
06a398c6f14259ed03899eae84d54d12fb4336c3 | Update test_code_style.py | _unittests/ut_module/test_code_style.py | _unittests/ut_module/test_code_style.py | """
@brief test log(time=0s)
"""
import sys
import os
import unittest
from pyquickhelper.loghelper import fLOG
from pyquickhelper.pycode import check_pep8, ExtTestCase
try:
import src
except ImportError:
path = os.path.normpath(
os.path.abspath(
os.path.join(
os.path.s... | """
@brief test log(time=0s)
"""
import sys
import os
import unittest
from pyquickhelper.loghelper import fLOG
from pyquickhelper.pycode import check_pep8, ExtTestCase
try:
import src
except ImportError:
path = os.path.normpath(
os.path.abspath(
os.path.join(
os.path.s... | Python | 0.000004 |
5f0e00378b49ca2431d819debaa6ad0d4b4921fe | manage account does not exist exception fix error handling | src/dm/api.py | src/dm/api.py | import json
from .pythontwitter import twitter
from bot.models import Account
import logging
import typing
from django.conf import settings
logger = logging.getLogger(__name__)
def get_api_dict(__screen_name: typing.Optional[str]=None):
if not __screen_name:
return
try:
account = Account.obje... | import json
from .pythontwitter import twitter
from bot.models import Account
import logging
import typing
from django.conf import settings
logger = logging.getLogger(__name__)
def get_api_dict(__screen_name: typing.Optional[str]=None):
if not __screen_name:
return
try:
account = Account.obje... | Python | 0 |
608c55bb681667a6e1fe65e328676a3a99deb391 | Update mupenGenerator.py | configgen/generators/mupen/mupenGenerator.py | configgen/generators/mupen/mupenGenerator.py | #!/usr/bin/env python
import Command
import mupenControllers
import recalboxFiles
from generators.Generator import Generator
class MupenGenerator(Generator):
# Main entry of the module
# Configure mupen and return a command
def generate(self, system, rom, playersControllers):
# Settings recalbox d... | #!/usr/bin/env python
import Command
import mupenControllers
import recalboxFiles
from generators.Generator import Generator
class MupenGenerator(Generator):
# Main entry of the module
# Configure mupen and return a command
def generate(self, system, rom, playersControllers):
# Settings recalbox d... | Python | 0 |
0c88ed9bce4004938d7119f784b82a630b22b95d | Revise doc string with complexity | alg_bellman_ford_shortest_path.py | alg_bellman_ford_shortest_path.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
def update_distance(v, v_neighbor,
w_graph_d, distance_d, previous_d):
if (distance_d[v_neighbor] >
distance_d[v] + w_graph_d[v][v_neighbor]):
... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
def update_distance(v, v_neighbor,
w_graph_d, distance_d, previous_d):
if (distance_d[v_neighbor] >
distance_d[v] + w_graph_d[v][v_neighbor]):
... | Python | 0.000006 |
67a3507ac90b25e632673a4f928a90bdd9e8cb3a | Add permutations generator | data.py | data.py | import numpy as np
import itertools
def _consecutive_index_generator(length, offset=1):
"""Generate pair of ids of consecutive images.
Offset is the distance between the images.
"""
for i in range(length - offset):
yield (i, i + offset)
def generate_learning_set(array, scans_to_average=1, r... | import numpy as np
def _consecutive_index_generator(length, offset=1):
"""Generate pair of ids of consecutive images.
Offset is the distance between the images.
"""
for i in range(length - offset):
yield (i, i + offset)
def generate_learning_set(array, scans_to_average=1, random_permutation... | Python | 0.000014 |
ad3554ae58f65a295ac94c131d8193e0b2e7e6f8 | Add reminder to look at the number of terms returned | termsuggester/word2vec.py | termsuggester/word2vec.py | from gensim.models import Word2Vec
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler())
class Word2VecSuggester():
def __init__(self, modelfile):
try:
self.model = Word2Vec.load(modelfile)
logger.info('Load Wo... | from gensim.models import Word2Vec
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler())
class Word2VecSuggester():
def __init__(self, modelfile):
try:
self.model = Word2Vec.load(modelfile)
logger.info('Load Wo... | Python | 0 |
73a375a3adb140c270444e886b3df842e0b28a86 | Fix formatting tests: cfloat and cdouble as well as np.float and np.double are the same; make sure we test 4 bytes float. | numpy/core/tests/test_print.py | numpy/core/tests/test_print.py | import numpy as np
from numpy.testing import *
def check_float_type(tp):
for x in [0, 1,-1, 1e10, 1e20] :
assert_equal(str(tp(x)), str(float(x)))
def test_float_types():
""" Check formatting.
This is only for the str function, and only for simple types.
The precision of np.float and n... | import numpy as np
from numpy.testing import *
def check_float_type(tp):
for x in [0, 1,-1, 1e10, 1e20] :
assert_equal(str(tp(x)), str(float(x)))
def test_float_types():
""" Check formatting.
This is only for the str function, and only for simple types.
The precision of np.float and n... | Python | 0.000011 |
8c8d97de4c5684f623194260997e01d9b5edbdae | Remove print statements. | dit/divergences/jensen_shannon_divergence.py | dit/divergences/jensen_shannon_divergence.py | """
The Jensen-Shannon Diverence.
This is a reasonable measure of distinguishablity between distribution.
"""
from __future__ import division
import numpy as np
from six.moves import zip # pylint: disable=redefined-builtin
import dit
from ..distconst import mixture_distribution
from ..shannon import entropy as H, e... | """
The Jensen-Shannon Diverence.
This is a reasonable measure of distinguishablity between distribution.
"""
from __future__ import division
import numpy as np
from six.moves import zip # pylint: disable=redefined-builtin
import dit
from ..distconst import mixture_distribution
from ..shannon import entropy as H, e... | Python | 0.000021 |
1bba6908b29e6a58d7ad98af588ef116d3129b85 | move code to separate method and take care with bool8 overflows | kameleon_mcmc/mcmc/samplers/DiscreteKameleon.py | kameleon_mcmc/mcmc/samplers/DiscreteKameleon.py | """
Copyright (c) 2013-2014 Heiko Strathmann
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
*
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and th... | """
Copyright (c) 2013-2014 Heiko Strathmann
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
*
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and th... | Python | 0 |
2eff2b835fe4a042c06b92844c9fa5c92cbeb3ea | change json to yaml when publishing legacy latest files (#186) | runtime_builders/publish_builders.py | runtime_builders/publish_builders.py | #!/usr/bin/python
# Copyright 2017 Google Inc. 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 app... | #!/usr/bin/python
# Copyright 2017 Google Inc. 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 app... | Python | 0 |
dfbedc63d6d8bce2a90feda98989f763eee1f2f4 | update example to latest changes in Bites | Samples/Python/bites_sample.py | Samples/Python/bites_sample.py | import Ogre
import OgreRTShader
import OgreOverlay
import OgreBites
class SampleApp(OgreBites.ApplicationContext, OgreBites.InputListener):
def __init__(self):
OgreBites.ApplicationContext.__init__(self, "PySample", False)
OgreBites.InputListener.__init__(self)
def keyPressed(self, evt):
... | import Ogre
import OgreRTShader
import OgreOverlay
import OgreBites
class SampleApp(OgreBites.ApplicationContext, OgreBites.InputListener):
def __init__(self):
OgreBites.ApplicationContext.__init__(self, "PySample", False)
OgreBites.InputListener.__init__(self)
self.addInputListener(self)
... | Python | 0 |
20202ab774bc064cb23d2c8a7c811e08d968b8da | Add forgotten import. | fedmsg/commands/relay.py | fedmsg/commands/relay.py | # This file is part of fedmsg.
# Copyright (C) 2012 Red Hat, Inc.
#
# fedmsg 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.
#... | # This file is part of fedmsg.
# Copyright (C) 2012 Red Hat, Inc.
#
# fedmsg 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.
#... | Python | 0 |
27d920372b215da7cb2625ce6d7d3f3666bf16e9 | Improve spelling | openfisca_country_template/variables/housing.py | openfisca_country_template/variables/housing.py | # -*- coding: utf-8 -*-
# This file defines the variables of our legislation.
# A variable is property of a person, or an entity (e.g. a household).
# See http://openfisca.org/doc/variables.html
# Import from openfisca-core the common python objects used to code the legislation in OpenFisca
from openfisca_core.model_... | # -*- coding: utf-8 -*-
# This file defines the variables of our legislation.
# A variable is property of a person, or an entity (e.g. a household).
# See http://openfisca.org/doc/variables.html
# Import from openfisca-core the common python objects used to code the legislation in OpenFisca
from openfisca_core.model_... | Python | 0.998348 |
d40b7bdb2cfa846aa170222d8e6eeb477cbf8633 | update pipeline-demo | pipeline/demo/pipeline-demo.py | pipeline/demo/pipeline-demo.py | from pipeline.backend.config import Backend
from pipeline.backend.config import WorkMode
from pipeline.backend.pipeline import PipeLine
from pipeline.component.dataio import DataIO
from pipeline.component.hetero_lr import HeteroLR
from pipeline.component.input import Input
from pipeline.component.intersection import In... | from pipeline.backend.pipeline import PipeLine
from pipeline.component.dataio import DataIO
from pipeline.component.input import Input
from pipeline.component.intersection import Intersection
from pipeline.component.hetero_lr import HeteroLR
from pipeline.interface.data import Data
from pipeline.backend.config import B... | Python | 0 |
2ee27b5b177bcb056889096a265b7a1ef2c21aff | Be more deterministic in the discriminator | adhocracy/lib/instance/discriminator.py | adhocracy/lib/instance/discriminator.py | import logging
from adhocracy import model
from pylons import config
from paste.deploy.converters import asbool
log = logging.getLogger(__name__)
class InstanceDiscriminatorMiddleware(object):
def __init__(self, app, domain):
self.app = app
self.domain = domain
log.debug("Host name: %s.... | import logging
from adhocracy import model
from pylons import config
log = logging.getLogger(__name__)
class InstanceDiscriminatorMiddleware(object):
def __init__(self, app, domain):
self.app = app
self.domain = domain
log.debug("Host name: %s." % domain)
def __call__(self, environ... | Python | 0.999985 |
39e6b8e9e5d3edaf8448b7ebc4ab17989b012ba1 | Add a test for setter and deleter. | server/kcsapi/model_test.py | server/kcsapi/model_test.py | #!/usr/bin/env python
import pytest
import model
class TestJsonSerializableObject(object):
def test_default_getter(self):
class DefaultGetter(model.JsonSerializableObject):
# Can decorate without any arguments.
@model.jsonproperty
def field_foo(self):
... | #!/usr/bin/env python
import pytest
import model
class TestJsonSerializableObject(object):
def test_default_getter(self):
class DefaultGetter(model.JsonSerializableObject):
# Can decorate without any arguments.
@model.jsonproperty
def field_foo(self):
... | Python | 0 |
ce02f48ea85b64a5a4503b22d3fb324c521904d0 | Enable graphiql only when DEBUG=True | saleor/urls.py | saleor/urls.py | from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.sitemaps.views import sitemap
from django.contrib.staticfiles.views import serve
from graphene_django.views import GraphQLView
from .cart.urls impor... | from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.sitemaps.views import sitemap
from django.contrib.staticfiles.views import serve
from graphene_django.views import GraphQLView
from .cart.urls impor... | Python | 0.000041 |
0bb0720616bebd308abae5cbee8d60c4dfa98fe4 | Add a metric ton of test cases (some of which currently fail) | feincms_cleanse/tests.py | feincms_cleanse/tests.py | from django.test import TestCase
from feincms_cleanse import cleanse_html
class CleanseTestCase(TestCase):
def run_tests(self, entries):
for before, after in entries:
after = before if after is None else after
result = cleanse_html(before)
self.assertEqual(result, afte... | from django.test import TestCase
from feincms_cleanse import cleanse_html
class CleanseTestCase(TestCase):
def test_01_cleanse(self):
entries = [
(u'<p> </p>', u''),
(u'<span style="font-weight: bold;">Something</span><p></p>',
u'<strong>Something</strong>'),... | Python | 0.000002 |
ae5977e960b1f4d7953b1929ad1e2ab96e746fce | Add a quick test for `every` mode | tests/test_arguments.py | tests/test_arguments.py | import pytest
import datetime
import argparse
from ding import ding
# Valid arguments
def test_time_a_second_in_the_past():
a_second_ago = datetime.datetime.now() - datetime.timedelta(seconds=1)
time_str = str(a_second_ago.time()).split('.')[0]
assert ding.get_args(['at', time_str])
def test_time_a_minu... | import pytest
import datetime
import argparse
from ding import ding
# Valid arguments
def test_time_a_second_in_the_past():
a_second_ago = datetime.datetime.now() - datetime.timedelta(seconds=1)
time_str = str(a_second_ago.time()).split('.')[0]
assert ding.get_args(['at', time_str])
def test_time_a_minu... | Python | 0.000063 |
67c6506bcc454eeba3aca223fe1de415eb684e4d | Replace os.tempnam with tempfile for python3 (#537) | tests/test_binary_io.py | tests/test_binary_io.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD+Patents license found in the
# LICENSE file in the root directory of this source tree.
#! /usr/bin/env python2
"""Binary indexes (de)serialization"""
import numpy as np
import unittest
import faiss
impo... | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD+Patents license found in the
# LICENSE file in the root directory of this source tree.
#! /usr/bin/env python2
"""Binary indexes (de)serialization"""
import numpy as np
import unittest
import faiss
impo... | Python | 0 |
cc934035033eff97ac698d9fa9b54b38dd2fbe9d | Update main.py | main.py | main.py | # Under MIT License, see LICENSE.txt
import sys
import argparse
import warnings
from PyQt5.QtWidgets import QApplication
from qtpy import QtCore
from Controller.MainController import MainController
__author__ = 'RoboCupULaval'
def argumentParser(argument):
""" Argument parser """
parser = argparse.Argument... | # Under MIT License, see LICENSE.txt
import sys
import argparse
from PyQt5.QtWidgets import QApplication
from qtpy import QtCore
from Controller.MainController import MainController
__author__ = 'RoboCupULaval'
def argumentParser(argument):
""" Argument parser """
parser = argparse.ArgumentParser(descript... | Python | 0 |
c5c67d08470de703ebcd249439c5c189c487e505 | Add a lock | main.py | main.py | from subprocess import Popen, PIPE
import threading
import Queue
import argparse
from itertools import product
class Tailor(threading.Thread):
def __init__(self, queue, server, file, lock):
self.lock = lock
threading.Thread.__init__(self)
self.server = server
self.file = file
self.queue = queue
... | from subprocess import Popen, PIPE
import threading
import Queue
import argparse
from itertools import product
class Tailor(threading.Thread):
def __init__(self, queue, server, file):
threading.Thread.__init__(self)
self.server = server
self.file = file
self.queue = queue
self.daemon = True
s... | Python | 0.00001 |
473ff95fcd1ac784cc3492a4727d668a10270594 | add today filter | main.py | main.py | # -*- coding: utf-8 -*-
import sys
import urllib
import subprocess
import argparse
import datetime
# Constants
URL = "http://www.gifu-nct.ac.jp/gakka/keijiyou/keijiyou.pdf"
LOCALPDF = "keijiyou.pdf"
LOCALTEXT = "keijiyou.txt"
def download():
urllib.urlretrieve(URL, LOCALPDF)
def pre_parse():
cmd = "pdftote... | # -*- coding: utf-8 -*-
import sys
import urllib
import subprocess
import argparse
# Constants
URL = "http://www.gifu-nct.ac.jp/gakka/keijiyou/keijiyou.pdf"
LOCALPDF = "keijiyou.pdf"
LOCALTEXT = "keijiyou.txt"
def download():
urllib.urlretrieve(URL, LOCALPDF)
def pre_parse():
cmd = "pdftotext -raw " + LOCAL... | Python | 0 |
34bd4dec6bc60ff676874c13cb993a8123bd0ddc | handle the exception of an invalid bitly url | main.py | main.py | #!/usr/bin/python
import urllib
import urllib2
import json
import settings as s
class ConsoleBitly:
def shorten(self,req):
url="http://api.bitly.com/v3/shorten?login="+s.bitly_username+"&apiKey="+s.bitly_apikey+"&longUrl="+req
print "Please wait... \n"
response=urllib2.urlopen(url)
a = json.loads(response.rea... | #!/usr/bin/python
import urllib
import urllib2
import json
import settings as s
class ConsoleBitly:
def shorten(self,req):
url="http://api.bitly.com/v3/shorten?login="+s.bitly_username+"&apiKey="+s.bitly_apikey+"&longUrl="+req
print "Please wait... \n"
response=urllib2.urlopen(url)
a = json.loads(response.rea... | Python | 0.000149 |
b57e12c4e01559ce5bcb1588b14758429ad552df | Revert "fix: error instance to pytest" | tests/test_envconfig.py | tests/test_envconfig.py | import pytest
@pytest.mark.parametrize("attribute, value", [
('ATTRIBUTE_STR', 'default_str'),
('ATTRIBUTE_INT', 1),
('ATTRIBUTE_FLOAT', 1.5),
('ATTRIBUTE_BOOL', True),
])
def test_get_attributes(config, attribute, value):
assert getattr(config, attribute) == value
def test_set_existing_attribut... | import pytest
@pytest.mark.parametrize("attribute, value", [
('ATTRIBUTE_STR', 'default_str'),
('ATTRIBUTE_INT', 1),
('ATTRIBUTE_FLOAT', 1.5),
('ATTRIBUTE_BOOL', True),
])
def test_get_attributes(config, attribute, value):
assert getattr(config, attribute) == value
def test_set_existing_attribut... | Python | 0 |
e392fa449150d91dcd07de00c4b9f8133d66e97f | convert a genbank file to a ppt file | genbank_to_ppt/genbank_to_ppt.py | genbank_to_ppt/genbank_to_ppt.py | """
Convert a genbank file to a .ppt file
This is a simple genbank to tbl converter using BioPython
"""
import os
import sys
import binascii
import gzip
import re
from Bio import SeqIO
def is_gzip(gbkf):
"""
Is the file compressed?
:param gbkf:
:return: true if compressed else false
"""
with ... | """
Convert a genbank file to a .ppt file
This is a simple genbank to tbl converter using BioPython
"""
import os
import sys
import binascii
import gzip
import re
from Bio import SeqIO
def is_gzip(gbkf):
"""
Is the file compressed?
:param gbkf:
:return: true if compressed else false
"""
with ... | Python | 0.00152 |
484b0d1d764a413f54f9e5f6f99eca84e6a947cd | Make rocket threads daemonized. Ignore tickets and sessions | main.py | main.py | # -*- coding: utf-8 -*-
import sys
import socket
import logging
import traceback
from select import select
from . import SERVER_NAME
from .worker import get_method
class Rocket:
def __init__(self,
app_info,
method='test',
bind_addr = ('127.0.0.1', 8000),
... | # -*- coding: utf-8 -*-
import sys
import socket
import logging
import traceback
from select import select
from . import SERVER_NAME
from .worker import get_method
class Rocket:
def __init__(self,
app_info,
method='test',
bind_addr = ('127.0.0.1', 8000),
... | Python | 0 |
f5ffdefed84c7ddc6dbb4ea897e9f476b5b4d245 | Add squares to table. | main.py | main.py | class Square:
def __init__(self, coords):
pass
def add_mark(self, player):
pass
class Line:
def __init__(self, params):
pass
def squares(self):
pass
def win(self):
pass
def not_winnable(self):
pass
class TTT_Table:
def __init__(self, base, power, players):
self.base = base
s... | class Square:
def __init__(self, coords):
pass
def add_mark(self, player):
pass
class Line:
def __init__(self, params):
pass
def squares(self):
pass
def win(self):
pass
def not_winnable(self):
pass
class TTT_Table:
def __init__(self, base, power, players):
self.base = base
s... | Python | 0.000005 |
a28eedba060934d498ac38e8704022dc38c43758 | Add stringio from six | tests/test_utilities.py | tests/test_utilities.py | from subprocess import Popen, PIPE
from six import StringIO
import sys
class Capturing(list):
def __enter__(self):
self._stdout = sys.stdout
sys.stdout = self._stringio = StringIO()
return self
def __exit__(self, *args):
self.extend(self._stringio.getvalue().splitlines())
... | from subprocess import Popen, PIPE
from StringIO import StringIO
import sys
class Capturing(list):
def __enter__(self):
self._stdout = sys.stdout
sys.stdout = self._stringio = StringIO()
return self
def __exit__(self, *args):
self.extend(self._stringio.getvalue().splitlines()... | Python | 0.999564 |
75b628453463a4199468b9f45dc80c22725c2b93 | remove unised import | tests/testapp/models.py | tests/testapp/models.py | # coding=utf-8
from __future__ import absolute_import, unicode_literals
from django.db import models
from tests.testapp.constants import ModelState
from tximmutability.models import MutableModel
from tximmutability.rule import MutabilityRule
class AbstractImmutableModel(MutableModel):
name = models.CharField(
... | # coding=utf-8
from __future__ import absolute_import, unicode_literals
from django.db import models
from model_utils import FieldTracker
from tests.testapp.constants import ModelState
from tximmutability.models import MutableModel
from tximmutability.rule import MutabilityRule
class AbstractImmutableModel(MutableM... | Python | 0.000006 |
603d0dbb3ce2911b62f3274e68b93812da9acf2d | Remove SuperOnline and UyduNet DNS addresses | main.py | main.py | # -*- coding: utf-8 -*-
"""
main.py
Jan 14, 2014
Copyright (C) 2014 Baris Sencan
"""
import os
import redis
from flask import Flask, render_template, url_for
from flask.ext.compress import Compress
app = Flask(__name__)
# Enable gzip compression.
Compress(app)
# Static file loading helper.
app.jinja_env.globals['s... | # -*- coding: utf-8 -*-
"""
main.py
Jan 14, 2014
Copyright (C) 2014 Barış Şencan
"""
import os
import redis
from flask import Flask, render_template, url_for
from flask.ext.compress import Compress
app = Flask(__name__)
# Enable gzip compression.
Compress(app)
# Static file loading helper.
app.jinja_env.globals['s... | Python | 0 |
3788876762107acf272ae91198f7f98e85de3349 | Add cache pruning function | main.py | main.py | import hashlib
import models
import os
import os.path
def init():
models.db.connect()
models.db.create_tables([models.Entry])
def digest(file_path):
h = hashlib.sha1()
file = open(file_path, 'rb')
buf = file.read(8192)
while len(buf) > 0:
h.update(buf)
buf = file.read(8192)
... | import hashlib
import models
import os
import os.path
def init():
models.db.connect()
models.db.create_tables([models.Entry])
def digest(file_path):
h = hashlib.sha1()
file = open(file_path, 'rb')
buf = file.read(8192)
while len(buf) > 0:
h.update(buf)
buf = file.read(8192)
... | Python | 0.000001 |
9c7660fd63bc1c48a0533e867c7d18faf9d90c03 | Make use thru uwsgi easier | main.py | main.py | #!/usr/bin/env python
from morss import main, cgi_wrapper as application
if __name__ == '__main__':
main()
| #!/usr/bin/env python
from morss import main
if __name__ == '__main__':
main()
| Python | 0 |
27cbdd93f2c5c723776b932d66a56699f9267b8d | Use single quotes instead of double quotes | main.py | main.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import re
import sys
from html.parser import HTMLParser
import urllib3
import taglib
class MyHTMLParser(HTMLParser):
ignore_tags = {'ul', 'dl', 'dd'}
def __init__(self, target_ol_count = 1):
self.target_ol_count = target_ol_count
... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import re
import sys
from html.parser import HTMLParser
import urllib3
import taglib
class MyHTMLParser(HTMLParser):
ignore_tags = {"ul", "dl", "dd"}
def __init__(self, target_ol_count = 1):
self.target_ol_count = target_ol_count
... | Python | 0 |
b3e61d648be5c5d28cfe3a7ef69f918c2a2c33a1 | optimize the logic of mail | main.py | main.py | # -*- coding: utf-8 -*-
import mail
import simplejson
import urllib2
import time
def moniter(m, send_to, high, low):
req = urllib2.Request("https://data.btcchina.com/data/ticker")
opener = urllib2.build_opener()
last_sent = 0
while True:
try:
f = opener.open(req)
da... | # -*- coding: utf-8 -*-
import mail
import simplejson
import urllib2
import time
from config import *
def moniter(m, send_to, high, low):
req = urllib2.Request("https://data.btcchina.com/data/ticker")
opener = urllib2.build_opener()
last_sent = 0
while True:
try:
f = opener.open(... | Python | 0.999999 |
6b6bbe079a6b68ac82f4caa11473b5b005824715 | Update crop_geotiff.py | geobeam/examples/crop_geotiff.py | geobeam/examples/crop_geotiff.py | # Copyright 2021 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2021 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | Python | 0.000001 |
3cff942af436f16aab2078e6aeedd3073f4a5522 | Add Flask-Mail, and null user loader | flask_roots/extension.py | flask_roots/extension.py | from __future__ import absolute_import
import os
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.images import Images
from flask.ext.mail import Mail
from flask.ext.login import LoginManager
from flask.ext.acl import AuthManager
class Roots(object):
def __init__(self, app):
self.extensions =... | from __future__ import absolute_import
import os
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.images import Images
# from flask.ext.mail import Mail
from flask.ext.login import LoginManager
from flask.ext.acl import AuthManager
class Roots(object):
def __init__(self, app):
self.extensions... | Python | 0.000001 |
18897bf535b4885b9dfbf0a014c92656e8ed74b7 | Update main to return properly formatted data | main.py | main.py | import telegram
import tornado.ioloop
import tornado.web
from tornado.options import define, options
from goodreads_api import get_book_details_by_name, BookNotFound
from utils import get_formatted_book_data
from settings import TELEGRAM_ACCESS_TOKEN, WEBHOOK_URL
define("port", default=5000, help="run on the given po... | import telegram
import tornado.ioloop
import tornado.web
from tornado.options import define, options
from goodreads_api import get_book_details_by_name, BookNotFound
from settings import TELEGRAM_ACCESS_TOKEN, WEBHOOK_URL
define("port", default=5000, help="run on the given port", type=int)
bot = telegram.Bot(token=T... | Python | 0 |
f9aa61fa326f9737e2af971a420da9c0652612ae | revise BaseDoctype to add generic generation method | tldp/doctypes/common.py | tldp/doctypes/common.py | #! /usr/bin/python
from __future__ import absolute_import, division, print_function
import os
from ..utils import logger
class SignatureChecker(object):
@classmethod
def signatureLocation(cls, f):
f.seek(0)
buf = f.read(1024).lower()
for sig in cls.signatures:
try:
... | #! /usr/bin/python
from __future__ import absolute_import, division, print_function
import os
from ..utils import logger
class SignatureChecker(object):
@classmethod
def signatureLocation(cls, f):
f.seek(0)
buf = f.read(1024).lower()
for sig in cls.signatures:
try:
... | Python | 0 |
577ebb6d4dc037bc912aa11d525ca4f2f09e7940 | set default schema to defm | db/log.py | db/log.py | from sqlalchemy.orm import sessionmaker
from forecast import util
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy import MetaData
from pysandag.database import get_connection_string
import os
def n... | from sqlalchemy.orm import sessionmaker
from forecast import util
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy import MetaData
from pysandag.database import get_connection_string
import os
def n... | Python | 0.000006 |
7c5dad065fc3cb391609c9dd9a8d1b3effc197b1 | fix typo | paths/recursive_total_path.py | paths/recursive_total_path.py | import cProfile
def numberOfPaths(nXm_matrix):
"""
Returns the total number of paths from the top left
to the bottom right by moving right and down in a 2D array
of size n x m. Where cells can only contain `1` or `0` while
real paths can only contain `1`.
"""
hight = len(nXm_matrix)
wi... | import cProfile
def numberOfPaths(nXm_matrix):
"""
Returns the total number of paths from the top left
to the bottom right by moving right and down in a 2D array
of size n x m. Where cells can only contain `1` or `0` while
real paths can only contain `1`.
"""
hight = len(nXm_matrix)
wi... | Python | 0.999991 |
b0d0c9b67c0faa583c216687544a544ed7fde631 | Fix up syntax in the minion | salt/minion.py | salt/minion.py | '''
Routines to set up a minion
'''
# Import zeromq libs
import zmq
# Import salt libs
import salt.crypt
import salt.utils
import salt.modules
# To set up a minion:
# 1, Read in the configuration
# 2. Generate the function mapping dict
# 3. Authenticate with the master
# 4. Store the aes key
# 5. connect to the publis... | '''
Routines to set up a minion
'''
# Import python libs
import os
import distutils.sysconfig
# Import zeromq libs
import zmq
# Import salt libs
import salt.crypt
import salt.utils
import salt.modules
# To set up a minion:
# 1, Read in the configuration
# 2. Generate the function mapping dict
# 3. Authenticate with th... | Python | 0.999989 |
feb1857ac556cca08513bb35599191ee9b46e174 | Use the new name of the library module. | pycurl/examples/sfquery.py | pycurl/examples/sfquery.py | #! /usr/bin/env python
# -*- coding: iso-8859-1 -*-
# vi:ts=4:et
#
# sfquery -- Source Forge query script using the ClientCGI high-level interface
#
# Retrieves a SourceForge XML export object for a given project.
# Specify the *numeric* project ID. the user name, and the password,
# as arguments. If you have a valid ~... | #! /usr/bin/env python
# -*- coding: iso-8859-1 -*-
# vi:ts=4:et
#
# sfquery -- Source Forge query script using the ClientCGI high-level interface
#
# Retrieves a SourceForge XML export object for a given project.
# Specify the *numeric* project ID. the user name, and the password,
# as arguments. If you have a valid ~... | Python | 0 |
03f05240145741fe1027c864a9047a2bf77c5161 | Fix e-d-addresses + boto 2.0 incompatibility | euca2ools/commands/euca/describeaddresses.py | euca2ools/commands/euca/describeaddresses.py | # Software License Agreement (BSD License)
#
# Copyright (c) 2009-2011, Eucalyptus Systems, Inc.
# All rights reserved.
#
# Redistribution and use of this software in source and binary forms, with or
# without modification, are permitted provided that the following conditions
# are met:
#
# Redistributions of source ... | # Software License Agreement (BSD License)
#
# Copyright (c) 2009-2011, Eucalyptus Systems, Inc.
# All rights reserved.
#
# Redistribution and use of this software in source and binary forms, with or
# without modification, are permitted provided that the following conditions
# are met:
#
# Redistributions of source ... | Python | 0.000442 |
f4bedfed9a7324574695c065f8a1b7132d5f4708 | update ftbfs logic | ethel/commands/build.py | ethel/commands/build.py | from ethel.runners.sbuild import sbuild
from ethel.utils import upload
import glob
import os
# target package firehose
def run(dsc, package, job, firehose):
suite = job['suite']
arch = job['arch']
info, out, ftbfs = sbuild(dsc, suite, arch)
changes = "{source}*{arch}.changes".format(
source=... | from ethel.runners.sbuild import sbuild
from ethel.utils import upload
import glob
import os
# target package firehose
def run(dsc, package, job, firehose):
suite = job['suite']
arch = job['arch']
info, out, ftbfs = sbuild(dsc, suite, arch)
changes = "{source}*{arch}.changes".format(
source=... | Python | 0 |
6fb8d542e29b29569c0d124e533a3f9fbf4f81e9 | make archive_forms task work with excel as it was | corehq/apps/data_interfaces/utils.py | corehq/apps/data_interfaces/utils.py | from django.utils.translation import ugettext as _
from couchdbkit import ResourceNotFound
from corehq.apps.casegroups.models import CommCareCaseGroup
from corehq.apps.hqcase.utils import get_case_by_identifier
from couchforms.models import XFormInstance
from dimagi.utils.couch.database import iter_docs
from soil impo... | from django.utils.translation import ugettext as _
from couchdbkit import ResourceNotFound
from corehq.apps.casegroups.models import CommCareCaseGroup
from corehq.apps.hqcase.utils import get_case_by_identifier
from couchforms.models import XFormInstance
from dimagi.utils.couch.database import iter_docs
from soil impo... | Python | 0 |
026f7d8c07d5ec4e307caa692c66a04653565f52 | 修复 notebook js 函数未转换的 bug | pyecharts/render/engine.py | pyecharts/render/engine.py | # coding=utf-8
import re
from jinja2 import Environment
from pyecharts.commons.types import Any, Optional
from ..commons.utils import write_utf8_html_file
from ..datasets import EXTRA, FILENAMES
from ..globals import CurrentConfig
class RenderEngine:
def __init__(self, env: Optional[Environment] = None):
... | # coding=utf-8
import re
from jinja2 import Environment
from pyecharts.commons.types import Any, Optional
from ..commons.utils import write_utf8_html_file
from ..datasets import EXTRA, FILENAMES
from ..globals import CurrentConfig
class RenderEngine:
def __init__(self, env: Optional[Environment] = None):
... | Python | 0 |
4682a44436d3267877c50735aca3f0f9f36672cc | Add more specific error message when deleting too many items at import | events/importer/sync.py | events/importer/sync.py | import logging
# Per module logger
logger = logging.getLogger(__name__)
class ModelSyncher(object):
def __init__(self, queryset, generate_obj_id,
delete_func=None, check_deleted_func=None, allow_deleting_func=None):
d = {}
self.generate_obj_id = generate_obj_id
self.delet... | import logging
# Per module logger
logger = logging.getLogger(__name__)
class ModelSyncher(object):
def __init__(self, queryset, generate_obj_id,
delete_func=None, check_deleted_func=None, allow_deleting_func=None):
d = {}
self.generate_obj_id = generate_obj_id
self.delet... | Python | 0 |
c5d224818903ccad9624ac4cb3449af82faa55f9 | fix typo | floyd/main.py | floyd/main.py | import click
import sys
from distutils.version import LooseVersion
import floyd
from floyd.cli.utils import get_cli_version
from floyd.cli.auth import login, logout
from floyd.cli.data import data
from floyd.cli.experiment import clone, delete, info, init, logs, output, status, stop
from floyd.cli.run import run, rest... | import click
import sys
from distutils.version import LooseVersion
import floyd
from floyd.cli.utils import get_cli_version
from floyd.cli.auth import login, logout
from floyd.cli.data import data
from floyd.cli.experiment import clone, delete, info, init, logs, output, status, stop
from floyd.cli.run import run, rest... | Python | 0.999991 |
41d3298eb716ad813a82f56fbfb2771373338c09 | Make this test pass by checking for 61 which is what OS X uses as connection refused, apparently | greentest/test__socket_errors.py | greentest/test__socket_errors.py | # Copyright (c) 2008-2009 AG Projects
# Author: Denis Bilenko
#
# 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, mo... | # Copyright (c) 2008-2009 AG Projects
# Author: Denis Bilenko
#
# 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, mo... | Python | 0 |
e25ff765e423511da57f04c96227d2ca69e7c149 | Update focal_loss.py | focal_loss.py | focal_loss.py | from keras import backend as K
'''
Compatible with tensorflow backend
'''
def focal_loss(gamma=2., alpha=.25):
def focal_loss_fixed(y_true, y_pred):
pt_1 = tf.where(tf.equal(y_true, 1), y_pred, tf.ones_like(y_pred))
pt_0 = tf.where(tf.equal(y_true, 0), y_pred, tf.zeros_like(y_pred))
return -K.mean(... | from keras import backend as K
'''
Compatible with tensorflow backend
'''
def focal_loss(gamma=2., alpha=.25):
def focal_loss_fixed(y_true, y_pred):
pt_1 = tf.where(tf.equal(y_true, 1), y_pred, tf.ones_like(y_pred))
pt_0 = tf.where(tf.equal(y_true, 0), y_pred, tf.zeros_like(y_pred))
return -K.sum(a... | Python | 0 |
6b992aa75c0f553ca5066cda269e93d4f63ea4a5 | Optimize banned host validation test | corehq/util/tests/test_validation.py | corehq/util/tests/test_validation.py | from random import sample
from corehq.util.validation import is_url_or_host_banned
from django.test import TestCase
def sample_range(start, stop):
yield start
num_samples = min(8, stop - start)
for middle in sample(xrange(start + 1, stop), num_samples):
yield middle
yield stop
class Validati... | from corehq.util.validation import is_url_or_host_banned
from django.test import TestCase
def inclusive_range(start, stop):
return range(start, stop + 1)
class ValidationTestCase(TestCase):
def testBannedHosts(self):
self.assertTrue(is_url_or_host_banned('anything.commcarehq.org'))
for i i... | Python | 0 |
a4b7be1a8c6d44c272ce25acf9513054d6bee4ad | Fix in listports to work with windows | python_loader/listports.py | python_loader/listports.py | """BlinkyTape Python communication library.
This code assumes stock serialLoop() in the firmware.
Commands are issued in 3-byte blocks, with pixel data
encoded in RGB triplets in range 0-254, sent sequentially
and a triplet ending with a 255 causes the accumulated pixel
data to display (a show command).
... | """BlinkyTape Python communication library.
This code assumes stock serialLoop() in the firmware.
Commands are issued in 3-byte blocks, with pixel data
encoded in RGB triplets in range 0-254, sent sequentially
and a triplet ending with a 255 causes the accumulated pixel
data to display (a show command).
... | Python | 0 |
c1ad95ee4680836fc359ee636a2252925a41b3a9 | fix raw_id_fields on admin. closes #33 | knowledge/admin.py | knowledge/admin.py | from django.contrib import admin
from knowledge.models import Question, Response, Category
class CategoryAdmin(admin.ModelAdmin):
list_display = [f.name for f in Category._meta.fields]
prepopulated_fields = {'slug': ('title', )}
admin.site.register(Category, CategoryAdmin)
class QuestionAdmin(admin.ModelAd... | from django.contrib import admin
from knowledge.models import Question, Response, Category
class CategoryAdmin(admin.ModelAdmin):
list_display = [f.name for f in Category._meta.fields]
prepopulated_fields = {'slug': ('title', )}
admin.site.register(Category, CategoryAdmin)
class QuestionAdmin(admin.ModelAd... | Python | 0.000001 |
4c052b2429d7b48768f51cef0627e7a1772909b3 | Fix import | dbaas/workflow/steps/tests/test_base_step.py | dbaas/workflow/steps/tests/test_base_step.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import logging
from django.test import TestCase
from ..util.base import BaseStep
LOG = logging.getLogger(__name__)
class BaseStepTestCase(TestCase):
def setUp(self):
self.base_step = BaseStep()
def test_has_do_method(s... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import logging
from django.test import TestCase
from ..base import BaseStep
LOG = logging.getLogger(__name__)
class BaseStepTestCase(TestCase):
def setUp(self):
self.base_step = BaseStep()
def test_has_do_method(self):... | Python | 0.000002 |
b70e34d399b171b3d8e0731206dde54f8d029379 | Add uuid to import | casstest/casstest.py | casstest/casstest.py | # -*- coding: utf-8 -*-
import os
import uuid
from cassandra.io.libevreactor import LibevConnection
from cassandra.cluster import Cluster
seed = os.environ.get('SEED', '127.0.0.1')
port = int(os.environ.get('PORT', '9042'))
keyspace = os.environ.get('KEYSPACE', 'test')
def test_read(session, user_id, age):
read... | # -*- coding: utf-8 -*-
import os
from cassandra.io.libevreactor import LibevConnection
from cassandra.cluster import Cluster
seed = os.environ.get('SEED', '127.0.0.1')
port = int(os.environ.get('PORT', '9042'))
keyspace = os.environ.get('KEYSPACE', 'test')
def test_read(session, user_id, age):
read_query = 'SE... | Python | 0 |
1da42cce0d963f02399772d2bd30eb054d99f3e0 | Switch to argparse | keyring/cli.py | keyring/cli.py | #!/usr/bin/env python
"""Simple command line interface to get/set password from a keyring"""
import getpass
import argparse
import sys
from . import core
from . import backend
from . import set_keyring, get_password, set_password, delete_password
class CommandLineTool:
def __init__(self):
self.parser = ... | #!/usr/bin/env python
"""Simple command line interface to get/set password from a keyring"""
import getpass
from optparse import OptionParser
import sys
from . import core
from . import backend
from . import set_keyring, get_password, set_password, delete_password
class CommandLineTool:
def __init__(self):
... | Python | 0.000077 |
85680ed5792456a109583830bcbfbc30ef3b62c4 | Complete 'About Lambdas' koans | jesusmtnez/python/koans/koans/about_lambdas.py | jesusmtnez/python/koans/koans/about_lambdas.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Based slightly on the lambdas section of AboutBlocks in the Ruby Koans
#
from runner.koan import *
class AboutLambdas(Koan):
def test_lambdas_can_be_assigned_to_variables_and_called_explicitly(self):
add_one = lambda n: n + 1
self.assertEqual(11, ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Based slightly on the lambdas section of AboutBlocks in the Ruby Koans
#
from runner.koan import *
class AboutLambdas(Koan):
def test_lambdas_can_be_assigned_to_variables_and_called_explicitly(self):
add_one = lambda n: n + 1
self.assertEqual(__, ... | Python | 0.001766 |
d9719a20d4ee433aaab27a648888966d1ce0163b | Implement inversion counting with global variable | count-inversions/count_inversions.py | count-inversions/count_inversions.py | from random import randint
import sys
count = 0
def sort_and_count(arr):
n = len(arr)
if n == 1:
return arr
else:
first_half = arr[:n/2]
second_half = arr[n/2:]
return merge_and_count_split(sort_and_count(first_half), sort_and_count(second_half))
def merge_and_count_split(arr1, arr2):
i, j = 0, 0
res... | from random import randint
import sys
def sort_and_count(arr):
n = len(arr)
if n == 1:
return arr
else:
first_half = arr[:n/2]
second_half = arr[n/2:]
return merge_and_count_split(sort_and_count(first_half), sort_and_count(second_half))
def merge_and_count_split(arr1, arr2):
i, j = 0, 0
result = []
... | Python | 0.000059 |
17dceb0d66ac72547c6de6153d79d9bcd5dd9926 | put _id and properties in the right places | gdcdatamodel/mappings/mappings.py | gdcdatamodel/mappings/mappings.py | from gdcdatamodel import node_avsc_json
from mapped_entities import (
file_tree, file_traversal,
participant_tree, participant_traversal,
annotation_tree, annotation_traversal,
ONE_TO_MANY, ONE_TO_ONE, annotation_tree
)
def _get_es_type(_type):
if 'long' in _type or 'int' in _type:
return ... | from gdcdatamodel import node_avsc_json
from mapped_entities import (
file_tree, file_traversal,
participant_tree, participant_traversal,
annotation_tree, annotation_traversal,
ONE_TO_MANY, ONE_TO_ONE, annotation_tree
)
def _get_es_type(_type):
if 'long' in _type or 'int' in _type:
return ... | Python | 0.000001 |
36b2ca696bf6955d54ade1f917a1caea59b2d2d1 | update version to 0.7.4 | dlstats/version.py | dlstats/version.py | VERSION = (0, 7, 4)
def version_str():
if len(VERSION) == 3:
return "%s.%s.%s" % VERSION
elif len(VERSION) == 4:
return "%s.%s.%s-%s" % VERSION
else:
raise IndexError("Incorrect format for the VERSION tuple")
| VERSION = (0, 7, 3)
def version_str():
if len(VERSION) == 3:
return "%s.%s.%s" % VERSION
elif len(VERSION) == 4:
return "%s.%s.%s-%s" % VERSION
else:
raise IndexError("Incorrect format for the VERSION tuple")
| Python | 0.000001 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.