commit
stringlengths 40
40
| subject
stringlengths 1
3.25k
| old_file
stringlengths 4
311
| new_file
stringlengths 4
311
| old_contents
stringlengths 0
26.3k
| lang
stringclasses 3
values | proba
float64 0
1
| diff
stringlengths 0
7.82k
|
|---|---|---|---|---|---|---|---|
64921ef6d8aafe505efdc30d070c138c741eb38f
|
Create __init__.py
|
bigbench/benchmark_tasks/meta_hello_world/__init__.py
|
bigbench/benchmark_tasks/meta_hello_world/__init__.py
|
Python
| 0.000429
|
@@ -0,0 +1 @@
+%0A
|
|
c5e11ce40df5ecd99dfa33cceadc6696ba442084
|
version bump for pypi
|
exa/__init__.py
|
exa/__init__.py
|
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2016, Exa Analytics Development Team
# Distributed under the terms of the Apache License 2.0
'''
Exa
#########
This package creates a systematic infrastructure for an ecosystem of packages,
tailored to specific industry or academic displines, for organizing, processing,
analyzing, and visualizing data. It is built with minimal dependencies, leverages
established open-source packages, is itself extensible, and is targeted at both
industry and academic applications.
At a high level, data objects such as series or dataframes (i.e. `pandas`_
like objects) are organized into containers which track relationships between
these objects and provide methods for computation, conversion to other formats,
analysis, and visualization within the `Jupyter notebook`_ environment.
.. _pandas: http://pandas.pydata.org/pandas-docs/stable/index.html
.. _Jupyter notebook: http://jupyter.org/
'''
__exa_version__ = (0, 2, 5)
__version__ = '.'.join((str(v) for v in __exa_version__))
from exa import _config
from exa import log
from exa import test
from exa import relational
from exa import widget
from exa import math
from exa import distributed
from exa import mpl, tex
from exa import error
# User API
from exa.numerical import Series, DataFrame, Field3D, SparseSeries, SparseDataFrame
from exa.container import Container
from exa.editor import Editor
from exa.filetypes import CSV
|
Python
| 0
|
@@ -972,17 +972,17 @@
(0, 2,
-5
+6
)%0D%0A__ver
|
ef70a530e9827e96f4984a9c51424cd50b2000cf
|
Create numbersinlists.py
|
udacity/numbersinlists.py
|
udacity/numbersinlists.py
|
Python
| 0.000004
|
@@ -0,0 +1,1695 @@
+# Numbers in lists by SeanMc from forums%0A# define a procedure that takes in a string of numbers from 1-9 and%0A# outputs a list with the following parameters:%0A# Every number in the string should be inserted into the list.%0A# If a number x in the string is less than or equal %0A# to the preceding number y, the number x should be inserted %0A# into a sublist. Continue adding the following numbers to the %0A# sublist until reaching a number z that%0A# is greater than the number y. %0A# Then add this number z to the normal list and continue.%0A%0A#Hint - %22int()%22 turns a string's element into a number%0A%0Adef numbers_in_lists(string):%0A masterlist, sublist = %5Bint(string%5B0%5D)%5D, %5B%5D%0A highestnumber = int(string%5B0%5D)%0A for i in string%5B1:%5D:%0A if int(i) %3C= highestnumber:%0A sublist.append(int(i))%0A else:%0A if sublist:%0A masterlist.append(sublist)%0A masterlist.append(int(i))%0A highestnumber = int(i)%0A sublist = %5B%5D%0A if sublist:%0A masterlist.append(sublist)%0A return masterlist%0A %0A %0A %0Astring = '543987'%0Aresult = %5B5,%5B4,3%5D,9,%5B8,7%5D%5D%0Aprint numbers_in_lists(string)%0A#testcases%0Astring = '543987'%0Aresult = %5B5,%5B4,3%5D,9,%5B8,7%5D%5D%0Aprint repr(string), numbers_in_lists(string) == result%0Astring= '987654321'%0Aresult = %5B9,%5B8,7,6,5,4,3,2,1%5D%5D%0Aprint numbers_in_lists(string)%0Aprint repr(string), numbers_in_lists(string) == result%0Astring = '455532123266'%0Aresult = %5B4, 5, %5B5, 5, 3, 2, 1, 2, 3, 2%5D, 6, %5B6%5D%5D%0Aprint numbers_in_lists(string)%0Aprint repr(string), numbers_in_lists(string) == result%0Astring = '123456789'%0Aresult = %5B1, 2, 3, 4, 5, 6, 7, 8, 9%5D%0Aprint numbers_in_lists(string)%0Aprint repr(string), numbers_in_lists(string) == result%0A
|
|
ba09b09e7315cafa96e162a8186abe14c51c8128
|
Add a script to download files from url
|
python/download_file_from_url.py
|
python/download_file_from_url.py
|
Python
| 0
|
@@ -0,0 +1,880 @@
+import urllib2%0A'''%0AScript to download pdf from a url, you need specify the website URL, and change the %0Afilename in the loop, it mostly useful to download a sequence of files with the %0Afilename only differ by a sequence number, e.g. CH1.PDF, CH2.PDF, CH3.PDF ...%0A'''%0A%0Adef download_file(download_url, output_name):%0A '''%0A Download part, %0A download_url is the url point to the file%0A output_name is filename you want to output%0A '''%0A response = urllib2.urlopen(download_url)%0A file = open(output_name, 'w')%0A file.write(response.read())%0A file.close()%0A print(output_name + %22 Completed%22)%0A%0Aif __name__ == %22__main__%22:%0A %0A path = 'http://www.dspguide.com/'%0A %0A for i in range(35):%0A #exmaple of the file name is: CH1.PDF%0A filename = 'CH' + str(i) + '.PDF'%0A %0A fileloc = path + filename%0A download_file(fileloc, filename)
|
|
69c01499e92808f2a513e695d09e58f55dcd569b
|
Update implement-rand10-using-rand7.py
|
Python/implement-rand10-using-rand7.py
|
Python/implement-rand10-using-rand7.py
|
# Time: O(1.199), counted by statistics, limit would be O(log10/log7) = O(1.183)
# Space: O(1)
# Given a function rand7 which generates a uniform random integer in the range 1 to 7,
# write a function rand10 which generates a uniform random integer in the range 1 to 10.
#
# Do NOT use system's Math.random().
#
# Example 1:
#
# Input: 1
# Output: [7]
# Example 2:
#
# Input: 2
# Output: [8,4]
# Example 3:
#
# Input: 3
# Output: [8,1,10]
#
# Note:
#
# rand7 is predefined.
# Each testcase has one argument: n, the number of times that rand10 is called.
#
# Follow up:
# - What is the expected value for the number of calls to rand7() function?
# - Could you minimize the number of calls to rand7()?
#
# The rand7() API is already defined for you.
import random
def rand7():
return random.randint(1, 7)
# Reference: https://leetcode.com/problems/implement-rand10-using-rand7/discuss/151567/C++JavaPython-Average-1.199-Call-rand7-Per-rand10
class Solution(object):
def __init__(self):
self.__cache = []
def rand10(self):
"""
:rtype: int
"""
def generate(cache):
n = 19 # if n = 32, it would be O(1.189)
curr = sum((rand7()-1) * (7**i) for i in xrange(n))
rang = 7**n
while curr < rang//10*10:
cache.append(curr%10+1)
curr /= 10
rang /= 10
while not self.__cache:
generate(self.__cache)
return self.__cache.pop()
# Time: O(2 * (1 + (9/49) + (9/49)^2 + ...)) = O(2/(1-(9/49)) = O(2.45)
# Space: O(1)
class Solution2(object):
def rand10(self):
"""
:rtype: int
"""
while True:
x = (rand7()-1)*7 + (rand7()-1)
if x < 40:
return x%10 + 1
|
Python
| 0.000002
|
@@ -7,17 +7,17 @@
: O(1.1
-9
+8
9), coun
@@ -1134,45 +1134,10 @@
n =
-19 # if n = 32, it would be O(1.189)
+32
%0A
|
a83282f43fdf87bad8abc63c5a0b41f8c9053a5f
|
Add setup script
|
setup.py
|
setup.py
|
Python
| 0.000001
|
@@ -0,0 +1,248 @@
+#!/usr/bin/python%0Afrom setuptools import setup%0Aimport sys%0Asys.path.insert(0, 'src')%0Afrom hszinc import __version__%0A%0Asetup (name = 'hszinc',%0A%09package_dir = %7B'': 'src'%7D,%0A version = __version__,%0A%09packages = %5B%0A 'hszinc',%0A %5D,%0A)%0A
|
|
60f6a83964b70700883121afb7aed22a7ffe7acc
|
Add setup.py
|
setup.py
|
setup.py
|
Python
| 0.000001
|
@@ -0,0 +1,502 @@
+from setuptools import setup%0A%0Asetup(%0A name='bfd',%0A version='0.1',%0A description='ML w/ Concord',%0A url='https://github.com/adi-labs/bfd',%0A author='Andrew Aday, Alan Du, Carlos Martin, Dennis Wei',%0A author_email='alanhdu@gmail.com',%0A license='Apache',%0A packages=%5B'bcd', 'data'%5D,%0A install_requires=%5B%0A %22yahoo-finance%22,%0A %22concord-py%22,%0A %22scipy%22,%0A %22pandas%22,%0A %22numpy%22,%0A %5D,%0A classifiers=%5B'Development Status :: 3 - Alpha'%5D,%0A zip_safe=False)%0A
|
|
68c0dd9d21a1de7c78f7df39d250f1714ff7c445
|
Deal with more cases of durations set in headers
|
apps/videos/types/htmlfive.py
|
apps/videos/types/htmlfive.py
|
# Amara, universalsubtitles.org
#
# Copyright (C) 2013-2015 Participatory Culture Foundation
#
# 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 useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see
# http://www.gnu.org/licenses/agpl-3.0.html.
import subprocess, sys
from videos.types.base import VideoType
import logging
logger= logging.getLogger(__name__)
class HtmlFiveVideoType(VideoType):
abbreviation = 'H'
name = 'HTML5'
valid_extensions = set(['ogv', 'ogg', 'mp4', 'm4v', 'webm'])
def __init__(self, url):
self.url = url
@classmethod
def matches_video_url(cls, url):
return cls.url_extension(url) in cls.valid_extensions
def get_direct_url(self):
return self.url
def set_values(self, video):
cmd = """avprobe -v error -show_format -show_streams "{}" 2>&1 | grep duration= | sed 's/^.*=//' | sort -n | head -n1""".format(self.url)
try:
duration = int(float(subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)))
video.duration = duration
except subprocess.CalledProcessError as e:
logger.error("CalledProcessError error({}) when running command {}".format(e.returncode, cmd))
except:
logger.error("Unexpected error({}) when running command {}".format(sys.exc_info()[0], cmd))
|
Python
| 0
|
@@ -784,16 +784,20 @@
ess, sys
+, re
%0Afrom vi
@@ -882,16 +882,1574 @@
ame__)%0A%0A
+def getDurationFromStreams(streams):%0A # this tries to get around most known cases%0A # of duration set with issues in headers%0A data = %7B%7D%0A durations = set()%0A index = None%0A for line in streams.splitlines():%0A index_m = re.match(r%22index=(%5Cw+)%22, line)%0A if index_m:%0A index = index_m.group(1)%0A data%5Bindex%5D = %7B%7D%0A duration_m = re.match(r%22duration=(%5Cw+)%22, line)%0A if duration_m and index:%0A duration = duration_m.group(1)%0A data%5Bindex%5D%5B%22duration%22%5D=int(float(duration))%0A codec_m = re.match(r%22codec_name=(%5Cw+)%22, line)%0A if codec_m and index:%0A codec = codec_m.group(1)%0A data%5Bindex%5D%5B%22codec%22%5D=codec%0A codec_type_m = re.match(r%22codec_type=(%5Cw+)%22, line)%0A if codec_type_m and index:%0A codec_type = codec_type_m.group(1)%0A data%5Bindex%5D%5B%22codec_type%22%5D=codec_type%0A frames_m = re.match(r%22nb_frames=(%5Cw+)%22, line)%0A if frames_m and index:%0A frames = frames_m.group(1)%0A try:%0A data%5Bindex%5D%5B%22frames%22%5D=int(frames)%0A except:%0A pass%0A for key, val in data.items():%0A if %22duration%22 in val and %22codec%22 in val and val%5B%22codec%22%5D != %22unknown%22:%0A if not (%22frames%22 in val and %22codec_type%22 in val and (val%5B%22codec_type%22%5D == %22video%22) and ((val%5B%22frames%22%5D / 25 / val%5B%22duration%22%5D %3E 1.1) or (val%5B%22frames%22%5D / 25 / val%5B%22duration%22%5D %3C 0.9))):%0A durations.add(val%5B%22duration%22%5D)%0A if len(durations) == 1:%0A return durations.pop()%0A return None%0A%0A
class Ht
@@ -2918,62 +2918,8 @@
%3E&1
-%7C grep duration= %7C sed 's/%5E.*=//' %7C sort -n %7C head -n1
%22%22%22.
@@ -2964,29 +2964,18 @@
-duration = int(float(
+streams =
subp
@@ -3036,17 +3036,70 @@
.STDOUT)
-)
+%0A duration = getDurationFromStreams(streams
)%0A
|
525e0656f57b67744dfa5529687c5d40d3f43327
|
Add address/serializers.py
|
address/serializers.py
|
address/serializers.py
|
Python
| 0.000001
|
@@ -0,0 +1,392 @@
+# file: address/serializers.py%0A%0Afrom rest_framework import serializers%0Afrom address.models import ipv6_address, ipv4_address%0A%0A%0Aclass Ipv6AddressSerializer(serializers.ModelSerializer):%0A class Meta:%0A model = ipv6_address%0A fields = ('__all__')%0A%0Aclass Ipv6AddressSerializer(serializers.ModelSerializer):%0A class Meta:%0A model = ipv6_address%0A fields = ('__all__')%0A
|
|
66bb6c75017eddd952d43e7dc72004a05c9659b1
|
add test for kvmha_manager
|
nova/tests/kvmha/test_kvmha_manager.py
|
nova/tests/kvmha/test_kvmha_manager.py
|
Python
| 0
|
@@ -0,0 +1,1791 @@
+#%0A# KVM HA in OpenStack (Demo Version)%0A#%0A# Copyright HP, Corp. 2014%0A#%0A# Authors:%0A# Lei Li %3Cli.lei2@hp.com%3E%0A#%0A# Licensed under the Apache License, Version 2.0 (the %22License%22); you may%0A# not use this file except in compliance with the License. You may obtain%0A# a copy of the License at%0A#%0A# http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS, WITHOUT%0A# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the%0A# License for the specific language governing permissions and limitations%0A# under the License.i%0A#%0A%0A%22%22%22%0AUnit Tests for nova.kvmha.manager%0A%22%22%22%0A%0Aimport mox%0Aimport mock%0Afrom oslo.config import cfg%0A%0Aimport nova%0Afrom nova import context%0Afrom nova import exception%0A#from nova.kvmha import manager as kvmha_manager%0Afrom nova.openstack.common import importutils%0Afrom nova.openstack.common import log as logging%0Afrom nova import test%0Afrom nova.tests import fake_instance%0Afrom nova import utils%0A%0ACONF = cfg.CONF%0ACONF.import_opt('kvmha_manager', 'nova.service')%0A%0ALOG = logging.getLogger(__name__)%0A%0A%0Aclass KvmhaTestCase(test.TestCase):%0A def setUp(self):%0A super(KvmhaTestCase, self).setUp()%0A self.context = context.RequestContext('fake', 'fake')%0A self.kvmha = importutils.import_object(CONF.kvmha_manager)%0A%0A @mock.patch('nova.kvmha.manager.KvmhaManager._get_target_instances')%0A def test_get_target_instances(self, get_target_instances):%0A fake_host = 'fake-host'%0A fake_instances = %5B'fake1', 'fake2'%5D%0A get_target_instances.return_value = fake_instances%0A res = self.kvmha._get_target_instances(fake_host)%0A self.assertEqual(fake_instances, res)%0A
|
|
e08a1f1db582f34e36d695b32b2377fd7b73d9fe
|
Fix relative path handling in setup.py
|
setup.py
|
setup.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
from os.path import join
from setuptools import setup, find_packages
RE_REQUIREMENT = re.compile(r'^\s*-r\s*(?P<filename>.*)$')
PYPI_RST_FILTERS = (
# Replace code-blocks
(r'\.\.\s? code-block::\s*(\w|\+)+', '::'),
# Remove travis ci badge
(r'.*travis-ci\.org/.*', ''),
# Remove pypip.in badges
(r'.*pypip\.in/.*', ''),
(r'.*crate\.io/.*', ''),
(r'.*coveralls\.io/.*', ''),
)
def rst(filename):
'''
Load rst file and sanitize it for PyPI.
Remove unsupported github tags:
- code-block directive
- travis ci build badge
'''
content = open(filename).read()
for regex, replacement in PYPI_RST_FILTERS:
content = re.sub(regex, replacement, content)
return content
def pip(filename):
'''Parse pip requirement file and transform it to setuptools requirements'''
requirements = []
for line in open(join('requirements', filename)):
line = line.strip()
if not line or '://' in line:
continue
match = RE_REQUIREMENT.match(line)
if match:
requirements.extend(pip(match.group('filename')))
else:
requirements.append(line)
return requirements
def dependency_links(filename):
return [line.strip() for line in open(join('requirements', filename)) if '://' in line]
long_description = '\n'.join((
rst('README.rst'),
rst('CHANGELOG.rst'),
''
))
install_requires = pip('install.pip')
tests_require = pip('test.pip')
setup(
name='udata',
version=__import__('udata').__version__,
description=__import__('udata').__description__,
long_description=long_description,
url='https://github.com/etalab/udata',
download_url='http://pypi.python.org/pypi/udata',
author='Axel Haustant',
author_email='axel@data.gouv.fr',
packages=find_packages(),
include_package_data=True,
install_requires=install_requires,
dependency_links=dependency_links('install.pip'),
tests_require=tests_require,
extras_require={
'test': tests_require,
},
entry_points={
'console_scripts': [
'udata = udata.commands:console_script',
]
},
license='GNU AGPLv3+',
# use_2to3=True,
keywords='',
classifiers=[
'Development Status :: 3 - Alpha',
'Programming Language :: Python',
'Environment :: Web Environment',
'Operating System :: OS Independent',
'Intended Audience :: Developers',
'Topic :: System :: Software Distribution',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules',
'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)',
],
)
|
Python
| 0.000002
|
@@ -114,17 +114,26 @@
ort join
+, dirname
%0A
-
%0Afrom se
@@ -512,16 +512,42 @@
''),%0A)%0A%0A
+ROOT = dirname(__file__)%0A%0A
%0Adef rst
@@ -730,16 +730,27 @@
= open(
+join(ROOT,
filename
@@ -750,16 +750,17 @@
ilename)
+)
.read()%0A
@@ -1022,32 +1022,38 @@
ne in open(join(
+ROOT,
'requirements',
@@ -1380,24 +1380,24 @@
(filename):%0A
-
return %5B
@@ -1431,16 +1431,22 @@
en(join(
+ROOT,
'require
|
c05210b4557c56e7b7585ec22b27dd0f34f69f09
|
add a setup.py to make this a nice official package
|
setup.py
|
setup.py
|
Python
| 0
|
@@ -0,0 +1,334 @@
+#!/usr/bin/python2.4%0A#%0A# Copyright 2006 Google Inc. All Rights Reserved.%0A%0Afrom distutils.core import setup%0A%0Asetup(name=%22google-mysql-tools%22,%0A description=%22Google MySQL Tools%22,%0A url=%22http://code.google.com/p/google-mysql-tools%22,%0A version=%220.1%22,%0A packages=%5B%22gmt%22%5D,%0A scripts=%5B%22mypgrep.py%22, %22compact_innodb.py%22%5D)%0A
|
|
4a92b178d6fe2138a70e5f4f9833d7697437561b
|
Add setup.py
|
setup.py
|
setup.py
|
Python
| 0.000001
|
@@ -0,0 +1,587 @@
+#!/usr/bin/env python%0A%0Afrom setuptools import setup%0A%0A%0Asetup(%0A name='django_plim',%0A version='0.0.1',%0A author='iMom0',%0A author_email='mobeiheart@gmail.com',%0A description=('Introduce plim to django'),%0A license='BSD',%0A keywords='plim mako django slim',%0A url='https://github.com/imom0/django-plim',%0A install_requires=%5B%0A 'plim%3E=0.9.1',%0A %5D,%0A test_suite='nose.collector',%0A tests_require='nose==1.3.0',%0A classifiers=%5B%0A 'Development Status :: 3 - Alpha',%0A 'Topic :: Utilities',%0A 'License :: OSI Approved :: BSD License',%0A %5D,%0A)%0A
|
|
ba0e4042e25ec007df5766da16902cbeb55388f4
|
add setup.py
|
setup.py
|
setup.py
|
Python
| 0
|
@@ -0,0 +1,324 @@
+#!/usr/bin/env python%0A%0Afrom setuptools import setup%0A%0Adef main():%0A setup(name = 'pyhpi',%0A version = '1.00',%0A description = 'Pure python HPI library',%0A author_email = 'michael.walle@kontron.com',%0A packages = %5B 'pyhpi',%0A %5D,%0A )%0A%0Aif __name__ == '__main__':%0A main()%0A
|
|
63faa61c35aafd658ced61ee95ed857a33eb398b
|
Add setup.py file
|
setup.py
|
setup.py
|
Python
| 0.000001
|
@@ -0,0 +1,348 @@
+#!/usr/bin/env python%0A%0Afrom setuptools import setup, find_packages%0A%0Asetup(%0A name='django-bcrypt',%0A description=%22bcrypt password hash support for Django.%22,%0A version='0.1',%0A url='http://code.playfire.com/django-bcrypt',%0A%0A author='Playfire.com',%0A author_email='tech@playfire.com',%0A license='BSD',%0A%0A packages=find_packages(),%0A)%0A
|
|
f830307dc9a904de7791fcdd8cb54020fa1c4977
|
update scipy version (#691)
|
setup.py
|
setup.py
|
# Copyright (c) 2015, Ecole Polytechnique Federale de Lausanne, Blue Brain Project
# All rights reserved.
#
# This file is part of NeuroM <https://github.com/BlueBrain/NeuroM>
#
# 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 the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the names of
# its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
""" Distribution configuration for neurom
"""
# pylint: disable=R0801
import os
from setuptools import setup
from setuptools import find_packages
VERSION = "1.4.6"
REQS = ['enum34>=1.0.4',
'future>=0.16.0',
'h5py==2.7.1',
'matplotlib>=1.3.1',
'numpy>=1.8.0',
'pylru>=1.0',
'pyyaml>=3.10',
'scipy>=0.13.3',
'tqdm>=4.8.4',
'future>=0.16.0',
]
# Hack to avoid installation of modules with C extensions
# in readthedocs documentation building environment.
if os.environ.get('READTHEDOCS') == 'True':
REQS = ['future>=0.16.0',
'pyyaml>=3.10',
]
config = {
'description': 'NeuroM: a light-weight neuron morphology analysis package',
'author': 'BBP Neuroscientific Software Engineering',
'url': 'http://https://github.com/BlueBrain/NeuroM',
'version': VERSION,
'install_requires': REQS,
'packages': find_packages(),
'license': 'BSD',
'scripts': ['apps/raw_data_check',
'apps/morph_check',
'apps/morph_stats',
],
'name': 'neurom',
'include_package_data': True,
}
setup(**config)
|
Python
| 0
|
@@ -2050,11 +2050,11 @@
=0.1
-3.3
+7.0
',%0A
|
52792b7a963af9c593e61c78c7f0c7f62550a85b
|
Update setup.py extra_requires
|
setup.py
|
setup.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import codecs
import logging
import os
import re
import sys
import pkg_resources
from setuptools import find_packages
from setuptools import setup
def read(*parts):
path = os.path.join(os.path.dirname(__file__), *parts)
with codecs.open(path, encoding='utf-8') as fobj:
return fobj.read()
def find_version(*file_paths):
version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
install_requires = [
'cached-property >= 1.2.0, < 2',
'colorama >= 0.3.7, < 0.4',
'docopt >= 0.6.1, < 0.7',
'PyYAML >= 3.10, < 4',
'requests >= 2.6.1, != 2.11.0, < 2.12',
'texttable >= 0.8.1, < 0.9',
'websocket-client >= 0.32.0, < 1.0',
'docker >= 2.0.1, < 3.0',
'dockerpty >= 0.4.1, < 0.5',
'six >= 1.3.0, < 2',
'jsonschema >= 2.5.1, < 3',
]
tests_require = [
'pytest',
]
if sys.version_info[:2] < (3, 4):
tests_require.append('mock >= 1.0.1')
extras_require = {
':python_version < "3.4"': ['enum34 >= 1.0.4, < 2']
}
try:
if 'bdist_wheel' not in sys.argv:
for key, value in extras_require.items():
if key.startswith(':') and pkg_resources.evaluate_marker(key[1:]):
install_requires.extend(value)
except Exception:
logging.getLogger(__name__).exception(
'Something went wrong calculating platform specific dependencies, so '
"you're getting them all!"
)
for key, value in extras_require.items():
if key.startswith(':'):
install_requires.extend(value)
setup(
name='docker-compose',
version=find_version("compose", "__init__.py"),
description='Multi-container orchestration for Docker',
url='https://www.docker.com/',
author='Docker, Inc.',
license='Apache License 2.0',
packages=find_packages(exclude=['tests.*', 'tests']),
include_package_data=True,
test_suite='nose.collector',
install_requires=install_requires,
extras_require=extras_require,
tests_require=tests_require,
entry_points="""
[console_scripts]
docker-compose=compose.cli.main:main
""",
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
],
)
|
Python
| 0
|
@@ -1311,16 +1311,145 @@
4, %3C 2'%5D
+,%0A ':python_version %3C %223.5%22': %5B'backports.ssl_match_hostname %3E= 3.5'%5D,%0A ':python_version %3C %223.3%22': %5B'ipaddress %3E= 1.0.16'%5D,
%0A%7D%0A%0A%0Atry
@@ -1738,58 +1738,52 @@
'
-Something went wrong calculating platform specific
+Failed to compute platform dependencies. All
dep
@@ -1795,12 +1795,16 @@
cies
-, so
+ will be
'%0A
@@ -1814,34 +1814,32 @@
-%22you're getting them all!%22
+'installed as a result.'
%0A
|
e2532bdbe28c8ee30391c67d2962357ce480cf52
|
Switch from PIL to pillow.
|
setup.py
|
setup.py
|
#!/usr/bin/env python
"""
Installation script:
To release a new version to PyPi:
- Ensure the version is correctly set in oscar.__init__.py
- Run: python setup.py sdist upload
"""
from setuptools import setup, find_packages
import os
import sys
from oscar import get_version
PROJECT_DIR = os.path.dirname(__file__)
# Change to the current directory to solve an issue installing Oscar on the
# Vagrant machine.
if PROJECT_DIR:
os.chdir(PROJECT_DIR)
setup(name='django-oscar',
version=get_version().replace(' ', '-'),
url='https://github.com/tangentlabs/django-oscar',
author="David Winterbottom",
author_email="david.winterbottom@tangentlabs.co.uk",
description="A domain-driven e-commerce framework for Django",
long_description=open(os.path.join(PROJECT_DIR, 'README.rst')).read(),
keywords="E-commerce, Django, domain-driven",
license='BSD',
platforms=['linux'],
packages=find_packages(exclude=["sandbox*", "tests*"]),
include_package_data=True,
install_requires=[
'django>=1.4,<1.5',
# PIL is required for image fields
'PIL==1.1.7',
# Oscar ships with migraations
'South>=0.7.6,<0.8',
# We use the ModelFormSetView from django-extra-views for the basket page
'django-extra-views>=0.2,<0.6',
# We ship a simple Haystack implementation (that needs to be
# improved). We are using the 2.0-beta release from Github and
# eagerly anticipating a stable 2.0 release on PyPI.
'django-haystack==2.0.0-beta',
# Treebeard is used for categories
'django-treebeard>=1.61,<1.62',
# Sorl is used as the default thumbnailer
'sorl-thumbnail==11.12',
'python-memcached>=1.48,<1.49',
# Babel is used for currency formatting
'Babel>=0.9,<0.10',
# Oscar's default templates use compressor (but you can override
# this)
'django-compressor>=1.2,<1.3',
# Oscar's default CSS is generated from Less and so we need node.js
# and lessc to be available to compile the Less files.
'virtual-node>=0.0.1',
'virtual-less>=0.0.1-1.3.3'],
dependency_links=['https://github.com/toastdriven/django-haystack/tarball/f91a9a7ce6fb26093f4ecf09b28d71cf4b59283c#egg=django-haystack-2.0.0-beta'],
# See http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: Unix',
'Programming Language :: Python',
'Topic :: Other/Nonlisted Topic']
)
# Show contributing instructions if being installed in 'develop' mode
if len(sys.argv) > 1 and sys.argv[1] == 'develop':
docs_url = 'http://django-oscar.readthedocs.org/en/latest/contributing.html'
mailing_list = 'django-oscar@googlegroups.com'
mailing_list_url = 'https://groups.google.com/forum/?fromgroups#!forum/django-oscar'
twitter_url = 'https://twitter.com/django_oscar'
msg = (
"You're installing Oscar in 'develop' mode so I presume you're thinking\n"
"of contributing:\n\n"
"(a) That's brilliant - thank you for your time\n"
"(b) If you have any questions, please use the mailing list:\n %s\n"
" %s\n"
"(c) There are more detailed contributing guidelines that you should "
"have a look at:\n %s\n"
"(d) Consider following @django_oscar on Twitter to stay up-to-date\n"
" %s\n\nHappy hacking!") % (mailing_list, mailing_list_url,
docs_url, twitter_url)
line = '=' * 82
print "\n%s\n%s\n%s" % (line, msg, line)
|
Python
| 0
|
@@ -1120,30 +1120,75 @@
elds
-%0A 'PIL==1.1.7
+, Pillow is the %22friendly%22 PIL fork%0A 'pillow%3E=1.7.8,%3C2.0.0
',%0A
|
b97cdbb63923ef3e28bbd329df1afb140f3a349f
|
add setup.py
|
setup.py
|
setup.py
|
Python
| 0.000001
|
@@ -0,0 +1,665 @@
+from setuptools import setup, find_packages%0A%0Asetup(%0A name = 'mobula',%0A version = '1.0',%0A description = 'A Lightweight & Flexible Deep Learning (Neural Network) Framework in Python',%0A author = 'wkcn',%0A author_email = 'wkcn@live.cn',%0A url = 'https://github.com/wkcn/mobula',%0A packages = find_packages(),%0A package_data = %7B%0A '' : %5B'*.md'%5D,%0A 'docs' : %5B'docs/*.md'%5D,%0A 'examples' : %5B'examples/*.py'%5D%0A %7D,%0A keywords = 'Deep Learning Framework in Python',%0A license = 'MIT',%0A install_requires = %5B%0A 'numpy',%0A 'numpy_groupies'%0A %5D%0A)%0A
|
|
0cd5bba6bddbc7b057ff18268e31d7eac50b2d2c
|
update setup.py
|
setup.py
|
setup.py
|
from setuptools import setup
from setuptools.command.test import test as TestCommand
class PyPackageTest(TestCommand):
def initialize_options(self):
TestCommand.initialize_options(self)
self.pytest_args = ['--strict']
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
errno = pytest.main(self.pytest_args)
sys.exit(errno)
setup(
name='mailthon',
version='0.0.0',
description='Elegant email library',
long_description=open('README.rst').read(),
author='Eeo Jun',
author_email='packwolf58@gmail.com',
url='https://github.com/eugene-eeo/mailthon/',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules'
],
include_package_data=True,
package_data={'mailthon': ['LICENSE', 'README.rst']},
packages=['mailthon'],
cmdclass={'test': PyPackageTest},
)
|
Python
| 0.000001
|
@@ -1,20 +1,31 @@
+import sys%0A
from setuptools impo
@@ -232,16 +232,25 @@
args = %5B
+'tests',
'--stric
@@ -251,16 +251,22 @@
-strict'
+, '-s'
%5D%0A%0A d
|
29c2f663556d762167499d23921007f025738188
|
update setup.py
|
setup.py
|
setup.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Thanks to Kenneth Reitz, I stole the template for this
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
PYTHON3 = sys.version_info[0] > 2
required = ['requests>=2.9', 'websocket-client==0.35.0',
'beautifulsoup4==4.4.1', 'html5lib==0.9999999', 'pyfiglet==0.7.4',
'certifi==2015.04.28']
if not PYTHON3:
required += ['importlib>=1.0.3']
packages = ['limbo', 'limbo.plugins']
try:
longdesc = open("README.rst").read()
except:
longdesc = ''
setup(
name='limbo',
version='5.0.3',
description='Simple and Clean Slack Chatbot',
long_description=longdesc,
author='Bill Mill',
author_email='bill@billmill.org',
url='https://github.com/llimllib/limbo',
packages=packages,
scripts = ['bin/limbo'],
package_data={'': ['LICENSE',], '': ['limbo/plugins/*.py']},
include_package_data=True,
install_requires=required,
license='MIT',
classifiers=(
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
),
)
|
Python
| 0.000001
|
@@ -275,17 +275,18 @@
ests%3E=2.
-9
+12
', 'webs
@@ -305,10 +305,10 @@
==0.
-35
+40
.0',
@@ -335,17 +335,17 @@
oup4==4.
-4
+5
.1', 'ht
@@ -361,16 +361,18 @@
.9999999
+99
', 'pyfi
@@ -381,17 +381,17 @@
et==0.7.
-4
+5
',%0A
@@ -410,15 +410,14 @@
=201
-5.04.28
+6.9.26
'%5D%0Ai
@@ -464,17 +464,17 @@
ib%3E=1.0.
-3
+4
'%5D%0A%0Apack
@@ -1066,16 +1066,29 @@
::
-4 - Beta
+5 - Production/Stable
',%0A
@@ -1362,13 +1362,171 @@
4',%0A
-)
+ 'Programming Language :: Python :: 3.5',%0A 'Programming Language :: Python :: Implementation :: PyPy',%0A ),%0A keywords=%22slack chatbot chat limbo%22
,%0A)%0A
|
a6e4f8bf2716eda79a27ec025399b18c76b3356a
|
Fix url
|
setup.py
|
setup.py
|
#!/usr/bin/env python
from graphitepager import __version__
import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def open_file(fname):
return open(os.path.join(os.path.dirname(__file__), fname))
def run_setup():
setup(
name='graphitepager',
version=__version__,
author='Philip Cristiano',
author_email='philipcristiano@gmail.com',
packages=['graphitepager', 'graphitepager.notifiers'],
url='http://github.com/philipcristiano/graphite-pager',
license='BSD',
classifiers=[
'Intended Audience :: System Administrators',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 2.6',
'Topic :: System :: Monitoring',
],
description='',
keywords='',
test_suite='tests',
long_description=open_file('README.rst').read(),
install_requires=open_file('requirements.txt').readlines(),
zip_safe=True,
entry_points="""
[console_scripts]
graphite-pager=graphitepager.worker:main
""",
)
if __name__ == '__main__':
run_setup()
|
Python
| 0.999531
|
@@ -515,31 +515,24 @@
hub.com/
-philipcristiano
+seatgeek
/graphit
|
b8c739f8befca266544d41d9ace34ae680fe5170
|
add setup.py
|
setup.py
|
setup.py
|
Python
| 0.000001
|
@@ -0,0 +1,387 @@
+#!/usr/bin/env python%0A%0Aimport os%0A%0ATHIS_DIR = os.path.dirname(os.path.realpath(__file__))%0ABIN_DIR = os.path.expanduser(%22~/bin%22)%0A%0Adef symlink_to_bin():%0A ln_src = os.path.join(THIS_DIR, %22webnull.py%22)%0A ln_dest = os.path.join(BIN_DIR, %22webnull%22)%0A if os.path.isfile(ln_dest):%0A os.remove(ln_dest)%0A os.symlink(ln_src, ln_dest)%0A%0Aif __name__ == %22__main__%22:%0A symlink_to_bin()%0A
|
|
a03ddd7dc0aa1166e88f71910ece2cd909d7b6c7
|
Add setup.py to executably document package requirements
|
setup.py
|
setup.py
|
Python
| 0
|
@@ -0,0 +1,440 @@
+#!/usr/bin/env python%0Afrom setuptools import setup%0Asetup(%0A name='remoteobjects',%0A version='1.0',%0A description='an Object RESTational Model',%0A packages=%5B'remoteobjects'%5D,%0A package_dir=%7B'remoteobjects': '.'%7D,%0A%0A install_requires=%5B'simplejson%3E=2.0.0', 'httplib2%3E=0.4.0'%5D,%0A provides=%5B'remoteobjects'%5D,%0A%0A author='Six Apart',%0A author_email='python@sixapart.com',%0A url='http://code.sixapart.com/svn/remoteobjects/',%0A)%0A
|
|
7046a54abc31ecc919c628bd197600ac09437989
|
Make dependency versions consistent.
|
setup.py
|
setup.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2016 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 applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import re
import sys
from setuptools import setup, find_packages
# Get the version
version_regex = r'__version__ = ["\']([^"\']*)["\']'
with open('endpoints/__init__.py', 'r') as f:
text = f.read()
match = re.search(version_regex, text)
if match:
version = match.group(1)
else:
raise RuntimeError("No version number found!")
install_requires = [
'google-endpoints-api-management>=1.0.0b1'
]
setup(
name='google-endpoints',
version=version,
description='Google Cloud Endpoints',
long_description=open('README.rst').read(),
author='Google Endpoints Authors',
author_email='googleapis-packages@google.com',
url='https://github.com/cloudendpoints/endpoints-python',
packages=find_packages(),
package_dir={'google-endpoints': 'endpoints'},
license='Apache',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: Implementation :: CPython',
],
scripts=['endpoints/endpointscfg.py'],
tests_require=['mox', 'protobuf', 'protorpc', 'pytest', 'webtest'],
install_requires=install_requires,
)
|
Python
| 0.000008
|
@@ -1067,12 +1067,10 @@
%3E=1.
-0.0b
+1.
1'%0A%5D
|
6d0f54db9654ffa02accb5c557e4d4a5952d0ba0
|
Add a setup.py
|
setup.py
|
setup.py
|
Python
| 0.000006
|
@@ -0,0 +1,989 @@
+#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A%0A# Import python libs%0Aimport os%0Aimport sys%0A%0Aif 'USE_SETUPTOOLS' in os.environ or 'setuptools' in sys.modules:%0A from setuptools import setup%0Aelse:%0A from distutils.core import setup%0A%0ANAME = 'pkgcmp'%0ADESC = ('Automate the creation of a normalized cross distribution package naming database')%0A%0A# Version info -- read without importing%0A_locals = %7B%7D%0Awith open('pkgcmp/version.py') as fp:%0A exec(fp.read(), None, _locals)%0AVERSION = _locals%5B'__version__'%5D%0A%0Asetup(name=NAME,%0A version=VERSION,%0A description=DESC,%0A author='Thomas S Hatch',%0A author_email='thatch@saltstack.com',%0A url='https://saltstack.com',%0A classifiers=%5B%0A 'Operating System :: OS Independent',%0A 'Programming Language :: Python',%0A 'Programming Language :: Python :: 3.4',%0A %5D,%0A scripts=%5B'scripts/pkgcmp'%5D,%0A packages=%5B%0A 'pkgcmp',%0A 'pkgcmp.scanners',%0A 'pkgcmp.dbs',%0A %5D)%0A
|
|
9aabb59303d59287f1f29119a03c979ca0aeaefc
|
Bump version number to 0.10.1
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
setup(
name='idalink',
description='An interface to the insides of IDA!',
long_description=open('README.md').read(),
version='0.10',
url='https://github.com/zardus/idalink',
license='GNU General Public License v3',
packages=find_packages(),
package_data={
'idalink': ['support/*'],
},
install_requires=[
'rpyc',
],
)
|
Python
| 0.00014
|
@@ -184,16 +184,18 @@
on='0.10
+.1
',%0A u
|
72e907ade08aa92f2a816c7a1d6511d125204dbc
|
Update package description
|
setup.py
|
setup.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
import re
import os
import sys
name = 'djangorestframework-jwt'
package = 'rest_framework_jwt'
description = ''
url = 'https://github.com/GetBlimp/django-rest-framework-jwt'
author = 'Jose Padilla'
author_email = 'jpadilla@getblimp.com'
license = 'BSD'
install_requires = open('requirements.txt').read().split('\n')
test_suite = 'rest_framework_jwt.runtests.runtests.main'
def get_version(package):
"""
Return package version as listed in `__version__` in `init.py`.
"""
init_py = open(os.path.join(package, '__init__.py')).read()
return re.search("^__version__ = ['\"]([^'\"]+)['\"]",
init_py, re.MULTILINE).group(1)
def get_packages(package):
"""
Return root package and all sub-packages.
"""
return [dirpath
for dirpath, dirnames, filenames in os.walk(package)
if os.path.exists(os.path.join(dirpath, '__init__.py'))]
def get_package_data(package):
"""
Return all files under the root package, that are not in a
package themselves.
"""
walk = [(dirpath.replace(package + os.sep, '', 1), filenames)
for dirpath, dirnames, filenames in os.walk(package)
if not os.path.exists(os.path.join(dirpath, '__init__.py'))]
filepaths = []
for base, filenames in walk:
filepaths.extend([os.path.join(base, filename)
for filename in filenames])
return {package: filepaths}
version = get_version(package)
if sys.argv[-1] == 'publish':
os.system("python setup.py sdist upload")
os.system("python setup.py bdist_wheel upload")
print("You probably want to also tag the version now:")
print(" git tag -a {0} -m 'version {0}'".format(version))
print(" git push --tags")
sys.exit()
setup(
name=name,
version=version,
url=url,
license=license,
description=description,
author=author,
author_email=author_email,
packages=get_packages(package),
package_data=get_package_data(package),
test_suite=test_suite,
install_requires=install_requires
)
|
Python
| 0.000001
|
@@ -181,16 +181,77 @@
tion = '
+JSON Web Token based authentication for Django REST framework
'%0Aurl =
|
4646873ec80076759c02deac7ff3c50665e31415
|
Update the PyPI version to 0.2.12
|
setup.py
|
setup.py
|
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='0.2.11',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
|
Python
| 0
|
@@ -241,17 +241,17 @@
n='0.2.1
-1
+2
',%0A p
|
380fd95d482af74f40ccc58dbf6238c691fa48f7
|
Version 1.0.8
|
setup.py
|
setup.py
|
#!/usr/bin/python
#
# Copyright 2014 Major Hayden
#
# 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 the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from setuptools import setup
setup(
name='supernova',
version='1.0.7',
author='Major Hayden',
author_email='major@mhtx.net',
description="novaclient wrapper for multiple nova environments",
install_requires=['keyring'],
packages=['supernova'],
url='https://github.com/rackerhacker/supernova',
entry_points={
'console_scripts': [
'supernova = supernova.executable:run_supernova',
'supernova-keyring = supernova.executable:run_supernova_keyring'],
},
)
|
Python
| 0
|
@@ -690,9 +690,9 @@
1.0.
-7
+8
',%0A
|
7efc61175c540a56b03e829ec917ce9efc1f06f9
|
Fix incorrect get_link_flags on Mac
|
tensorflow/python/platform/sysconfig.py
|
tensorflow/python/platform/sysconfig.py
|
# Copyright 2015 The TensorFlow 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 applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""System configuration library."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path as _os_path
import platform as _platform
from tensorflow.python.framework.versions import CXX11_ABI_FLAG as _CXX11_ABI_FLAG
from tensorflow.python.framework.versions import MONOLITHIC_BUILD as _MONOLITHIC_BUILD
from tensorflow.python.framework.versions import VERSION as _VERSION
from tensorflow.python.util.tf_export import tf_export
# pylint: disable=g-import-not-at-top
@tf_export('sysconfig.get_include')
def get_include():
"""Get the directory containing the TensorFlow C++ header files.
Returns:
The directory as string.
"""
# Import inside the function.
# sysconfig is imported from the tensorflow_core module, so having this
# import at the top would cause a circular import, resulting in
# the tensorflow_core module missing symbols that come after sysconfig.
import tensorflow_core as tf
return _os_path.join(_os_path.dirname(tf.__file__), 'include')
@tf_export('sysconfig.get_lib')
def get_lib():
"""Get the directory containing the TensorFlow framework library.
Returns:
The directory as string.
"""
import tensorflow_core as tf
return _os_path.join(_os_path.dirname(tf.__file__))
@tf_export('sysconfig.get_compile_flags')
def get_compile_flags():
"""Get the compilation flags for custom operators.
Returns:
The compilation flags.
"""
flags = []
flags.append('-I%s' % get_include())
flags.append('-D_GLIBCXX_USE_CXX11_ABI=%d' % _CXX11_ABI_FLAG)
return flags
@tf_export('sysconfig.get_link_flags')
def get_link_flags():
"""Get the link flags for custom operators.
Returns:
The link flags.
"""
is_mac = _platform.system() == 'Darwin'
ver = _VERSION.split('.')[0]
flags = []
if not _MONOLITHIC_BUILD:
flags.append('-L%s' % get_lib())
if is_mac:
flags.append('-l:libtensorflow_framework.%s.dylib' % ver)
else:
flags.append('-l:libtensorflow_framework.so.%s' % ver)
return flags
|
Python
| 0
|
@@ -2605,36 +2605,32 @@
flags.append('-l
-:lib
tensorflow_frame
@@ -2640,14 +2640,8 @@
k.%25s
-.dylib
' %25
|
14a96a82209f21ca468a4f765c514ffd68f30f31
|
add my little test script, 'cuz why not
|
plugins/python/test.py
|
plugins/python/test.py
|
Python
| 0
|
@@ -0,0 +1,836 @@
+#!/usr/bin/env python%0A#%0A# Copyright (C) 2005 David Trowbridge%0A#%0A# This program is free software; you can redistribute it and/or%0A# modify it under the terms of the GNU General Public License%0A# as published by the Free Software Foundation; either version 2%0A# of the License, or (at your option) any later version.%0A#%0A# This program is distributed in the hope that it will be useful,%0A# but WITHOUT ANY WARRANTY; without even the implied warranty of%0A# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the%0A# GNU General Public License for more details.%0A#%0A# You should have received a copy of the GNU General Public License%0A# along with this program; if not, write to the Free Software%0A# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.%0A#%0A%0Aimport BZFlag%0A%0Aprint 'test'%0ABZFlag.SendTextMessage (0, 0, 'hello')%0A
|
|
d22abe4ede958779a64c190bdd54451253eb2778
|
Add to model only if part of bunsen xxx
|
bunsenscrapper/spiders/bunsen.py
|
bunsenscrapper/spiders/bunsen.py
|
# -*- coding: utf-8 -*-
import scrapy
from bunsenscrapper.items import BunsenscrapperItem
from scrapy.http.request import Request
class BunsenSpider(scrapy.Spider):
name = "bunsen"
allowed_domains = ["bunsencomics.com"]
start_urls = (
'http://www.bunsencomics.com/?category=Bunsen+C%C3%B3mics',
)
def parse(self, response):
for sel in response.xpath('//article'):
item = BunsenscrapperItem()
item['title'] = sel.xpath('h1/a/text()').extract()
item['link'] = sel.xpath('h1/a/@href').extract()
item['img'] = sel.css('.thumb-image').xpath('@data-src').extract()
yield item
pass
next_link = response.xpath('//a[contains(text(), "Older")]/@href').extract()
if next_link:
yield Request('http://www.bunsencomics.com' + next_link[0], self.parse)
|
Python
| 0
|
@@ -452,16 +452,44 @@
th('h1/a
+%5Bcontains(text(), %22Bunsen%22)%5D
/text()'
@@ -620,16 +620,109 @@
tract()%0A
+%09%09isLinkGood = sel.xpath('h1/a/@href').re('bunsen-%5Cd*$')%0A%09%09if isLinkGood and item%5B'title'%5D:%0A%09
%09%09yield
|
23df7b77cde8b5351cf2902b8b11ee07e4b478f4
|
Add a basic smoke test to check for exceptions and programming errors.
|
tests/smoke_test.py
|
tests/smoke_test.py
|
Python
| 0
|
@@ -0,0 +1,1198 @@
+# -*- coding: utf-8 -*-%0A%0Aimport unittest%0Aimport sys%0Asys.path.insert(0, '../mafia')%0A%0Afrom game import Game%0Afrom game import Player%0A%0Aclass TestMessenger:%0A def message_all_players(self, message: str):%0A print ('public: %7Bmessage%7D'.format(message=message))%0A%0A def message_player(self, player, message: str):%0A print ('%7Bname%7D: %7Bmessage%7D'.format(name=player.nickname, message=message))%0A%0Aclass SmokeTest(unittest.TestCase):%0A def setUp(self):%0A self.messenger = TestMessenger()%0A %0A def test_smoke_test(self):%0A game = Game('t,c,c,m', self.messenger)%0A player_one = Player('one', 'one')%0A player_two = Player('two', 'two')%0A player_three = Player('three', 'three')%0A player_four = Player('four', 'four')%0A game.join(player_one)%0A game.join(player_two)%0A game.join(player_three)%0A game.join(player_four)%0A game.vote('one', 'three')%0A game.vote('three', 'one')%0A game.vote('two', 'three')%0A game.vote('four', 'three')%0A game.target('one', 'two')%0A game.target('two', 'one')%0A game.target('four', 'one')%0A print(game.actions)%0A%0Aif __name__ == '__main__':%0A unittest.main()%0A
|
|
a1f1efe712205b3bd4702a7ae3d06aa3171ad32f
|
add missing file...
|
simuvex/plugins/uc_manager.py
|
simuvex/plugins/uc_manager.py
|
Python
| 0
|
@@ -0,0 +1,863 @@
+%0Aimport logging%0Al = logging.getLogger('simuvex.plugins.uc_manager')%0A%0Afrom .plugin import SimStatePlugin%0A%0Aclass SimUCManager(SimStatePlugin):%0A def __init__(self, man=None):%0A%0A SimStatePlugin.__init__(self)%0A%0A if man:%0A self._uc_region_base = man._uc_region_base%0A self._uc_pos = man._uc_pos%0A else:%0A self._uc_region_base = 0xd0000000%0A self._uc_pos = 0%0A%0A def assign(self):%0A %22%22%22%0A Assign a new region for under-constrained symbolic execution%0A%0A :return: as ast of memory address that points to a new region%0A %22%22%22%0A%0A ptr = self.state.se.BVV(self._uc_region_base + self._uc_pos, self.state.arch.bits)%0A self._uc_pos += 0x1000%0A return ptr%0A%0A def copy(self):%0A return SimUCManager(man=self)%0A%0ASimStatePlugin.register_default('uc_manager', SimUCManager)%0A
|
|
e33ce5f613c2a7bb9c2c42fba695ee37d3bb66ce
|
Add integration tests
|
tests/test_flask.py
|
tests/test_flask.py
|
Python
| 0
|
@@ -0,0 +1,759 @@
+from main import app%0Aimport pytest%0Aimport json%0A%0A%0A@pytest.fixture%0Adef client():%0A client = app.test_client()%0A%0A yield client%0A%0A%0Asites = %5B%0A %22/kwejk%22,%0A %22/jbzd%22,%0A %22/9gag%22,%0A %22/9gagnsfw%22,%0A %22/demotywatory%22,%0A %22/mistrzowie%22,%0A %22/anonimowe%22,%0A%5D%0A%0A%0A# This test could fail if the site changes it's schema or is not functional%0A@pytest.mark.parametrize(%22site%22, sites)%0Adef test_sites(client, site):%0A r = client.get(site)%0A%0A assert r.status == %22200 OK%22%0A data = json.loads(r.data)%0A%0A assert len(data%5B%22memes%22%5D) %3E 0%0A assert data%5B%22next_page_url%22%5D is not None%0A%0A r = client.get(data%5B%22next_page_url%22%5D)%0A%0A assert r.status == %22200 OK%22%0A data = json.loads(r.data)%0A%0A assert len(data%5B%22memes%22%5D) %3E 0%0A assert data%5B%22next_page_url%22%5D is not None%0A
|
|
36a85fac06fd1bfe6934883f98b60edcbf3814be
|
Add test for scuba.utils.format_cmdline()
|
tests/test_utils.py
|
tests/test_utils.py
|
Python
| 0
|
@@ -0,0 +1,1338 @@
+from __future__ import print_function%0A%0Afrom nose.tools import *%0Afrom unittest import TestCase%0A%0Aimport logging%0Aimport shlex%0Afrom itertools import chain%0A%0Afrom .utils import *%0A%0Aimport scuba.utils%0A%0A%0Aclass TestUtils(TestCase):%0A%0A def _parse_cmdline(self, cmdline):%0A # Strip the formatting and whitespace%0A lines = %5Bl.rstrip('%5C%5C').strip() for l in cmdline.splitlines()%5D%0A%0A # Split each line, and return a flattened list of arguments%0A return chain.from_iterable(map(shlex.split, lines))%0A%0A def _test_format_cmdline(self, args):%0A%0A # Call the unit-under-test to get the formatted command line%0A result = scuba.utils.format_cmdline(args)%0A%0A # Parse the result back out to a list of arguments%0A out_args = self._parse_cmdline(result)%0A%0A # Verify that they match%0A assert_seq_equal(out_args, args)%0A%0A%0A def test_basic(self):%0A '''format_cmdline works as expected'''%0A%0A self._test_format_cmdline(%5B%0A 'something',%0A '-a',%0A '-b',%0A '--long', 'option text',%0A '-s', 'hort',%0A 'a very long argument here that will end up on its own line because it is so wide and nothing else will fit at the default width',%0A 'and now',%0A 'some', 'more', 'stuff',%0A 'and even more stuff',%0A %5D)%0A
|
|
424db0df3c8be8538d551bd6974a8eccee6e53cc
|
add tenki.py
|
tenki.py
|
tenki.py
|
Python
| 0.000162
|
@@ -0,0 +1,1259 @@
+import urllib.request%0D%0Aimport sys%0D%0Aimport numpy as np%0D%0A%0D%0Aurl=%22http://weather.is.kochi-u.ac.jp/sat/gms.fareast/%22%0D%0Aa=1%0D%0Ab=0%0D%0Ax = input(%22Please Enter Year You Want: %22)%0D%0Ay = input(%22And Enter Folder You Save File: %22) + %22/%22%0D%0Ac=%5B%5D%0D%0Afor ii in range(1,13):%0D%0A for i in range(1,32):%0D%0A if i%3C10:%0D%0A url=%22http://weather.is.kochi-u.ac.jp/sat/gms.fareast/%22+x+%22/0%22+str(a)+%22/0%22+str(i)+%22/fe.%22+x%5B2:%5D+%220%22+str(a)+%220%22+str(i)+%2209.jpg%22%0D%0A title=y+str(b)+%22.jpg%22%0D%0A else:%0D%0A url=%22http://weather.is.kochi-u.ac.jp/sat/gms.fareast/%22+x+%22/0%22+str(a)+%22/%22+str(i)+%22/fe.%22+x%5B2:%5D+%220%22+str(a)+str(i)+%2209.jpg%22%0D%0A title=y+str(b)+%22.jpg%22%0D%0A try:%0D%0A urllib.request.urlretrieve(url,title)%0D%0A except:%0D%0A if ii == 2:%0D%0A if i == 29:%0D%0A ii+=1%0D%0A continue%0D%0A if ii == 4 or ii == 6 or ii == 9 or ii == 11:%0D%0A if i == 31:%0D%0A ii+=1%0D%0A continue%0D%0A d = str(ii)+%22/%22+str(i)%0D%0A c = np.append(c,%5Bd%5D,axis=0)%0D%0A continue%0D%0A print(b,url)%0D%0A b+=1%0D%0A a+=1%0D%0Aprint(%22I Was Able To Download Files About %22+str(x))%0D%0Aprint(%22This Is Files I Could Not Download:%22)%0D%0Afor i in c:%0D%0A print(i)%0D%0A
|
|
d5250790d3509dfe4cbd1f507c83a92bef9614fe
|
Test cache instance.
|
tests.py
|
tests.py
|
Python
| 0
|
@@ -0,0 +1,1729 @@
+# -*- coding: utf-8 -*-%0A%0Aimport pytest%0A%0Afrom flask import Flask%0Afrom flask.ext.cacheobj import FlaskCacheOBJ, Msgpackable%0A%0Aapp = Flask(__name__)%0Acache = FlaskCacheOBJ()%0Acache.init_app(app)%0A%0A@pytest.fixture%0Adef app(request):%0A app = Flask(__name__)%0A ctx = app.app_context()%0A ctx.push()%0A request.addfinalizer(ctx.pop)%0A return app%0A%0A@pytest.fixture%0Adef cache(app, request):%0A cache = FlaskCacheOBJ()%0A app.config%5B'CACHE_HOST'%5D = 'localhost'%0A cache.init_app(app)%0A request.addfinalizer(cache.mc._flushall)%0A return cache%0A%0Adef test_mc_initialized(cache):%0A assert cache.mc%0A%0Aclass Obj(Msgpackable):%0A%0A def __init__(self, id):%0A self.id = id%0A%0Adef test_cache_obj(cache):%0A @cache.obj(%7B'key': 'test_cache_obj:%7Bid%7D', 'expire': 1%7D)%0A def get(id):%0A return Obj(id)%0A assert not cache.mc.get('test_cache_obj:1')%0A assert get(1)%0A assert cache.mc.get('test_cache_obj:1')%0A assert get(1)%0A%0Adef test_cache_list(cache):%0A @cache.list(%7B'key': 'test_cache_list:%7Bid%7D', 'expire': 1%7D)%0A def get(id):%0A return range(id)%0A assert not cache.mc.smembers('test_cache_list:1')%0A assert get(1)%0A assert cache.mc.exists('test_cache_list:1')%0A assert get(1)%0A%0Adef test_cache_hash(cache):%0A @cache.hash(%7B'key': '%7Bid%7D', 'hash_key': 'item', 'expire': 1%7D)%0A def get(id):%0A return Obj(1)%0A assert not cache.mc.hget('item', '1')%0A assert get(1)%0A assert cache.mc.hget('item', '1')%0A assert get(1)%0A%0Adef test_cache_counter(cache):%0A @cache.counter(%7B'key': 'test_cache_counter:%7Bid%7D', 'expire': 1%7D)%0A def get(id):%0A return int(id)%0A%0A assert not cache.mc.get('test_cache_counter:1')%0A assert get(1)%0A assert int(cache.mc.get('test_cache_counter:1'))%0A assert get(1)%0A
|
|
e87fb6fc09e70dbcd9c65d183c0addb1b290ffcf
|
Add test cases for Tradfri sensor platform (#64165)
|
tests/components/tradfri/test_sensor.py
|
tests/components/tradfri/test_sensor.py
|
Python
| 0
|
@@ -0,0 +1,2369 @@
+%22%22%22Tradfri sensor platform tests.%22%22%22%0A%0Afrom unittest.mock import MagicMock, Mock%0A%0Afrom .common import setup_integration%0A%0A%0Adef mock_sensor(state_name: str, state_value: str, device_number=0):%0A %22%22%22Mock a tradfri sensor.%22%22%22%0A dev_info_mock = MagicMock()%0A dev_info_mock.manufacturer = %22manufacturer%22%0A dev_info_mock.model_number = %22model%22%0A dev_info_mock.firmware_version = %221.2.3%22%0A%0A # Set state value, eg battery_level = 50%0A setattr(dev_info_mock, state_name, state_value)%0A%0A _mock_sensor = Mock(%0A id=f%22mock-sensor-id-%7Bdevice_number%7D%22,%0A reachable=True,%0A observe=Mock(),%0A device_info=dev_info_mock,%0A has_light_control=False,%0A has_socket_control=False,%0A has_blind_control=False,%0A has_signal_repeater_control=False,%0A has_air_purifier_control=False,%0A )%0A _mock_sensor.name = f%22tradfri_sensor_%7Bdevice_number%7D%22%0A%0A return _mock_sensor%0A%0A%0Aasync def test_battery_sensor(hass, mock_gateway, mock_api_factory):%0A %22%22%22Test that a battery sensor is correctly added.%22%22%22%0A mock_gateway.mock_devices.append(%0A mock_sensor(state_name=%22battery_level%22, state_value=60)%0A )%0A await setup_integration(hass)%0A%0A sensor_1 = hass.states.get(%22sensor.tradfri_sensor_0%22)%0A assert sensor_1 is not None%0A assert sensor_1.state == %2260%22%0A assert sensor_1.attributes%5B%22unit_of_measurement%22%5D == %22%25%22%0A assert sensor_1.attributes%5B%22device_class%22%5D == %22battery%22%0A%0A%0Aasync def test_sensor_observed(hass, mock_gateway, mock_api_factory):%0A %22%22%22Test that sensors are correctly observed.%22%22%22%0A%0A sensor = mock_sensor(state_name=%22battery_level%22, state_value=60)%0A mock_gateway.mock_devices.append(sensor)%0A await setup_integration(hass)%0A assert len(sensor.observe.mock_calls) %3E 0%0A%0A%0Aasync def test_sensor_available(hass, mock_gateway, mock_api_factory):%0A %22%22%22Test sensor available property.%22%22%22%0A%0A sensor = mock_sensor(state_name=%22battery_level%22, state_value=60, device_number=1)%0A sensor.reachable = True%0A%0A sensor2 = mock_sensor(state_name=%22battery_level%22, state_value=60, device_number=2)%0A sensor2.reachable = False%0A%0A mock_gateway.mock_devices.append(sensor)%0A mock_gateway.mock_devices.append(sensor2)%0A await setup_integration(hass)%0A%0A assert hass.states.get(%22sensor.tradfri_sensor_1%22).state == %2260%22%0A assert hass.states.get(%22sensor.tradfri_sensor_2%22).state == %22unavailable%22%0A
|
|
5938881e939ce5088974489a943bd7d86925732f
|
Add unittest for inception
|
tests/functions_tests/test_inception.py
|
tests/functions_tests/test_inception.py
|
Python
| 0
|
@@ -0,0 +1,1590 @@
+import unittest%0A%0Aimport numpy%0A%0Aimport chainer%0Afrom chainer import cuda%0Afrom chainer import functions%0Afrom chainer import gradient_check%0Afrom chainer import testing%0Afrom chainer.testing import attr%0Afrom chainer.testing import condition%0A%0A%0Aif cuda.available:%0A cuda.init()%0A%0A%0Aclass TestInception(unittest.TestCase):%0A%0A in_channels = 3%0A out1, proj3, out3, proj5, out5, proj_pool = 3, 2, 3, 2, 3, 3%0A%0A def setUp(self):%0A self.x = numpy.random.uniform(-1, 1, (10, self.in_channels, 5, 5)).astype(numpy.float32)%0A out = self.out1 + self.out3 + self.out5 + self.proj_pool%0A self.gy = numpy.random.uniform(-1, 1, (10, out, 5, 5)).astype(numpy.float32)%0A self.f = functions.Inception(self.in_channels, self.out1, self.proj3, self.out3, self.proj5, self.out5, self.proj_pool)%0A%0A def check_forward(self, x_data):%0A x = chainer.Variable(x_data)%0A y = self.f(x)%0A%0A @condition.retry(3)%0A def test_forward_cpu(self):%0A self.check_forward(self.x)%0A%0A @condition.retry(3)%0A @attr.gpu%0A def test_forward_gpu(self):%0A self.f.to_gpu()%0A self.check_forward(cuda.to_gpu(self.x))%0A%0A def check_backward(self, x_data, y_grad):%0A x = chainer.Variable(x_data)%0A y = self.f(x)%0A y.grad = y_grad%0A y.backward()%0A%0A @condition.retry(3)%0A def test_backward_cpu(self):%0A self.check_backward(self.x, self.gy)%0A%0A @condition.retry(3)%0A @attr.gpu%0A def test_backward_gpu(self):%0A self.f.to_gpu()%0A self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.gy))%0A%0Atesting.run_module(__name__, __file__)%0A
|
|
92a911a53158a89f0bd7f7e989de47f1854268ff
|
make ogvs for just one episode
|
dj/scripts/dv2ogv.py
|
dj/scripts/dv2ogv.py
|
#!/usr/bin/python
# makes .ogv for all dv in a show
import os
import subprocess
from process import process
from main.models import Client, Show, Location, Episode, Raw_File, Cut_List
class mkpreview(process):
def one_dv(self,loc_dir,dv):
src = os.path.join(loc_dir,dv.filename)
dst = os.path.join(loc_dir,dv.basename()+'.ogv')
if not os.path.exists(dst):
cmd="ffmpeg2theora --videoquality 1 --audioquality 3 --audiobitrate 48 --speedlevel 2 --width 360 --keyint 256".split()
# cmd="ffmpeg2theora --videoquality 1 --audioquality 3 --audiobitrate 48 --speedlevel 2 --width 360 --height 240 --framerate 2 --keyint 256 --channels 1".split()
# cmd="ffmpeg2theora --videoquality 10 --videobitrate 16778 --optimize --audioquality 10 --audiobitrate 500 --keyint 1".split()
cmd+=[ src, '-o', dst, ]
print ' '.join(cmd)
p=subprocess.Popen(cmd).wait()
return
"""
def process_ep(self, ep):
dir=os.path.join(self.show_dir,'dv',ep.location.slug)
dvs = Raw_File.objects.filter(cut_list__episode=ep)
for dv in dvs:
self.one_dv(dir,dv)
return True
"""
def one_loc(self,location,dir):
for dv in Raw_File.objects.filter(location=location):
self.one_dv(dir,dv)
def one_show(self, show):
self.set_dirs(show)
for loc in Location.objects.filter(show=show):
dir=os.path.join(self.show_dir,'dv',loc.slug)
if self.options.verbose: print show,loc,dir
self.one_loc(loc, dir)
def work(self):
"""
find and process show
"""
if self.options.client and self.options.show:
client = Client.objects.get(slug=self.options.client)
show = Show.objects.get(client=client, slug=self.options.show)
self.one_show(show)
return
def add_more_options(self, parser):
parser.add_option('-o', '--orphans', action='store_true',
help='csv file' )
if __name__=='__main__':
p=mkpreview()
p.main()
|
Python
| 0
|
@@ -244,16 +244,44 @@
ir,dv):%0A
+ print dv.filename, %0A
@@ -377,16 +377,51 @@
'.ogv')%0A
+ print os.path.exists(dst) %0A
@@ -423,16 +423,17 @@
if
+(
not os.p
@@ -447,16 +447,39 @@
sts(dst)
+) or self.options.whack
:%0A
@@ -963,24 +963,26 @@
%0A
+ #
print ' '.j
@@ -990,16 +990,104 @@
in(cmd)%0A
+ if self.options.test:%0A print %22testing%22%0A else:%0A
@@ -1140,24 +1140,16 @@
urn%0A %0A
- %22%22%22%0A
def
@@ -1367,24 +1367,25 @@
rn True%0A
+%0A
%22%22%22%0A
%0A def
@@ -1376,17 +1376,16 @@
%22%22%22%0A
-%0A
def
@@ -1778,27 +1778,17 @@
-%22%22%22%0A
+#
find an
@@ -1806,20 +1806,8 @@
how%0A
- %22%22%22%0A
@@ -2172,19 +2172,42 @@
lp='
-csv file' )
+process orpahans (too?)' )%0A %22%22%22
%0A%0A%0Ai
|
36756dbd6b287f8dc6d5629027a8fe75d0f4bb09
|
Add Chuck Norris bot to the team
|
NorrisIsSoFunny_bot.py
|
NorrisIsSoFunny_bot.py
|
Python
| 0
|
@@ -0,0 +1,2154 @@
+import telegram%0A%0A%0ALAST_UPDATE_ID = None%0A%0A%0Adef main():%0A%0A ''' This is the main function that has to be called '''%0A%0A global LAST_UPDATE_ID%0A%0A # Telegram Bot Authorization Token%0A bot = telegram.Bot('put your token here')%0A%0A # This will be our global variable to keep the latest update_id when requesting%0A # for updates. It starts with the latest update_id if available.%0A try:%0A LAST_UPDATE_ID = bot.getUpdates()%5B-1%5D.update_id%0A except IndexError:%0A LAST_UPDATE_ID = None%0A%0A while True:%0A fetch_url(bot)%0A%0A%0Adef list_compare(first_list, second_list):%0A%0A ''' Function to compare two list and return the index of first matched index'''%0A%0A for word in first_list:%0A if word in second_list:%0A return second_list.index(word)%0A return -1%0A%0Adef fetch_url(bot):%0A global LAST_UPDATE_ID%0A%0A # Following is a dictionary of commands that the bot can use%0A%0A commands = %7B'/help':%22Jokes are what I am made for, my speciality is Chuck Norris%22, '/start':'I am here to give you more jokes about Chuck Norris, because he is the best'%7D%0A%0A magic_words = %5B'more','More','/more','/More'%5D%0A%0A for update in bot.getUpdates(offset=LAST_UPDATE_ID, timeout=10):%0A chat_id = update.message.chat_id%0A message = update.message.text.encode('utf-8')%0A message_list = message.split()%0A%0A if(message in commands):%0A bot.sendMessage(chat_id=chat_id, text=commands%5Bmessage%5D)%0A LAST_UPDATE_ID = update.update_id + 1%0A # Name of my bot is NorrisIsFunny_bot replace your bot name with this%0A if ( list_compare(magic_words, message_list)!= -1 or message == '/more@NorrisIsSoFunny_bot'):%0A import requests %0A import json%0A url = 'http://api.icndb.com/jokes/random'%0A myResponse = requests.get(url)%0A if (myResponse.ok):%0A jData = json.loads(myResponse.content)%0A jValue = jData.get('value')%0A jJoke = str(jValue.get('joke'))%0A bot.sendMessage(chat_id=chat_id,text=jJoke)%0A LAST_UPDATE_ID = update.update_id + 1%0A %0Aif __name__ == '__main__':%0A main()%0A
|
|
924ef1395214c2f71b96c21f41e240c88f0570a1
|
Add project_security.xml file entry in update_xml section
|
addons/project/__terp__.py
|
addons/project/__terp__.py
|
{
"name" : "Project Management",
"version": "1.0",
"author" : "Tiny",
"website" : "http://tinyerp.com/module_project.html",
"category" : "Generic Modules/Projects & Services",
"depends" : ["product", "account", 'mrp', 'sale', 'base'],
"description": "Project management module that track multi-level projects, tasks, works done on tasks, eso. It is able to render planning, order tasks, eso.",
"init_xml" : [],
"demo_xml" : ["project_demo.xml"],
"update_xml": ["project_data.xml", "project_wizard.xml", "project_view.xml", "project_report.xml", "project_workflow.xml"],
"active": False,
"installable": True
}
|
Python
| 0.000001
|
@@ -464,16 +464,19 @@
_xml%22: %5B
+%0A%09%09
%22project
@@ -483,24 +483,27 @@
_data.xml%22,
+%0A%09%09
%22project_wiz
@@ -508,24 +508,27 @@
izard.xml%22,
+%0A%09%09
%22project_vie
@@ -531,24 +531,27 @@
_view.xml%22,
+%0A%09%09
%22project_rep
@@ -560,16 +560,19 @@
t.xml%22,
+%0A%09%09
%22project
@@ -581,24 +581,53 @@
orkflow.xml%22
+,%0A%09%09%22project_security.xml%22,%0A%09
%5D,%0A%09%22active%22
|
c1a378adcfd4ccccc44b0c9272e84a765f61f88a
|
add import script for Selby
|
polling_stations/apps/data_collection/management/commands/import_selby.py
|
polling_stations/apps/data_collection/management/commands/import_selby.py
|
Python
| 0
|
@@ -0,0 +1,357 @@
+from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter%0A%0Aclass Command(BaseXpressDemocracyClubCsvImporter):%0A council_id = 'E07000169'%0A addresses_name = 'SelbyDemocracy_Club__04May2017.tsv'%0A stations_name = 'SelbyDemocracy_Club__04May2017.tsv'%0A elections = %5B'local.north-yorkshire.2017-05-04'%5D%0A csv_delimiter = '%5Ct'%0A
|
|
821aa6a0130075183a9e8d1ca2d1f3c76ec6d977
|
Add coverage annotation
|
lib/python2.6/aquilon/aqdb/model/address_assignment.py
|
lib/python2.6/aquilon/aqdb/model/address_assignment.py
|
# ex: set expandtab softtabstop=4 shiftwidth=4: -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
#
# Copyright (C) 2010,2011,2012 Contributor
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the EU DataGrid Software License. You should
# have received a copy of the license with this program, and the
# license is published at
# http://eu-datagrid.web.cern.ch/eu-datagrid/license.html.
#
# THE FOLLOWING DISCLAIMER APPLIES TO ALL SOFTWARE CODE AND OTHER
# MATERIALS CONTRIBUTED IN CONNECTION WITH THIS PROGRAM.
#
# THIS SOFTWARE IS LICENSED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE AND ANY WARRANTY OF NON-INFRINGEMENT, ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
# OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
# OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THIS
# SOFTWARE MAY BE REDISTRIBUTED TO OTHERS ONLY BY EFFECTIVELY USING
# THIS OR ANOTHER EQUIVALENT DISCLAIMER AS WELL AS ANY OTHER LICENSE
# TERMS THAT MAY APPLY.
""" Assign Addresses to interfaces """
from datetime import datetime
import re
from sqlalchemy import (Column, Integer, String, DateTime, ForeignKey, Sequence,
UniqueConstraint)
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.orm import relation, backref, object_session, deferred
from sqlalchemy.sql import and_
from aquilon.aqdb.column_types import IPV4, AqStr, Enum
from aquilon.aqdb.model import (Base, Interface, ARecord, DnsEnvironment, Fqdn,
Network)
from aquilon.aqdb.model.a_record import dns_fqdn_mapper
_TN = 'address_assignment'
_ABV = 'addr_assign'
# Valid values:
# - system: used/configured by the operating system
# - zebra: used/configured by Zebra
ADDR_USAGES = ['system', 'zebra']
class AddressAssignment(Base):
"""
Assignment of IP addresses to network interfaces.
It's kept as an association map to model the linkage, since we need to
have maximum ability to provide potentially complex configuration
scenarios, such as advertising certain VIP addresses from some, but not
all of the network interfaces on a machine (to be used for backup
servers, cluster filesystem servers, NetApp filers, etc.). While in
most cases we can assume VIPs are broadcast out all interfaces on the
box we still need to have the underlying model as the more complex
many to many relationship implemented here.
"""
__tablename__ = _TN
_label_check = re.compile('^[a-z0-9]{0,16}$')
id = Column(Integer, Sequence('%s_seq' % _TN), primary_key=True)
interface_id = Column(Integer, ForeignKey('interface.id',
name='%s_interface_id_fk' % _ABV,
ondelete='CASCADE'),
nullable=False)
_label = Column("label", AqStr(16), nullable=False)
ip = Column(IPV4, nullable=False)
network_id = Column(Integer, ForeignKey('network.id',
name='%s_network_fk' % _TN),
nullable=False)
usage = Column(Enum(16, ADDR_USAGES), nullable=False, default="system")
dns_environment_id = Column(Integer, ForeignKey('dns_environment.id',
name='%s_dns_env_fk' %
_ABV),
nullable=False)
creation_date = deferred(Column(DateTime, default=datetime.now,
nullable=False))
comments = deferred(Column(String(255), nullable=True))
interface = relation(Interface, lazy=False, innerjoin=True,
backref=backref('assignments', order_by=[_label],
cascade='all, delete-orphan'))
dns_environment = relation(DnsEnvironment, innerjoin=True)
# Setting viewonly is very important here as we do not want the removal of
# an AddressAssignment record to change the linked DNS record(s)
# Can't use backref or back_populates due to the different mappers
dns_records = relation(dns_fqdn_mapper, uselist=True,
primaryjoin=and_(ip == ARecord.ip,
dns_environment_id == Fqdn.dns_environment_id),
foreign_keys=[ARecord.ip, Fqdn.dns_environment_id],
viewonly=True)
fqdns = association_proxy('dns_records', 'fqdn')
network = relation(Network, backref=backref('assignments',
passive_deletes=True,
order_by=[ip]))
@property
def logical_name(self):
"""
Compute an OS-agnostic name for this interface/address combo.
BIG FAT WARNING: do _NOT_ assume that this name really exist on the
host!
There are external systems like DSDB that can not handle having multiple
addresses on the same interface. Because of that this function generates
an unique name for every interface/address tuple.
"""
# Use the Linux naming convention because people are familiar with that
# and it is easy to parse if needed
name = self.interface.name
if self.label:
name += ":%s" % self.label
return name
@property
def label(self):
if self._label == '-':
return ""
else:
return self._label
def __init__(self, label=None, network=None, **kwargs):
# This is dirty. We want to allow empty labels, but Oracle converts
# empty strings to NULL, violating the NOT NULL constraint. We could
# allow label to be NULL and relying on the unique indexes to forbid
# adding multiple empty labels, but that is again Oracle-specific
# behavior which actually violates the SQL standard, so it would not
# work with other databases.
if not label:
label = '-'
elif not self._label_check.match(label):
raise ValueError("Illegal address label '%s'." % label)
# Right now network_id is nullable due to how refresh_network works, so
# verify the network here
if not network:
raise ValueError("AddressAssignment needs a network")
super(AddressAssignment, self).__init__(_label=label, network=network,
**kwargs)
def __repr__(self):
return "<Address %s on %s/%s>" % (self.ip,
self.interface.hardware_entity.label,
self.logical_name)
address = AddressAssignment.__table__ # pylint: disable=C0103, E1101
address.primary_key.name = '%s_pk' % _TN
address.append_constraint(
UniqueConstraint("interface_id", "ip", name="%s_iface_ip_uk" % _ABV))
address.append_constraint(
UniqueConstraint("interface_id", "label", name="%s_iface_label_uk" % _ABV))
# Assigned to external classes here to avoid circular dependencies.
Interface.addresses = association_proxy('assignments', 'ip')
# Can't use backref or back_populates due to the different mappers
# This relation gives us the two other sides of the triangle mentioned above
ARecord.assignments = relation(
AddressAssignment,
primaryjoin=and_(AddressAssignment.ip == ARecord.ip,
ARecord.fqdn_id == Fqdn.id,
AddressAssignment.dns_environment_id == Fqdn.dns_environment_id),
foreign_keys=[AddressAssignment.ip, Fqdn.id],
viewonly=True)
|
Python
| 0
|
@@ -1912,16 +1912,62 @@
t and_%0A%0A
+from aquilon.exceptions_ import InternalError%0A
from aqu
@@ -6943,16 +6943,36 @@
network:
+ # pragma: no cover
%0A
@@ -6978,29 +6978,32 @@
raise
-Value
+Internal
Error(%22Addre
|
76ea699d9b9ffd119f080e79b60d664133bfadbe
|
Fix trusts initliazation problem
|
senlin/api/middleware/trust.py
|
senlin/api/middleware/trust.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 the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_config import cfg
from oslo_utils import importutils
import six
import webob
from senlin.common import exception
from senlin.common.i18n import _
from senlin.common import wsgi
from senlin.db import api as db_api
from senlin.drivers.openstack import keystone_v3
class TrustMiddleware(wsgi.Middleware):
'''Extract trust info from request.
The extracted information is filled into the request context.
Senlin engine will use this information for access control.
'''
def _get_service_user_id(self, ctx):
# Convert user name to user ID first
importutils.import_module('keystonemiddleware.auth_token')
admin_user = cfg.CONF.keystone_authtoken.admin_user
admin_passwd = cfg.CONF.keystone_authtoken.admin_password
project_name = cfg.CONF.keystone_authtoken.admin_tenant_name
params = {
'auth_url': ctx.auth_url,
'user_name': admin_user,
'password': admin_passwd,
'project_name': project_name,
# This is a hack, we need to know the domain name somehow
'user_domain_name': 'Default',
'project_domain_name': 'Default',
}
kc = keystone_v3.KeystoneClient(params)
try:
admin_id = kc.user_get_by_name(admin_user)
except exception.UserNotFound:
# This is unacceptable, treat it as a server error
msg = _("Failed Senlin user checking.")
raise webob.exc.HTTPInternalServerError(msg)
return admin_id
def _get_trust(self, ctx):
'''List trusts with current user as the trustor.'''
# DB table is used as a cache for the trusts.
cred_exists = False
res = db_api.cred_get(ctx, ctx.user, ctx.project)
if res is not None:
try:
trust_id = res.cred['openstack']['trust']
return trust_id
except KeyError:
# Garbage in the store, ignore it
cred_exists = True
pass
admin_id = self._get_service_user_id(ctx)
params = {
'auth_url': ctx.auth_url,
'auth_token': ctx.auth_token,
'project': ctx.project,
'user': ctx.user,
}
kc = keystone_v3.KeystoneClient(params)
try:
trusts = kc.trust_get_by_trustor(ctx.user, admin_id, ctx.project)
except exception.TrustNotFound:
# No trust found is okay
pass
if len(trusts) > 0:
trust = trusts[0]
else:
# Create a trust if no existing one found
try:
trust = kc.trust_create(ctx.user, admin_id, ctx.project,
ctx.roles)
except exception.Error as ex:
msg = _("Failed building trust from user: "
"%s.") % six.text_type(ex)
raise webob.exc.HTTPInternalServerError(msg)
# update cache
if cred_exists:
db_api.cred_update(ctx.user, ctx.project,
{'cred': {'openstack': {'trust': trust.id}}})
else:
values = {
'user': ctx.user,
'project': ctx.project,
'cred': {'openstack': {'trust': trust.id}}
}
db_api.cred_create(ctx, values)
return trust.id
def process_request(self, req):
trust_id = self._get_trust(req.context)
req.context.trusts = trust_id
|
Python
| 0.000011
|
@@ -3033,36 +3033,43 @@
kay%0A
-pass
+trusts = %5B%5D
%0A%0A if len
|
b01b2757e5bfd9835ce28e6d5e27137c7aa5075b
|
Add a small test script to call individual methods of a driver
|
tools/testdriver.py
|
tools/testdriver.py
|
Python
| 0
|
@@ -0,0 +1,2444 @@
+# -*- Mode: Python; coding: utf-8 -*-%0A# vi:si:et:sw=4:sts=4:ts=4%0A%0A##%0A## Copyright (C) 2007 Async Open Source %3Chttp://www.async.com.br%3E%0A## All rights reserved%0A##%0A## This program is free software; you can redistribute it and/or modify%0A## it under the terms of the GNU General Public License as published by%0A## the Free Software Foundation; either version 2 of the License, or%0A## (at your option) any later version.%0A##%0A## This program is distributed in the hope that it will be useful,%0A## but WITHOUT ANY WARRANTY; without even the implied warranty of%0A## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the%0A## GNU General Public License for more details.%0A##%0A## You should have received a copy of the GNU General Public License%0A## along with this program; if not, write to the Free Software%0A## Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,%0A## USA.%0A##%0A## Author(s): Johan Dahlin %3Cjdahlin@async.com.br%3E%0A##%0A%0Aimport optparse%0Aimport sys%0A%0Afrom kiwi.python import namedAny%0A%0Afrom stoqdrivers.devices.serialbase import SerialPort%0A%0Adef main(args):%0A usage = %22usage: %25prog %5Boptions%5D command %5Bargs%5D%22%0A parser = optparse.OptionParser(usage=usage)%0A parser.add_option('-t', '--type',%0A action=%22store%22,%0A dest=%22type%22,%0A default=%22printers%22,%0A help='Device type')%0A parser.add_option('-b', '--brand',%0A action=%22store%22,%0A dest=%22brand%22,%0A help='Device brand')%0A parser.add_option('-m', '--model',%0A action=%22store%22,%0A dest=%22model%22,%0A help='Device model')%0A parser.add_option('-p', '--port',%0A action=%22store%22,%0A dest=%22port%22,%0A default=%22/dev/ttyS0%22,%0A help='Printer port')%0A%0A options, args = parser.parse_args(args)%0A if len(args) %3C 2:%0A raise SystemExit(%22Need a command%22)%0A%0A driver = namedAny('stoqdrivers.devices.%25s.%25s.%25s.%25s' %25 (%0A options.type, options.brand, options.model, options.model))%0A%0A device = driver(port=SerialPort(options.port))%0A%0A command = args%5B1%5D%0A cb = getattr(device, command)%0A%0A args = map(int, tuple(args%5B2:%5D))%0A retval = cb(*args)%0A if retval is not None:%0A print '%25s returned: %25r' %25 (command, retval)%0A return 0%0A%0Aif __name__ == '__main__':%0A sys.exit(main(sys.argv))%0A
|
|
fb08ad77a821d86a3049628d907577949d525dac
|
Add unittests to test environment.py methods
|
toolium/test/behave/test_environment.py
|
toolium/test/behave/test_environment.py
|
Python
| 0.000001
|
@@ -0,0 +1,1611 @@
+# -*- coding: utf-8 -*-%0Au%22%22%22%0ACopyright 2016 Telef%C3%B3nica Investigaci%C3%B3n y Desarrollo, S.A.U.%0AThis file is part of Toolium.%0A%0ALicensed under the Apache License, Version 2.0 (the %22License%22);%0Ayou may not use this file except in compliance with the License.%0AYou may obtain a copy of the License at%0A%0A http://www.apache.org/licenses/LICENSE-2.0%0A%0AUnless required by applicable law or agreed to in writing, software%0Adistributed under the License is distributed on an %22AS IS%22 BASIS,%0AWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0ASee the License for the specific language governing permissions and%0Alimitations under the License.%0A%22%22%22%0A%0Aimport unittest%0A%0Aimport mock%0Afrom ddt import ddt, data, unpack%0Afrom nose.tools import assert_equal%0A%0Afrom toolium.behave.environment import get_jira_key_from_scenario%0A%0Atags = (%0A (%5B%22jira('PROJECT-32')%22%5D, 'PROJECT-32'),%0A (%5B%22jira=PROJECT-32%22%5D, 'PROJECT-32'),%0A (%5B%22jira(PROJECT-32)%22%5D, 'PROJECT-32'),%0A (%5B%22jira='PROJECT-32'%22%5D, 'PROJECT-32'),%0A (%5B%22jiraPROJECT-32%22%5D, 'PROJECT-32'),%0A (%5B%22jira%22%5D, None),%0A (%5B%22PROJECT-32%22%5D, None),%0A (%5B'slow', %22jira('PROJECT-32')%22, 'critical'%5D, 'PROJECT-32'),%0A (%5B'slow', %22PROJECT-32%22, 'critical'%5D, None),%0A (%5B'slow', %22jira('PROJECT-32')%22, %22jira('PROJECT-33')%22%5D, 'PROJECT-32'),%0A)%0A%0A%0A@ddt%0Aclass EnvironmentTests(unittest.TestCase):%0A @data(*tags)%0A @unpack%0A def test_get_jira_key_from_scenario(self, tag_list, jira_key):%0A scenario = mock.Mock()%0A scenario.tags = tag_list%0A%0A # Extract Jira key and compare with expected key%0A assert_equal(jira_key, get_jira_key_from_scenario(scenario))%0A
|
|
032876577fa94e2d9ca668d6fe108d725696088b
|
add 20newsgroups/ml.py
|
20newsgroups/ml.py
|
20newsgroups/ml.py
|
Python
| 0
|
@@ -0,0 +1,1303 @@
+from __future__ import division, print_function, unicode_literals%0Aimport numpy%0Afrom sklearn.datasets import fetch_20newsgroups_vectorized%0Afrom sklearn.preprocessing import StandardScaler%0Afrom sklearn.naive_bayes import MultinomialNB%0Afrom sklearn.linear_model import SGDClassifier%0Afrom sklearn.svm import LinearSVC%0Afrom sklearn.grid_search import RandomizedSearchCV%0A%0Adef best_cv_num(n):%0A return int(1+numpy.log2(n))%0A%0Adef best_n_iter(n):%0A return numpy.ceil(10**6 / n)%0A%0Aif __name__ == '__main__':%0A d = fetch_20newsgroups_vectorized(%0A remove=('headers', 'footers', 'quotes'))%0A X = d.data%0A X = StandardScaler(with_mean=False).fit_transform(X)%0A #X = TruncatedSVD(n_components=400).fit_transform(X)%0A y = d.target%0A _n = X.shape%5B0%5D%0A%0A #clf = MultinomialNB()%0A #params = %7B%0A # 'alpha': numpy.linspace(0,0.1,1000)%0A #%7D%0A%0A # http://scikit-learn.org/stable/modules/sgd.html#tips-on-practical-use%0A #clf = SGDClassifier(n_iter=best_n_iter(_n))%0A #params = %7B%0A # 'alpha': 10**numpy.linspace(-7,-1)%0A #%7D%0A clf = LinearSVC()%0A params = %7B%0A 'C': 2**numpy.linspace(-3,3)%0A %7D%0A cv = RandomizedSearchCV(clf, params, n_iter=20, cv=best_cv_num(_n), n_jobs=-1, verbose=3)%0A cv.fit(X, y)%0A print(cv.best_score_)%0A print(cv.best_params_)%0A
|
|
63a0a0347272b2ae19f9caa5200aca5c03d67bab
|
add userselfinfo
|
api/user.py
|
api/user.py
|
Python
| 0
|
@@ -0,0 +1,1313 @@
+#coding:utf-8%0Afrom flask import Flask%0Afrom . import app, jsonrpc%0Aimport json%0Afrom auth import auth_login%0A%0A%0A@jsonrpc.method('user.getinfo')%0A@auth_login%0Adef userselfinfo(auth_info, **kwargs):%0A username = auth_info%5B'username'%5D%0A fields = %5B'id','username','name','email','mobile','is_lock','r_id'%5D%0A try:%0A user = app.config%5B'db'%5D.get_one_result('user', fields, where=%7B'username':username%7D)%0A if user.get('r_id', None):%0A r_id = user%5B'r_id'%5D.split(',')%0A rids = app.config%5B'db'%5D.get_results('role', %5B'id','name','p_id'%5D, where=%7B'id': r_id%7D)%0A else:%0A rids = %7B%7D%0A pids = %5B%5D%0A for x in rids:%0A pids += x%5B'p_id'%5D.split(',')%0A pids = list(set(pids)) #%E5%8E%BB%E9%87%8D%EF%BC%8C%E9%80%9A%E8%BF%87%E7%94%A8%E6%88%B7%E5%90%8D%E6%9F%A5%E5%88%B0%E8%A7%92%E8%89%B2id%EF%BC%8C%E5%86%8D%E9%80%9A%E8%BF%87%E8%A7%92%E8%89%B2id%E5%8F%96%E5%88%B0%E7%94%A8%E6%88%B7%E6%9D%83%E9%99%90id%0A user%5B'r_id'%5D = %5Bx%5B'name'%5D for x in rids%5D%0A%0A if pids: #%E5%B0%86%E7%94%A8%E6%88%B7%E5%88%B0%E6%9D%83%E9%99%90id%E8%BD%AC%E4%B8%BA%E6%9D%83%E9%99%90%E5%90%8D%0A mypids = app.config%5B'db'%5D.get_results('power', %5B'id', 'name', 'name_cn', 'url'%5D, where=%7B'id': pids%7D)%0A user%5B'p_id'%5D = dict(%5B(str(x%5B'name'%5D), dict(%5B(k, x%5Bk%5D) for k in ('name_cn','url')%5D)) for x in mypids%5D) #%E8%BF%94%E5%9B%9E%E6%A0%BC%E5%BC%8F%EF%BC%9A%7B'git':%7B'name_cn':'git','url':'http://git.com'%7D,......%7D%0A else:%0A user%5B'p_id'%5D = %7B%7D%0A%0A return json.dumps(%7B'code':0, 'user':user%7D)%0A except:%0A return json.dumps(%7B'code':1, 'errmsg':%22get userinfo failed%22%7D)%0A%0A%0A%0A%0A
|
|
c43000d2f9ec20a1c0cdbbec86270d88acb36104
|
Add implementation of more generic store calls
|
bench_examples/sparqlstore.py
|
bench_examples/sparqlstore.py
|
Python
| 0
|
@@ -0,0 +1,453 @@
+from ktbs_bench.graph_store import GraphStore%0Aimport rdflib%0A%0Ardflib.plugin.register('BN', rdflib.store.Store, 'ktbs_bench.bnsparqlstore', 'SPARQLUpdateStore')%0A%0A%0Adef get_sparqlstore(query_endpoint, update_endpoint, identifier=%22http://localhost/generic_sparqlstore/%22):%0A triple_store = GraphStore(store='BN', identifier=identifier,%0A connect_args=%7B'configuration': (query_endpoint, update_endpoint)%7D)%0A return triple_store%0A
|
|
a6c96caa1392868402be9f89db034ef664a12bda
|
Add open time range support.
|
utils.py
|
utils.py
|
Python
| 0
|
@@ -0,0 +1,1569 @@
+import datetime%0Aimport flask%0Aimport functools%0Afrom app import app%0A%0A# Use dateutil if available%0Atry:%0A from dateutil import parser as dateutil%0Aexcept ImportError:%0A dateutil = None%0A%0Aclass GameTime(object):%0A%0A @classmethod%0A def setup(cls):%0A %22%22%22Get start and end time.%22%22%22%0A cls.start, cls.end = app.config.get('GAME_TIME', (None, None))%0A if isinstance(cls.start, basestring):%0A cls.start = cls._parsedate(cls.start)%0A if isinstance(cls.end, basestring):%0A cls.end = cls._parsedate(cls.end)%0A%0A @classmethod%0A def countdown(cls, end=False):%0A %22%22%22Time remaining to start or end.%22%22%22%0A until = cls.end if end else cls.start%0A if until is None:%0A return None%0A return until - datetime.datetime.utcnow()%0A%0A @classmethod%0A def open(cls, after_end=False):%0A %22%22%22Is the game open? If after_end, keeps open.%22%22%22%0A now = datetime.datetime.utcnow()%0A if cls.start and cls.start %3E now:%0A return False%0A if after_end:%0A return True%0A if cls.end and cls.end %3C now:%0A return False%0A return True%0A%0A @classmethod%0A def require_open(cls, f, after_end=False):%0A @functools.wraps(f)%0A def wrapper(*args, **kwargs):%0A if cls.open(after_end):%0A return f(*args, **kwargs)%0A flask.abort(403)%0A return wrapper%0A%0A @staticmethod%0A def _parsedate(datestr):%0A if dateutil:%0A return dateutil.parse(datestr)%0A # TODO: parse with strptime%0A raise RuntimeError('No parser available.')%0A%0AGameTime.setup()%0Arequire_gametime = GameTime.require_open%0A%0A%0A@app.context_processor%0Adef util_contexts():%0A return dict(gametime=GameTime)%0A
|
|
70f48f8b72a49929ddba7908fd47175fd4c1685d
|
add yarn support (test failing)
|
autoload/thesaurus_query/backends/yarn_synsets_lookup.py
|
autoload/thesaurus_query/backends/yarn_synsets_lookup.py
|
Python
| 0
|
@@ -0,0 +1,1999 @@
+# Thesaurus Lookup routine for local synsets.csv file.%0A# Author: HE Chong %5B%5Bchong.he.1989@gmail.com%5D%5BE-mail%5D%5D%0A%0A'''%0ALookup routine for local mthesaur.txt file. When query_from_source is called, return:%0A %5Bstatus, %5B%5Bdef_0, %5Bsynonym_0, synonym_1, ...%5D%5D, %5Bdef_1, %5Bsynonym_0, synonym_1, ...%5D%5D, ...%5D%5D%0Astatus:%0A 0: normal, synonym found, list will be returned as%0A 1: normal, synonym not found, return empty synonym list%0A -1: unexpected result from query, return empty synonym list%0Asynonym list = %5Bdef, list wordlist%5D%0A def('str'): definition the synonyms belong to%0A wordlist = %5Bsynonym_0, synonym_1, ...%5D: list of words belonging to a same definition%0A'''%0A%0Aimport os%0Afrom ..tq_common_lib import decode_utf_8, get_variable%0A%0Aidentifier=%22yarn_synsets%22%0Alanguage=%22ru%22%0A%0Adef query(word):%0A _synsets_valid , _synsets_file = _synsets_file_locate()%0A if not _synsets_valid:%0A return %5B-1, %5B%5D%5D%0A match_found = 0%0A thesaur_file = open(os.path.expanduser(_synsets_file), 'r')%0A found_synList=%5B%5D%0A while True:%0A line_curr=decode_utf_8(thesaur_file.readline())%0A if not line_curr:%0A break%0A line_data = line_curr.rstrip().split(u',')%0A synonym_list = line_data%5B1%5D.split(u';')%0A if len(line_data):%0A grammar = %22%7B0%7D, %22.format(line_data%5B2%5D)%0A else:%0A grammar = %22%22%0A wordDomain = line_data%5B3%5D%0A if word in synonym_list:%0A synonym_list.remove(word)%0A else:%0A continue%0A if len(synonym_list):%0A found_synList.append(%5B%0A u%22%7B0%7D%7B1%7D%22.format(grammar, wordDomain), synonym_list%5D)%0A %0A return %5B0 if len(found_synList) else 1, found_synList%5D%0A%0Adef _synsets_file_locate():%0A verified_file = get_variable(%0A %22yarn_synsets_file%22,%0A %22~/.vim/thesaurus/yarn_synsets.csv%22)%0A if os.path.exists(os.path.expanduser(verified_file)):%0A return (True, verified_file)%0A%0A return (False, None)%0A%0A%0A# initiation ------------%0A_synsets_file_locate()%0A
|
|
b036acb164bc0efce18299341b04a7acf226c7db
|
solve pep_745
|
pe-solution/src/main/python/pep_745.py
|
pe-solution/src/main/python/pep_745.py
|
Python
| 0.999978
|
@@ -0,0 +1,820 @@
+from collections import defaultdict%0A%0Afrom math import sqrt%0A%0AMODULO = 1_000_000_007%0A%0A%0Adef g_naive(n: int) -%3E int:%0A %22%22%22maximum perfect square that divides n.%22%22%22%0A upper = int(sqrt(n))%0A for i in range(0, upper):%0A sq = (upper - i) ** 2%0A if n %25 sq == 0:%0A return sq %25 MODULO%0A%0A%0Adef s_naive(nn: int) -%3E int:%0A return sum(%5Bg_naive(n) for n in range(1, nn + 1)%5D) %25 MODULO%0A%0A%0Adef solve(n: int) -%3E int:%0A upper = int(sqrt(n))%0A t = defaultdict(int)%0A for i in range(upper, 0, -1):%0A t%5Bi%5D = n // (i * i) - sum(%5Bt%5Bi * j%5D for j in range(2, upper // i + 1)%5D)%0A return (sum(%5Bi * i * v for i, v in t.items()%5D)) %25 MODULO%0A%0A%0Aif __name__ == %22__main__%22:%0A assert g_naive(18) == 9%0A assert g_naive(19) == 1%0A%0A assert solve(10) == 24%0A assert solve(100) == 767%0A%0A print(solve(10 ** 14))%0A
|
|
a59d07a5bfb9f32c37242fd8ffb06d0409896485
|
add a welch periodogram tool
|
welch.py
|
welch.py
|
Python
| 0
|
@@ -0,0 +1,1444 @@
+#!/bin/env python%0A%0Aimport numpy as np%0Aimport scipy.signal as ss%0Aimport astropy.io.fits as fits%0Aimport matplotlib.pyplot as plt%0A%0A%0Ainpt = str(raw_input(%22Nome do Arquivo: %22))%0Alc = fits.open(inpt)%0Abin = float(raw_input(%22bin size (or camera resolution): %22))%0A%0A# Convert to big-endian array is necessary to the lombscargle function%0Arate = np.array(lc%5B1%5D.data%5B%22RATE%22%5D, dtype='float64')%0Atime = np.array(lc%5B1%5D.data%5B%22TIME%22%5D, dtype='float64')%0Atime -= time.min()%0A%0A# Exclue NaN values -------------------------%0Aprint ''%0Aprint 'Excluding nan and negative values...'%0Aprint ''%0A%0Aexclude = %5B%5D%0Afor i in xrange(len(rate)):%0A if rate%5Bi%5D %3E 0:%0A pass%0A else:%0A exclude.append(i)%0A%0Aexclude = np.array(exclude)%0Anrate = np.delete(rate, exclude)%0Antime = np.delete(time, exclude)%0A# --------------------------------------------%0A%0A# normalize count rate%0Anrate -= nrate.mean()%0A%0A# maximum frequecy limited by resolution%0Afreqmax = 1.0/bin%0A%0A# Ther periodogram itself%0Af, p = ss.welch(nrate, fs=freqmax, nperseg=len(nrate), nfft=10*len(nrate))%0A%0A# Plot lightcurve on top panel%0Aplt.subplot(2, 1, 1)%0Aplt.plot(ntime, nrate, 'bo-')%0Aplt.xlabel('Time %5Bs%5D', fontsize=12)%0Aplt.ylabel('Normalized Count Rate %5Bcounts/s%5D', fontsize=12)%0A%0A# Plot powerspectrum on bottom panel%0Aplt.subplot(2, 1, 2)%0Aplt.plot(f, p, 'b.-', label='f = %7B0%7D'.format(f%5Bnp.argmax(p)%5D))%0Aplt.xlabel('Frequency %5BHz%5D', fontsize=12)%0Aplt.ylabel('Power', fontsize=12)%0Aplt.legend(loc='best')%0A%0A# show plot%0Aplt.show()%0A
|
|
f204c881aabb07dbe6f04008e0637dc4430ae8c8
|
Add jon submission for problem 01
|
problem-01/submissions/jon.py
|
problem-01/submissions/jon.py
|
Python
| 0
|
@@ -0,0 +1,2527 @@
+from submission import Submission%0Aimport collections%0Aimport random%0A%0Aclass JonSubmission(Submission):%0A%0A def author(self):%0A return 'jon'%0A%0A def run(self, input):%0A%0A class Traveler(object):%0A%0A def __init__(self, graph, start_point):%0A if start_point not in graph:%0A raise Exception(%22Start point not in the graph%22)%0A self._graph = graph%0A self._current = start_point%0A self._history = %5Bstart_point%5D%0A%0A def possibilities(self):%0A return self._graph%5Bself._current%5D%0A%0A def goto(self, position):%0A if position in self.possibilities():%0A self._current = position%0A self._history.append(position)%0A else:%0A raise Exception(%22Not possible, try again.%22)%0A%0A def current(self):%0A return self._current%0A%0A def step_count(self):%0A return len(self._history) - 1%0A%0A def travel_path(self):%0A return list(self._history)%0A%0A class ShuffledTraveler(Traveler):%0A%0A def __init__(self, graph, start_point):%0A super().__init__(graph, start_point)%0A%0A def possibilities(self):%0A l = super().possibilities()%5B:%5D%0A random.shuffle(l)%0A return l%0A%0A def connected_component_using_shorter_dfs(traveler):%0A visited = %7Btraveler.current()%7D%0A found = set(traveler.possibilities())%0A found.add(traveler.current())%0A path = %5B%5D # Path to the starting point%0A while len(visited) %3C len(found):%0A new_found = False%0A for node in traveler.possibilities():%0A # Ignore already visited nodes to avoid loops !%0A if node not in visited:%0A path.append(traveler.current())%0A traveler.goto(node)%0A new_found = True%0A break%0A if not new_found:%0A if len(path) %3E 0:%0A traveler.goto(path.pop())%0A else:%0A break%0A visited.add(traveler.current())%0A found.update(traveler.possibilities())%0A return visited%0A%0A graph, start = input%0A traveler = ShuffledTraveler(graph, start)%0A connected_component_using_shorter_dfs(traveler)%0A return traveler.travel_path()%0A
|
|
9999c27f5a6121d8488c14dd4a2b9843eef9cec9
|
Add merge migration
|
events/migrations/0030_merge.py
|
events/migrations/0030_merge.py
|
Python
| 0.000001
|
@@ -0,0 +1,346 @@
+# -*- coding: utf-8 -*-%0A# Generated by Django 1.9.10 on 2016-09-27 09:05%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('events', '0029_make_api_key_non_nullable'),%0A ('events', '0028_add_photographer_name'),%0A %5D%0A%0A operations = %5B%0A %5D%0A
|
|
aa0e10116580ab013e911c2b14cf216a19716abd
|
Add schedule to static renderers
|
wafer/schedule/renderers.py
|
wafer/schedule/renderers.py
|
Python
| 0
|
@@ -0,0 +1,214 @@
+from django_medusa.renderers import StaticSiteRenderer%0A%0A%0Aclass ScheduleRenderer(StaticSiteRenderer):%0A def get_paths(self):%0A paths = %5B%22/schedule/%22, %5D%0A return paths%0A%0Arenderers = %5BScheduleRenderer, %5D%0A
|
|
51d3dee22c3c563b486038edcd9f18fa02b46448
|
Add new admin views to show how to use RBAC system
|
project/admin/views.py
|
project/admin/views.py
|
Python
| 0
|
@@ -0,0 +1,1297 @@
+from werkzeug.exceptions import HTTPException%0Afrom flask import Response, redirect%0Afrom flask_admin import BaseView, expose%0Afrom flask_admin.contrib.sqla import ModelView as DefaultModelView%0Afrom flask_login import login_required%0Afrom project.home.decorators import roles_required%0A%0A%0Aclass BasicAuthException(HTTPException):%0A def __init__(self, message):%0A super().__init__(message, Response(%0A %22You could not be authenticated. Please refresh the page.%22, 401,%0A %7B'WWW-Authenticate': 'Basic realm=%22Login Required%22'%7D%0A ))%0A%0A%0Aclass ModelView(DefaultModelView):%0A%0A column_auto_select_related = True%0A%0A def __init__(self, model, session, basic_auth, *args, **kwargs):%0A super(ModelView, self).__init__(model, session, *args, **kwargs)%0A self.basic_auth = basic_auth%0A%0A def is_accessible(self):%0A if not self.basic_auth.authenticate():%0A raise BasicAuthException('Not authenticated.')%0A else:%0A return True%0A%0A def inaccessible_callback(self, name, **kwargs):%0A return redirect(self.basic_auth.challenge())%0A%0A%0Aclass SuperSecretPage(BaseView):%0A%0A @expose(url=%22/%22, methods=(%22GET%22, ))%0A @login_required%0A @roles_required('admin')%0A def secret(self):%0A return self.render('admin/super-secret-page.html')%0A
|
|
68babe2de9a8204c46ad23e1c82dd0ff8fe44c94
|
Add a unittest on plot_figs module.
|
pyarm/tests/test_plot_figs.py
|
pyarm/tests/test_plot_figs.py
|
Python
| 0
|
@@ -0,0 +1,1350 @@
+#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A%0A# Copyright (c) 2010 J%C3%A9r%C3%A9mie DECOCK (http://www.jdhp.org)%0A%0Aimport unittest%0Aimport os%0Aimport sys%0A%0Adirname = os.path.dirname(__file__)%0Aif dirname == '':%0A dirname = '.'%0A%0Adirname = os.path.realpath(dirname)%0Aupdir = os.path.split(dirname)%5B0%5D%0Aif updir not in sys.path:%0A sys.path.append(updir)%0A%0A###%0A%0Aimport plot_figs%0A%0Aclass PlotFigsTest(unittest.TestCase):%0A%0A def setUp(self):%0A pass%0A%0A def test_main(self):%0A try:%0A plot_figs.main()%0A except:%0A self.fail()%0A%0A def tearDown(self):%0A # Remove files%0A files = (%22arm_Kambara_c_forearm.png%22, %22muscle_Kambara_k.png%22,%0A %22muscle_Kambara_lr.png%22, %22muscle_Li_fa.png%22,%0A %22muscle_Li_fl.png%22, %22muscle_Li_nf.png%22,%0A %22muscle_Mitrovic_lm.png%22, %22muscle_Mitrovic_v.png%22,%0A %22arm_Mitrovic_c_forearm.png%22, %22muscle_Kambara_lm.png%22,%0A %22muscle_Kambara_v.png%22, %22muscle_Li_fe.png%22,%0A %22muscle_Li_fv.png%22, %22muscle_Mitrovic_k.png%22,%0A %22muscle_Mitrovic_lr.png%22)%0A try:%0A map(os.remove, files)%0A except:%0A pass%0A%0A###%0A%0Adef test_suite():%0A tests = %5Bunittest.makeSuite(PlotFigsTest)%5D%0A return unittest.TestSuite(tests)%0A%0Aif __name__ == '__main__':%0A unittest.main(defaultTest='test_suite')%0A%0A
|
|
f34fb2b060c7fd977ca50753c8c1c9d5beaf0516
|
return index at which acf drops below thresh
|
agent_model/acfanalyze.py
|
agent_model/acfanalyze.py
|
Python
| 0
|
@@ -0,0 +1,1920 @@
+__author__ = 'richard'%0A%0Aimport os%0Aimport numpy as np%0Aimport pandas as pd%0Afrom glob import glob%0Aimport statsmodels.tsa%0Aimport statsmodels.graphics.tsaplots%0Aimport matplotlib.pyplot as plt%0A%0Aplt.style.use('ggplot')%0A%0ATRAJECTORY_DATA_DIR = %22experimental_data/control_trajectories/%22%0A%0Adef make_csv_name_list():%0A # TODO export this to io%0A %0A print %22Loading + filtering CSV files from %22, TRAJECTORY_DATA_DIR%0A os.chdir(TRAJECTORY_DATA_DIR)%0A csv_list = sorted(%5Bos.path.splitext(file)%5B0%5D for file in glob(%22*.csv%22)%5D)%0A os.chdir(os.path.dirname(__file__)) # go back to old dir%0A%0A return csv_list%0A%0Adef load_trajectory_dynamics_csv(data_fname):%0A file_path = os.path.join(os.getcwd(), TRAJECTORY_DATA_DIR, data_fname + %22.csv%22)%0A%0A col_labels = %5B%0A 'pos_x',%0A 'pos_y',%0A 'pos_z',%0A 'velo_x',%0A 'velo_y',%0A 'velo_z',%0A 'accel_x',%0A 'accel_y',%0A 'accel_z',%0A 'heading_angle',%0A 'angular_velo_xy',%0A 'angular_velo_yz',%0A 'curvature'%0A %5D%0A%0A dyn_trajectory_DF = pd.read_csv(file_path, na_values=%22NaN%22, names=col_labels) # recognize string as NaN%0A dyn_trajectory_DF.fillna(value=0, inplace=True)%0A%0A%0A return dyn_trajectory_DF%0A%0A%0Adef arg_less(inarray,threshold):%0A filtered = np.nonzero(inarray%3Cthreshold)%0A return np.nonzero(inarray%3Cthreshold)%5B0%5D%5B0%5D # return index of first item that is under thresh%0A%0A%0Acsv_list = make_csv_name_list()%0A%0Afor csv_name in csv_list:%0A df = load_trajectory_dynamics_csv(csv_name)%0A print csv_name, 'size/timesteps = ', df.size%0A%0A if not os.path.exists('./correlation_figs/%7Bdata_name%7D'.format(data_name = csv_name)):%0A os.makedirs('./correlation_figs/%7Bdata_name%7D'.format(data_name = csv_name))%0A%0A for label, col in df.iteritems():%0A if label in %5B'velo_x', 'velo_y', 'velo_z'%5D:%0A acf = statsmodels.tsa.stattools.acf(col, nlags = 70)%0A print label, arg_less(acf, .5)
|
|
e3b5f7b0f47b1e7ad4ab024c76a270ba9e88aa02
|
add impala sqlalchemy resource function
|
blaze/sql.py
|
blaze/sql.py
|
from __future__ import absolute_import, division, print_function
from .compute.sql import select
from .data.sql import SQL, dispatch, first
from .expr import Expr, TableExpr, Projection, Column, UnaryOp
from .expr.scalar.core import Scalar
from .compatibility import basestring
from .api.resource import resource
import sqlalchemy as sa
__all__ = ['compute_up', 'SQL']
@dispatch((Column, Projection, Expr, UnaryOp), SQL)
def compute_up(t, ddesc, **kwargs):
return compute_up(t, ddesc.table, **kwargs)
@dispatch(Expr, sa.sql.ClauseElement, dict)
def post_compute(expr, query, d):
""" Execute SQLAlchemy query against SQLAlchemy engines
If the result of compute is a SQLAlchemy query then it is likely that the
data elements are themselves SQL objects which contain SQLAlchemy engines.
We find these engines and, if they are all the same, run the query against
these engines and return the result.
"""
if not all(isinstance(val, SQL) for val in d.values()):
return query
engines = set([dd.engine for dd in d.values()])
if len(set(map(str, engines))) != 1:
raise NotImplementedError("Expected single SQLAlchemy engine")
engine = first(engines)
with engine.connect() as conn: # Perform query
result = conn.execute(select(query)).fetchall()
if isinstance(expr, Scalar):
return result[0][0]
if isinstance(expr, TableExpr) and expr.iscolumn:
return [x[0] for x in result]
return result
@dispatch(SQL)
def drop(s):
s.table.drop(s.engine)
@dispatch(SQL, basestring)
def create_index(s, column, name=None, unique=False):
if name is None:
raise ValueError('SQL indexes must have a name')
sa.Index(name, getattr(s.table.c, column), unique=unique).create(s.engine)
@dispatch(SQL, list)
def create_index(s, columns, name=None, unique=False):
if name is None:
raise ValueError('SQL indexes must have a name')
args = name,
args += tuple(getattr(s.table.c, column) for column in columns)
sa.Index(*args, unique=unique).create(s.engine)
@resource.register('(sqlite|postgresql|mysql)://.*')
def resource_sql(uri, table_name, *args, **kwargs):
return SQL(uri, table_name, *args, **kwargs)
|
Python
| 0.000002
|
@@ -2220,20 +2220,186 @@
e, *args, **kwargs)%0A
+%0A%0A@resource.register('impala://.*')%0Adef resource_sql(uri, table_name, *args, **kwargs):%0A import impala.sqlalchemy%0A return SQL(uri, table_name, *args, **kwargs)%0A
|
d952776a78901ecd20cb8e79cd00f5498e4b04be
|
Add generate anagrams
|
algo/generate_anagrams.py
|
algo/generate_anagrams.py
|
Python
| 0.999999
|
@@ -0,0 +1,159 @@
+import sys%0Aimport shuffle from random%0A%0Aword = list(sys.argv%5B1%5D)%0Aanagrams = %5B%5D%0A%0Afor i in range(10):%0A anagrams.append(''.join(shuffle(word)))%0A%0Aprint anagrams%0A
|
|
4d021acd89abc127d50e6bf82064bd7aac2bca1a
|
Solve compree the string with groupby
|
python/compress-the-string.py
|
python/compress-the-string.py
|
Python
| 0.999999
|
@@ -0,0 +1,145 @@
+from itertools import groupby%0A%0Astring = input()%0A%0Aprint(%22 %22.join(%5B%22(%7B%7D, %7B%7D)%22.format(len(list(group)), char) for char, group in groupby(string)%5D))%0A
|
|
cf3a1c26ab650ad2a87d4b4dcc6754c70abde802
|
Create compat.py
|
backend/compat.py
|
backend/compat.py
|
Python
| 0.000001
|
@@ -0,0 +1 @@
+%0A
|
|
f11ce837f0200d501c34c8fa7b2f5cfd149c18b6
|
Add db migrations
|
SMSFlyCRM/SMSApp/migrations/0002_auto_20160602_2034.py
|
SMSFlyCRM/SMSApp/migrations/0002_auto_20160602_2034.py
|
Python
| 0
|
@@ -0,0 +1,961 @@
+# -*- coding: utf-8 -*-%0A# Generated by Django 1.9.6 on 2016-06-02 20:34%0Afrom __future__ import unicode_literals%0A%0Aimport datetime%0Afrom django.db import migrations, models%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('SMSApp', '0001_initial'),%0A %5D%0A%0A operations = %5B%0A migrations.RemoveField(%0A model_name='task',%0A name='start_date',%0A ),%0A migrations.AddField(%0A model_name='task',%0A name='start_datetime',%0A field=models.DateTimeField(default=datetime.datetime.now),%0A ),%0A migrations.AlterField(%0A model_name='alphaname',%0A name='status',%0A field=models.IntegerField(choices=%5B(0, 'ACTIVE'), (1, 'BLOCKED'), (2, 'MODERATE'), (3, 'LIMITED')%5D, null=True),%0A ),%0A migrations.AlterField(%0A model_name='task',%0A name='end_date',%0A field=models.DateField(null=True),%0A ),%0A %5D%0A
|
|
86657d78f220345391dc764db22cd9f02903f3a9
|
Add tests
|
bluebottle/initiatives/tests/test_admin.py
|
bluebottle/initiatives/tests/test_admin.py
|
Python
| 0.000001
|
@@ -0,0 +1,1953 @@
+# -*- coding: utf-8 -*-%0A%0Afrom django.contrib.admin.sites import AdminSite%0Afrom django.urls.base import reverse%0A%0Afrom bluebottle.initiatives.admin import InitiativeAdmin%0Afrom bluebottle.initiatives.models import Initiative%0Afrom bluebottle.initiatives.tests.factories import InitiativeFactory%0Afrom bluebottle.test.utils import BluebottleAdminTestCase%0A%0A%0Aclass TestInitiativeAdmin(BluebottleAdminTestCase):%0A def setUp(self):%0A super(TestInitiativeAdmin, self).setUp()%0A self.site = AdminSite()%0A self.initiative_admin = InitiativeAdmin(Initiative, self.site)%0A self.initiative = InitiativeFactory.create()%0A self.initiative.submit()%0A self.initiative.save()%0A%0A def test_review_initiative(self):%0A self.client.force_login(self.superuser)%0A review_url = reverse('admin:initiatives_initiative_transition',%0A args=(self.initiative.id, 'accept'))%0A response = self.client.get(review_url)%0A%0A # Should show confirmation page%0A self.assertEqual(response.status_code, 200)%0A self.assertContains(response, 'Are you sure you want to change')%0A%0A # Confirm should change status%0A response = self.client.post(review_url, %7B'confirm': True%7D)%0A self.assertEqual(response.status_code, 302, 'Should redirect back to initiative change')%0A self.initiative = Initiative.objects.get(pk=self.initiative.id)%0A self.assertEqual(self.initiative.review_status, 'accepted')%0A%0A def test_review_initiative_unauthorized(self):%0A review_url = reverse('admin:initiatives_initiative_transition',%0A args=(self.initiative.id, 'accept'))%0A response = self.client.post(review_url, %7B'confirm': False%7D)%0A # Should be denied%0A self.assertEqual(response.status_code, 403)%0A self.initiative = Initiative.objects.get(pk=self.initiative.id)%0A self.assertEqual(self.initiative.review_status, 'submitted')%0A
|
|
a383d1220c31f153a5519e4aab4703db2b71ef53
|
Add initial version of season goal leader retrieval
|
analysis/_goal_leaders.py
|
analysis/_goal_leaders.py
|
Python
| 0
|
@@ -0,0 +1,1478 @@
+#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A%0Aimport requests%0Afrom lxml import html%0A%0A%0ASEASON_URL_TEMPLATE = %22http://www.hockey-reference.com/leagues/NHL_%25d.html%22%0ACAREER_GOAL_LEADERS_URL = %22http://www.hockey-reference.com/leaders/goals_career.html%22%0A%0A%0Aseason_goal_leaders = set()%0A%0Afor year in range(1918, 2017)%5B:0%5D:%0A%0A # skipping season completely lost to a lockout%0A if year == 2005:%0A continue%0A%0A season = %22%25d-%25s%22 %25 (year - 1, str(year)%5B-2:%5D)%0A%0A # retrieving raw html data and parsing it%0A url = SEASON_URL_TEMPLATE %25 year%0A r = requests.get(url)%0A doc = html.fromstring(r.text)%0A%0A # the stuff we're interested in is hidden in comments%0A comments = doc.xpath(%22//comment()%22)%0A%0A for comment in comments:%0A # removing comment markup%0A sub = html.fromstring(str(comment)%5B3:-3%5D)%0A if not sub.xpath(%22//table/caption/text()%22):%0A continue%0A if sub.xpath(%22//table/caption/text()%22)%5B0%5D == %22Goals%22:%0A leaders = sub%0A break%0A%0A # retrieving five best goalscorers in current season as list%0A five_goal_leaders = leaders.xpath(%0A %22//div%5B@id='leaders_goals'%5D/table/tr/td%5B@class='who'%5D/a%22)%0A # adding name and link to player page to goalscorer dictionary%0A for leader in five_goal_leaders:%0A season_goal_leaders.add(%0A (leader.xpath(%22@href%22)%5B0%5D, leader.xpath(%22text()%22)%5B0%5D))%0A%0Ar = requests.get(CAREER_GOAL_LEADERS_URL)%0Adoc = html.fromstring(r.text)%0A%0A%0A%0Aprint(sorted(season_goal_leaders))%0A
|
|
10ce581d1ecbba29913982a56f32c3d93a1b54fe
|
Add Python benchmark
|
lib/node_modules/@stdlib/math/base/special/gamma/benchmark/python/benchmark.py
|
lib/node_modules/@stdlib/math/base/special/gamma/benchmark/python/benchmark.py
|
Python
| 0.000138
|
@@ -0,0 +1,1558 @@
+#!/usr/bin/env python%0A%22%22%22Benchmark gamma.%22%22%22%0A%0Afrom __future__ import print_function%0Aimport timeit%0A%0ANAME = %22gamma%22%0AREPEATS = 3%0AITERATIONS = 1000000%0A%0A%0Adef print_version():%0A %22%22%22Print the TAP version.%22%22%22%0A print(%22TAP version 13%22)%0A%0A%0Adef print_summary(total, passing):%0A %22%22%22Print the benchmark summary.%0A%0A # Arguments%0A%0A * %60total%60: total number of tests%0A * %60passing%60: number of passing tests%0A%0A %22%22%22%0A print(%22#%22)%0A print(%221..%22 + str(total)) # TAP plan%0A print(%22# total %22 + str(total))%0A print(%22# pass %22 + str(passing))%0A print(%22#%22)%0A print(%22# ok%22)%0A%0A%0Adef print_results(elapsed):%0A %22%22%22Print benchmark results.%0A%0A # Arguments%0A%0A * %60elapsed%60: elapsed time (in seconds)%0A%0A # Examples%0A%0A %60%60%60 python%0A python%3E print_results(0.131009101868)%0A %60%60%60%0A %22%22%22%0A rate = ITERATIONS / elapsed%0A%0A print(%22 ---%22)%0A print(%22 iterations: %22 + str(ITERATIONS))%0A print(%22 elapsed: %22 + str(elapsed))%0A print(%22 rate: %22 + str(rate))%0A print(%22 ...%22)%0A%0A%0Adef benchmark():%0A %22%22%22Run the benchmark and print benchmark results.%22%22%22%0A setup = %22from math import gamma; from random import random;%22%0A stmt = %22y = gamma(171.0*random() - 0.0)%22%0A%0A t = timeit.Timer(stmt, setup=setup)%0A%0A print_version()%0A%0A for i in xrange(REPEATS):%0A print(%22# python::%22 + NAME)%0A elapsed = t.timeit(number=ITERATIONS)%0A print_results(elapsed)%0A print(%22ok %22 + str(i+1) + %22 benchmark finished%22)%0A%0A print_summary(REPEATS, REPEATS)%0A%0A%0Adef main():%0A %22%22%22Run the benchmark.%22%22%22%0A benchmark()%0A%0A%0Aif __name__ == %22__main__%22:%0A main()%0A
|
|
66328709459b2217b3c964848a363c4f3b1cdf5e
|
Add Python benchmark
|
lib/node_modules/@stdlib/math/base/special/trunc/benchmark/python/benchmark.py
|
lib/node_modules/@stdlib/math/base/special/trunc/benchmark/python/benchmark.py
|
Python
| 0.000138
|
@@ -0,0 +1,1561 @@
+#!/usr/bin/env python%0A%22%22%22Benchmark trunc.%22%22%22%0A%0Afrom __future__ import print_function%0Aimport timeit%0A%0ANAME = %22trunc%22%0AREPEATS = 3%0AITERATIONS = 1000000%0A%0A%0Adef print_version():%0A %22%22%22Print the TAP version.%22%22%22%0A print(%22TAP version 13%22)%0A%0A%0Adef print_summary(total, passing):%0A %22%22%22Print the benchmark summary.%0A%0A # Arguments%0A%0A * %60total%60: total number of tests%0A * %60passing%60: number of passing tests%0A%0A %22%22%22%0A print(%22#%22)%0A print(%221..%22 + str(total)) # TAP plan%0A print(%22# total %22 + str(total))%0A print(%22# pass %22 + str(passing))%0A print(%22#%22)%0A print(%22# ok%22)%0A%0A%0Adef print_results(elapsed):%0A %22%22%22Print benchmark results.%0A%0A # Arguments%0A%0A * %60elapsed%60: elapsed time (in seconds)%0A%0A # Examples%0A%0A %60%60%60 python%0A python%3E print_results(0.131009101868)%0A %60%60%60%0A %22%22%22%0A rate = ITERATIONS / elapsed%0A%0A print(%22 ---%22)%0A print(%22 iterations: %22 + str(ITERATIONS))%0A print(%22 elapsed: %22 + str(elapsed))%0A print(%22 rate: %22 + str(rate))%0A print(%22 ...%22)%0A%0A%0Adef benchmark():%0A %22%22%22Run the benchmark and print benchmark results.%22%22%22%0A setup = %22from math import trunc; from random import random;%22%0A stmt = %22y = trunc(1000.0*random() - 500.0)%22%0A%0A t = timeit.Timer(stmt, setup=setup)%0A%0A print_version()%0A%0A for i in xrange(REPEATS):%0A print(%22# python::%22 + NAME)%0A elapsed = t.timeit(number=ITERATIONS)%0A print_results(elapsed)%0A print(%22ok %22 + str(i+1) + %22 benchmark finished%22)%0A%0A print_summary(REPEATS, REPEATS)%0A%0A%0Adef main():%0A %22%22%22Run the benchmark.%22%22%22%0A benchmark()%0A%0A%0Aif __name__ == %22__main__%22:%0A main()%0A
|
|
37b175b6a6ac3f0fd7fdaa5c2ed6435c159a29c2
|
Add py solution for 553. Optimal Division
|
py/optimal-division.py
|
py/optimal-division.py
|
Python
| 0.000072
|
@@ -0,0 +1,1611 @@
+from fractions import Fraction%0Aclass Solution(object):%0A def optimalDivision(self, nums):%0A %22%22%22%0A :type nums: List%5Bint%5D%0A :rtype: str%0A %22%22%22%0A min_result, max_result = dict(), dict()%0A min_offset, max_offset = dict(), dict()%0A lnums = len(nums)%0A def print_ans(start, end, need_max=True):%0A if start + 1 == end:%0A return str(nums%5Bstart%5D)%0A%0A if need_max:%0A cut = max_offset%5Bstart, end%5D%0A else:%0A cut = min_offset%5Bstart, end%5D%0A ans = print_ans(start, cut, need_max) + %22/%22%0A if end - cut %3E 1:%0A ans += %22(%22%0A ans += print_ans(cut, end, not need_max)%0A if end - cut %3E 1:%0A ans += %22)%22%0A return ans%0A%0A for i, n in enumerate(nums):%0A min_result%5Bi, i + 1%5D = max_result%5Bi, i + 1%5D = Fraction(n)%0A%0A for l in xrange(2, lnums + 1):%0A for i in xrange(lnums - l + 1):%0A m, M = None, None%0A mj, Mj = None, None%0A for j in xrange(1, l):%0A tm = min_result%5Bi, i + j%5D / max_result%5Bi + j, i + l%5D%0A tM = max_result%5Bi, i + j%5D / min_result%5Bi + j, i + l%5D%0A if m is None or m %3E tm:%0A m, mj = tm, i + j%0A if M is None or M %3C tM:%0A M, Mj = tM, i + j%0A min_result%5Bi, i + l%5D = m%0A max_result%5Bi, i + l%5D = M%0A min_offset%5Bi, i + l%5D = mj%0A max_offset%5Bi, i + l%5D = Mj%0A return print_ans(0, lnums)%0A
|
|
e14c4f1aeb15491ecbf2981527e2409ab3e82653
|
Test for BuildQuerySet.concurrent logic
|
readthedocs/builds/tests/test_build_queryset.py
|
readthedocs/builds/tests/test_build_queryset.py
|
Python
| 0
|
@@ -0,0 +1,2353 @@
+import pytest%0A%0Aimport django_dynamic_fixture as fixture%0Afrom django.conf import settings%0A%0Afrom readthedocs.builds.querysets import BuildQuerySet%0Afrom readthedocs.builds.models import Build, Version%0Afrom readthedocs.projects.models import Project, Feature%0A%0A%0A@pytest.mark.django_db%0Aclass TestBuildQuerySet:%0A%0A def test_concurrent_builds(self):%0A project = fixture.get(%0A Project,%0A max_concurrent_builds=None,%0A main_language_project=None,%0A )%0A for state in ('triggered', 'building', 'cloning', 'finished'):%0A fixture.get(%0A Build,%0A project=project,%0A state=state,%0A )%0A assert (False, 2, 4) == Build.objects.concurrent(project)%0A for state in ('building', 'cloning'):%0A fixture.get(%0A Build,%0A project=project,%0A state=state,%0A )%0A assert (True, 4, 4) == Build.objects.concurrent(project)%0A%0A def test_concurrent_builds_project_limited(self):%0A project = fixture.get(%0A Project,%0A max_concurrent_builds=2,%0A main_language_project=None,%0A )%0A for state in ('triggered', 'building', 'cloning', 'finished'):%0A fixture.get(%0A Build,%0A project=project,%0A state=state,%0A )%0A assert (True, 2, 2) == Build.objects.concurrent(project)%0A%0A def test_concurrent_builds_translations(self):%0A project = fixture.get(%0A Project,%0A max_concurrent_builds=None,%0A main_language_project=None,%0A )%0A translation = fixture.get(%0A Project,%0A max_concurrent_builds=None,%0A main_language_project=project,%0A )%0A for state in ('triggered', 'building', 'cloning', 'finished'):%0A fixture.get(%0A Build,%0A project=project,%0A state=state,%0A )%0A assert (False, 2, 4) == Build.objects.concurrent(translation)%0A%0A for state in ('building', 'cloning'):%0A fixture.get(%0A Build,%0A project=translation,%0A state=state,%0A )%0A assert (True, 4, 4) == Build.objects.concurrent(translation)%0A assert (True, 4, 4) == Build.objects.concurrent(project)%0A
|
|
4c428b78f9bf4d5f044a23921a6f29df34c93753
|
add python process pool example
|
python/process_pool.py
|
python/process_pool.py
|
Python
| 0.000001
|
@@ -0,0 +1,189 @@
+#!/usr/bin/env python3%0A# -*- coding: utf-8 -*-%0A%0Afrom multiprocessing import Pool%0A%0Adef worker(a):%0A print(a)%0A%0Aif __name__ == %22__main__%22:%0A p = Pool(10)%0A p.map(worker, range(0, 1000))%0A
|
|
f75bb5319884e9ce9fa36326b1dbd686aeb6add1
|
use loc='best'
|
crystal/plot.py
|
crystal/plot.py
|
"""Plotting functions for Clusters."""
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
def logit(a): return np.log(a / (1 - a))
def ilogit(m): return 1.0 / (1 + np.exp(-m))
sns.set(style="white", context="talk")
colors = sns.color_palette("Set1", 8)
def _plot_continuous(feature, var, ax):
ax.scatter(ilogit(feature.values), var, s=(2 if len(var) > 40 else 4),
c=colors[0])
def _plot_dichotomous(feature, var, ax, normed=False):
var = np.asarray(var)
cats = np.unique(var)
cats.sort()
xvals = []
for i, cat in enumerate(cats):
vals = ilogit(feature.values[var == cat])
xvals.append(vals)
ax.hist(xvals, alpha=0.8, color=colors[:len(cats)], label=list(cats), normed=normed)
def is_dichotomous(col):
dichotomous = not np.issubdtype(col, float) or len(col.unique()) == 2
return dichotomous
def plot_cluster(cluster, covs, normed=False):
"""
Plot a cluster (output from `crystal.model_cluster`)
Plot will vary depending on if cluster['var'] is dichotomous
or continuous.
"""
dichotomous = is_dichotomous(covs[cluster['var']])
fig, axs = plt.subplots(cluster['n_sites'], sharey=not dichotomous)
for i, f in enumerate(cluster['cluster']):
ax = axs[i]
ax.set_xlim(0, 1)
ax.set_xticklabels([])
ax.locator_params(tight=True, nbins=4)
#ax.set_yticks(np.arange(0, 1.001, 0.25))
ax.set_title(f.spos)
if dichotomous:
_plot_dichotomous(f, covs[cluster['var']], ax, normed=normed)
else:
_plot_continuous(f, covs[cluster['var']], ax)
ax.set_ylabel(cluster['var'])
ax.set_xticks(np.arange(0, 1.001, 0.25))
ax.set_xticklabels(np.arange(0, 1.001, 0.25))
if dichotomous:
axs[0].legend()
return fig, axs
def barplot_cluster(cluster, covs, normed=False, n_bins=50):
# this only works for 2-class data.
group = np.array(covs[cluster['var']])
grps = sorted(np.unique(group))
assert len(grps) == 2
fig, ax = plt.subplots(1)
# get min and max for all features so we can use same scale.
dmin = ilogit(min(f.values.min() for f in cluster['cluster']))
dmax = ilogit(max(f.values.max() for f in cluster['cluster']))
for i, feature in enumerate(cluster['cluster']):
g0 = ilogit(feature.values[group == grps[0]])
g1 = ilogit(feature.values[group == grps[1]])
shape0 = half_horizontal_bar(g0, i , ax, True,
dmin=dmin, dmax=dmax, edgecolor='0.4',
facecolor=colors[0], n_bins=n_bins)
shape1 = half_horizontal_bar(g1, i, ax, False,
dmin=dmin, dmax=dmax, edgecolor='0.4',
facecolor=colors[1], n_bins=n_bins)
ax.set_xticks(range(len(cluster['cluster'])))
ax.set_xticklabels([f.position for f in cluster['cluster']])
l = ax.legend((shape0, shape1),
("%s - %s" % (cluster['var'], grps[0]),
("%s - %s" % (cluster['var'], grps[1]))), fancybox=True, loc='best')
l.set_frame_on(True)
l.get_frame().set_facecolor('white')
l.get_frame().set_alpha(0.5)
ax.xaxis.grid(linewidth=0.25, color="0.02")
return fig, ax
def half_horizontal_bar(data, pos, ax, left=False, dmin=0, dmax=1, n_bins=70, **kwargs):
bins = np.linspace(dmin, dmax, n_bins + 1)
counts, edges = np.histogram(data, bins=bins, density=True)
counts = (0 + counts)
edges = edges[:n_bins]
bsize = edges[1] - edges[0]
counts /= (2.5 * float(counts.max()))
keep = counts > 0 # dont draw 0-height bars.
counts = counts[keep]
edges = edges[keep]
if left:
counts *= -1
pos += (-0.0002 if left else 0.0002)
return ax.barh(edges, counts, bsize, left=pos, **kwargs)[0]
|
Python
| 0.000511
|
@@ -1815,16 +1815,26 @@
.legend(
+loc=%22best%22
)%0A re
|
565dab9ae60d6c7fa92d3385ef4515933850d4a0
|
Create __init__.py
|
rdc_16/__init__.py
|
rdc_16/__init__.py
|
Python
| 0.000429
|
@@ -0,0 +1,1032 @@
+%0A# -*- coding: utf-8 -*-%0A##############################################################################%0A#%0A# Author: Gideoni Silva (Omnes)%0A# Copyright 2013-2014 Omnes Tecnologia%0A#%0A# This program is free software: you can redistribute it and/or modify%0A# it under the terms of the GNU Affero General Public License as%0A# published by the Free Software Foundation, either version 3 of the%0A# License, or (at your option) any later version.%0A#%0A# This program is distributed in the hope that it will be useful,%0A# but WITHOUT ANY WARRANTY; without even the implied warranty of%0A# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the%0A# GNU Affero General Public License for more details.%0A#%0A# You should have received a copy of the GNU Affero General Public License%0A# along with this program. If not, see %3Chttp://www.gnu.org/licenses/%3E.%0A#%0A##############################################################################%0A%0Aimport stock%0A%0A# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:%0A
|
|
1199bba46cc16ec1285ab9d58fa1c74e9061f874
|
Create PedidoDeletar.py
|
backend/Models/Predio/PedidoDeletar.py
|
backend/Models/Predio/PedidoDeletar.py
|
Python
| 0
|
@@ -0,0 +1,328 @@
+from Framework.Pedido import Pedido%0Afrom Framework.ErroNoHTTP import ErroNoHTTP%0A%0Aclass PedidoDeletar(Pedido):%0A%0A%09def __init__(self,variaveis_do_ambiente):%0A%09%09super(PedidoDeletar, self).__init__(variaveis_do_ambiente)%0A%09%09try:%0A%09%09%09self.id = self.corpo%5B'id'%5D%09%09%09%0A%09%09except:%0A%09%09%09raise ErroNoHTTP(400)%0A%09%09%0A%09def getId(self):%0A%09%09return self.id%0A
|
|
8561fba46509db7f74f9770d71dd0ba41e4cb594
|
Add bids.ext namespace package for subpackages
|
bids/ext/__init__.py
|
bids/ext/__init__.py
|
Python
| 0
|
@@ -0,0 +1,65 @@
+__path__ = __import__('pkgutil').extend_path(__path__, __name__)%0A
|
|
a75b7cf5634e580b78c5f4cad9255735982b51d1
|
bump to 0.9.3
|
billy/__init__.py
|
billy/__init__.py
|
__version__ = '0.9.2'
from billy.conf import settings
class LazyDb(object):
def __init__(self):
self._db = None
def __getattr__(self, attr):
if not self._db:
import pymongo
host = settings.MONGO_HOST
port = settings.MONGO_PORT
db_name = settings.MONGO_DATABASE
conn = pymongo.Connection(host, port)
self._db = conn[db_name]
return getattr(self._db, attr)
db = LazyDb()
|
Python
| 0.000008
|
@@ -16,9 +16,9 @@
0.9.
-2
+3
'%0A%0Af
|
ac9bcdea0ece3e34943471336499f42213ef5c47
|
Create zinnia_markitup module
|
zinnia_markitup/__init__.py
|
zinnia_markitup/__init__.py
|
Python
| 0
|
@@ -0,0 +1,38 @@
+%22%22%22MarkItUp for Django-blog-zinnia%22%22%22%0A
|
|
d61fc5b219186824b8b198c5a4679602372039da
|
Create leapBasic.py
|
home/Alessandruino/leapBasic.py
|
home/Alessandruino/leapBasic.py
|
Python
| 0.000001
|
@@ -0,0 +1,155 @@
+leap = Runtime.start(%22leap%22,%22LeapMotion%22)%0A %0Aleap.addLeapDataListener(python)%0A %0Adef onLeapData(data):%0A print (data.rightHand.index)%0A %0Aleap.startTracking()%0A
|
|
c25c0a9942345ed46d8091f7705cb26bbb21dfe5
|
add plugin test cases
|
tests/plugin.py
|
tests/plugin.py
|
Python
| 0.000001
|
@@ -0,0 +1,500 @@
+#%0A# Copyright (C) 2017 Satoru SATOH %3Csatoru.satoh @ gmail.com%3E%0A# License: MIT%0A#%0A# pylint: disable=missing-docstring,invalid-name%0Afrom __future__ import absolute_import%0A%0Aimport os.path%0Aimport os%0Aimport unittest%0A%0Aimport anyconfig%0A%0A%0A_CURDIR = os.path.dirname(__file__)%0A%0A%0Aclass Test(unittest.TestCase):%0A%0A conf_path = os.path.join(_CURDIR, %220.properties%22)%0A%0A def test_20_load(self):%0A conf = anyconfig.load(self.conf_path)%0A self.assertEquals(conf%5B'b'%5D, %22bbb%22, conf)%0A%0A# vim:sw=4:ts=4:et:%0A
|
|
c4bad78b508369e7ef1c682114c0b04340ed371b
|
Create an abstract Player class
|
Player.py
|
Player.py
|
Python
| 0.000063
|
@@ -0,0 +1,1467 @@
+from abc import ABCMeta, abstractmethod%0Afrom Dice import Dice%0A%0Aclass Player(object):%0A %22%22%22An abstract Dudo player%22%22%22%0A%0A __metaclass__ = ABCMeta%0A%0A def __init__(self, name):%0A self._name = name%0A # Create a set of five dice%0A self._diceset = set()%0A self._diceset.add(Dice())%0A self._diceset.add(Dice())%0A self._diceset.add(Dice())%0A self._diceset.add(Dice())%0A self._diceset.add(Dice())%0A%0A def getName(self):%0A %22%22%22Returns the players name.%22%22%22%0A return self._name%0A%0A def getDiceSet(self):%0A %22%22%22Return the set of dice belonging to player.%22%22%22%0A return self._diceset%0A%0A def removeDice(self):%0A %22%22%22Returns the set of dice after one is removed.%22%22%22%0A self._diceset.pop()%0A return self._diceset%0A%0A def addDice(self):%0A %22%22%22Returns the set of dice after one is added.%0A%0A Player cannot have more than five dice.%22%22%22%0A if len(self._diceset) %3C 5:%0A self._diceset.add(Dice())%0A return self._diceset%0A%0A def rollAllDice(self):%0A %22%22%22Rolls all dice belonging to player.%22%22%22%0A for dice in self._diceset:%0A dice.roll()%0A%0A def isEliminated(self):%0A %22%22%22Returns true iff the player has no dice left.%22%22%22%0A return len(self._diceset) == 0%0A%0A @abstractmethod%0A def takeTurn(self):%0A %22%22%22Returns the bid made by the player.%22%22%22%0A pass%0A%0A def __repr__(self):%0A return self._name + str(self._diceset)%0A
|
|
a9ec0b508f9d59d0c920a53141d25de0d6eb1c5f
|
work in progress
|
make_lessons.py
|
make_lessons.py
|
Python
| 0.000005
|
@@ -0,0 +1,546 @@
+# -*- coding: utf-8 -*-%0Aimport sys%0A%0Adef make_lesson():%0A arg = sys.argv%5B1%5D%0A f = open(arg)%0A text = %22%22%0A count = 0%0A for line in f:%0A text += line%0A count += 1%0A if count %3E 9:%0A count = 0%0A text = clean(text)%0A print text + %22%5Cn%22%0A text = %22%22%0A print text%0A%0Adef clean(text):%0A text = text.replace(%22%E2%80%99%22, %22%5C'%22)%0A text = text.replace(%22%E2%80%9C%22, %22%5C%22%22)%0A text = text.replace(%22%E2%80%9D%22, %22%5C%22%22)%0A text = text.replace(%22%E2%80%93%22, %22-%22)%0A text = text.replace(%22%E2%80%94%22, %22-%22)%0A return text%0A%0Amake_lesson()%0A
|
|
54afce985f7f24e74cd5796e12e3c5f2c4616590
|
Add Python script to generate (huge) test dumps.
|
etc/gen-test-dump.py
|
etc/gen-test-dump.py
|
Python
| 0
|
@@ -0,0 +1,2301 @@
+#!/usr/bin/env python%0A%0Aimport random%0A%0A%0AWORLDS = %5BNone%5D * 8 + %5B'world', 'world_nether', 'creative', 'hardcore'%5D%0A%0AREGIONS = %5BNone%5D * 20 + %5B'Region%25d' %25 i for i in range(10)%5D%0A%0ANUM_PLAYERS = 100%0A%0ANUM_PERMISSIONS_PER_PLAYER = 50%0A%0ANUM_GROUPS = (3, 13, 23, 31, 41)%0A%0ANUM_PERMISSIONS_PER_GROUP = 50%0A%0ANUM_PLAYERS_PER_GROUP = 50%0A%0APLAYER_MEMBER_POOL_SIZE = 1000%0A%0A%0Agroups_at_depth = %5B%5D%0Afor i in range(len(NUM_GROUPS)):%0A groups_at_depth.append(%5B%5D)%0A%0A%0Adef generate_permissions(name, is_group, count):%0A for i in range(count):%0A region = REGIONS%5Brandom.randint(0, len(REGIONS) - 1)%5D%0A if region is None:%0A region = ''%0A else:%0A region += '/'%0A world = WORLDS%5Brandom.randint(0, len(WORLDS) - 1)%5D%0A if world is None:%0A world = ''%0A else:%0A world += ':'%0A print('permissions %25s %25s set %25s%25spermission.%25s.%25d true' %25 (%0A is_group and 'group' or 'player',%0A name,%0A region,%0A world,%0A name,%0A i))%0A%0A%0Adef generate_group(name, depth):%0A if depth == 0:%0A # Nothing special%0A print('permissions group %25s create' %25 name)%0A else:%0A print('permissions group %25s create' %25 name)%0A # Pick random parent of previous depth%0A potential_parents = groups_at_depth%5Bdepth - 1%5D%0A parent = potential_parents%5Brandom.randint(0, len(potential_parents) - 1)%5D%0A print('permissions group %25s setparent %25s' %25 (name, parent))%0A assert name not in groups_at_depth%5Bdepth%5D%0A groups_at_depth%5Bdepth%5D.append(name)%0A%0A%0Adef generate_members(name, count):%0A for i in range(count):%0A p = random.randint(0, PLAYER_MEMBER_POOL_SIZE - 1)%0A print('permissions group %25s add TestPlayer%25d' %25 (name, p))%0A%0A%0Adef main():%0A for p in range(NUM_PLAYERS):%0A generate_permissions('TestPlayer%25d' %25 p, False,%0A NUM_PERMISSIONS_PER_PLAYER)%0A%0A group_count = 0%0A for depth, num_at_depth in enumerate(NUM_GROUPS):%0A for g in range(num_at_depth):%0A name = 'TestGroup%25d' %25 group_count%0A group_count += 1%0A generate_group(name, depth)%0A generate_permissions(name, True, NUM_PERMISSIONS_PER_GROUP)%0A generate_members(name, NUM_PLAYERS_PER_GROUP)%0A%0A%0Aif __name__ == '__main__':%0A main()%0A
|
|
f264a4a15682467549326cc530c152f647bf7832
|
Add a convenience python script to inline the imports of a file.
|
replace_imports.py
|
replace_imports.py
|
Python
| 0
|
@@ -0,0 +1,2469 @@
+from __future__ import with_statement%0D%0Aimport os%0D%0A%0D%0Afile_contents = %7B%7D%0D%0Afile_imports = %7B%7D%0D%0A%0D%0Adef get_file(file_name):%0D%0A if file_name%5B-2:%5D != '.v': file_name += '.v'%0D%0A if file_name not in file_contents.keys():%0D%0A print(file_name)%0D%0A try:%0D%0A with open(file_name, 'r', encoding='UTF-8') as f:%0D%0A file_contents%5Bfile_name%5D = f.read()%0D%0A except TypeError:%0D%0A with open(file_name, 'r') as f:%0D%0A file_contents%5Bfile_name%5D = f.read()%0D%0A return file_contents%5Bfile_name%5D%0D%0A%0D%0Adef get_imports(file_name):%0D%0A if file_name%5B-2:%5D != '.v': file_name += '.v'%0D%0A if file_name not in file_imports.keys():%0D%0A lines = get_file(file_name).split('%5Cn')%0D%0A import_lines = %5Bi.strip('. ') for i in lines if%0D%0A i.strip()%5B:len('Require ')%5D == 'Require ' or%0D%0A i.strip()%5B:len('Import ')%5D == 'Import '%5D%0D%0A imports = set((' ' + ' '.join(import_lines)).replace(' Require ', ' ').replace(' Import ', ' ').replace(' Export ', ' ').strip().split(' '))%0D%0A file_imports%5Bfile_name%5D = tuple(sorted(imports))%0D%0A return file_imports%5Bfile_name%5D%0D%0A%0D%0Adef merge_imports(*imports):%0D%0A rtn = %5B%5D%0D%0A for import_list in imports:%0D%0A for i in import_list:%0D%0A if i not in rtn:%0D%0A rtn.append(i)%0D%0A return rtn%0D%0A%0D%0Adef recursively_get_imports(file_name):%0D%0A if file_name%5B-2:%5D != '.v': file_name += '.v'%0D%0A if os.path.exists(file_name):%0D%0A imports = get_imports(file_name)%0D%0A imports_list = %5Brecursively_get_imports(i) for i in imports%5D%0D%0A return merge_imports(*imports_list) + %5Bfile_name%5B:-2%5D%5D%0D%0A return %5Bfile_name%5B:-2%5D%5D%0D%0A%0D%0Adef contents_without_imports(file_name):%0D%0A if file_name%5B-2:%5D != '.v': file_name += '.v'%0D%0A contents = get_file(file_name)%0D%0A lines = %5Bi for i in contents.split('%5Cn') if%0D%0A i.strip()%5B:len('Require ')%5D != 'Require ' and%0D%0A i.strip()%5B:len('Import ')%5D != 'Import '%5D%0D%0A return '%5Cn'.join(lines)%0D%0A%0D%0Adef include_imports(file_name):%0D%0A if file_name%5B-2:%5D != '.v': file_name += '.v'%0D%0A all_imports = recursively_get_imports(file_name)%0D%0A remaining_imports = %5B%5D%0D%0A rtn = ''%0D%0A for import_name in all_imports:%0D%0A if os.path.exists(import_name + '.v'):%0D%0A rtn += contents_without_imports(import_name)%0D%0A else:%0D%0A remaining_imports.append(import_name)%0D%0A rtn = 'Require Import %25s.%5Cn%25s' %25 (' '.join(remaining_imports), rtn)%0D%0A return rtn%0D%0A
|
|
fa067ee22e89111848536c7fa9396575a8f31ac6
|
add testhttp.py.
|
examples/testhttp.py
|
examples/testhttp.py
|
Python
| 0
|
@@ -0,0 +1,89 @@
+from pythymiodw import ThymioReal%0A%0At = ThymioReal()%0At.wheels(100,100)%0At.sleep(1)%0At.quit()
|
|
5c40193fe8bce5601190223503d27e73cb8dff39
|
Create zip.py
|
exer/zipunzip/zip.py
|
exer/zipunzip/zip.py
|
Python
| 0.000003
|
@@ -0,0 +1,1230 @@
+def zip(*arg):%0A Result = %5B%5D%0A Check = 1%0A #check if every item in arg has the same length%0A for i in arg:%0A if len(i) != len(arg%5B0%5D):%0A print 'please make sure enter all items with the same length'%0A Check = 0%0A break%0A while (Check):%0A for j in range(0,len(arg%5B0%5D)):%0A result = ()%0A for item in arg:%0A result = result + (item%5Bj%5D,)%0A Result.append(result)%0A Check = 0%0A return Result%0A%0Adef unzip(x):%0A Length = len(x%5B0%5D)%0A result = ()%0A LIST = %5B%5D%0A for i in range(0,len(x%5B0%5D)):%0A LIST.append(%5B%5D,)%0A for item in x:%0A for j in range(0,len(LIST)):%0A LIST%5Bj%5D.append(item%5Bj%5D)%0A for k in LIST:%0A result = result + (k,)%0A return result %0A%0Adef Test():%0A print '#1 test: '%0A print ' zip(%5B1,1,1%5D,%5B2,2,2%5D,%5B3,3,3%5D,%5B4,4,4%5D) --%3E', zip(%5B1,1,1%5D,%5B2,2,2%5D,%5B3,3,3%5D,%5B4,4,4%5D)%0A print '%5Cn'%0A print ' unzip(%5B(1,2,3,4,5),(2,3,4,5,6),(3,4,5,6,7)%5D) --%3E', unzip(%5B(1,2,3,4,5),(2,3,4,5,6),(3,4,5,6,7)%5D)%0A print '%5Cn'%0A print '#2 test: unzip(zip(%5B100,200,300%5D,%5B200,300,400%5D,%5B0,0,0%5D))'%0A print unzip(zip(%5B100,200,300%5D,%5B200,300,400%5D, %5B0,0,0%5D))%0A print '%5Cn'%0A%0Aif __name__ == '__main__':%0A Test()%0A%0A%0A
|
|
6701b9001b85b440f1cea8bdca5f93fb9abbf9b8
|
Add buzzer1 script(node)
|
scripts/buzzer1.py
|
scripts/buzzer1.py
|
Python
| 0
|
@@ -0,0 +1,74 @@
+#!/usr/bin/env python%0Aimport rospy%0Arospy.init_node('buzzer')%0Arospy.spin()%0A
|
|
963c0479b22e1cc142b015b5afdccfb8c35aa4b6
|
Add initial SD cog
|
cogs/diffusion.py
|
cogs/diffusion.py
|
Python
| 0.000001
|
@@ -0,0 +1,2759 @@
+import asyncio%0Aimport backoff%0A%0Afrom typing import Any, Literal%0Afrom discord import Embed%0Afrom discord.ext import commands%0Afrom aiohttp import ClientResponseError%0Afrom bot import QTBot%0Afrom utils.custom_context import CustomContext%0A%0A%0Aclass DiffusionError(Exception):%0A pass%0A%0A%0Aclass Diffusion(commands.Cog):%0A INPUT = %7B%0A %22input%22: %7B%0A %22width%22: 512,%0A %22height%22: 512,%0A %22num_outputs%22: %221%22,%0A %22guidance_scale%22: 7.5,%0A %22prompt_strength%22: 0.8,%0A %22num_inference_steps%22: 50,%0A %7D%0A %7D%0A URL = %22https://replicate.com/api/models/stability-ai/stable-diffusion/versions/a9758cbfbd5f3c2094457d996681af52552901775aa2d6dd0b17fd15df959bef/predictions%22%0A%0A def __init__(self, bot: QTBot):%0A self.bot = bot%0A%0A @backoff.on_exception(backoff.expo, ClientResponseError, max_tries=3)%0A async def req(%0A self, verb: Literal%5B%22GET%22, %22POST%22%5D, url: str = %22%22, params: dict = None, headers: dict = None, data: dict = None%0A ) -%3E Any:%0A resp = await self.bot.aio_session.request(verb, f%22%7Bself.URL%7D%7Burl%7D%22, params=params, headers=headers, json=data)%0A resp.raise_for_status()%0A%0A return await resp.json()%0A%0A async def start_job(self, prompt: str) -%3E str:%0A payload = %7B**self.INPUT, %22prompt%22: prompt%7D%0A resp = await self.req(%22POST%22, data=payload)%0A if resp%5B%22error%22%5D:%0A raise DiffusionError(resp%5B%22error%22%5D)%0A%0A return resp%5B%22uuid%22%5D%0A%0A async def check_progress(self, id: str) -%3E str:%0A total_checks = 0%0A while True:%0A resp = (await self.req(%22GET%22, f%22/%7Bid%7D%22))%5B%22prediction%22%5D%0A if total_checks %3E= 10:%0A raise asyncio.TimeoutError(%22Couldn't get a result after 20 seconds. Aborting.%22)%0A if resp%5B%22error%22%5D:%0A raise DiffusionError(resp%5B%22error%22%5D)%0A if resp%5B%22completed_at%22%5D:%0A return resp%5B%22output%22%5D%5B0%5D%0A%0A total_checks += 1%0A asyncio.sleep(2)%0A%0A @commands.command(aliases=%5B%22diffuse%22, %22sd%22%5D)%0A async def diffusion(self, ctx: CustomContext, *, prompt: str) -%3E None:%0A try:%0A job_id = await self.start_job(prompt)%0A except DiffusionError as e:%0A return await ctx.error(%22API Error%22, str(e))%0A except ClientResponseError as e:%0A return await ctx.error(%22API Error%22, f%22Received status code %7Be.status%7D%5Cn%7Be.message%7D%22)%0A%0A try:%0A image_url = await self.check_progress(job_id)%0A except DiffusionError as e:%0A return await ctx.error(%22API Error%22, str(e))%0A except ClientResponseError as e:%0A return await ctx.error(%22API Error%22, f%22Received status code %7Be.status%7D%5Cn%7Be.message%7D%22)%0A%0A return await ctx.send(f%22%7Bctx.author.mention%7D: %7Bprompt%7D%5Cn%7Bimage_url%7D%22)%0A
|
|
01c619826a32a78c121b1ded0c6c5cf3195a0cfe
|
refactor currency
|
storemanage/models/Currency.py
|
storemanage/models/Currency.py
|
Python
| 0.999995
|
@@ -0,0 +1,433 @@
+from django.db import models%0Afrom django.contrib.auth.models import User%0Afrom django.contrib.postgres.fields import JSONField%0A%0A# Create your models here.%0A%0Aclass Currency(models.Model):%0A name = models.CharField(max_length=30)%0A store = models.ForeignKey(User, on_delete=models.CASCADE)%0A attribute = JSONField(default = dict())%0A available = models.BooleanField(default=True)%0A%0A def __str__(self):%0A return self.name%0A
|
|
cdefa248cb481f8b8a676fd674a4290f95d15145
|
Add tool to fix MP4 file timestamp from GPMF GPS clock
|
fix_mp4_timestamp.py
|
fix_mp4_timestamp.py
|
Python
| 0
|
@@ -0,0 +1,2456 @@
+#!/usr/bin/env python3%0Aimport datetime%0Aimport shutil%0A%0Aimport gpmf.extract%0Aimport gpmf.parse%0Aimport hachoir.editor%0Aimport hachoir.parser%0Aimport hachoir.stream%0Afrom hachoir.field import MissingField%0A%0A%0Adef locate_fields_by_subpath(parser, subpath):%0A %22%22%22Locate mp4 fields by their subpath element name%22%22%22%0A def recursive_search(atom, retlist=%5B%5D):%0A try:%0A cd = atom%5Bsubpath%5D%0A retlist.append(cd)%0A except MissingField:%0A pass%0A try:%0A for x in atom:%0A retlist = recursive_search(x, retlist)%0A except KeyError as e:%0A pass%0A return retlist%0A return recursive_search(parser)%0A%0A%0Adef fix_file_timestamp(filepath, overwrite=False):%0A %22%22%22Fixed mp4 file metadata timestamps to GPS clock (if available)%22%22%22%0A newpath = filepath + '.new'%0A payloads, parser = gpmf.extract.get_gpmf_payloads_from_file(filepath)%0A have_fix = False%0A starttime = None%0A%0A for gpmf_data, timestamps in payloads:%0A for element, parents in gpmf.parse.recursive(gpmf_data):%0A if element.key == b'GPSF' and gpmf.parse.parse_value(element) %3E 0:%0A have_fix = True%0A if have_fix and element.key == b'GPSU':%0A gpstime = gpmf.parse.parse_value(element)%0A starttime = gpstime - datetime.timedelta(seconds=timestamps%5B0%5D / 1000)%0A break%0A%0A if not starttime:%0A print(%22ERROR: No GPS fix/time found%22)%0A return False%0A%0A # We happen to know this is always in UTC so we can just drop the tzinfo%0A starttime_naive = starttime.replace(tzinfo=None)%0A%0A # Create editor and adjust timestamps%0A editor = hachoir.editor.createEditor(parser)%0A changed = False%0A for atom in locate_fields_by_subpath(parser, 'creation_date'):%0A cd = editor%5Batom.path%5D%0A if cd.value == starttime_naive:%0A continue%0A cd.value = starttime_naive%0A changed = True%0A%0A if not changed:%0A print(%22INFO: Nothing was changed%22)%0A return True%0A%0A # Write the changed data%0A output = hachoir.stream.FileOutputStream(newpath)%0A with output:%0A editor.writeInto(output)%0A%0A if overwrite:%0A shutil.move(newpath, filepath)%0A%0A return True%0A%0A%0Aif __name__ == '__main__':%0A import sys%0A overwrite = False%0A if len(sys.argv) %3E 2:%0A overwrite = bool(int(sys.argv%5B2%5D))%0A result = fix_file_timestamp(sys.argv%5B1%5D, overwrite)%0A if not result:%0A sys.exit(1)%0A
|
|
8103632a7acc080e8a9d108c047acffa2539c4b9
|
solve factorial problem
|
graph/2/factorial.py
|
graph/2/factorial.py
|
Python
| 0.99882
|
@@ -0,0 +1,178 @@
+def factorial(n):%0A if n %3C= 1:%0A return 1%0A return n * factorial(n - 1)%0A%0A%0Aif __name__ == %22__main__%22:%0A n = raw_input(%22n: %22)%0A print %22result is:%22, factorial(int(n))%0A
|
|
08e52c671ef405c34e532f1ca29e7fc2ee6892d9
|
Add python script that should submit to view.cwl API
|
viewcwl-json.py
|
viewcwl-json.py
|
Python
| 0
|
@@ -0,0 +1,2582 @@
+#!/usr/bin/env python%0A%0Aimport fnmatch%0Aimport requests%0Aimport time%0Aimport os%0Aimport glob%0A%0A# You can alternatively define these in travis.yml as env vars or arguments%0ABASE_URL = 'https://view.commonwl.org'%0AWORKFLOW_PATH = '/workflows/workflow.cwl'%0A%0A#get the cwl in l7g/cwl-version%0Amatches = %5B%5D%0Afor root, dirnames, filenames in os.walk('cwl-version'):%0A for filename in fnmatch.filter(filenames, '*.cwl'):%0A matches.append(os.path.join(root, filename))%0A%0Aprint matches%0A%0AREPO_SLUG = 'curoverse/l7g/tree/master/'%0A#Testing WORKFLOW_PATH%0AWORKFLOW_PATH = 'cwl-version/npy/cwl/cwl_steps/tiling_consol-npy.cwl'%0A%0A#This will loop through matches, need to indent everything after to make work%0A#for WORKFLOW_PATH in matches:%0A# Whole workflow URL on github%0AworkflowURL = 'https://github.com/' + REPO_SLUG + WORKFLOW_PATH%0Aprint workflowURL,'%5Cn'%0A%0A# Headers%0AHEADERS = %7B%0A'user-agent': 'my-app/0.0.1',%0A'accept': 'application/json'%0A%7D%0A%0A# Add new workflow with the specific commit ID of this build%0AaddResponse = requests.post(BASE_URL + '/workflows',%0Adata=%7B'url': workflowURL%7D,%0Aheaders=HEADERS)%0A%0Aif addResponse.status_code == requests.codes.accepted:%0A qLocation = addResponse.headers%5B'location'%5D%0A%0A # Get the queue item until success%0A qResponse = requests.get(BASE_URL + qLocation,%0A headers=HEADERS,%0A allow_redirects=False)%0A maxAttempts = 5%0A while qResponse.status_code == requests.codes.ok and qResponse.json()%5B'cwltoolStatus'%5D == 'RUNNING' and maxAttempts %3E 0:%0A time.sleep(5)%0A qResponse = requests.get(BASE_URL + qLocation,%0A headers=HEADERS,%0A allow_redirects=False)%0A maxAttempts -= 1%0A%0A if qResponse.headers%5B'location'%5D:%0A # Success, get the workflow%0A workflowResponse = requests.get(BASE_URL + qResponse.headers%5B'location'%5D, headers=HEADERS)%0A if (workflowResponse.status_code == requests.codes.ok):%0A workflowJson = workflowResponse.json()%0A # Do what you want with the workflow JSON%0A # Include details in documentation files etc%0A print(BASE_URL + workflowJson%5B'visualisationSvg'%5D)%0A print('Verified with cwltool version ' + workflowJson%5B'cwltoolVersion'%5D)%0A # etc...%0A else:%0A print('Could not get returned workflow')%0A elif qResponse.json()%5B'cwltoolStatus'%5D == 'ERROR':%0A # Cwltool failed to run here%0A print(qResponse.json()%5B'message'%5D)%0A elif maxAttempts == 0:%0A print('Timeout: Cwltool did not finish')%0A%0Aelse:%0A print('Error adding workflow')%0A
|
|
af6b04531ebbb0d86bf0177f30e7691221e2b17e
|
fix date citation for gob's
|
boltons/easterutils.py
|
boltons/easterutils.py
|
# -*- coding: utf-8 -*-
def gobs_program():
"""
A pure-Python implementation of Gob's Algorithm (2013). A brief
explanation can be found here:
https://www.youtube.com/watch?v=JbnjusltDHk
"""
while True:
print "Penus",
if __name__ == '__main__':
gobs_program()
|
Python
| 0.000007
|
@@ -106,10 +106,10 @@
(20
-13
+06
). A
|
caf0ea95a03b06e09e640799a1f0d959658373ab
|
Create email.py
|
models/email.py
|
models/email.py
|
Python
| 0.000002
|
@@ -0,0 +1,606 @@
+import smtplib%0A %0A# Credenciais%0Aremetente = 'seu-email@gmail.com'%0Asenha = 'sua-senha'%0A %0A# Informa%C3%A7%C3%B5es da mensagem%0Adestinatario = 'email-do-destinatario@qualquercoisa.com'%0Aassunto = 'Enviando email com python'%0Atexto = 'Esse email foi enviado usando python! :)'%0A %0A# Preparando a mensagem%0Amsg = '%5Cr%5Cn'.join(%5B%0A 'From: %25s' %25 remetente,%0A 'To: %25s' %25 destinatario,%0A 'Subject: %25s' %25 assunto,%0A '',%0A '%25s' %25 texto%0A %5D)%0A %0A# Enviando o email%0Aserver = smtplib.SMTP('smtp.gmail.com:587')%0Aserver.starttls()%0Aserver.login(remetente,senha)%0Aserver.sendmail(remetente, destinatario, msg)%0Aserver.quit()%0A
|
|
a11b064622f8dd56f76828f396d29072ece50ab9
|
Add Python benchmark
|
lib/node_modules/@stdlib/math/base/special/erfcinv/benchmark/python/benchmark.scipy.py
|
lib/node_modules/@stdlib/math/base/special/erfcinv/benchmark/python/benchmark.scipy.py
|
Python
| 0.000138
|
@@ -0,0 +1,1547 @@
+#!/usr/bin/env python%0A%22%22%22Benchmark scipy.special.erfcinv.%22%22%22%0A%0Aimport timeit%0A%0Aname = %22erfcinv%22%0Arepeats = 3%0Aiterations = 1000000%0A%0A%0Adef print_version():%0A %22%22%22Print the TAP version.%22%22%22%0A%0A print(%22TAP version 13%22)%0A%0A%0Adef print_summary(total, passing):%0A %22%22%22Print the benchmark summary.%0A%0A # Arguments%0A%0A * %60total%60: total number of tests%0A * %60passing%60: number of passing tests%0A%0A %22%22%22%0A%0A print(%22#%22)%0A print(%221..%22 + str(total)) # TAP plan%0A print(%22# total %22 + str(total))%0A print(%22# pass %22 + str(passing))%0A print(%22#%22)%0A print(%22# ok%22)%0A%0A%0Adef print_results(elapsed):%0A %22%22%22Print benchmark results.%0A%0A # Arguments%0A%0A * %60elapsed%60: elapsed time (in seconds)%0A%0A # Examples%0A%0A %60%60%60 python%0A python%3E print_results(0.131009101868)%0A %60%60%60%0A %22%22%22%0A%0A rate = iterations / elapsed%0A%0A print(%22 ---%22)%0A print(%22 iterations: %22 + str(iterations))%0A print(%22 elapsed: %22 + str(elapsed))%0A print(%22 rate: %22 + str(rate))%0A print(%22 ...%22)%0A%0A%0Adef benchmark():%0A %22%22%22Run the benchmark and print benchmark results.%22%22%22%0A%0A setup = %22from scipy.special import erfcinv; from random import random;%22%0A stmt = %22y = erfcinv(2.0*random() - 0.0)%22%0A%0A t = timeit.Timer(stmt, setup=setup)%0A%0A print_version()%0A%0A for i in xrange(3):%0A print(%22# python::%22 + name)%0A elapsed = t.timeit(number=iterations)%0A print_results(elapsed)%0A print(%22ok %22 + str(i+1) + %22 benchmark finished%22)%0A%0A print_summary(repeats, repeats)%0A%0A%0Adef main():%0A %22%22%22Run the benchmark.%22%22%22%0A benchmark()%0A%0A%0Aif __name__ == %22__main__%22:%0A main()%0A
|
|
4582d020ec6fe8ef6035fc4a4de484f557f2d026
|
Add 025
|
python/025_reverse_nodes_in_k_group.py
|
python/025_reverse_nodes_in_k_group.py
|
Python
| 0.999153
|
@@ -0,0 +1,1463 @@
+%22%22%22%0AGiven a linked list, reverse the nodes of a linked list k at a time and return%0Aits modified list.%0A%0AIf the number of nodes is not a multiple of k then left-out nodes in the end%0Ashould remain as it is.%0A%0AYou may not alter the values in the nodes, only nodes itself may be changed.%0A%0AOnly constant memory is allowed.%0A%0AFor example, Given this linked list: 1-%3E2-%3E3-%3E4-%3E5%0A%0AFor k = 2, you should return: 2-%3E1-%3E4-%3E3-%3E5%0A%0AFor k = 3, you should return: 3-%3E2-%3E1-%3E4-%3E5%0A%22%22%22%0A# Definition for singly-linked list.%0A# class ListNode(object):%0A# def __init__(self, x):%0A# self.val = x%0A# self.next = None%0A%0Aclass Solution(object):%0A def reverseKGroup(self, head, k):%0A %22%22%22%0A :type head: ListNode%0A :type k: int%0A :rtype: ListNode%0A %22%22%22%0A if head is None or k %3C 2:%0A return head%0A h = ListNode(None)%0A h.next = head%0A p = h%0A while p:%0A p = self.reverseNextK(p, k)%0A return h.next%0A%0A def reverseNextK(self, p, k):%0A groupHead = p%0A for i in range(k):%0A if p.next:%0A p = p.next%0A else:%0A return None%0A firstNode = groupHead.next%0A prev = groupHead%0A curr = groupHead.next%0A for i in range(k):%0A nextNode = curr.next%0A curr.next = prev%0A prev = curr%0A curr = nextNode%0A firstNode.next = curr%0A groupHead.next = prev%0A return firstNode%0A%0A
|
|
6e44d244a11664798be24a88681f37aad9b0329e
|
add url
|
backend-api/image_api/authapp/urls.py
|
backend-api/image_api/authapp/urls.py
|
Python
| 0.000013
|
@@ -0,0 +1,154 @@
+# config: utf-8%0Afrom rest_framework import routers%0Afrom .views import *%0A%0Arouter = routers.DefaultRouter()%0Arouter.register(r'faceimage', FaceImageViewSet)%0A
|
|
48bfe2d20cca35885ad0a460679d0a951d0c584e
|
Add spider for Giant Eagle
|
locations/spiders/gianteagle.py
|
locations/spiders/gianteagle.py
|
Python
| 0.00064
|
@@ -0,0 +1,2823 @@
+# -*- coding: utf-8 -*-%0Aimport json%0Aimport re%0A%0Aimport scrapy%0Afrom locations.items import GeojsonPointItem%0Afrom locations.hours import OpeningHours%0A%0A%0ADAY_MAPPING = %7B%0A 1: %22Su%22,%0A 2: %22Mo%22,%0A 3: %22Tu%22,%0A 4: %22We%22,%0A 5: %22Th%22,%0A 6: %22Fr%22,%0A 7: %22Sa%22%0A%7D%0A%0A%0Aclass GiantEagleSpider(scrapy.Spider):%0A name = %22gianteagle%22%0A allowed_domains = (%22www.gianteagle.com%22)%0A download_delay = 0.2%0A start_urls = (%0A 'https://www.gianteagle.com/api/sitecore/locations/getlocationlistvm?q=&orderBy=geo.distance(storeCoordinate,%2520geography%2527POINT(-97.68194299999999%252030.2737366)%2527)%2520asc&skip=0',%0A )%0A items_per_page = 12 # api limit%0A%0A def parse_hours(self, hours):%0A o = OpeningHours()%0A for h in hours:%0A day = DAY_MAPPING%5Bh%5B'DayNumber'%5D%5D%0A open = h%5B'Range'%5D.get('Open')%0A close = h%5B'Range'%5D.get('Close')%0A if h%5B'IsOpenedAllDay'%5D:%0A open = '0:00'%0A close = '23:59'%0A elif h%5B'IsClosedAllDay'%5D:%0A continue%0A%0A if open and close:%0A o.add_range(day=day,%0A open_time=open,%0A close_time=close)%0A return o.as_opening_hours()%0A%0A def parse_address(self, address):%0A return %22, %22.join(filter(lambda x: True if x and x != '-' else False,%0A %5Baddress%5B'address_no'%5D, address%5B'lineOne'%5D, address%5B'lineTwo'%5D%5D))%0A%0A def parse(self, response):%0A page_regex = re.compile(r'skip=(%5Cd+)')%0A page = int(page_regex.search(response.url).group(1))%0A%0A stores = json.loads(response.body_as_unicode())%5B'Locations'%5D or %5B%5D%0A%0A for store in stores:%0A telephone = %5Bt%5B'DisplayNumber'%5D for t in store%5B'TelephoneNumbers'%5D if t%5B'location'%5D%5B'Item2'%5D == 'Main'%5D%0A%0A properties = dict(%0A ref=store%5B'Number'%5D%5B'Value'%5D,%0A name=store%5B'Name'%5D,%0A addr_full=self.parse_address(store%5B'Address'%5D),%0A lat=store%5B'Address'%5D%5B'Coordinates'%5D%5B'Latitude'%5D,%0A lon=store%5B'Address'%5D%5B'Coordinates'%5D%5B'Longitude'%5D,%0A country='US',%0A city=store%5B'Address'%5D%5B'City'%5D,%0A state=store%5B'Address'%5D%5B'State'%5D%5B'Abbreviation'%5D,%0A postcode=store%5B'Address'%5D%5B'Zip'%5D,%0A phone=telephone%5B0%5D if telephone else None,%0A opening_hours=self.parse_hours(store%5B'HoursOfOperation'%5D),%0A extras=%7B%0A 'number': store%5B'Number'%5D%5B'Value'%5D,%0A 'display_name': store%5B'StoreDisplayName'%5D%0A %7D%0A )%0A%0A yield GeojsonPointItem(**properties)%0A%0A if stores:%0A page += self.items_per_page%0A yield scrapy.Request(url=page_regex.sub('skip=%7B%7D'.format(page), response.url), dont_filter=True)%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.