commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
ac0f0780beb61cab95809b2e0d02e5dab481e225
py/valid-parenthesis-string.py
py/valid-parenthesis-string.py
from collections import Counter class Solution(object): def dfs(self, s, pos, stack): if stack + self.min_possible_opening[-1] - self.min_possible_opening[pos] > self.max_possible_closing[-1] - self.max_possible_closing[pos]: return False if stack + self.max_possible_opening[-1] - self.m...
class Solution(object): def checkValidString(self, s): """ :type s: str :rtype: bool """ lowest, highest = 0, 0 for c in s: if c == '(': lowest += 1 highest += 1 elif c == ')': if lowest > 0: ...
Add py solution for 678. Valid Parenthesis String
Add py solution for 678. Valid Parenthesis String 678. Valid Parenthesis String: https://leetcode.com/problems/valid-parenthesis-string/ Approach2: Maintain the lowest/highest possible stack size and check if one of them is invalid O(n) time, O(1) size
Python
apache-2.0
ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode
e1e7b72685df12d1d7d782e03878253663a4c790
mysite/scripts/remove_numbers_from_locations.py
mysite/scripts/remove_numbers_from_locations.py
import re import mysite Person = mysite.profile.models.Person people_with_weird_locations = Person.objects.filter(location_display_name__regex=', [0-9][0-9],') for p in people_with_weird_locations: location_pieces = re.split(r', \d\d', p.location_display_name) unweirded_location = "".join(location_pieces) ...
import re import mysite Person = mysite.profile.models.Person people_with_weird_locations = Person.objects.filter(location_display_name__regex=', [0-9][0-9],') for p in people_with_weird_locations: location_pieces = re.split(r', \d\d,', p.location_display_name) unweirded_location = ",".join(location_pieces) ...
Fix script that removes numerals from people's locations.
Fix script that removes numerals from people's locations.
Python
agpl-3.0
campbe13/openhatch,heeraj123/oh-mainline,moijes12/oh-mainline,ojengwa/oh-mainline,Changaco/oh-mainline,vipul-sharma20/oh-mainline,campbe13/openhatch,SnappleCap/oh-mainline,SnappleCap/oh-mainline,waseem18/oh-mainline,eeshangarg/oh-mainline,moijes12/oh-mainline,waseem18/oh-mainline,sudheesh001/oh-mainline,onceuponatimefo...
b23c843fda57e0ffa56aaf430d9a590e2ed0ec9a
ch06/extract_airlines.py
ch06/extract_airlines.py
# Load the on-time parquet file on_time_dataframe = spark.read.parquet('data/on_time_performance.parquet') # The first step is easily expressed as SQL: get all unique tail numbers for each airline on_time_dataframe.registerTempTable("on_time_performance") carrier_airplane = spark.sql( "SELECT DISTINCT Carrier, TailN...
# Load the on-time parquet file on_time_dataframe = spark.read.parquet('data/on_time_performance.parquet') # The first step is easily expressed as SQL: get all unique tail numbers for each airline on_time_dataframe.registerTempTable("on_time_performance") carrier_airplane = spark.sql( "SELECT DISTINCT Carrier, TailN...
Check variable for None value before null string when filtering tail numbers
Check variable for None value before null string when filtering tail numbers
Python
mit
rjurney/Agile_Data_Code_2,naoyak/Agile_Data_Code_2,rjurney/Agile_Data_Code_2,naoyak/Agile_Data_Code_2,rjurney/Agile_Data_Code_2,naoyak/Agile_Data_Code_2,rjurney/Agile_Data_Code_2,naoyak/Agile_Data_Code_2
dbc09d03f62bf2d5ee1661492a4c20a7942f81a9
tests/basics/list_slice.py
tests/basics/list_slice.py
# test slices; only 2 argument version supported by Micro Python at the moment x = list(range(10)) a = 2 b = 4 c = 3 print(x[:]) print(x[::]) #print(x[::c]) print(x[:b]) print(x[:b:]) #print(x[:b:c]) print(x[a]) print(x[a:]) print(x[a::]) #print(x[a::c]) print(x[a:b]) print(x[a:b:]) #print(x[a:b:c]) # these should not...
# test list slices, getting values x = list(range(10)) a = 2 b = 4 c = 3 print(x[:]) print(x[::]) print(x[::c]) print(x[:b]) print(x[:b:]) print(x[:b:c]) print(x[a]) print(x[a:]) print(x[a::]) print(x[a::c]) print(x[a:b]) print(x[a:b:]) print(x[a:b:c]) # these should not raise IndexError print([][1:]) print([][-1:]) ...
Enable tests for list slice getting with 3rd arg.
tests/basics: Enable tests for list slice getting with 3rd arg. Also add a test to check case when 3rd arg is 0.
Python
mit
tuc-osg/micropython,mhoffma/micropython,trezor/micropython,blazewicz/micropython,AriZuu/micropython,kerneltask/micropython,swegener/micropython,MrSurly/micropython,mhoffma/micropython,hiway/micropython,alex-robbins/micropython,henriknelson/micropython,tuc-osg/micropython,adafruit/micropython,selste/micropython,ryannath...
351c05b6e474b266a7594a775cb48cd7cfe0b833
shapely/linref.py
shapely/linref.py
"""Linear referencing """ from shapely.topology import Delegating class LinearRefBase(Delegating): def _validate_line(self, ob): super(LinearRefBase, self)._validate(ob) try: assert ob.geom_type in ['LineString', 'MultiLineString'] except AssertionError: raise Type...
"""Linear referencing """ from shapely.topology import Delegating class LinearRefBase(Delegating): def _validate_line(self, ob): super(LinearRefBase, self)._validate(ob) if not ob.geom_type in ['LinearRing', 'LineString', 'MultiLineString']: raise TypeError("Only linear types support ...
Allow linear referencing on rings.
Allow linear referencing on rings. Closes #286. Eliminating the assert is good for optimization reasons, too.
Python
bsd-3-clause
abali96/Shapely,mouadino/Shapely,mindw/shapely,abali96/Shapely,jdmcbr/Shapely,jdmcbr/Shapely,mindw/shapely,mouadino/Shapely
6f6e16cfabb7c3ff3f634718b16f87bd7705d284
tests/v7/test_item_list.py
tests/v7/test_item_list.py
from .context import tohu from tohu.v7.item_list import ItemList def test_item_list(): values = [11, 55, 22, 66, 33] item_list = ItemList(values) assert item_list.items == values assert item_list == values assert len(item_list) == 5 assert item_list[3] == 66 assert [x for x in item_list] =...
from .context import tohu from tohu.v7.item_list import ItemList def test_item_list(): values = [11, 55, 22, 66, 33] item_list = ItemList(values) assert item_list.items == values assert item_list == values assert len(item_list) == 5 assert item_list[3] == 66 assert [x for x in item_list] =...
Add a couple more test cases for item list
Add a couple more test cases for item list
Python
mit
maxalbert/tohu
70b037496140dd2e9e6d71508835390f0c85bc02
skltn/metadata.py
skltn/metadata.py
# -*- coding: utf-8 -*- """Project metadata Information describing the project. """ # The package name, which is also the "UNIX name" for the project. package = 'my_module' project = "My Awesome Module" project_no_spaces = project.replace(' ', '') version = '0.1.0' description = 'It does cool things' authors = ['John...
# -*- coding: utf-8 -*- """Project metadata Information describing the project. """ import subprocess def get_author_detail(arg='name'): p = subprocess.Popen(['git', 'config', 'user.{}'.format(arg)], stdout=subprocess.PIPE) try: out, _ = p.communicate() except: ou...
Change year to 2016, try to guess author details from git config
Change year to 2016, try to guess author details from git config
Python
mit
ksonj/skltn
f9012b88f60f8e4ac96cb55aea763edc74ad586e
shell/view/BuddyIcon.py
shell/view/BuddyIcon.py
from sugar.canvas.MenuIcon import MenuIcon from view.BuddyMenu import BuddyMenu class BuddyIcon(MenuIcon): def __init__(self, shell, menu_shell, friend): MenuIcon.__init__(self, menu_shell, icon_name='stock-buddy', color=friend.get_color(), size=96) self._shell = shell self._friend = friend def set_p...
from sugar.canvas.MenuIcon import MenuIcon from view.BuddyMenu import BuddyMenu class BuddyIcon(MenuIcon): def __init__(self, shell, menu_shell, friend): MenuIcon.__init__(self, menu_shell, icon_name='stock-buddy', color=friend.get_color(), size=96) self._shell = shell self._friend = friend def set_p...
Move remove code down to fix undefined var error
Move remove code down to fix undefined var error
Python
lgpl-2.1
samdroid-apps/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit-gtk3,gusDuarte/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit,samdroid-apps/sugar-toolkit-gtk3,godiard/sugar-toolkit-gtk3,i5o/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit,godiard/sugar-toolkit-gtk3,Daksh/sugar-toolkit-gtk3,manuq/sugar-toolkit-gt...
de0bbf978695d206189ee4effb124234968525cb
django_afip/views.py
django_afip/views.py
from django.http import HttpResponse from django.utils.translation import ugettext as _ from django.views.generic import View from .pdf import generate_receipt_pdf class ReceiptHTMLView(View): def get(self, request, pk): return HttpResponse( generate_receipt_pdf(pk, request, True), )...
from django.http import HttpResponse from django.utils.translation import ugettext as _ from django.views.generic import View from .pdf import generate_receipt_pdf class ReceiptHTMLView(View): """Renders a receipt as HTML.""" def get(self, request, pk): return HttpResponse( generate_recei...
Add a view to display PDF receipts
Add a view to display PDF receipts Fixes #23 Closes !7 Closes !8
Python
isc
hobarrera/django-afip,hobarrera/django-afip
03d8a4e20ee4b6fd49495b7b047ea78d0b9a5bb4
dmoj/graders/base.py
dmoj/graders/base.py
class BaseGrader(object): def __init__(self, judge, problem, language, source): self.source = source self.language = language self.problem = problem self.judge = judge self.binary = self._generate_binary() self._terminate_grading = False self._current_proc = N...
class BaseGrader(object): def __init__(self, judge, problem, language, source): if isinstance(source, unicode): source = source.encode('utf-8') self.source = source self.language = language self.problem = problem self.judge = judge self.binary = self._gene...
Make source utf-8 encoded bytes.
Make source utf-8 encoded bytes.
Python
agpl-3.0
DMOJ/judge,DMOJ/judge,DMOJ/judge
a773d29d7bce78abea28209e53909ab52eee36a9
routes.py
routes.py
from flask import Flask, render_template from setup_cardsets import CardOperations co = CardOperations() app = Flask(__name__) @app.route('/') def home(): return render_template('home.html') @app.route('/rules') def rules(): return render_template('rules.html') @app.route('/setup') def setup(): return render_t...
from flask import Flask, render_template, redirect from setup_cardsets import CardOperations co = CardOperations() app = Flask(__name__) @app.route('/') def home(): return render_template('home.html') @app.route('/rules') def rules(): return render_template('rules.html') @app.route('/setup') def setup(): retur...
Use flask's redirect() method to go to result link
Use flask's redirect() method to go to result link
Python
mit
AlexMathew/tcg-ui
e14b3fad26dce8dad3ca97c06e624f1d6b0764f9
mqueue/__init__.py
mqueue/__init__.py
__version__ = '0.5.5' default_app_config = 'mqueue.apps.MqueueConfig'
__version__ = '0.5.5' default_app_config = 'mqueue.apps.MqueueConfig' import sys reload(sys) sys.setdefaultencoding("utf-8")
Set default encoding to fix unicode errors
Set default encoding to fix unicode errors
Python
mit
synw/django-mqueue,synw/django-mqueue,synw/django-mqueue
50836f606c5bdb9aa4472d109f0dc40e2f0f8dc6
examples/apc2016/download_dataset.py
examples/apc2016/download_dataset.py
#!/usr/bin/env python import os.path as osp import chainer import fcn.data import fcn.util def main(): dataset_dir = chainer.dataset.get_dataset_directory('apc2016') path = osp.join(dataset_dir, 'APC2016rbo.tgz') fcn.data.cached_download( url='https://drive.google.com/uc?id=0B9P1L--7Wd2vSV9oL...
#!/usr/bin/env python import os.path as osp import chainer import fcn def main(): dataset_dir = chainer.dataset.get_dataset_directory('apc2016') path = osp.join(dataset_dir, 'APC2016rbo.tgz') fcn.data.cached_download( url='https://drive.google.com/uc?id=0B9P1L--7Wd2vSV9oLTd1U2I3TDg', p...
Fix for renamed module util -> utils
Fix for renamed module util -> utils
Python
mit
wkentaro/fcn
3caab02c5e0ca0ebc57f57c77ed550b7e3fc55d2
analyze.py
analyze.py
import os import pickle import numpy as np import matplotlib.pyplot as plt from datetime import datetime def load_data(data_path): '''Return dictionary `data` from string `data_path` ''' os.path.join(data_path, '1.dat') data = pickle.load(open(data_path, 'rb')) return data def get_baseline(data...
import os import pickle import numpy as np import matplotlib.pyplot as plt from glob import glob from datetime import datetime def load_data(data_path): '''Return dictionary `data` from string `data_path` ''' os.path.join(data_path, '1.dat') data = pickle.load(open(data_path, 'rb')) return data ...
Add helper functions for loading data
Add helper functions for loading data
Python
mit
JustinShenk/sensei
82457741a352602f6ef946e387070c77eb50781c
examples/macallan.py
examples/macallan.py
# -*- coding: utf-8 -*- from malt import Malt, Response, json from wsgiref.simple_server import make_server app = Malt() @app.get('/') def hello(request): return Response(request.url + '\n') @app.post('/users') def hello(request): return Response('Creating new user\n') @app.get('/tasks') def hello(reque...
# -*- coding: utf-8 -*- from malt import Malt, Response, json from wsgiref.simple_server import make_server app = Malt() @app.get('/') def hello(request): return Response(request.url + '\n') @app.post('/users') def hello(request): return Response('Creating new user\n') @app.get('/tasks') def hello(reque...
Print a serving message in the example app
Print a serving message in the example app
Python
mit
nickfrostatx/malt
a3d65892ef572b115de919f62929e093dfb27400
examples/json_editor.py
examples/json_editor.py
""" This is a very basic usage example of the JSONCodeEdit. The interface is minimalist, it will open a test file. You can open other documents by pressing Ctrl+O """ import logging import os import sys from pyqode.qt import QtWidgets from pyqode.json.widgets import JSONCodeEdit class Window(QtWidgets.QMainWindow): ...
""" This is a very basic usage example of the JSONCodeEdit. The interface is minimalist, it will open a test file. You can open other documents by pressing Ctrl+O """ import logging import os import random import sys from pyqode.qt import QtWidgets from pyqode.core import api, modes from pyqode.json.widgets import JSO...
Make example use random color scheme
Make example use random color scheme
Python
mit
pyQode/pyqode.json,pyQode/pyqode.json
7d10c18c1feb0c61aee9d3a44c3a7fa24e4e3c25
code_snippets/guides-agentchecks-methods.py
code_snippets/guides-agentchecks-methods.py
self.gauge( ... ) # Sample a gauge metric self.increment( ... ) # Increment a counter metric self.decrement( ... ) # Decrement a counter metric self.histogram( ... ) # Sample a histogram metric self.rate( ... ) # Sample a point, with the rate calculated at the end of the check self.count( ... ) # Sample a raw coun...
self.gauge( ... ) # Sample a gauge metric self.increment( ... ) # Increment a counter metric self.decrement( ... ) # Decrement a counter metric self.histogram( ... ) # Sample a histogram metric self.rate( ... ) # Sample a point, with the rate calculated at the end of the check
Revert "Document AgentCheck count and monotonic_count methods"
Revert "Document AgentCheck count and monotonic_count methods" This reverts commit e731c3a4a8590f5cddd23fd2f9af265749f08a38.
Python
bsd-3-clause
inokappa/documentation,macobo/documentation,inokappa/documentation,jhotta/documentation,jhotta/documentation,jhotta/documentation,macobo/documentation,macobo/documentation,inokappa/documentation,jhotta/documentation,jhotta/documentation,jhotta/documentation,inokappa/documentation,inokappa/documentation,macobo/documenta...
6dd43f5fcd6af5582423af5a34a5fcf273026f1b
sirius/TI_V00/record_names.py
sirius/TI_V00/record_names.py
import sirius def get_record_names(family_name = None): """Return a dictionary of record names for given subsystem each entry is another dictionary of model families whose values are the indices in the pyaccel model of the magnets that belong to the family. The magnet models ca be segmented, in wh...
import sirius def get_record_names(family_name = None): """Return a dictionary of record names for given subsystem each entry is another dictionary of model families whose values are the indices in the pyaccel model of the magnets that belong to the family. The magnet models ca be segmented, in wh...
Change names of timing pvs
Change names of timing pvs
Python
mit
lnls-fac/sirius
d207bf14b30636959e09659607bddcf4e349852b
django_migration_linter/sql_analyser/__init__.py
django_migration_linter/sql_analyser/__init__.py
from .analyser import analyse_sql_statements # noqa from .base import BaseAnalyser # noqa from .mysql import MySqlAnalyser # noqa from .postgresql import PostgresqlAnalyser # noqa from .sqlite import SqliteAnalyser # noqa
from .base import BaseAnalyser # noqa from .mysql import MySqlAnalyser # noqa from .postgresql import PostgresqlAnalyser # noqa from .sqlite import SqliteAnalyser # noqa from .analyser import analyse_sql_statements # noqa isort:skip
Fix import order which was important
Fix import order which was important
Python
apache-2.0
3YOURMIND/django-migration-linter
5f113ffd768431991f87cea1f5f804a25a1777d3
frappe/patches/v13_0/replace_old_data_import.py
frappe/patches/v13_0/replace_old_data_import.py
# Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe def execute(): frappe.db.sql( """INSERT INTO `tabData Import Legacy` SELECT * FROM `tabData Import`""" ) frappe.db.commit() frappe.db.sql("DROP TABLE IF EXIS...
# Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe def execute(): frappe.rename_doc('DocType', 'Data Import', 'Data Import Legacy') frappe.db.commit() frappe.db.sql("DROP TABLE IF EXISTS `tabData Import`") frap...
Use rename doc instead of manually moving the data
fix: Use rename doc instead of manually moving the data
Python
mit
StrellaGroup/frappe,saurabh6790/frappe,mhbu50/frappe,yashodhank/frappe,frappe/frappe,yashodhank/frappe,almeidapaulopt/frappe,yashodhank/frappe,frappe/frappe,mhbu50/frappe,almeidapaulopt/frappe,adityahase/frappe,saurabh6790/frappe,frappe/frappe,adityahase/frappe,mhbu50/frappe,adityahase/frappe,almeidapaulopt/frappe,yash...
216294a0ea36c2fbabb43c31ce4fde3a9eee4bf3
anchor/models.py
anchor/models.py
# Copyright 2014 Dave Kludt # # 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, s...
# Copyright 2014 Dave Kludt # # 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, s...
Update model for CBS host and volume information
Update model for CBS host and volume information
Python
apache-2.0
oldarmyc/anchor,oldarmyc/anchor,oldarmyc/anchor
31fb8b576edda4d88685fd45537f68d3f067ae7b
source/cytoplasm/errors.py
source/cytoplasm/errors.py
class ControllerError(StandardError): pass class InterpreterError(StandardError): pass
class CytoplasmError(Exception): pass class ControllerError(CytoplasmError): pass class InterpreterError(CytoplasmError): pass
Use Exception instead of StandardError
Use Exception instead of StandardError Python 3 doesn't have StandardError...
Python
mit
startling/cytoplasm
a85c21dc324750c3fa7e96d2d0baf3c45657201e
sconsole/static.py
sconsole/static.py
''' Holds static data components, like the palette ''' def msg(msg, logfile='console_log.txt'): ''' Send a message to a logfile, defaults to console_log.txt. This is useful to replace a print statement since curses does put a bit of a damper on this ''' with open(logfile, 'a+') as fp_: ...
''' Holds static data components, like the palette ''' import pprint def tree_seed(): return {'jids': [ {'_|-76789876543456787654': [{'localhost': {'return': True}}, {'otherhost': {'return': True}}],}, {'_|-7678987654345678765...
Add convenience function to load in some test data
Add convenience function to load in some test data
Python
apache-2.0
saltstack/salt-console
401e60837c13af5a350b1487225a296c2e803069
Lib/test/test_dumbdbm.py
Lib/test/test_dumbdbm.py
#! /usr/bin/env python """Test script for the dumbdbm module Original by Roger E. Masse """ # XXX This test is a disgrace. It doesn't test that it works. import dumbdbm as dbm from dumbdbm import error from test_support import verbose filename = '/tmp/delete_me' d = dbm.open(filename, 'c') d['a'] = 'b' d['12345...
#! /usr/bin/env python """Test script for the dumbdbm module Original by Roger E. Masse """ # XXX This test is a disgrace. It doesn't test that it works. import dumbdbm as dbm from dumbdbm import error from test_support import verbose, TESTFN as filename d = dbm.open(filename, 'c') d['a'] = 'b' d['12345678910'] ...
Use a saner test filename, to work on Windows.
Use a saner test filename, to work on Windows.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
37ade5f4ce1feb44cdb7f8de1e373f5085c77a40
socrates.py
socrates.py
from socrates.main import main from socrates.bootstrap import run from optparse import OptionParser parser = OptionParser() parser.add_option('-i', '--init', action='store_true', help='Some help') parser.add_option('-g', '--generate', action='store_true', help='Some help') options, args = parser.parse_args() if opt...
from socrates.main import main from socrates.bootstrap import run from optparse import OptionParser parser = OptionParser() parser.add_option('-i', '--init', action='store_true', help='Some help') parser.add_option('-g', '--generate', action='store_true', help='Some help') parser.add_option('-r', '--run', action='sto...
Add simple server for testing purposes.
Add simple server for testing purposes.
Python
bsd-3-clause
thurloat/socrates,thurloat/socrates
cf245e71e770d21db8a48a74f8833d1099157e73
txircd/modules/ircv3/multiprefix.py
txircd/modules/ircv3/multiprefix.py
from twisted.plugin import IPlugin from txircd.module_interface import IModuleData, ModuleData from zope.interface import implements class MultiPrefix(ModuleData): implements(IPlugin, IModuleData) name = "MultiPrefix" def actions(self): return [ ("channelstatuses", 2, self.allStatuses), ("capabilit...
from twisted.plugin import IPlugin from txircd.module_interface import IModuleData, ModuleData from zope.interface import implements class MultiPrefix(ModuleData): implements(IPlugin, IModuleData) name = "MultiPrefix" def actions(self): return [ ("channelstatuses", 2, self.allStatuses), ("capabilit...
Reduce undoings of multi-prefix on users
Reduce undoings of multi-prefix on users
Python
bsd-3-clause
ElementalAlchemist/txircd,Heufneutje/txircd
1400a71d9827d76f14e70d4e8310dd20b9b47af4
life/life.py
life/life.py
import sys, random, time boardSize = (10,10) while True: foo, bar, baz, globals()['board'] = None if globals().get('board') is None else [ ( [sys.stdout.write('X' if cell else ' ') for cell in row], sys.stdout.write('\n') ) for row in board ], time.sleep(1), sys.stdout.writ...
import sys, random, time boardSize = (10,10) while True: foo, bar, baz, globals()['board'] = None if globals().get('board') is None else [ ( [sys.stdout.write('X' if cell else ' ') for cell in row], sys.stdout.write('\n') ) for row in board ], time.sleep(1), sys.stdout.writ...
Make separator line match width of board
Make separator line match width of board
Python
bsd-2-clause
bladams/golf
12f835d9060decfc675c81f7a1499b373b78f4cc
TrevorNet/tests/test_idx.py
TrevorNet/tests/test_idx.py
from .. import idx import os def test__count_dimensions(): yield check__count_dimensions, 9, 0 yield check__count_dimensions, [1, 2], 1 yield check__count_dimensions, [[1, 2], [3, 6, 2]], 2 yield check__count_dimensions, [[[1,2], [2]]], 3 def check__count_dimensions(lst, i): assert idx._count_dime...
from .. import idx import os def test__count_dimensions(): yield check__count_dimensions, 9, 0 yield check__count_dimensions, [1, 2], 1 yield check__count_dimensions, [[1, 2], [3, 6, 2]], 2 yield check__count_dimensions, [[[1,2], [2]]], 3 def check__count_dimensions(lst, i): assert idx._count_dime...
Fix issue where idx test uses wrong bytes object
Fix issue where idx test uses wrong bytes object Forgot to include the sizes of each dimension
Python
mit
tmerr/trevornet
f590080fc4d431b333f73ad548a50bc24d4fcf5b
fuzzer/main.py
fuzzer/main.py
import generator from ctypes import CDLL import numpy as np # Initializes the harness and sets it up for work harness = CDLL("harness/harness.so") while True: t = generator.generate() harness.register_testcase(t) try: exec(t, {'np':np}) except: # If the exec fails, then we should not s...
import generator from ctypes import CDLL import numpy as np # Initializes the harness and sets it up for work harness = CDLL("harness/harness.so") while True: t = generator.generate() harness.register_testcase(bytes(t, 'ascii')) try: exec(t, {'np':np}) except: # If the exec fails, then...
Send char string instead of widechar string
Send char string instead of widechar string
Python
apache-2.0
jaybosamiya/fuzzing-numpy,jaybosamiya/fuzzing-numpy,jaybosamiya/fuzzing-numpy
627729380b8fbd6d1b4e4eec0362418dbf698d55
libs/qpanel/upgrader.py
libs/qpanel/upgrader.py
# -*- coding: utf-8 -*- # # Copyright (C) 2015-2016 Rodrigo Ramírez Norambuena <a@rodrigoramirez.com> # from urllib2 import Request, urlopen from distutils.version import LooseVersion BRANCH = 'stable' REPO = 'git@github.com:roramirez/qpanel.git' URL_STABLE_VERSION = 'https://raw.githubusercontent.com/roramirez/qpan...
# -*- coding: utf-8 -*- # # Copyright (C) 2015-2016 Rodrigo Ramírez Norambuena <a@rodrigoramirez.com> # from urllib2 import Request, urlopen from distutils.version import LooseVersion BRANCH = 'stable' REPO = 'git@github.com:roramirez/qpanel.git' URL_STABLE_VERSION = 'https://rodrigoramirez.com/qpanel/version/' + BR...
Change url to get stable version number
Change url to get stable version number
Python
mit
roramirez/qpanel,roramirez/qpanel,skazancev/qpanel,skazancev/qpanel,skazancev/qpanel,roramirez/qpanel,roramirez/qpanel,skazancev/qpanel
798a716cb6c3acd6e636d3b9cab755950ead5539
Seeder/voting/signals.py
Seeder/voting/signals.py
# pylint: disable=W0613 from django.dispatch import receiver from django.db.models.signals import post_save from voting import constants from source.models import Source from voting.models import VotingRound from source import constants as source_constants from contracts.models import Contract @receiver(signal=post_...
# pylint: disable=W0613 from django.dispatch import receiver from django.db.models.signals import post_save from voting import constants from source.models import Source from voting.models import VotingRound from source import constants as source_constants from contracts.models import Contract @receiver(signal=post_...
Fix process_voting_round to reflect contract model
Fix process_voting_round to reflect contract model
Python
mit
WebArchivCZ/Seeder,WebArchivCZ/Seeder,WebArchivCZ/Seeder,WebArchivCZ/Seeder,WebArchivCZ/Seeder
856207c8399d94e99a6f2ffb1e10befecb6150cf
src/generate-jobs/calculate_quad_key.py
src/generate-jobs/calculate_quad_key.py
#!/usr/bin/env python """Calculate QuadKey for TSV file and append it as column Usage: calculate_quad_key.py <list_file> calculate_quad_key.py (-h | --help) calculate_quad_key.py --version Options: -h --help Show this screen. --version Show version. """ import system im...
#!/usr/bin/env python """Calculate QuadKey for TSV file and append it as column Usage: calculate_quad_key.py <list_file> calculate_quad_key.py (-h | --help) calculate_quad_key.py --version Options: -h --help Show this screen. --version Show version. """ import sys impor...
Fix line endings in CSV and stdout typo
Fix line endings in CSV and stdout typo
Python
mit
geometalab/osm2vectortiles,geometalab/osm2vectortiles,osm2vectortiles/osm2vectortiles,osm2vectortiles/osm2vectortiles
74ce850d7db766328e2931f5a8119b7e2e5b1ded
examples/basic_example.py
examples/basic_example.py
#!/usr/bin/env python ''' A simple script using sparqllib and rdflib to retrieve a JSON representation of some information about Barack Obama from dbpedia. ''' from sparqllib import Query from rdflib import BNode, Literal from rdflib.namespace import FOAF from pprint import pprint if __name__ == "__main__": # co...
#!/usr/bin/env python ''' A simple script using sparqllib and rdflib to retrieve a JSON representation of some information about Barack Obama from dbpedia. ''' from sparqllib import Query from rdflib import BNode, Literal from rdflib.namespace import FOAF from pprint import pprint def main(): # construct the que...
Switch to main method in examples
Switch to main method in examples
Python
mit
ALSchwalm/sparqllib
ee49f4f592cf04199f9d82c2da2af9e34dd1d9d4
avwx_api/views.py
avwx_api/views.py
""" Michael duPont - michael@mdupont.com avwx_api.views - Routes and views for the Quart application """ # pylint: disable=W0702 # stdlib from dataclasses import asdict # library import avwx from quart import Response, jsonify from quart_openapi.cors import crossdomain # module from avwx_api import app # Static Web ...
""" Michael duPont - michael@mdupont.com avwx_api.views - Routes and views for the Quart application """ # pylint: disable=W0702 # stdlib from dataclasses import asdict # library import avwx from quart import Response, jsonify from quart_openapi.cors import crossdomain # module from avwx_api import app # Static Web ...
Add error handling to station endpoint
Add error handling to station endpoint
Python
mit
flyinactor91/AVWX-API,flyinactor91/AVWX-API,flyinactor91/AVWX-API
c5c12e1f5aaeb56921b69cbb64a7d6a1b7585936
languages_plus/admin.py
languages_plus/admin.py
from django.contrib import admin from .models import Language, CultureCode class LanguageAdmin(admin.ModelAdmin): list_display = ('name_en', 'name_native', 'iso_639_1', 'iso_639_2T', 'iso_639_2B', 'iso_639_2T', 'iso_639_3', 'iso_639_6', 'notes') list_display_links = ('name_en',) class C...
from django.contrib import admin from .models import Language, CultureCode class LanguageAdmin(admin.ModelAdmin): list_display = ('name_en', 'name_native', 'iso_639_1', 'iso_639_2T', 'iso_639_2B', 'iso_639_2T', 'iso_639_3', 'iso_639_6', 'notes') list_display_links = ('name_en',) searc...
Define `search_fields` for Admin classes
Define `search_fields` for Admin classes This enables the search box on the admin change list page [1], and can be used by other apps like django-autocomplete-light [2]. 1: https://docs.djangoproject.com/en/1.7/ref/contrib/admin/#django.contrib.admin.ModelAdmin.search_fields 2: https://github.com/yourlabs/django-auto...
Python
mit
cordery/django-languages-plus
2b08ce1d980ff01c2f0ac258aaba52f2ca758427
beethoven/urls.py
beethoven/urls.py
from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns( '', url(r'^$', 'beethoven.views.index', name='index'), url(r'^admin/', include(admin.site.urls)), url(r'^', include('allauth.urls')), url(r'^', include('courses.urls', namespace='courses'))...
from django.conf.urls import patterns, include, url from django.contrib import admin from beethoven import settings urlpatterns = patterns( '', url(r'^$', 'beethoven.views.index', name='index'), url(r'^admin/', include(admin.site.urls)), url(r'^', include('allauth.urls')), url(r'^', include('cour...
Fix static file 404 error
Fix static file 404 error
Python
mit
lockhawksp/beethoven,lockhawksp/beethoven
6d0fa6dda7613e734ce958f88bc0eaf55cfddf3c
st2common/st2common/persistence/pack.py
st2common/st2common/persistence/pack.py
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use th...
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use th...
Add persistance class for ConfigSchema.
Add persistance class for ConfigSchema.
Python
apache-2.0
pixelrebel/st2,Plexxi/st2,emedvedev/st2,lakshmi-kannan/st2,StackStorm/st2,punalpatel/st2,Plexxi/st2,peak6/st2,StackStorm/st2,Plexxi/st2,pixelrebel/st2,StackStorm/st2,Plexxi/st2,punalpatel/st2,nzlosh/st2,emedvedev/st2,peak6/st2,emedvedev/st2,punalpatel/st2,peak6/st2,lakshmi-kannan/st2,tonybaloney/st2,nzlosh/st2,tonybalo...
f7e218b72a09615259b4d77e9169f5237a4cae32
mopidy/core/mixer.py
mopidy/core/mixer.py
from __future__ import absolute_import, unicode_literals import logging logger = logging.getLogger(__name__) class MixerController(object): pykka_traversable = True def __init__(self, mixer): self._mixer = mixer self._volume = None self._mute = False def get_volume(self): ...
from __future__ import absolute_import, unicode_literals import logging logger = logging.getLogger(__name__) class MixerController(object): pykka_traversable = True def __init__(self, mixer): self._mixer = mixer self._volume = None self._mute = False def get_volume(self): ...
Remove test-only code paths in MixerController
core: Remove test-only code paths in MixerController
Python
apache-2.0
jmarsik/mopidy,vrs01/mopidy,SuperStarPL/mopidy,diandiankan/mopidy,SuperStarPL/mopidy,mokieyue/mopidy,pacificIT/mopidy,vrs01/mopidy,diandiankan/mopidy,jcass77/mopidy,tkem/mopidy,glogiotatidis/mopidy,dbrgn/mopidy,bencevans/mopidy,bencevans/mopidy,SuperStarPL/mopidy,kingosticks/mopidy,swak/mopidy,glogiotatidis/mopidy,Supe...
47273357ac7bd646e8a9326c87688191eb8a1a89
airesources/Python/MyBot.py
airesources/Python/MyBot.py
from hlt import * from networking import * playerTag, gameMap = getInit() sendInit("BasicBot"+str(playerTag)) while True: moves = [] gameMap = getFrame() for y in range(0, len(gameMap.contents)): for x in range(0, len(gameMap.contents[y])): site = gameMap.contents[y][x] if site.owner == playerTag: dir...
from hlt import * from networking import * playerTag, gameMap = getInit() sendInit("PythonBot"+str(playerTag)) while True: moves = [] gameMap = getFrame() for y in range(0, len(gameMap.contents)): for x in range(0, len(gameMap.contents[y])): site = gameMap.contents[y][x] if site.owner == playerTag: mo...
Revert python mybot to random bot
Revert python mybot to random bot Former-commit-id: b08897ea13c57ce3700439954b432a6453fcfb3f Former-commit-id: 28471a6712bd57db5dc7fd6d42d614d2f7ae7069 Former-commit-id: 871c6ab61f365689493b0663b761317cfb786507
Python
mit
yangle/HaliteIO,yangle/HaliteIO,HaliteChallenge/Halite,HaliteChallenge/Halite-II,yangle/HaliteIO,lanyudhy/Halite-II,HaliteChallenge/Halite,HaliteChallenge/Halite-II,HaliteChallenge/Halite,HaliteChallenge/Halite-II,yangle/HaliteIO,HaliteChallenge/Halite,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge...
6a9524502ebf3c04dede24fb937baec5c48342ef
widgy/contrib/widgy_mezzanine/search_indexes.py
widgy/contrib/widgy_mezzanine/search_indexes.py
from haystack import indexes from widgy.contrib.widgy_mezzanine import get_widgypage_model from widgy.templatetags.widgy_tags import render_root from widgy.utils import html_to_plaintext from .signals import widgypage_pre_index WidgyPage = get_widgypage_model() class PageIndex(indexes.SearchIndex, indexes.Indexabl...
from haystack import indexes from widgy.contrib.widgy_mezzanine import get_widgypage_model from widgy.templatetags.widgy_tags import render_root from widgy.utils import html_to_plaintext from .signals import widgypage_pre_index WidgyPage = get_widgypage_model() class PageIndex(indexes.SearchIndex, indexes.Indexabl...
Use a more realistic context to render pages for search
Use a more realistic context to render pages for search The Mezzanine page middleware adds a page and _current_page to the context for pages, so our search index should too.
Python
apache-2.0
j00bar/django-widgy,j00bar/django-widgy,j00bar/django-widgy
edf08b9928558688c2402d1c144f04777f4b4bc5
gb/helpers.py
gb/helpers.py
"""Helpers to facilitate API interaction.""" # Spoken strings come to us as words, not numbers. NUM_WORD_INT = { 'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9 } # The same thing as NUM_WORD_INT, but already stringi...
"""Helpers to facilitate API interaction.""" from functools import wraps from datetime import datetime # Spoken strings come to us as words, not numbers. NUM_WORD_INT = { 'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': ...
Add caching feature to API lookup requests
Add caching feature to API lookup requests
Python
mit
jaykwon/giantanswers
750c7bef1483c914e195e26a179a3b362fa3f059
pmg/admin/validators.py
pmg/admin/validators.py
from wtforms.validators import AnyOf class BillEventTitleAllowed(object): """ Checks that the bill event title is one of the allowed titles when the event type is "bill-passed". """ ALLOWED_TITLES = [ 'Bill passed by the National Assembly and transmitted to the NCOP for concurrence', ...
from wtforms.validators import AnyOf from wtforms.compat import string_types, text_type class BillEventTitleAllowed(object): """ Checks that the bill event title is one of the allowed titles when the event type is "bill-passed". """ ALLOWED_TITLES = [ 'Bill passed by the National Assembly...
Format event title error message titles in quotation marks
Format event title error message titles in quotation marks
Python
apache-2.0
Code4SA/pmg-cms-2,Code4SA/pmg-cms-2,Code4SA/pmg-cms-2
fd176b8eae33cac5fa7b2ba4f7a7586d9e6ebf14
mlat/connection.py
mlat/connection.py
# -*- mode: python; indent-tabs-mode: nil -*- class Connection(object): """Interface for receiver connections. A receiver connection is something that can send messages (filter requests, multilateration results) to a particular receiver. A single connection may handle only a single receiver, or may m...
# -*- mode: python; indent-tabs-mode: nil -*- class Connection(object): """Interface for receiver connections. A receiver connection is something that can send messages (filter requests, multilateration results) to a particular receiver. A single connection may handle only a single receiver, or may m...
Raise NotImplemented if methods aren't overridden
Raise NotImplemented if methods aren't overridden
Python
agpl-3.0
tmuic/mlat-server,mutability/mlat-server,mutability/mlat-server,tmuic/mlat-server
8f2d6d2714aa1b60950a2fc355d39297b7f2cdfb
keras/activations.py
keras/activations.py
from __future__ import absolute_import from . import backend as K def softmax(x): return K.softmax(x) def softplus(x): return K.softplus(x) def relu(x, alpha=0., max_value=None): return K.relu(x, alpha=alpha, max_value=max_value) def tanh(x): return K.tanh(x) def sigmoid(x): return K.sigmo...
from __future__ import absolute_import from . import backend as K def softmax(x): ndim = K.ndim(x) if ndim == 2: return K.softmax(x) elif ndim == 3: # apply softmax to each timestep def step(x, states): return K.softmax(x), [] last_output, outputs, states = K.rn...
Add support for time-distributed softmax.
Add support for time-distributed softmax.
Python
mit
daviddiazvico/keras,DeepGnosis/keras,kemaswill/keras,keras-team/keras,relh/keras,keras-team/keras,dolaameng/keras,kuza55/keras,nebw/keras
0c833808e9c761a98e11ffb4834b8344221db1d5
matador/commands/deployment/deploy_sql_script.py
matador/commands/deployment/deploy_sql_script.py
#!/usr/bin/env python import os import shutil import subprocess from matador.session import Session from .deployment_command import DeploymentCommand from matador.commands.run_sql_script import run_sql_script class DeploySqlScript(DeploymentCommand): def _execute(self): scriptPath = self.args[0] ...
#!/usr/bin/env python import os import shutil import subprocess from matador.session import Session from .deployment_command import DeploymentCommand from matador.commands.run_sql_script import run_sql_script class DeploySqlScript(DeploymentCommand): def _execute(self): scriptPath = self.args[0] ...
Remove lines which deleted and checked out file for substitution
Remove lines which deleted and checked out file for substitution
Python
mit
Empiria/matador
05b2874c54658e451841637d534156c2407f0b0a
streak-podium/render.py
streak-podium/render.py
import matplotlib.pyplot as plt; plt.rcdefaults() import numpy as np def horizontal_bar(sorted_streaks, sort): """ Render a horizontal bar chart of streaks. Values have already been sorted by sort. """ # Only extract those users & streaks for streaks that are non-zero: users, streaks = zip(*[...
import matplotlib.pyplot as plt import numpy as np def horizontal_bar(sorted_streaks, sort): """ Render a horizontal bar chart of streaks. Values have already been sorted by sort. """ # Only extract those users & streaks for streaks that are non-zero: users, streaks = zip(*[(user, streak.get(...
Remove weird matplot lib defaults thing that did nothing
Remove weird matplot lib defaults thing that did nothing
Python
mit
jollyra/hubot-streak-podium,supermitch/streak-podium,jollyra/hubot-commit-streak,jollyra/hubot-streak-podium,jollyra/hubot-commit-streak,supermitch/streak-podium
242f27f943a107bf7dd2a472f08a71a8382f6467
mopidy/__init__.py
mopidy/__init__.py
import os import sys if not (2, 6) <= sys.version_info < (3,): sys.exit(u'Mopidy requires Python >= 2.6, < 3') VERSION = (0, 4, 0) def is_in_git_repo(): git_dir = os.path.abspath(os.path.join( os.path.dirname(__file__), '../.git')) return os.path.exists(git_dir) def get_git_version(): if not ...
import sys if not (2, 6) <= sys.version_info < (3,): sys.exit(u'Mopidy requires Python >= 2.6, < 3') from subprocess import PIPE, Popen VERSION = (0, 4, 0) def get_git_version(): process = Popen(['git', 'describe'], stdout=PIPE) if process.wait() != 0: raise Exception|('Execution of "git describe...
Use subprocess instead of os.popen
Use subprocess instead of os.popen
Python
apache-2.0
ZenithDK/mopidy,bacontext/mopidy,adamcik/mopidy,kingosticks/mopidy,jcass77/mopidy,jmarsik/mopidy,bacontext/mopidy,mopidy/mopidy,hkariti/mopidy,bencevans/mopidy,ZenithDK/mopidy,dbrgn/mopidy,hkariti/mopidy,SuperStarPL/mopidy,jodal/mopidy,adamcik/mopidy,jcass77/mopidy,jodal/mopidy,vrs01/mopidy,ali/mopidy,diandiankan/mopid...
5ac7c07277ef1c7e714336e1b96571cdfea15a13
ktbs_bench_manager/benchable_graph.py
ktbs_bench_manager/benchable_graph.py
import logging from rdflib import Graph class BenchableGraph(object): """ Provides a convenient way to use a graph for benchmarks. """ def __init__(self, store, graph_id, store_config, graph_create=False): """ :param str store: Type of store to use. :param str graph_id: The g...
from rdflib import Graph class BenchableGraph(object): """ Provides a convenient way to use a graph for benchmarks. """ def __init__(self, store, graph_id, store_config, graph_create=False): """ :param str store: Type of store to use. :param str graph_id: The graph identifier....
Remove unnecessary import of logging
Remove unnecessary import of logging
Python
mit
vincent-octo/ktbs_bench_manager,vincent-octo/ktbs_bench_manager
81f4f4b1318ff800e3febbc1bd7bbd9ff8e868b1
node/dictionary.py
node/dictionary.py
#!/usr/bin/env python from nodes import Node import json class Dictionary(Node): char = ".d" args = 0 results = 1 def __init__(self, word_ids:Node.IntList): if not hasattr(Dictionary, "word_list"): Dictionary.word_list = init_words() self.words = " ".join(Dictionary.wo...
#!/usr/bin/env python from nodes import Node import json class Dictionary(Node): char = ".d" args = 0 results = 1 def __init__(self, word_ids:Node.IntList): if not hasattr(Dictionary, "word_list"): Dictionary.word_list = init_words() self.words = " ".join(Dictionary.wo...
Add some exception handling for dict
Add some exception handling for dict
Python
mit
muddyfish/PYKE,muddyfish/PYKE
bb3605bd99892bed37ecb2b6371d2bc88d599e1a
caso/__init__.py
caso/__init__.py
# -*- coding: utf-8 -*- # Copyright 2014 Spanish National Research Council (CSIC) # # 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 # # Unle...
# -*- coding: utf-8 -*- # Copyright 2014 Spanish National Research Council (CSIC) # # 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 # # Unle...
Include "OpenStack" string in the user agent
Include "OpenStack" string in the user agent EGI's accounting team requires that we put "OpenStack" in the UA string. closes IFCA/caso#38
Python
apache-2.0
alvarolopez/caso,IFCA/caso,IFCA/caso
ebf5e05acfb7f1edce0c0987576ee712f3fdea54
test/scripts/test_sequana_coverage.py
test/scripts/test_sequana_coverage.py
from sequana.scripts import coverage from nose.plugins.attrib import attr from sequana import sequana_data #@attr("skip") class TestPipeline(object): @classmethod def setup_class(klass): """This method is run once for each class before any tests are run""" klass.prog = "sequana_coverage" ...
from sequana.scripts import coverage from sequana import sequana_data import pytest prog = "sequana_coverage" @pytest.fixture def coveragefix(): import os # local nosetests execution try:os.remove('README') except:pass try:os.remove('quality.rules') except:pass try:os.remove('config.yaml')...
Fix tests to use pytest
Fix tests to use pytest
Python
bsd-3-clause
sequana/sequana,sequana/sequana,sequana/sequana,sequana/sequana,sequana/sequana
2b5c186337bcb396f630c0b86938e43eb06d3e5b
tests/test_i10knobs.py
tests/test_i10knobs.py
from pkg_resources import require require("cothread") require("mock") import unittest import mock import sys # Mock out catools as it requires EPICS binaries at import sys.modules['cothread.catools'] = mock.MagicMock() import cothread import sys import os from PyQt4 import QtGui sys.path.append(os.path.join(os.path.d...
from pkg_resources import require require("cothread") require("mock") import unittest import mock import sys # Mock out catools as it requires EPICS binaries at import sys.modules['cothread.catools'] = mock.MagicMock() import cothread import sys import os from PyQt4 import QtGui sys.path.append(os.path.join(os.path.d...
Add test checking only for imports
Add test checking only for imports
Python
apache-2.0
dls-controls/i10switching,dls-controls/i10switching
a55dd124d54955476411ee8ae830c9fd3c4f00dc
tests/test_pdfbuild.py
tests/test_pdfbuild.py
from latex import build_pdf from latex.exc import LatexBuildError import pytest def test_generates_something(): min_latex = r""" \documentclass{article} \begin{document} Hello, world! \end{document} """ pdf = build_pdf(min_latex) assert pdf def test_raises_correct_exception_on_fail(): broken_late...
from latex import build_pdf, LatexBuildError from latex.errors import parse_log import pytest def test_generates_something(): min_latex = r""" \documentclass{article} \begin{document} Hello, world! \end{document} """ pdf = build_pdf(min_latex) assert pdf def test_raises_correct_exception_on_fail(): ...
Test get_errors() method of LatexBuildError.
Test get_errors() method of LatexBuildError.
Python
bsd-3-clause
mbr/latex
8535c59c26e2c5badfd3637d41901f1bc987e200
tests/test_requests.py
tests/test_requests.py
"""Test the api_requests module.""" from pytest import mark from gobble.api_requests import APIRequest SIMPLE = ('foo.bar', dict(), ['https://foo.bar']) LOCAL = ('0.0.0.0', dict(port=5000, schema='http'), ['http://0.0.0.0:5000']) LONG = ( 'foo.bar', dict( path=['spam', 'eggs'], query={'foo': ...
"""Test the api_requests module.""" from pytest import mark from gobble.api_requests import APIRequest SIMPLE = ('foo.bar', dict(), ['https://foo.bar']) LOCAL = ('0.0.0.0', dict(port=5000, schema='http'), ['http://0.0.0.0:5000']) LONG = ( 'foo.bar', dict( path=['spam', 'eggs'], query={'foo': ...
Add a test for the __call__ method of the APIRequest class.
Add a test for the __call__ method of the APIRequest class.
Python
mit
openspending/gobble
ca7403462588f374cf1af39d537765c02fc7726c
mctrl/rest.py
mctrl/rest.py
from flask import Flask, url_for, Response, json, request class MonitorApp(object): def __init__(self, monitor): self.app = Flask(__name__) self.app.monitor = monitor self.setup() def setup(self): @self.app.route('/anomaly', methods = ['POST']) def api_anomaly(): ...
from flask import Flask, url_for, Response, json, request class MonitorApp(object): def __init__(self, monitor): self.app = Flask(__name__) self.app.monitor = monitor self.setup() def setup(self): @self.app.route('/anomaly', methods = ['POST']) def api_anomaly(): ...
Fix status codes of handled responses
Fix status codes of handled responses
Python
apache-2.0
h2020-endeavour/endeavour,h2020-endeavour/endeavour
87bf261345919e90cb88853165fb1556046c80ef
tests/mpd/protocol/test_connection.py
tests/mpd/protocol/test_connection.py
from __future__ import absolute_import, unicode_literals from mock import patch from tests.mpd import protocol class ConnectionHandlerTest(protocol.BaseTestCase): def test_close_closes_the_client_connection(self): with patch.object(self.session, 'close') as close_mock: self.send_request('cl...
from __future__ import absolute_import, unicode_literals from mock import patch from tests.mpd import protocol class ConnectionHandlerTest(protocol.BaseTestCase): def test_close_closes_the_client_connection(self): with patch.object(self.session, 'close') as close_mock: self.send_request('cl...
Fix typo in mock usage
tests: Fix typo in mock usage The error was made evident by a newer mock version that no longer swallowed the wrong assert as regular use of a spec-less mock.
Python
apache-2.0
hkariti/mopidy,bencevans/mopidy,diandiankan/mopidy,dbrgn/mopidy,kingosticks/mopidy,mopidy/mopidy,ali/mopidy,jmarsik/mopidy,quartz55/mopidy,mopidy/mopidy,vrs01/mopidy,diandiankan/mopidy,ali/mopidy,adamcik/mopidy,pacificIT/mopidy,tkem/mopidy,pacificIT/mopidy,dbrgn/mopidy,adamcik/mopidy,hkariti/mopidy,jmarsik/mopidy,vrs01...
e34bcec834bf4d84168d04a1ea0a98613ad0df4e
corehq/apps/locations/management/commands/migrate_new_location_fixture.py
corehq/apps/locations/management/commands/migrate_new_location_fixture.py
from django.core.management.base import BaseCommand from toggle.models import Toggle from corehq.apps.locations.models import LocationFixtureConfiguration, SQLLocation from corehq.toggles import FLAT_LOCATION_FIXTURE class Command(BaseCommand): help = """ To migrate to new flat fixture for locations. Update ...
import json from django.core.management.base import BaseCommand from toggle.models import Toggle from corehq.apps.locations.models import SQLLocation from corehq.apps.domain.models import Domain from corehq.toggles import HIERARCHICAL_LOCATION_FIXTURE, NAMESPACE_DOMAIN class Command(BaseCommand): help = """ ...
Update migration to fetch domains with applications using old location fixture
Update migration to fetch domains with applications using old location fixture
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
a17ed4f65b7fa5a035efb7c6ff19fcf477a65429
categories_i18n/managers.py
categories_i18n/managers.py
""" The manager classes. """ import django from django.db.models.query import QuerySet from mptt.managers import TreeManager from mptt.querysets import TreeQuerySet from parler.managers import TranslatableManager, TranslatableQuerySet class CategoryQuerySet(TranslatableQuerySet, TreeQuerySet): """ The Querys...
""" The manager classes. """ import django from django.db.models.query import QuerySet from mptt.managers import TreeManager from mptt.querysets import TreeQuerySet from parler.managers import TranslatableManager, TranslatableQuerySet class CategoryQuerySet(TranslatableQuerySet, TreeQuerySet): """ The Querys...
Remove remaining django-mptt 0.7 compatibility code
Remove remaining django-mptt 0.7 compatibility code
Python
apache-2.0
edoburu/django-categories-i18n,edoburu/django-categories-i18n
e775613d43dac702565cf266d9995c9cd706d7c8
pwndbg/commands/cpsr.py
pwndbg/commands/cpsr.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import gdb import pwndbg.arch import pwndbg.color import pwndbg.commands import pwndbg.regs @pwndbg.commands.Command @pwndbg.commands.OnlyWhenRunning def cpsr(): if pwndbg.arch.current != 'arm': print("This is only availabl...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import gdb import pwndbg.arch import pwndbg.color import pwndbg.commands import pwndbg.regs @pwndbg.commands.Command @pwndbg.commands.OnlyWhenRunning def cpsr(): 'Print out the ARM CPSR register' if pwndbg.arch.current != 'arm'...
Add documentation for the CPSR command
Add documentation for the CPSR command
Python
mit
0xddaa/pwndbg,pwndbg/pwndbg,anthraxx/pwndbg,pwndbg/pwndbg,disconnect3d/pwndbg,zachriggle/pwndbg,anthraxx/pwndbg,pwndbg/pwndbg,disconnect3d/pwndbg,anthraxx/pwndbg,cebrusfs/217gdb,pwndbg/pwndbg,chubbymaggie/pwndbg,chubbymaggie/pwndbg,disconnect3d/pwndbg,zachriggle/pwndbg,0xddaa/pwndbg,cebrusfs/217gdb,cebrusfs/217gdb,0xdd...
91eca37144d0c378761e47c143e66a79af37c226
repo_manage/forms.py
repo_manage/forms.py
from django import forms from django.forms import ModelForm from django.forms.models import inlineformset_factory from common.models import Repository, Collaboration, User slug_errors = { 'invalid' : "Use only letters, numbers, underscores, and hyphens", } class NewRepositoryForm(forms.Form): repo_name ...
from django import forms from django.forms import ModelForm from django.forms.models import inlineformset_factory from common.models import Repository, Collaboration, User slug_errors = { 'invalid' : "Use only letters, numbers, underscores, and hyphens", } class NewRepositoryForm(forms.Form): repo_name ...
Fix IntegrityError and DoesNotExist 500s
Fix IntegrityError and DoesNotExist 500s
Python
mit
vault/bugit,vault/bugit,vault/bugit
f6ddd5c4d79ada59d9db4b467849d9b52c5fef75
landlab/field/__init__.py
landlab/field/__init__.py
from landlab.field.scalar_data_fields import ScalarDataFields, FieldError from landlab.field.grouped import ModelDataFields, GroupError, GroupSizeError from landlab.field.field_mixin import ModelDataFieldsMixIn __all__ = ['ScalarDataFields', 'ModelDataFields', 'ModelDataFieldsMixIn', 'FieldError', 'GroupErr...
from landlab.field.scalar_data_fields import ScalarDataFields, FieldError from landlab.field.grouped import ModelDataFields, GroupError, GroupSizeError from landlab.field.field_mixin import ModelDataFieldsMixIn from .graph_field import GraphFields __all__ = ['ScalarDataFields', 'ModelDataFields', 'ModelDataFieldsMixIn...
Add GraphFields to package import.
Add GraphFields to package import.
Python
mit
cmshobe/landlab,cmshobe/landlab,cmshobe/landlab,RondaStrauch/landlab,amandersillinois/landlab,RondaStrauch/landlab,landlab/landlab,Carralex/landlab,RondaStrauch/landlab,landlab/landlab,amandersillinois/landlab,csherwood-usgs/landlab,Carralex/landlab,Carralex/landlab,csherwood-usgs/landlab,landlab/landlab
75f236f8fd0ba368197da3070002b60233a01d49
tests/test_track_bed.py
tests/test_track_bed.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2015 by Gaik Tamazian # gaik (dot) tamazian (at) gmail (dot) com import os import logging import unittest from chromosomer.track.bed import BedRecord from chromosomer.track.bed import Reader path = os.path.dirname(__file__) os.chdir(path) class TestBedR...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2015 by Gaik Tamazian # gaik (dot) tamazian (at) gmail (dot) com import os import logging import unittest from chromosomer.track.bed import BedRecord from chromosomer.track.bed import Reader from chromosomer.track.bed import Writer from itertools import iz...
Test routines to the BED writer added
Test routines to the BED writer added
Python
mit
gtamazian/Chromosomer
9e666e97b07d7c08e434791a061086010da6e6eb
main.py
main.py
# -*- utf-8 -*- import config import requests from base64 import b64encode def get_access_token(): token = config.twitter_key + ':' + config.twitter_secret h = {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', 'Authorization': b'Basic ' + b64encode(bytes(token, 'utf8'))} print(...
# -*- coding: utf-8 -*- import config import requests from base64 import b64encode def get_access_token(): token = config.twitter_key + ':' + config.twitter_secret h = {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', 'Authorization': b'Basic ' + b64encode(bytes(token, 'utf8'))} ...
Add ability to get the latest TwoHeadlines tweet
Add ability to get the latest TwoHeadlines tweet
Python
mit
underyx/TheMajorNews
789ac1de1e94eda1224fb314ccad14c061c58ad4
pact/group.py
pact/group.py
from .base import PactBase from .utils import GroupWaitPredicate class PactGroup(PactBase): def __init__(self, pacts): self._pacts = list(pacts) super(PactGroup, self).__init__() def __iadd__(self, other): self._pacts.append(other) return self def _is_finished(self): ...
from .base import PactBase from .utils import GroupWaitPredicate class PactGroup(PactBase): def __init__(self, pacts=None): self._pacts = [] if pacts is None else list(pacts) super(PactGroup, self).__init__() def __iadd__(self, other): self._pacts.append(other) return self ...
Create empty PactGroup if no arguments given
Create empty PactGroup if no arguments given
Python
bsd-3-clause
vmalloc/pact
d1ec190f1a4dc84db0540481f2489f1db8421799
oemof_pg/db.py
oemof_pg/db.py
from sqlalchemy import create_engine import keyring from . import config as cfg def connection(): engine = create_engine( "postgresql+psycopg2://{user}:{passwd}@{host}:{port}/{db}".format( user=cfg.get("postGIS", "username"), passwd=keyring.get_password( cfg.get("po...
from configparser import NoOptionError as option, NoSectionError as section from sqlalchemy import create_engine import keyring from . import config as cfg def connection(): pw = keyring.get_password(cfg.get("postGIS", "database"), cfg.get("postGIS", "username")) if pw is None: ...
Enable specifying the password in `config.ini`
Enable specifying the password in `config.ini`
Python
mit
oemof/oemof.db
901a47adf6726d50c01ac743e9661c0caac2b555
test_openfolder.py
test_openfolder.py
import pytest from mock import patch, MagicMock from open_folder import * def test_folder_exists(): with patch('subprocess.check_call', MagicMock(return_value="NOOP")): result = open_folder(".") assert result == None def test_folder_does_not_exists(): with patch('subprocess.check_call', Magic...
import pytest from mock import patch, MagicMock from open_folder import * def test_folder_exists(): with patch('subprocess.check_call', MagicMock(return_value="NOOP")): result = open_folder(".") assert result == None def test_folder_does_not_exists(): with patch('subprocess.check_call', Magic...
Check to ensure the excpetions return the text we expect.
Check to ensure the excpetions return the text we expect.
Python
mit
golliher/dg-tickler-file
ea972c89cd7abe4fdb772ce359dd9acd83817242
tests/test.py
tests/test.py
from devicehive import Handler from devicehive import DeviceHive class TestHandler(Handler): """Test handler class.""" def handle_connect(self): if not self.options['handle_connect'](self): self.api.disconnect() def handle_event(self, event): pass class Test(object): ""...
from devicehive import Handler from devicehive import DeviceHive class TestHandler(Handler): """Test handler class.""" def handle_connect(self): if not self.options['handle_connect'](self): self.api.disconnect() def handle_event(self, event): pass class Test(object): ""...
Add http_transport and websocket_transport methods
Add http_transport and websocket_transport methods
Python
apache-2.0
devicehive/devicehive-python
42a4a8b4480bc481e0467ae7ee46c60400d63f77
theme-installer.py
theme-installer.py
#!/usr/bin/env python import sys from inc.functions import * from PySide.QtGui import QApplication, QPixmap, QSplashScreen from ui.mainwindow import MainWindow # The app if __name__ == '__main__': # Create app app = QApplication(sys.argv) app.setApplicationName('LMMS Theme Installer') # Show window window = Mai...
#!/usr/bin/env python import sys from inc.functions import * from PySide.QtGui import QApplication, QPixmap, QSplashScreen from ui.mainwindow import MainWindow # Create tmp directory if it doesn't exist if not os.path.exists(os.path.join(os.getcwd(), 'tmp')): os.mkdir(os.path.join(os.getcwd(), 'tmp')) # The app if ...
Create tmp directory if it doesn't exist
Create tmp directory if it doesn't exist
Python
lgpl-2.1
kmklr72/LMMS-Theme-Installer
dd40b392b73ddc1bcf88d932418b4f891bcc6a89
twine/__init__.py
twine/__init__.py
# Copyright 2013 Donald Stufft # # 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, so...
# Copyright 2013 Donald Stufft # # 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, so...
Allow star imports from twine
Allow star imports from twine Unicode literals on Python 2 prevent people from being able to use from twine import * Closes gh-209 (cherry picked from commit c2cd72d0f4ff4d380845333fbfaaf2c92d6a5674)
Python
apache-2.0
pypa/twine
0c84f6dd314ea62019356b09363f98118a4da776
txircd/factory.py
txircd/factory.py
from twisted.internet.protocol import ClientFactory, Factory from txircd.server import IRCServer from txircd.user import IRCUser from ipaddress import ip_address import re ipv4MappedAddr = re.compile("::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})") def unmapIPv4(ip: str) -> str: """ Converts an IPv6-mapped IPv4 addres...
from twisted.internet.protocol import ClientFactory, Factory from txircd.server import IRCServer from txircd.user import IRCUser from ipaddress import ip_address from typing import Union def unmapIPv4(ip: str) -> Union["IPv4Address", "IPv6Address"]: """ Converts an IPv6-mapped IPv4 address to a bare IPv4 address. "...
Use built-in IP address functionality to unmap IPv4 addresses
Use built-in IP address functionality to unmap IPv4 addresses
Python
bsd-3-clause
Heufneutje/txircd
bee5ed1d9815a4c4291179d0de3ec54fe467b219
project.py
project.py
import os, cPickle as pickle import fileutil class Project(object): def __init__(self, name, rootdir, filename, session=None): self.name = name self.rootdir = rootdir self.filename = filename self.session = session def read_project(filename, rootdir): with open(filename, "rb") ...
import os import json import fileutil class Project(object): def __init__(self, name, rootdir, filename, session=None): self.name = name self.rootdir = rootdir self.filename = filename self.session = session def read_project(filename, rootdir): with open(filename, "rb") as f: ...
Save sessions in JSON format instead of pickle.
Save sessions in JSON format instead of pickle.
Python
mit
shaurz/devo
a587d48694690957934a159bad98cacd3f012a6a
cms/tests/test_externals.py
cms/tests/test_externals.py
from django.test import TestCase from ..externals import External from contextlib import GeneratorContextManager from types import FunctionType class TestExternals(TestCase): def test_load(self): external = External('foo') with self.assertRaises(ImportError): external._load('') ...
from django.test import TestCase from ..externals import External try: from contextlib import GeneratorContextManager except ImportError: from contextlib import _GeneratorContextManager as GeneratorContextManager from types import FunctionType class TestExternals(TestCase): def test_load(self): ...
Change contextlib import to handle the new location in Python 3.
Change contextlib import to handle the new location in Python 3.
Python
bsd-3-clause
danielsamuels/cms,jamesfoley/cms,jamesfoley/cms,jamesfoley/cms,dan-gamble/cms,danielsamuels/cms,dan-gamble/cms,lewiscollard/cms,jamesfoley/cms,dan-gamble/cms,lewiscollard/cms,danielsamuels/cms,lewiscollard/cms
278069a0637f7f329ceaff0975e3b95d609a7b9f
cosmoscope/cli.py
cosmoscope/cli.py
# -*- coding: utf-8 -*- """Console script for cosmoscope.""" import sys import click @click.command() def main(args=None): """Console script for cosmoscope.""" click.echo("Replace this message by putting your code into " "cosmoscope.cli.main") click.echo("See click documentation at http://...
# -*- coding: utf-8 -*- """Console script for cosmoscope.""" import sys import click from .core.server import launch @click.command() @click.option('--server-address', default="tcp://127.0.0.1:4242", help="Server IP address.") @click.option('--publisher-address', default="tcp://127.0.0.1:4243", help="Publisher IP a...
Improve the command line interface
Improve the command line interface
Python
mit
cosmoscope/cosmoscope
4efa9c87264eabb6712f4fb787ab0de42be18de6
places/urls.py
places/urls.py
from django.conf.urls import url from . import views app_name = 'places' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<slug>[-\w]+)/$', views.PlaceView.as_view(), name='place'), ]
from django.urls import include, path from . import views app_name = 'places' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<slug:slug>/', views.PlaceView.as_view(), name='place'), ]
Move places urlpatterns to Django 2.0 preferred method
Move places urlpatterns to Django 2.0 preferred method
Python
mit
evanepio/dotmanca,evanepio/dotmanca,evanepio/dotmanca
a9dc245f99e5c29f3b11cadc77dcfa0f44274b74
ctfbackend/backend/urls.py
ctfbackend/backend/urls.py
from django.conf.urls import url, include from django.http import HttpResponseRedirect from django.conf import settings from django.contrib.auth import views as auth_views from . import views urlpatterns = [ # Authentication ## Override logout next_page url(r'^accounts/logout/$', auth_views.logout, {'next_...
from django.conf.urls import url, include from django.contrib.auth import views as auth_views from . import views from django.contrib.auth.decorators import login_required urlpatterns = [ # Authentication ## Override logout next_page url(r'^accounts/logout/$', auth_views.logout, {'next_page...
Add login_required decorator to protected sites
Add login_required decorator to protected sites
Python
agpl-3.0
c0d3z3r0/ctf-backend,c0d3z3r0/ctf-backend,c0d3z3r0/ctf-backend,c0d3z3r0/ctf-backend
6ff6f7ecf75551dc49685c4bb0501e6f4b2de854
packages/Python/lldbsuite/test/expression_command/vector_of_enums/TestVectorOfEnums.py
packages/Python/lldbsuite/test/expression_command/vector_of_enums/TestVectorOfEnums.py
""" Test Expression Parser regression test to ensure that we handle enums correctly, in this case specifically std::vector of enums. """ import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class TestVectorOfEnums(TestBase): mydir = TestBase...
""" Test Expression Parser regression test to ensure that we handle enums correctly, in this case specifically std::vector of enums. """ import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class TestVectorOfEnums(TestBase): mydir = TestBase...
Fix for regression test, since we rely on the formatter for std::vector in the test we need a libc++ category.
Fix for regression test, since we rely on the formatter for std::vector in the test we need a libc++ category. See differential https://reviews.llvm.org/D59847 for initial change that this fixes git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@357210 91177308-0d34-0410-b5e6-96231b3b80d8
Python
apache-2.0
llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb
df7e834b8418aeeeaee7fb90b953468c2490b93d
pypiup/cli.py
pypiup/cli.py
import os import click from pypiup.requirements import Requirements BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @click.command() @click.option('--requirement', '-r', default='requirements.txt', type=click.STRING, help='Specify the path of the requirements file. Defaults to "requirements.t...
import __init__ import os import click from pypiup.requirements import Requirements BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @click.command() @click.option('--requirement', '-r', default='requirements.txt', type=click.STRING, help='Specify the path of the requirements file. Defaults to...
Add Ascii Art & Version Number
Add Ascii Art & Version Number
Python
bsd-2-clause
ekonstantinidis/pypiup
6c9a3e5133115a4724c8499380ee690a9cca0552
pmagpy/__init__.py
pmagpy/__init__.py
from __future__ import absolute_import from . import pmag from . import ipmag from . import pmagplotlib from . import find_pmag_dir from . import version from . import controlled_vocabularies2 as controlled_vocabularies from . import data_model3 from . import new_builder from . import mapping #import set_env __all__ =...
from __future__ import absolute_import import sys if sys.version_info <= (3,): raise Exception(""" You are running Python {}. This version of pmagpy is only compatible with Python 3. Make sure you have pip >= 9.0 to avoid this kind of issue, as well as setuptools >= 24.2: $ pip install pip setuptools --upgrade T...
Add Exception on import of pmagpy if using wrong Python version (should be impossible to install this version, but people are tricky….)
Add Exception on import of pmagpy if using wrong Python version (should be impossible to install this version, but people are tricky….)
Python
bsd-3-clause
lfairchild/PmagPy,lfairchild/PmagPy,Caoimhinmg/PmagPy,lfairchild/PmagPy,Caoimhinmg/PmagPy,Caoimhinmg/PmagPy
d3cbcfa3d134ef7ce158f229eff75a83418afc52
tools/dmqmc/extract_n_k.py
tools/dmqmc/extract_n_k.py
#!/usr/bin/env python '''Extract the momentum distribution from a analysed DMQMC simulation.''' import pandas as pd import numpy as np import sys # [review] - JSS: use if __name__ == '__main__' and functions so code can easily be reused in another script if necessary. if (len(sys.argv) < 2): print ("Usage: extra...
#!/usr/bin/env python '''Extract the momentum distribution from an analysed DMQMC simulation.''' import pandas as pd import numpy as np import sys def main(args): if (len(sys.argv) < 2): print ("Usage: extract_n_k.py file bval") sys.exit() bval = float(sys.argv[2]) data = pd.read_csv(s...
Write the extraction script properly.
Write the extraction script properly.
Python
lgpl-2.1
hande-qmc/hande,hande-qmc/hande,hande-qmc/hande,hande-qmc/hande,hande-qmc/hande
bea80411c13ed72b1e7d5a5ac79fdba64b4b4661
benchmarks/benchmarks/sparse_csgraph_djisktra.py
benchmarks/benchmarks/sparse_csgraph_djisktra.py
"""benchmarks for the scipy.sparse.csgraph module""" import numpy as np import scipy.sparse from .common import Benchmark, safe_import with safe_import(): from scipy.sparse.csgraph import dijkstra class Dijkstra(Benchmark): params = [ [30, 300, 900], [True, False] ] param_names = ['n...
"""benchmarks for the scipy.sparse.csgraph module""" import numpy as np import scipy.sparse from .common import Benchmark, safe_import with safe_import(): from scipy.sparse.csgraph import dijkstra class Dijkstra(Benchmark): params = [ [30, 300, 900], [True, False], ['random', 'star']...
Add star graph for sparse.csgraph.dijkstra benchmark
ENH: Add star graph for sparse.csgraph.dijkstra benchmark
Python
bsd-3-clause
scipy/scipy,scipy/scipy,scipy/scipy,scipy/scipy,scipy/scipy,scipy/scipy
d1fd32946ba422e8f240bd44bffab3107f4d1057
pymoji/__init__.py
pymoji/__init__.py
"""Python Library Boilerplate contains all the boilerplate you need to create a Python package.""" __author__ = 'Michael Joseph' __email__ = 'michaeljoseph@gmail.com' __url__ = 'https://github.com/michaeljoseph/pymoji' __version__ = '0.0.1' def pymoji(): return 'Hello World!'
"""Emits HTML from emoji""" __author__ = 'Michael Joseph' __email__ = 'michaeljoseph@gmail.com' __url__ = 'https://github.com/michaeljoseph/pymoji' __version__ = '0.0.1' from .emoji import emoji def pymoji(text): if text[0] <> text[:-1] and text[0] <> ':': text = ':%s:' % text return emoji(text)
Return the emoji and format it
Return the emoji and format it
Python
apache-2.0
michaeljoseph/pymoji,michaeljoseph/pymoji
bca6ca83ce43f6d9b96ac590bda9c6253384ab69
winthrop/people/viaf.py
winthrop/people/viaf.py
import requests from django.conf import settings class ViafAPI(object): """Wrapper for ViafAPI""" def __init__(self): default_url = 'https://www.viaf.org/viaf/AutoSuggest?query=' self.base_url = getattr(settings, "VIAF_AUTOSUGGEST_URL", default_url) def search(self, query): """Do...
import json import requests class ViafAPI(object): """Wrapper for Viaf API""" def __init__(self): self.base_url = "https://www.viaf.org/" def suggest(self, query): """Do a GET request to pull in JSON""" url = self.base_url + "viaf/AutoSuggest?query=" r = requests.get("%s%...
Refactor for other search options later (search -> suggest)
Refactor for other search options later (search -> suggest)
Python
apache-2.0
Princeton-CDH/winthrop-django,Princeton-CDH/winthrop-django,Princeton-CDH/winthrop-django
e503ef58e801cfbc3ba72ba84bc2150c79a401d3
girder/molecules/molecules/models/geometry.py
girder/molecules/molecules/models/geometry.py
from bson.objectid import ObjectId from girder.models.model_base import AccessControlledModel from girder.constants import AccessType from .molecule import Molecule as MoleculeModel class Geometry(AccessControlledModel): def __init__(self): super(Geometry, self).__init__() def initialize(self): ...
from bson.objectid import ObjectId from girder.models.model_base import AccessControlledModel from girder.constants import AccessType from .molecule import Molecule as MoleculeModel class Geometry(AccessControlledModel): def __init__(self): super(Geometry, self).__init__() def initialize(self): ...
Save creatorId as well for geometries
Save creatorId as well for geometries This is to keep track of the creator, even when the provenance is not the user. Signed-off-by: Patrick Avery <743342299f279e7a8c3ff5eb40671fce3e95f13a@kitware.com>
Python
bsd-3-clause
OpenChemistry/mongochemserver
5006ba3124cd80a4529b9ed645aa8981d06a9886
publishconf.py
publishconf.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals # This file is only used if you use `make publish` or # explicitly specify it as your config file. import os import sys sys.path.append(os.curdir) from pelicanconf import * SITEURL = '' RELATIVE_URLS = False FEED_ALL_ATOM = 'fee...
#!/usr/bin/env python3 # This file is only used if you use `make publish` or # explicitly specify it as your config file. import os import sys sys.path.append(os.curdir) from pelicanconf import * SITEURL = '' RELATIVE_URLS = False DELETE_OUTPUT_DIRECTORY = True # Following items are often useful when publishing #...
Stop generate feeds when publishing
Stop generate feeds when publishing
Python
mit
andrewheiss/scorecarddiplomacy-org,andrewheiss/scorecarddiplomacy-org,andrewheiss/scorecarddiplomacy-org,andrewheiss/scorecarddiplomacy-org
ddd3373ce078cf9bf40da7ebd8591995e819b750
phell/utils.py
phell/utils.py
# -*- coding: utf-8 -*- # # (c) 2016 Björn Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'phell' for details. # import sys def to_hex(value): if sys.version_info.major < 3: return value.encode('hex') return "".join("%02x" % b for b in value) def from_hex(value): if sy...
# -*- coding: utf-8 -*- # # (c) 2016 Björn Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'phell' for details. # import sys def to_hex(value): if sys.version_info.major < 3: return value.encode('hex') return "".join("%02x" % b for b in value) def from_hex(value): if sy...
Add function to swap byte order
Add function to swap byte order
Python
mit
bjoernricks/phell
c8ffd1fc4c4e06cd71e86d1d48749a3fe527a54e
biosys/apps/main/tests/api/test_serializers.py
biosys/apps/main/tests/api/test_serializers.py
from django.test import TestCase from main.api.serializers import DatasetSerializer from main.tests.api import helpers class TestDatsetSerializer(helpers.BaseUserTestCase): def test_name_uniqueness(self): """ Test that the serializer report an error if the dataset name is not unique within a pro...
from django.test import TestCase from main.api.serializers import DatasetSerializer from main.tests.api import helpers class TestDatsetSerializer(helpers.BaseUserTestCase): def test_name_uniqueness(self): """ Test that the serializer report an error if the dataset name is not unique within a pro...
Fix test to accommodate change of error message.
Fix test to accommodate change of error message.
Python
apache-2.0
gaiaresources/biosys,parksandwildlife/biosys,gaiaresources/biosys,serge-gaia/biosys,ropable/biosys,parksandwildlife/biosys,serge-gaia/biosys,ropable/biosys,gaiaresources/biosys,ropable/biosys,serge-gaia/biosys,parksandwildlife/biosys
27c9da3129c6fbdd8d54276cf054c1f46e665aaf
flask_app.py
flask_app.py
from flask import Flask, abort, jsonify from flask_caching import Cache from flask_cors import CORS import main import slack app = Flask(__name__) cache = Cache(app, config={"CACHE_TYPE": "simple"}) cors = CORS(app, resources={r"/*": {"origins": "*"}}) app.register_blueprint(slack.blueprint, url_prefix="/api/slack")...
import flask import flask_caching import flask_cors import main import slack app = flask.Flask(__name__) cache = flask_caching.Cache(app, config={"CACHE_TYPE": "simple"}) cors = flask_cors.CORS(app, resources={r"/*": {"origins": "*"}}) app.register_blueprint(slack.blueprint, url_prefix="/api/slack") @app.route("/a...
Remove trailing slashes, add origin url to responses
Remove trailing slashes, add origin url to responses
Python
bsd-3-clause
talavis/kimenu
e2f83a6a5d43ebc52d03d4059a7526a579a425c1
darkoob/social/models.py
darkoob/social/models.py
from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save SEX_CHOICES = ( ('Male', 'Male'), ('Female', 'Female'), ) class UserProfile(models.Model): user = models.OneToOneField(User) sex = models.CharField(max_length = 6, choices = SEX_CHO...
from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save SEX_CHOICES = ( ('Male', 'Male'), ('Female', 'Female'), ) class UserProfile(models.Model): user = models.OneToOneField(User) sex = models.CharField(max_length = 6, choices = SEX_CHO...
Set User Profile Unicode Function
Set User Profile Unicode Function
Python
mit
s1na/darkoob,s1na/darkoob,s1na/darkoob
74ca49c62ba63b7eb42f3825ea5c036e32b98d50
busstops/management/commands/import_tfl_stops.py
busstops/management/commands/import_tfl_stops.py
""" Usage: ./manage.py import_tfl_stops < data/tfl/bus-stops.csv """ import requests from titlecase import titlecase from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned from busstops.management.import_from_csv import ImportFromCSVCommand from busstops.models import StopPoint class C...
""" Usage: ./manage.py import_tfl_stops < data/tfl/bus-stops.csv """ import requests from titlecase import titlecase from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned from busstops.management.import_from_csv import ImportFromCSVCommand from busstops.models import StopPoint class C...
Work around null TfL common names
Work around null TfL common names
Python
mpl-2.0
jclgoodwin/bustimes.org.uk,stev-0/bustimes.org.uk,jclgoodwin/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk,jclgoodwin/bustimes.org.uk,stev-0/bustimes.org.uk,jclgoodwin/bustimes.org.uk,stev-0/bustimes.org.uk
9a8fd944fb78d582f06d7165f097c1e54cb870dc
project/asylum/mixins.py
project/asylum/mixins.py
from reversion import revisions from django.db import transaction # Monkeypatch the revisions try: revisions.create_revision except AttributeError: revisions.create_revision = revisions.revision_context_manager.create_revision class AtomicVersionMixin(object): def save(self, *args, **kwargs): wit...
from reversion import revisions from django.db import transaction # Monkeypatch the revisions try: revisions.create_revision except AttributeError: revisions.create_revision = revisions.revision_context_manager.create_revision class AtomicVersionMixin(object): """Makes sure saves and deletes go via transa...
Add a mixin for calling full_clean() on save()
Add a mixin for calling full_clean() on save()
Python
mit
ojousima/asylum,rambo/asylum,HelsinkiHacklab/asylum,ojousima/asylum,hacklab-fi/asylum,hacklab-fi/asylum,jautero/asylum,HelsinkiHacklab/asylum,jautero/asylum,hacklab-fi/asylum,HelsinkiHacklab/asylum,rambo/asylum,jautero/asylum,rambo/asylum,HelsinkiHacklab/asylum,jautero/asylum,hacklab-fi/asylum,ojousima/asylum,rambo/asy...
6794bb897e7e8730b1c3ab2fc6b856865887ac8b
scripts/upsrv_schema.py
scripts/upsrv_schema.py
#!/usr/bin/python # Copyright (c) 2006 rPath, Inc # All rights reserved import sys import os import pwd from conary.server import schema from conary.lib import cfgtypes, tracelog from conary.repository.netrepos.netserver import ServerConfig from conary import dbstore cnrPath = '/srv/conary/repository.cnr' cfg = Ser...
#!/usr/bin/python # Copyright (c) 2006 rPath, Inc # All rights reserved import sys import os import pwd from conary.server import schema from conary.lib import cfgtypes, tracelog from conary.repository.netrepos.netserver import ServerConfig from conary import dbstore class SimpleFileLog(tracelog.FileLog): def pr...
Use a simpler trace logger that does not prepend timestamps
Use a simpler trace logger that does not prepend timestamps
Python
apache-2.0
sassoftware/rbm,sassoftware/rbm,sassoftware/rbm
31e4da5e782c29d7d0c893a3fc9af48260c50a3a
src/ansible/views.py
src/ansible/views.py
from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect, HttpResponse from formtools.wizard.views import SessionWizardView from ansible.models import Github def index(request): return HttpResponse("200") class PlaybookWizard(SessionWizardView): def get_form_initial(...
from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect, HttpResponse from formtools.wizard.views import SessionWizardView from ansible.models import Github, Playbook import sys def index(request): return HttpResponse("200") class PlaybookWizard(SessionWizardView): ...
Save form data to DB on each step
Save form data to DB on each step
Python
bsd-3-clause
lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin
aa026fb39bd4a053766988383e9374dba20fd7f5
scripts/init_tree.py
scripts/init_tree.py
import os import shutil def main(): cwd = os.getcwd() if not cwd.endswith(os.path.join('FRENSIE', 'scripts')): print 'This script must be run in \"FRENSIE/scipts\"' return 1 os.chdir('../../') os.mkdir('frensie_build_tree') os.renames('FRENSIE', 'frensie_build_tree/FRENSIE') ...
import os import shutil def main(): cwd = os.getcwd() if not cwd.endswith(os.path.join('FRENSIE', 'scripts')): print 'This script must be run in \"FRENSIE/scipts\"' print 'Your CWD is', cwd return 1 os.chdir('../../') os.mkdir('frensie_build_tree') #os.renames('FRENSIE'...
Use symlinks to avoid weird behavior from removing the CWD while we're in it
Use symlinks to avoid weird behavior from removing the CWD while we're in it
Python
bsd-3-clause
lkersting/SCR-2123,lkersting/SCR-2123,lkersting/SCR-2123,lkersting/SCR-2123
cd48c66406c39ca6dd6bdc6ba7c2be0df623e6ae
src/leap/mx/check_recipient_access.py
src/leap/mx/check_recipient_access.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- # check_recipient_access.py # Copyright (C) 2013 LEAP # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at ...
#!/usr/bin/env python # -*- encoding: utf-8 -*- # check_recipient_access.py # Copyright (C) 2013 LEAP # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at ...
Fix return codes for check recipient
Fix return codes for check recipient
Python
agpl-3.0
meskio/leap_mx,meskio/leap_mx,leapcode/leap_mx,micah/leap_mx,leapcode/leap_mx,micah/leap_mx
aefd972c7fb423396f59da03a1d460cd3559d1e1
duplicate_questions/data/tokenizers/word_tokenizers.py
duplicate_questions/data/tokenizers/word_tokenizers.py
class SpacyWordTokenizer(): """ A Tokenizer splits strings into word tokens. """ def __init__(self): # Import is here it's slow, and can be unnecessary. import spacy self.en_nlp = spacy.load('en') # def tokenize(self, sentence: str) -> List[str]: def tokenize(self, sente...
class SpacyWordTokenizer(): """ A Tokenizer splits strings into word tokens. """ def __init__(self): # Import is here it's slow, and can be unnecessary. import spacy self.en_nlp = spacy.load('en') def tokenize(self, sentence): return [str(token.lower_) for token in s...
Remove unnecesssary comments of old function signatures
Remove unnecesssary comments of old function signatures
Python
mit
nelson-liu/paraphrase-id-tensorflow,nelson-liu/paraphrase-id-tensorflow
d9c677a35d18a878ef8d253a9453e93da3341e96
runTwircBot.py
runTwircBot.py
#!/usr/bin/env python3 from src.TwircBot import TwircBot import sys try: bot = TwircBot(sys.argv[1]) except IndexError: bot = TwircBot() bot.print_config() bot.start()
#!/usr/bin/env python3 from src.TwircBot import TwircBot from src.CommandModule import CommandModule import sys try: bot = TwircBot(sys.argv[1]) except IndexError: bot = TwircBot() module = CommandModule() bot.print_config() # bot.start()
Add extremely basic template for command modules
Add extremely basic template for command modules
Python
mit
johnmarcampbell/twircBot
16b3e30a88e9101db58c0549e515848df29f29b9
raygun4py-sample/test.py
raygun4py-sample/test.py
import sys, os import traceback from provider import raygunprovider def handle_exception(exc_type, exc_value, exc_traceback): cl = raygunprovider.RaygunSender("onPbQXtZKqJX38IuN4AQKA==") cl.set_version("1.2") print cl.send(exc_type, exc_value, exc_traceback, "myclass", ["tag1", "tag2"], {"key1": 1111, ...
import sys, os, urllib2 import traceback from provider import raygunprovider def handle_exception(exc_type, exc_value, exc_traceback): cl = raygunprovider.RaygunSender("onPbQXtZKqJX38IuN4AQKA==") cl.set_version("1.2") print cl.send(exc_type, exc_value, exc_traceback, "myclass", ["tag1", "tag2"], {"key1": 1...
Set up sample project to throw web exceptions (for request oject)
Set up sample project to throw web exceptions (for request oject)
Python
mit
Osmose/raygun4py,MindscapeHQ/raygun4py,ferringb/raygun4py
9f3356d06067dbcc77a79afee6bccf80600dab28
server/systeminfo.py
server/systeminfo.py
#!/bin/python3 """ This script contains functions to access various system's info. Author: Julien Delplanque """ import subprocess def get_uptime(): """ Return the uptime of the system as a str using the command: $ uptime """ proc = subprocess.Popen(["uptime"], stdout=subprocess.PIPE, shell=True) ...
#!/bin/python3 """ This script contains functions to access various system's info. Author: Julien Delplanque """ import subprocess from datetime import timedelta def get_uptime(): """ Return the uptime of the system as a timedelta object. """ proc = subprocess.Popen(["cat /proc/uptime"], ...
Add a method to get the idle time. Also data are directly readed in /proc/uptime.
Add a method to get the idle time. Also data are directly readed in /proc/uptime.
Python
mit
juliendelplanque/raspirestmonitor
595218c33892facf0cf26e5e6b3e16b2c02e737e
spring/settings.py
spring/settings.py
from urlparse import urlparse from logger import logger class WorkloadSettings(object): def __init__(self, options): self.creates = options.creates self.reads = options.reads self.updates = options.updates self.deletes = options.deletes self.cases = 0 # Stub for library ...
from urlparse import urlparse from logger import logger class WorkloadSettings(object): def __init__(self, options): self.creates = options.creates self.reads = options.reads self.updates = options.updates self.deletes = options.deletes self.cases = 0 # Stub for library ...
Add a stub for fts_updates
Add a stub for fts_updates Change-Id: Ieb48f98a0072dcd27de0b50027ff6c5f3ecc1513 Reviewed-on: http://review.couchbase.org/70413 Tested-by: buildbot <80754af91bfb6d1073585b046fe0a474ce868509@couchbase.com> Reviewed-by: Pavel Paulau <dd88eded64e90046a680e3a6c0828ceb8fe8a0e7@gmail.com>
Python
apache-2.0
pavel-paulau/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner
427292a82aea2a2291833ca0cb3f30cee2afd497
ixdjango/management/commands/newrelic_notify_deploy.py
ixdjango/management/commands/newrelic_notify_deploy.py
""" Management command to enable New Relic notification of deployments .. moduleauthor:: Infoxchange Development Team <development@infoxchange.net.au> """ import os from subprocess import call, Popen, PIPE from django.conf import settings from django.core.management.base import NoArgsCommand class Command(NoArgsC...
""" Management command to enable New Relic notification of deployments .. moduleauthor:: Infoxchange Development Team <development@infoxchange.net.au> """ import os from subprocess import call, Popen, PIPE from django.conf import settings from django.core.management.base import NoArgsCommand class Command(NoArgsC...
Fix NR deploy notification bug
Fix NR deploy notification bug
Python
mit
infoxchange/ixdjango