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
6e8895d08ff85bf5ba35765161890e77faba5715
pryvate/blueprints/simple/simple.py
pryvate/blueprints/simple/simple.py
"""Simple blueprint.""" import os from flask import Blueprint, current_app, render_template blueprint = Blueprint('simple', __name__, url_prefix='/simple', template_folder='templates') @blueprint.route('', methods=['GET']) def get_simple(): """List all packages.""" packages = os.listdir(c...
"""Simple blueprint.""" import os from flask import Blueprint, current_app, make_response, render_template blueprint = Blueprint('simple', __name__, url_prefix='/simple', template_folder='templates') @blueprint.route('', methods=['POST']) def search_simple(): """Handling pip search.""" re...
Return 501 on pip search requests
Return 501 on pip search requests
Python
mit
Dinoshauer/pryvate,Dinoshauer/pryvate
5054e882194adae4b76681e78c45d41ae2c2f0f7
pymatgen/util/sequence.py
pymatgen/util/sequence.py
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. """ This module provides utilities to chunk large sequences and display progress bars during processing. """ import math def get_chunks(sequence, size=1): """ Args: sequence (): size ...
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. """ This module provides utilities to chunk large sequences and display progress bars during processing. """ import math def get_chunks(sequence, size=1): """ Args: sequence (): size ...
Allow `PBar` to accept any kwargs (e.g. those used by `tqdm`)
Allow `PBar` to accept any kwargs (e.g. those used by `tqdm`)
Python
mit
gVallverdu/pymatgen,vorwerkc/pymatgen,vorwerkc/pymatgen,davidwaroquiers/pymatgen,gVallverdu/pymatgen,gVallverdu/pymatgen,fraricci/pymatgen,vorwerkc/pymatgen,gVallverdu/pymatgen,davidwaroquiers/pymatgen,fraricci/pymatgen,davidwaroquiers/pymatgen,davidwaroquiers/pymatgen,fraricci/pymatgen,vorwerkc/pymatgen,fraricci/pymat...
6fa751accb736b3c32522ca498210ffeebfef650
pytablereader/tsv/core.py
pytablereader/tsv/core.py
""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from .._validator import FileValidator, TextValidator from ..csv.core import CsvTableFileLoader, CsvTableTextLoader class TsvTableFileLoader(CsvTableFileLoader): """ Tab separated values (TSV) format file loader class. :param str fi...
""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from .._validator import FileValidator, TextValidator from ..csv.core import CsvTableFileLoader, CsvTableTextLoader class TsvTableFileLoader(CsvTableFileLoader): """ Tab separated values (TSV) format file loader class. :param str fi...
Modify TsvTableFileLoader/TsvTableTextLoader to accept additional keyword arguments
Modify TsvTableFileLoader/TsvTableTextLoader to accept additional keyword arguments
Python
mit
thombashi/pytablereader,thombashi/pytablereader,thombashi/pytablereader
566a200a11a587a9293d6926348c3df77a4c840d
project/apps/api/management/commands/denormalize.py
project/apps/api/management/commands/denormalize.py
from django.core.management.base import ( BaseCommand, ) from apps.api.models import ( Convention, Contest, Contestant, Performance, ) class Command(BaseCommand): help = "Command to denormailze data." def handle(self, *args, **options): vs = Convention.objects.all() for v...
from django.core.management.base import ( BaseCommand, ) from apps.api.models import ( Convention, Contest, Contestant, Performance, ) class Command(BaseCommand): help = "Command to denormailze data." def handle(self, *args, **options): vs = Convention.objects.all() for v...
Remove ranking from denormalization command
Remove ranking from denormalization command
Python
bsd-2-clause
barberscore/barberscore-api,dbinetti/barberscore,barberscore/barberscore-api,dbinetti/barberscore-django,barberscore/barberscore-api,dbinetti/barberscore,barberscore/barberscore-api,dbinetti/barberscore-django
f18cf3c17e450eb6f8db5288ecf146eff0968a47
xmt/select.py
xmt/select.py
from itertools import groupby from nltk.translate.gleu_score import sentence_gleu as gleu from nltk.tokenize.toktok import ToktokTokenizer _tokenize = ToktokTokenizer().tokenize def select_first(p): """ Return (hypothesis, reference) translation pairs using the first realization result per item. """...
from itertools import groupby from nltk.translate import bleu_score from nltk.tokenize.toktok import ToktokTokenizer _tokenize = ToktokTokenizer().tokenize _smoother = bleu_score.SmoothingFunction().method3 bleu = bleu_score.sentence_bleu def select_first(p): """ Return (hypothesis, reference) translation p...
Use NIST-BLEU instead of GLEU for oracle.
Use NIST-BLEU instead of GLEU for oracle.
Python
mit
goodmami/xmt,goodmami/xmt
499add1d29847490141cda4625d9a4199e386283
ncdc_download/download_mapper2.py
ncdc_download/download_mapper2.py
#!/usr/bin/env python3 import ftplib import gzip import os import sys host = 'ftp.ncdc.noaa.gov' base = '/pub/data/noaa' retries = 3 ftp = ftplib.FTP(host) ftp.login() for line in sys.stdin: (year, filename) = line.strip().split() for i in range(retries): sys.stderr.write('reporter:status:Processing ...
#!/usr/bin/env python3 import ftplib import gzip import os import sys host = 'ftp.ncdc.noaa.gov' base = '/pub/data/noaa' retries = 3 ftp = ftplib.FTP(host) ftp.login() for line in sys.stdin: (year, filename) = line.strip().split() for i in range(retries): sys.stderr.write('reporter:status:Processing ...
Remove downloaded file before updating counter
Remove downloaded file before updating counter
Python
mit
simonbrady/cat,simonbrady/cat
1d1dcccc31cb566ec0e8d37926cf72fecef1b70d
weaveserver/services/simpledb/__init__.py
weaveserver/services/simpledb/__init__.py
from .service import SimpleDatabaseService __meta__ = { "name": "Simple Database", "class": SimpleDatabaseService, "deps": ["messaging", "appmanager"], "config": [] }
from .service import SimpleDatabaseService __meta__ = { "name": "Simple Database", "class": SimpleDatabaseService, "deps": ["messaging", "appmanager"], "config": [ { "name": "core", "loaders": [ {"type": "env"}, {"type": "sysvarfile"} ...
Add sysvarfile and env config loaders to simpledb.
Add sysvarfile and env config loaders to simpledb.
Python
mit
supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer
96512dd8484353bacd134a0bf9db774a166d530c
mitmproxy/platform/osx.py
mitmproxy/platform/osx.py
import subprocess import pf """ Doing this the "right" way by using DIOCNATLOOK on the pf device turns out to be a pain. Apple has made a number of modifications to the data structures returned, and compiling userspace tools to test and work with this turns out to be a pain in the ass. Parsing pfctl ou...
import subprocess import pf """ Doing this the "right" way by using DIOCNATLOOK on the pf device turns out to be a pain. Apple has made a number of modifications to the data structures returned, and compiling userspace tools to test and work with this turns out to be a pain in the ass. Parsing pfctl ou...
Include correct documentation URL in error message
Include correct documentation URL in error message
Python
mit
mhils/mitmproxy,laurmurclar/mitmproxy,vhaupert/mitmproxy,dufferzafar/mitmproxy,mitmproxy/mitmproxy,laurmurclar/mitmproxy,cortesi/mitmproxy,vhaupert/mitmproxy,StevenVanAcker/mitmproxy,jvillacorta/mitmproxy,mitmproxy/mitmproxy,zlorb/mitmproxy,StevenVanAcker/mitmproxy,dwfreed/mitmproxy,Kriechi/mitmproxy,dwfreed/mitmproxy,...
d500e290f8c1422f74b1d8c8d2bbb8ec9e5529cb
misc/singleton.py
misc/singleton.py
""" File: singleton.py Purpose: Defines a class whose subclasses will act like the singleton pattern. """ class Singleton(object): """ This is a class that implements singleton for its subclasses. The technique is based on a variant of other techniques found in: http://stackoverflow.com/questions/6...
class Singleton(object): """ This is a class that implements singleton for its subclasses. The technique is based on a variant of other techniques found in: http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python https://gist.github.com/werediver/4396488 The technique is simp...
Add comments to Singleton about usage.
Add comments to Singleton about usage.
Python
mit
dpazel/music_rep
6b04211b42e76f6428fbaac361059fad4bef70de
txircd/modules/conn_join.py
txircd/modules/conn_join.py
from txircd.channel import IRCChannel from txircd.modbase import Module class Autojoin(Module): def joinOnConnect(self, user): if "client_join_on_connect" in self.ircd.servconfig: for channel in self.ircd.servconfig["client_join_on_connect"]: user.join(self.ircd.channels[channel] if channel in self.ircd.chan...
from txircd.channel import IRCChannel from txircd.modbase import Module class Autojoin(Module): def joinOnConnect(self, user): if "client_join_on_connect" in self.ircd.servconfig: for channel in self.ircd.servconfig["client_join_on_connect"]: user.join(self.ircd.channels[channel] if channel in self.ircd.chan...
Fix once again nobody being allowed to connect
Fix once again nobody being allowed to connect
Python
bsd-3-clause
Heufneutje/txircd,DesertBus/txircd,ElementalAlchemist/txircd
dcf0e140303259f7b3df2609281b635dbcd4806f
knapsack.py
knapsack.py
# Knapsack 0-1 function wieights, values and size n. from pyspark.sql import Row from pyspark.sql.functions import lit from pyspark.sql.functions import col # Greedy implementation of 0-1 Knapsack algorithm. def knapsack(knapsackDF, W): ratioDF = knapsackDF.withColumn("ratio", lit(knapsackDF.values / knapsackDF.w...
# Knapsack 0-1 function wieights, values and size n. import sys import pyspark.sql.functions as func from pyspark.sql.window import Window from pyspark.sql import Row from pyspark.sql.functions import lit from pyspark.sql.functions import col # Greedy implementation of 0-1 Knapsack algorithm. def knapsack(knapsackDF...
Add Window functions to attempt partial sum
Add Window functions to attempt partial sum
Python
apache-2.0
drulm/Spark_Knapsack,drulm/Spark_Knapsack
f0166ba101c131b5331e141128fc65e71c753015
flocker/common/__init__.py
flocker/common/__init__.py
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Shared flocker components. """ __all__ = [ 'INode', 'FakeNode', 'ProcessNode', 'gather_deferreds', 'auto_threaded', 'auto_openstack_logging', 'get_all_ips', ] import platform from ._ipc import INode, FakeNode, ProcessNode from ._defer impo...
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Shared flocker components. """ __all__ = [ 'INode', 'FakeNode', 'ProcessNode', 'gather_deferreds', 'auto_threaded', 'auto_openstack_logging', 'get_all_ips', 'ipaddress_from_string', ] import platform from ._ipc import INode, FakeNode, Proc...
Make the new helper function public
Make the new helper function public
Python
apache-2.0
Azulinho/flocker,1d4Nf6/flocker,hackday-profilers/flocker,wallnerryan/flocker-profiles,mbrukman/flocker,adamtheturtle/flocker,1d4Nf6/flocker,AndyHuu/flocker,jml/flocker,wallnerryan/flocker-profiles,achanda/flocker,agonzalezro/flocker,AndyHuu/flocker,adamtheturtle/flocker,runcom/flocker,achanda/flocker,runcom/flocker,ag...
f30a560db83d8a7ac87685c69f5b519faaa929fa
project_issue_department/__openerp__.py
project_issue_department/__openerp__.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2012 Daniel Reis # # 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...
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2012 Daniel Reis # # 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...
Fix pep8 to pass super checks
Fix pep8 to pass super checks
Python
agpl-3.0
OCA/department,Antiun/department,acsone/department,kmee/department,Endika/department
d851aae653ce87aed9b9f6ac3cf7f5312672a08c
radmin/templatetags/radmin_extras.py
radmin/templatetags/radmin_extras.py
from django import template import json from django.conf import settings register = template.Library() @register.simple_tag(takes_context=True) def get_admin_context(context): ctx = {'location':None, 'param1':None, 'param2':None, 'static':settings.STATIC_URL} try: context['app_list'] if len(co...
from django import template import json from django.conf import settings register = template.Library() @register.simple_tag(takes_context=True) def get_admin_context(context): ctx = {'location':None, 'param1':None, 'param2':None, 'static':settings.STATIC_URL} try: context['app_list'] if len(co...
Check if original object is None
Check if original object is None
Python
bsd-2-clause
mick-t/django-radmin-console,mick-t/django-radmin-console,mick-t/django-radmin-console
146a2217fba0614d5f03e6a8648ced9613dc2cb8
readux/books/management/commands/web_export.py
readux/books/management/commands/web_export.py
from eulfedora.server import Repository from django.core.management.base import BaseCommand from readux.books import export from readux.books.models import Volume class Command(BaseCommand): help = 'Construct web export of an annotated volume' def add_arguments(self, parser): parser.add_argument('p...
from eulfedora.server import Repository from django.core.management.base import BaseCommand import shutil from readux.books import annotate, export from readux.books.models import Volume class Command(BaseCommand): help = 'Construct web export of an annotated volume' def add_arguments(self, parser): ...
Update web export manage command to generate static/jekyll site
Update web export manage command to generate static/jekyll site
Python
apache-2.0
emory-libraries/readux,emory-libraries/readux,emory-libraries/readux
a425db8ec0b21a5ff72af7481e7a7e30638ef9e3
sorl_thumbnail_serializer/fields.py
sorl_thumbnail_serializer/fields.py
from rest_framework import serializers from sorl.thumbnail import get_thumbnail class HyperlinkedSorlImageField(serializers.ImageField): def __init__(self, dimensions, options={}, *args, **kwargs): self.dimensions = dimensions self.options = options super(HyperlinkedSorlImageField, self...
from rest_framework import serializers from sorl.thumbnail import get_thumbnail class HyperlinkedSorlImageField(serializers.ImageField): def __init__(self, dimensions, options={}, *args, **kwargs): self.dimensions = dimensions self.options = options super(HyperlinkedSorlImageField, self...
Support for DRF 3.0 and above
Support for DRF 3.0 and above See http://www.django-rest-framework.org/topics/3.0-announcement/
Python
mit
dessibelle/sorl-thumbnail-serializer-field
22209f8de06a4a179cddd885566066dd6acdb8dd
python_course_1604/class_01/tests/test_04.py
python_course_1604/class_01/tests/test_04.py
''' Created on 6 Apr 2016 @author: fressi ''' import unittest import python_course_1604.class_01.exercize_04_stack_limit as exercize from python_course_1604.tests.utils import skip_if_exercize_not_started @skip_if_exercize_not_started(exercize) class TestStackLimit(unittest.TestCase): def test_failing_functi...
''' Created on 6 Apr 2016 @author: fressi ''' import unittest import python_course_1604.class_01.exercize_04_stack_limit as exercize from python_course_1604.tests.utils import skip_if_exercize_not_started @skip_if_exercize_not_started(exercize) class TestStackLimit(unittest.TestCase): def test_failing_functi...
Make stack limit check more tollerant.
Make stack limit check more tollerant.
Python
apache-2.0
FedericoRessi/pythoncourse
84cd432f2df46e24e7eaee81d899bf33fe551b70
netsecus/korrekturtools.py
netsecus/korrekturtools.py
from __future__ import unicode_literals import os import logging from . import helper def readStatus(config, student): student = student.lower() path = config("attachment_path") if not os.path.exists(path): return path = os.path.join(path, student) if not os.path.exists(path): ...
from __future__ import unicode_literals import os import logging import sqlite3 from . import helper def readStatus(config, student): database = getStatusTable(config) cursor = database.cursor() cursor.execute("SELECT status FROM status WHERE identifier = ?", (student,)) statusRow = cursor.fetchone...
Move status to database instead of status file (server side)
Move status to database instead of status file (server side)
Python
mit
hhucn/netsec-uebungssystem,hhucn/netsec-uebungssystem,hhucn/netsec-uebungssystem
3ec3948dfde67c15204964d35c2df1c60e7706a1
rwt/tests/test_scripts.py
rwt/tests/test_scripts.py
from __future__ import unicode_literals import textwrap import sys import subprocess from rwt import scripts def test_pkg_imported(tmpdir): """ Create a script that loads cython and ensure it runs. """ body = textwrap.dedent(""" import cython print("Successfully imported cython") """).lstrip() script_fil...
from __future__ import unicode_literals import textwrap import sys import subprocess from rwt import scripts def test_pkg_imported(tmpdir): """ Create a script that loads cython and ensure it runs. """ body = textwrap.dedent(""" import cython print("Successfully imported cython") """).lstrip() script_fil...
Add another test demonstrating that multiple assignment doesn't affect __requires__ parsing.
Add another test demonstrating that multiple assignment doesn't affect __requires__ parsing.
Python
mit
jaraco/rwt
5444e755e819004b4da6560d5a6caad2d9993945
klustakwik2/scripts.py
klustakwik2/scripts.py
''' Utilities for scripts ''' import sys __all__ = ['parse_args'] def parse_args(num_args, allowed_params, msg, string_args=set()): msg += '\nAllowed arguments and default values:\n' for k, v in allowed_params.iteritems(): msg += '\n %s = %s' % (k, v) if len(sys.argv)<=num_args: print ...
''' Utilities for scripts ''' import sys __all__ = ['parse_args'] def parse_args(num_args, allowed_params, msg, string_args=set()): msg += '\nAllowed arguments and default values:\n' for k, v in allowed_params.iteritems(): msg += '\n %s = %s' % (k, v) if len(sys.argv)<=num_args: print ...
Handle true/false as well as True/False arguments
Handle true/false as well as True/False arguments
Python
bsd-3-clause
kwikteam/klustakwik2,benvermaercke/klustakwik2
727ec507284776f3eec91b644cd5bb112bdb0af1
july/people/forms.py
july/people/forms.py
from django import forms class EditUserForm(forms.Form): about_me = forms.CharField(widget=forms.Textarea, required=False) url = forms.CharField(max_length=255, required=False) facebook_url = forms.CharField(max_length=255, required=False) email = forms.EmailField(max_length=255) def __init__(self...
from django import forms class EditUserForm(forms.Form): about_me = forms.CharField(widget=forms.Textarea, required=False) url = forms.CharField(max_length=255, required=False) facebook_url = forms.CharField(max_length=255, required=False) email = forms.EmailField(max_length=255) def __init__(self...
Use getattr for expando props
Use getattr for expando props
Python
mit
julython/julython.org,julython/julython.org,ChimeraCoder/GOctober,julython/julython.org,ChimeraCoder/GOctober,julython/julython.org,ChimeraCoder/GOctober
2267f31ba91ea649c54a51ab3e8f3babbe72f44e
openliveq/collection.py
openliveq/collection.py
from collections import defaultdict class Collection(object): DOC_FROM = ["question_body", "best_answer_body"] def __init__(self): ''' Compute the following statistics df: document frequency cf: collection frequency dn: total number of documents cn: total number...
from collections import defaultdict class Collection(object): DOC_FROM = ["question_body", "best_answer_body"] def __init__(self): ''' Compute the following statistics df: document frequency cf: collection frequency dn: total number of documents cn: total number...
Add avddlen property to Collection
Add avddlen property to Collection
Python
mit
mpkato/openliveq
072eeaf0efbc299efac0be6fc7499f2d48dacd1a
BudgetModelHelper.py
BudgetModelHelper.py
from DataModel import DataModel from DataModelAdapter import DataModelAdapter from Ledger import Ledger import pickle DATA_FILE='ledger.pickle' def get_ledger() : result = None try: with open(DATA_FILE, 'rb') as infile: result = pickle.load(infile) except FileNotFoundError: re...
from DataModel import DataModel from DataModelAdapter import DataModelAdapter from Ledger import Ledger import pickle DATA_FILE='ledger.pickle' def get_ledger() : result = None try: with open(DATA_FILE, 'rb') as infile: result = pickle.load(infile) except FileNotFoundError: pa...
Handle EOFError on pickle load
Handle EOFError on pickle load
Python
apache-2.0
mattdeckard/wherewithal
73f75efcfe69210d8e22ff55c19b02b7408b9671
pseudorandom.py
pseudorandom.py
from flask import Flask, render_template from names import get_full_name app = Flask(__name__) @app.route("/") def index(): return render_template('index.html', name=get_full_name()) if __name__ == "__main__": app.run()
import os from flask import Flask, render_template from names import get_full_name app = Flask(__name__) @app.route("/") def index(): return render_template('index.html', name=get_full_name()) if __name__ == "__main__": port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port)
Use environment variable PORT for flask port
Use environment variable PORT for flask port
Python
mit
treyhunner/pseudorandom.name,treyhunner/pseudorandom.name
41b1d36a9d5fcb0dd2f6da53a7a0d4604b21a0eb
tests/query_test/test_scan_range_lengths.py
tests/query_test/test_scan_range_lengths.py
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, Inc. All rights reserved. # Validates running with different scan range length values # import pytest from copy import copy from tests.common.test_vector import TestDimension from tests.common.impala_test_suite import ImpalaTestSuite, ALL_NODES_ONLY # We use very sm...
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, Inc. All rights reserved. # Validates running with different scan range length values # import pytest from copy import copy from tests.common.test_vector import TestDimension from tests.common.impala_test_suite import ImpalaTestSuite, ALL_NODES_ONLY # We use very sm...
Fix IMPALA-122: Lzo scanner with small scan ranges.
Fix IMPALA-122: Lzo scanner with small scan ranges. Change-Id: I5226fd1a1aa368f5b291b78ad371363057ef574e Reviewed-on: http://gerrit.ent.cloudera.com:8080/140 Reviewed-by: Skye Wanderman-Milne <6d4b168ab637b0a20cc9dbf96abb2537f372f946@cloudera.com> Reviewed-by: Nong Li <99a5e5f8f5911755b88e0b536d46aafa102bed41@cloudera...
Python
apache-2.0
michaelhkw/incubator-impala,cloudera/Impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,cloudera/Impala,cloudera/Impala,cloudera/Impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,cloudera/Impala,cloudera/Impala,michaelhkw/incubator-impala,cloudera/Impala
d1e56cfcd11bcd509d8fa3954c00e06a84bddd87
synapse/storage/engines/__init__.py
synapse/storage/engines/__init__.py
# -*- coding: utf-8 -*- # Copyright 2015, 2016 OpenMarket Ltd # # 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 applica...
# -*- coding: utf-8 -*- # Copyright 2015, 2016 OpenMarket Ltd # # 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 applica...
Fix pep8 error on psycopg2cffi hack
Fix pep8 error on psycopg2cffi hack
Python
apache-2.0
matrix-org/synapse,matrix-org/synapse,matrix-org/synapse,matrix-org/synapse,matrix-org/synapse,matrix-org/synapse
d8cc0fdaea848ed5d626ba6ba4292fd3cb906da3
project7/TrackParser.py
project7/TrackParser.py
""" Created by Max 12/2/2017 """ import pprint import numpy as np class TrackParser: @staticmethod def parse_track(path_to_track_file: str) -> np.ndarray: track = None with open(path_to_track_file, 'r') as track_file: lines = track_file.readlines() dimensions_str = li...
""" Created by Max 12/2/2017 """ import pprint import numpy as np class TrackParser: @staticmethod def parse_track(path_to_track_file: str) -> np.ndarray: track = None with open(path_to_track_file, 'r') as track_file: lines = track_file.readlines() dimensions_str = li...
Add comment to clarify coordinate order
Add comment to clarify coordinate order coordinates are (y,x) in the track.
Python
apache-2.0
MaxRobinson/CS449,MaxRobinson/CS449,MaxRobinson/CS449
2806254823ae46e4a8fd7204cda58be6eea18743
tests/10_test_elbaas.py
tests/10_test_elbaas.py
import otc class TestElbClient: """ELB client tests""" def setUp(self): """Setup test cloud""" self.cloud = otc.OtcCloud(cloud='test') def tearDown(self): pass def test_elbclient_user_agent(self): """Check user agent""" assert self.cloud.elbclient.client.USER_...
import otc class TestElbClient: """ELB client tests""" def setUp(self): """Setup test cloud""" self.cloud = otc.OtcCloud(cloud='test') def tearDown(self): pass def test_elbclient_user_agent(self): """Check user agent""" assert self.cloud.elbclient.client.USER_...
Check the ELB service url
Check the ELB service url
Python
apache-2.0
zamiam69/otc
5ec1ba120642686b87cec0ad2ccc2c1428c4a553
samples/config.default.py
samples/config.default.py
#!/usr/bin/env python # -*- coding: utf-8 -*- credentials = { 'verify-email.org': { 'username': 'YOURUSERNAME', 'password': 'YOURPASSWORD', } 'emailhippo.com': { 'api_url': 'https://domain.com/api/v2', 'api_key': 'YOURAPIKEY', } }
#!/usr/bin/env python # -*- coding: utf-8 -*- credentials = { 'verify-email.org': { 'username': 'YOURUSERNAME', 'password': 'YOURPASSWORD', } 'emailhippo.com': { 'api_url': 'https://domain.com/api/v2', 'api_key': 'YOURAPIKEY', }, 'email-validator.net': { 'api...
Add an other provider to config
Add an other provider to config
Python
bsd-3-clause
scls19fr/email-verif
9bc9ec9468459ab49530e6463255cca38aba721c
findaconf/tests/test_site_routes.py
findaconf/tests/test_site_routes.py
# coding: utf-8 from unittest import TestCase from findaconf import app, db from findaconf.tests.config import set_app, unset_app class TestSiteRoutes(TestCase): def setUp(self): self.app = set_app(app, db) def tearDown(self): unset_app(db) # test routes from blueprint/site.py def...
# coding: utf-8 from findaconf import app, db from findaconf.tests.config import set_app, unset_app from unittest import TestCase class TestSiteRoutes(TestCase): def setUp(self): self.app = set_app(app, db) def tearDown(self): unset_app(db) # test routes from blueprint/site.py def ...
Create tests for login page
Create tests for login page
Python
mit
cuducos/findaconf,cuducos/findaconf,koorukuroo/findaconf,cuducos/findaconf,koorukuroo/findaconf,koorukuroo/findaconf
d8d6054a64c07952ff0a60ef5d86d7a5b572d1b4
fireplace/cards/brawl/blingbrawl.py
fireplace/cards/brawl/blingbrawl.py
""" Blingtron's Beauteous Brawl """ from ..utils import * # Cash In class TP_Bling_HP2: activate = Destroy(FRIENDLY_WEAPON) # Blingtron's Blade class TB_BlingBrawl_Blade1e: events = Death(OWNER).on(Summon(CONTROLLER, RandomWeapon())) # Blingtron's Blade HERO class TB_BlingBrawl_Blade2: events = Summon(CONTROLL...
""" Blingtron's Beauteous Brawl """ from ..utils import * # Cash In class TP_Bling_HP2: activate = Destroy(FRIENDLY_WEAPON) # Blingtron's Blade class TB_BlingBrawl_Blade1e: events = Death(OWNER).on(Summon(CONTROLLER, RandomWeapon())) # Blingtron's Blade HERO class TB_BlingBrawl_Blade2: events = Summon(CONTROLL...
Implement Sharpen (unused Blingtron Brawl Hero Power)
Implement Sharpen (unused Blingtron Brawl Hero Power)
Python
agpl-3.0
Ragowit/fireplace,Ragowit/fireplace,smallnamespace/fireplace,NightKev/fireplace,smallnamespace/fireplace,beheh/fireplace,jleclanche/fireplace
86273d96e33e3bd686904377ba2b53fbbbcbc38b
tests/test_crossword.py
tests/test_crossword.py
import unittest from crossword import Crossword class CrosswordTestCase(unittest.TestCase): def test_crossword_set_and_get_element(self): c = Crossword(10, 10) c[3, 3] = 'A' self.assertEqual(c[3, 3], 'A')
import unittest from crossword import Crossword class CrosswordTestCase(unittest.TestCase): def test_crossword_set_and_get_element(self): crossword = Crossword(10, 10) crossword[3, 3] = 'A' self.assertEqual(crossword[3, 3], 'A')
Use a better variable name instead of one character
Use a better variable name instead of one character
Python
mit
svisser/crossword
10c2d1dcc9079a3166642a3d75947472ec377343
simple_scheduler/jobs/curl_job.py
simple_scheduler/jobs/curl_job.py
"""A job to send a HTTP GET periodically.""" import logging import requests from ndscheduler import job logger = logging.getLogger(__name__) class CurlJob(job.JobBase): TIMEOUT = 10 @classmethod def meta_info(cls): return { 'job_class_string': '%s.%s' % (cls.__module__, cls.__name_...
"""A job to send a HTTP GET periodically.""" import logging import requests from ndscheduler import job logger = logging.getLogger(__name__) class CurlJob(job.JobBase): TIMEOUT = 10 @classmethod def meta_info(cls): return { 'job_class_string': '%s.%s' % (cls.__module__, cls.__name_...
Add delete example in CURL job
Add delete example in CURL job
Python
bsd-2-clause
Nextdoor/ndscheduler,Nextdoor/ndscheduler,Nextdoor/ndscheduler,Nextdoor/ndscheduler
ab500891a44e7034e02889acc5f8ac1d44cb9aad
tests/test_error.py
tests/test_error.py
from __future__ import unicode_literals import unittest import six import spotify class ErrorTest(unittest.TestCase): def test_error_has_error_code(self): error = spotify.Error(0) self.assertEqual(error.error_code, 0) error = spotify.Error(1) self.assertEqual(error.error_code, 1...
from __future__ import unicode_literals import unittest import six import spotify class ErrorTest(unittest.TestCase): def test_error_has_error_code(self): error = spotify.Error(0) self.assertEqual(error.error_code, 0) error = spotify.Error(1) self.assertEqual(error.error_code, 1...
Make Error behavior consistent across Pythons
Make Error behavior consistent across Pythons
Python
apache-2.0
felix1m/pyspotify,jodal/pyspotify,jodal/pyspotify,felix1m/pyspotify,kotamat/pyspotify,jodal/pyspotify,kotamat/pyspotify,mopidy/pyspotify,mopidy/pyspotify,kotamat/pyspotify,felix1m/pyspotify
8ee35fe46e978fcb17e99b50f045009ea8235067
tools/pdtools/pdtools/devices/camera.py
tools/pdtools/pdtools/devices/camera.py
import base64 import requests import six class Camera(object): def __init__(self, host): self.host = host def get_image(self): """ Get an image from the camera. Returns image data as a BytesIO/StringIO object. """ url = "http://{}/image.jpg".format(self.host)...
import base64 import requests import six class Camera(object): def __init__(self, host): self.host = host def __repr__(self): return "Camera({})".format(self.host) def get_image(self): """ Get an image from the camera. Returns image data as a BytesIO/StringIO ob...
Define __repr__ for pdtools Camera class.
Define __repr__ for pdtools Camera class.
Python
apache-2.0
ParadropLabs/Paradrop,ParadropLabs/Paradrop,ParadropLabs/Paradrop
8e5c55a4710352d5f3b211c9df7d11c3cf9ef104
us_ignite/dummy/text.py
us_ignite/dummy/text.py
from random import choice from django.conf import settings words = open(settings.WORDS_PATH, "r").readlines() def random_words(total): return " ".join([choice(words).lower().rstrip() for i in range(total)]) def random_paragraphs(total, word_no=30): return ".\n\n".join([random_words(word_no) for i in rang...
from random import choice from django.conf import settings from django.utils.encoding import smart_text words = open(settings.WORDS_PATH, "r").readlines() def random_words(total): return u" ".join([smart_text(choice(words).lower().rstrip()) for i in range(total)]) def random_paragraphs(total, word_no=30): ...
Handle encoding of the random words.
Handle encoding of the random words.
Python
bsd-3-clause
us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite
7d94abed2316c5ee6679f33d43c122b9bfcedab7
extra_countries/migrations/0001_initial.py
extra_countries/migrations/0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('continents', '0001_initial'), ('currencies', '0001_initial'), ('cities', '0002_auto_20151112_1857'), ] operations = ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('continents', '0001_initial'), ('currencies', '0001_initial'), ] operations = [ migrations.CreateModel( n...
Remove reference to nonexistent migration to fix tests
Remove reference to nonexistent migration to fix tests
Python
mit
openspending/cosmopolitan,kiote/cosmopolitan
8a71fe98d50f7603742c60273502fb840e967c97
scalpel/event.py
scalpel/event.py
""" Author: Thiago Marcos P. Santos Created: August 28, 2008 Purpose: A signal/slot implementation """ from weakref import WeakValueDictionary class Signal(object): def __init__(self): self.__slots = WeakValueDictionary() def __call__(self, *args, **kargs): for key in self._...
""" Author: Thiago Marcos P. Santos Created: August 28, 2008 Purpose: A signal/slot implementation URL: http://code.activestate.com/recipes/576477/ Comment: Slightly modified with code from Patrick Chasco (http://code.activestate.com/recipes/439356/) to support connecting functions. """ ...
Add support for connecting functions to Signal objects.
Add support for connecting functions to Signal objects. Less elegant than the original recipe, but more functional.
Python
bsd-3-clause
stackp/Gum,stackp/Gum,stackp/Gum
fec482c6b1655d7108386760a3e0297850da6e7b
editorsnotes/api/validators.py
editorsnotes/api/validators.py
from rest_framework.serializers import ValidationError class UniqueToProjectValidator: message = u'{model_name} with this {field_name} already exists.' def __init__(self, field, message=None): self.field_name = field self.message = message or self.message def set_context(self, serializer...
from rest_framework.serializers import ValidationError class UniqueToProjectValidator: message = u'{model_name} with this {field_name} already exists.' def __init__(self, field, message=None): self.field_name = field self.message = message or self.message def set_context(self, serializer...
Make sure a project is set for the project-specific validator
Make sure a project is set for the project-specific validator
Python
agpl-3.0
editorsnotes/editorsnotes,editorsnotes/editorsnotes
57f131218ac7362fdf85389b73dcafb9d35897f4
TriangleSimilarityDistanceCalculator.py
TriangleSimilarityDistanceCalculator.py
# Calculate the distance to an object of known size. # We need to know the perceived focal length for this to work. # # Known Focal Length values for calibrated cameras # Logitech C920: H620 V? # Microsoft Lifecam HD-3000: H652 V? # class TriangleSimilarityDistanceCalculator: knownSize = 0...
# Calculate the distance to an object of known size. # We need to know the perceived focal length for this to work. # # Known Focal Length values for calibrated cameras # Logitech C920: H622 V625 # Microsoft Lifecam HD-3000: H652 V? # PFL_H_C920 = 622 PFL_V_C920 = 625 PFL_H_LC3000 = 652 PF...
Update measured Focal Lengths for C920.
Update measured Focal Lengths for C920.
Python
mit
AluminatiFRC/Vision2016,AluminatiFRC/Vision2016
e82474c0281aebe3b623a5be9adc0adf14fa58d5
ann_util.py
ann_util.py
import math import random def logistic(x): return 1.0 / (1 + math.exp(-x)) def deriv_logistic(x): lgst = logistic(x) return (1 - lgst) * lgst def hyperbolic_tangent(x): return math.tanh(x) def deriv_hyperbolic_tangent(x): th = math.tanh(x) return 1 - th * th def between(min, max): ...
import math import pickle import random def logistic(x): return 1.0 / (1 + math.exp(-x)) def deriv_logistic(x): lgst = logistic(x) return (1 - lgst) * lgst def hyperbolic_tangent(x): return math.tanh(x) def deriv_hyperbolic_tangent(x): th = math.tanh(x) return 1 - th * th def between(m...
Add pickle serialize and deserialize
Add pickle serialize and deserialize
Python
apache-2.0
Razvy000/ANN_Course
6dd403ae88a11457c7930639781182afff892761
UM/__init__.py
UM/__init__.py
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. #Shoopdawoop ## \package UM # This is the main library for Uranium applications.
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. #Shoopdawoop ## \package UM # This is the main library for Uranium applications. from .Application import Application from .ColorGenerator import ColorGenerator from .Controller import Controller from .Event import Ev...
Allow new import style for UM directory
Allow new import style for UM directory This imports all public classes in the UM namespace rather than leaving them inside the modules in that namespace. For example, this allows directly importing UM.Logger and then using UM.Logger.log(...) to log a message. Contributes to ALL ISSUES AT THE SAME TIME.
Python
agpl-3.0
onitake/Uranium,onitake/Uranium
69f7490b6ed28c28784148295dec2144344f4ed8
config.py
config.py
import os if os.environ.get('DATABASE_URL') is None: SQLALCHEMY_DATABASE_URI = 'sqlite:///meetup.db' else: SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning ACCESS_TOKEN = os.environ['ACCESS_TOKEN'] PAGE_ID = os.environ['PAGE_ID'] APP_...
import os SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] SQLALCHEMY_TRACK_MODIFICATIONS = False # suppress deprecation warning ACCESS_TOKEN = os.environ['ACCESS_TOKEN'] PAGE_ID = os.environ['PAGE_ID'] APP_ID = os.environ['APP_ID'] VERIFY_TOKEN = os.environ['VERIFY_TOKEN']
Remove automatic fallback to SQLite
Remove automatic fallback to SQLite It's better to be explicit if there's no DATABASE_URL.
Python
mit
Stark-Mountain/meetup-facebook-bot,Stark-Mountain/meetup-facebook-bot
ab1a2982b6a44bfcfcaff5a3469f2d85f56a86a4
src/cli/_dbus/_manager.py
src/cli/_dbus/_manager.py
""" Manager interface. """ class Manager(object): """ Manager interface. """ _INTERFACE_NAME = 'org.storage.stratis1.Manager' def __init__(self, dbus_object): """ Initializer. :param dbus_object: the dbus object """ self._dbus_object = dbus_object def...
""" Manager interface. """ from ._properties import Properties class Manager(object): """ Manager interface. """ _INTERFACE_NAME = 'org.storage.stratis1.Manager' def __init__(self, dbus_object): """ Initializer. :param dbus_object: the dbus object """ se...
Use Properties interface to get Manager properties.
Use Properties interface to get Manager properties. Signed-off-by: mulhern <7b51bcf507bcd7afb72bf8663752c0ddbeb517f6@redhat.com>
Python
apache-2.0
stratis-storage/stratis-cli,stratis-storage/stratis-cli
bdc554d18dc67cd4979bac3bc5d4b7d01b23b8b4
grako/rendering.py
grako/rendering.py
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import, unicode_literals import itertools from .util import trim def render(item, **fields): """ Render the given item """ if item is None: return '' elif isinstance(item, Renderer): return item.render(**f...
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import, unicode_literals import itertools from .util import trim def render(item, **fields): """ Render the given item """ if item is None: return '' elif isinstance(item, Renderer): return item.render(**f...
Allow override of template through return value of render_fields.
Allow override of template through return value of render_fields.
Python
bsd-2-clause
swayf/grako,swayf/grako
f0984c9855a6283de27e717fad73bb4f1b6394ab
flatten-array/flatten_array.py
flatten-array/flatten_array.py
def flatten(lst): """Completely flatten an arbitrarily-deep list""" return [*_flatten(lst)] def _flatten(lst): """Generator for flattening arbitrarily-deep lists""" if isinstance(lst, (list, tuple)): for item in lst: if item is None: continue else: ...
def flatten(lst): """Completely flatten an arbitrarily-deep list""" return [*_flatten(lst)] def _flatten(lst): """Generator for flattening arbitrarily-deep lists""" for item in lst: if isinstance(item, (list, tuple)): yield from _flatten(item) elif item is not None: ...
Tidy and simplify generator code
Tidy and simplify generator code
Python
agpl-3.0
CubicComet/exercism-python-solutions
8e6a835cf98212545d00f0967b6f6ce936143687
fluxghost/http_server_debug.py
fluxghost/http_server_debug.py
from multiprocessing import Process import sys from fluxghost.http_server_base import HttpServerBase, logger def fork_entry(request, client, server): from fluxghost.http_handler import HttpHandler HttpHandler(request, client, server) def check_autoreload(): if "fluxghost.http_handler" in sys.modules:...
from multiprocessing import Process import sys from fluxghost.http_server_base import HttpServerBase, logger def fork_entry(request, client, server): from fluxghost.http_handler import HttpHandler HttpHandler(request, client, server) def check_autoreload(): if "fluxghost.http_handler" in sys.modules:...
Fix missing close socket error
Fix missing close socket error
Python
agpl-3.0
flux3dp/fluxghost,flux3dp/fluxghost,flux3dp/fluxghost,flux3dp/fluxghost
25746ab22ce7031e1bbee27bb04af73264525f4c
game/functional/test_input.py
game/functional/test_input.py
from twisted.trial.unittest import TestCase from twisted.internet import reactor from game.functional.test_view3d import SceneMixin from game.player import Player from game.vector import Vector class StdoutReportingController(object): # XXX Make an interface for the controller and verify this fake. def __ini...
from pygame import K_q from twisted.trial.unittest import TestCase from twisted.internet import reactor from game.functional.test_view3d import SceneMixin from game.player import Player from game.vector import Vector class QuittableController(object): # XXX Make an interface for the controller and verify these...
Add a functional test for mouse grab.
Add a functional test for mouse grab.
Python
mit
eriknelson/gam3
2c00876b60cdebfe1ed9ffd93b3064abaf3a20a0
rma/rule/GlobalKeySpace.py
rma/rule/GlobalKeySpace.py
from rma.redis import * class GlobalKeySpace: def __init__(self, redis): """ :param RmaRedis redis: :return: """ self.redis = redis def analyze(self, keys=[]): total_keys = self.redis.total_keys() return [ { 'headers': ['Stat'...
from rma.redis import * class GlobalKeySpace: def __init__(self, redis): """ :param RmaRedis redis: :return: """ self.redis = redis def analyze(self, keys=[]): total_keys = self.redis.total_keys() keys_ = [ ["Total keys in db", total_keys], ...
Add max config to globals
Add max config to globals
Python
mit
gamenet/redis-memory-analyzer
4c90c7445b0ccec8658fa71d50aa78a7de9c74b2
salt/defaults/exitcodes.py
salt/defaults/exitcodes.py
# -*- coding: utf-8 -*- ''' Classification of Salt exit codes. These are intended to augment universal exit codes (found in Python's `os` module with the `EX_` prefix or in `sysexits.h`). ''' # Too many situations use "exit 1" - try not to use it when something # else is more appropriate. EX_GENERIC = 1 # Salt SSH "...
# -*- coding: utf-8 -*- ''' Classification of Salt exit codes. These are intended to augment universal exit codes (found in Python's `os` module with the `EX_` prefix or in `sysexits.h`). ''' # Too many situations use "exit 1" - try not to use it when something # else is more appropriate. EX_GENERIC = 1 # Salt SSH "...
Add Salt specific exit code
Add Salt specific exit code
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
e94cb9d7277b2c9312f5b0526faded654d79abcb
tests/test_integration.py
tests/test_integration.py
import os from unittest import TestCase from yoconfigurator.base import read_config from yoconfig import configure_services from pycloudflare.services import CloudFlareService app_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) conf = read_config(app_dir) class ZonesTest(TestCase): def set...
import os from unittest import TestCase from yoconfigurator.base import read_config from yoconfig import configure_services from pycloudflare.services import CloudFlareService app_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) conf = read_config(app_dir) class ZonesTest(TestCase): def set...
Test the actual get_zone call
Test the actual get_zone call
Python
mit
gnowxilef/pycloudflare,yola/pycloudflare
54fdf3922615d5907a2e5344bf027df389572feb
byceps/services/user/transfer/models.py
byceps/services/user/transfer/models.py
""" byceps.services.user.transfer.models ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from __future__ import annotations from dataclasses import dataclass from datetime import date from typing import Any, Optional from .......
""" byceps.services.user.transfer.models ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from __future__ import annotations from dataclasses import dataclass from datetime import date from typing import Any, Optional from .......
Fix display of full user name at least on current user's settings page
Fix display of full user name at least on current user's settings page
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps
8c8c0562e42ce789a283cec59771b1d1f3e95a2d
foreman/data_refinery_foreman/surveyor/management/commands/survey_sra.py
foreman/data_refinery_foreman/surveyor/management/commands/survey_sra.py
""" This command will create and run survey jobs for each SRA run accession in the range from start_accession to end_accession. """ from django.core.management.base import BaseCommand from data_refinery_foreman.surveyor import surveyor from data_refinery_common.logging import get_and_configure_logger logger = get_an...
""" This command will create and run survey jobs for each SRA run accession in the range from start_accession to end_accession. """ import boto3 import botocore import uuid from django.core.management.base import BaseCommand from data_refinery_foreman.surveyor import surveyor from data_refinery_common.logging import ...
Add support of s3 path
Add support of s3 path
Python
bsd-3-clause
data-refinery/data_refinery,data-refinery/data_refinery,data-refinery/data_refinery
6b365ae7d7ab01255643c48755590b8a1a0ae173
src/lib/constants/path.py
src/lib/constants/path.py
VIRTUALENV_DIR = "virtual_env/" VIRTUALENV_ACTIVATE = VIRTUALENV_DIR + "bin/activate_this.py" LOGS = "logs/" YAML = "/etc/ggrc_test.yaml" RESOURCES = "resources/" REQUIREMENTS = RESOURCES + "requirements.txt" SRC = "src/"
VIRTUALENV_DIR = "virtual_env/" BIN_DIR = "bin/" VIRTUALENV_ACTIVATE = "activate_this.py" LOGS = "logs/" YAML = "/etc/ggrc_test.yaml" RESOURCES = "resources/" REQUIREMENTS = RESOURCES + "requirements.txt" SRC = "src/" CHROME_DRIVER = "chromedriver"
Remove operations in module reserved for declaring constants.
Remove operations in module reserved for declaring constants.
Python
apache-2.0
NejcZupec/ggrc-core,plamut/ggrc-core,j0gurt/ggrc-core,NejcZupec/ggrc-core,jmakov/ggrc-core,jmakov/ggrc-core,j0gurt/ggrc-core,VinnieJohns/ggrc-core,jmakov/ggrc-core,kr41/ggrc-core,kr41/ggrc-core,kr41/ggrc-core,VinnieJohns/ggrc-core,andrei-karalionak/ggrc-core,AleksNeStu/ggrc-core,josthkko/ggrc-core,selahssea/ggrc-core,s...
5f6d994dfde18206e000537510b87f451234f1d3
installer/installer_config/forms.py
installer/installer_config/forms.py
from django import forms from django.forms.models import ModelForm from installer_config.models import EnvironmentProfile, Package, TerminalPrompt class EnvironmentForm(ModelForm): packages = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryse...
from django import forms from django.forms.models import ModelForm from installer_config.models import EnvironmentProfile, UserChoice class EnvironmentForm(ModelForm): packages = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=UserChoice....
Fix form to query UserChoices, not Packages
Fix form to query UserChoices, not Packages
Python
mit
ezPy-co/ezpy,ezPy-co/ezpy,alibulota/Package_Installer,alibulota/Package_Installer
e69c9db3efc5f71a5852a28ea77a215d083a6b64
server/inventory/views.py
server/inventory/views.py
from django.shortcuts import render from django.core import serializers from inventory.models import Item from decimal import Decimal import json from django.utils import simplejson # Create your views here. from django.http import HttpResponse from inventory.models import Item def index(request): if request.meth...
from django.shortcuts import render from django.core import serializers from inventory.models import Item from decimal import Decimal import json from django.utils import simplejson # Create your views here. from django.http import HttpResponse from inventory.models import Item def index(request): if request.meth...
Add the 401 Unauthorized when no username is detected, thus no user is logged in. This is the most basic form of permissions, where any user can log in and do anything.
Add the 401 Unauthorized when no username is detected, thus no user is logged in. This is the most basic form of permissions, where any user can log in and do anything.
Python
agpl-3.0
TomDataworks/angular-inventory,TomDataworks/angular-inventory
428b4b0025dd7bb0edf5d3df8c32703d96ab577b
src/shared/unit_orders.py
src/shared/unit_orders.py
class UnitOrders(object): def __init__(self): self.orders = {} def giveOrders(self, unit, orders): if orders is not None and not isinstance(orders, list): orders = list(orders) self.orders[unit] = orders def getNextOrder(self, unit): try: return self...
class UnitOrders(object): def __init__(self): self.orders = {} def giveOrders(self, unit, orders): if orders is not None and not isinstance(orders, list): orders = list(orders) self.orders[unit] = orders def getNextOrder(self, unit): try: orders = se...
Check for None before indexing.
Check for None before indexing.
Python
mit
CheeseLord/warts,CheeseLord/warts
74b03f3d47011bad6129f8ccfe466a4b28d2338a
troposphere/workspaces.py
troposphere/workspaces.py
# Copyright (c) 2015, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject from .validators import boolean class Workspace(AWSObject): resource_type = "AWS::WorkSpaces::Workspace" props = { 'BundleId': (basestring, True), 'DirectoryI...
# Copyright (c) 2015, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, AWSProperty, Tags from .validators import boolean, integer class WorkspaceProperties(AWSProperty): props = { 'ComputeTypeName': (basestring, False), 'RootVolumeSi...
Add Tags and WorkspaceProperties to WorkSpaces::Workspace
Add Tags and WorkspaceProperties to WorkSpaces::Workspace
Python
bsd-2-clause
johnctitus/troposphere,cloudtools/troposphere,johnctitus/troposphere,pas256/troposphere,pas256/troposphere,cloudtools/troposphere,ikben/troposphere,ikben/troposphere
0218edee60a56996d97fbaa7e35f0c695bf5e3a9
src/hpp/utils.py
src/hpp/utils.py
# Copyright (c) 2020, CNRS # Authors: Guilhem Saurel <guilhem.saurel@laas.fr> import os import subprocess import time import hpp.corbaserver try: from subprocess import DEVNULL, run except ImportError: # Python2 fallback DEVNULL = os.open(os.devnull, os.O_RDWR) def run(*args): subprocess.Popen(*...
# Copyright (c) 2020, CNRS # Authors: Guilhem Saurel <guilhem.saurel@laas.fr> import os import subprocess import time import hpp.corbaserver try: from subprocess import DEVNULL, run except ImportError: # Python2 fallback DEVNULL = os.open(os.devnull, os.O_RDWR) def run(*args): subprocess.Popen(*...
Add sleep after shutting down hppcorbaserver in ServerManager
Add sleep after shutting down hppcorbaserver in ServerManager Co-authored-by: Joseph Mirabel <c794dc978753694c40f4d5fd4b8c12595a76e068@gmail.com>
Python
bsd-2-clause
humanoid-path-planner/hpp-corbaserver,humanoid-path-planner/hpp-corbaserver
cfa3851b83e8c13ed1bb553eced344d162c05dfb
singleuser/user-config.py
singleuser/user-config.py
import os mylang = 'test' family = 'wikipedia' custom_path = os.path.expanduser('~/user-config.py') if os.path.exists(custom_path): with open(custom_path, 'r') as f: variables = globals() # Do not pass in variables we do not want users to change for var in ['usernames', 'sysopnames']: ...
import os mylang = 'test' family = 'wikipedia' custom_path = os.path.expanduser('~/user-config.py') if os.path.exists(custom_path): with open(custom_path, 'r') as f: exec(compile(f.read(), custom_path, 'exec'), globals()) del f # Clean up temp variables, since pwb issues a warning otherwise # to hel...
Revert "Do not allow easy setting of username to something else"
Revert "Do not allow easy setting of username to something else" This removes the usernames completely, making it fail when we try to set it later. This reverts commit b49967ad58c520279a244a15ed81bca5453b923e.
Python
mit
yuvipanda/paws,yuvipanda/paws
91d613ace34bf8f50a86ec3464612af561d398c4
tests/test_boto_store.py
tests/test_boto_store.py
#!/usr/bin/env python import os from tempdir import TempDir import pytest boto = pytest.importorskip('boto') from simplekv.net.botostore import BotoStore from basic_store import BasicStore from url_store import UrlStore from bucket_manager import boto_credentials, boto_bucket @pytest.fixture(params=boto_credentia...
#!/usr/bin/env python import os from tempdir import TempDir import pytest boto = pytest.importorskip('boto') from simplekv.net.botostore import BotoStore from basic_store import BasicStore from url_store import UrlStore from bucket_manager import boto_credentials, boto_bucket @pytest.fixture(params=boto_credentia...
Fix another boto /dev/null testing error.
Fix another boto /dev/null testing error.
Python
mit
karteek/simplekv,fmarczin/simplekv,fmarczin/simplekv,mbr/simplekv,mbr/simplekv,karteek/simplekv
05b54e3ac66da81733e8bb04eb949dec4e6be904
lamana/lt_exceptions.py
lamana/lt_exceptions.py
# ----------------------------------------------------------------------------- '''General classes for a custom exceptions.''' class Error(Exception): pass class FormatError(Error): '''Associate with geo_string formatting.''' pass class InvalidError(Error): '''Associate with invalid, impossible ge...
# ----------------------------------------------------------------------------- '''General classes for a custom exceptions.''' class Error(Exception): pass class FormatError(Error): '''Associated with geo_string formatting.''' pass #class ValidationError(Error): # '''Associate with invalid, impossi...
Add and deprecate custom expections
Add and deprecate custom expections
Python
bsd-3-clause
par2/lamana
b180c7e3907df74252ee3270468a768036dc4467
tests/test_timeseries.py
tests/test_timeseries.py
import unittest from datetime import datetime, timedelta import sys sys.path.append(r"..") from daymetpy import download_Daymet class TimeseriesTest(unittest.TestCase): def setUp(self): pass def test_ornl_df(self): ornl_lat, ornl_long = 35.9313167, -84.3104124 df = down...
import unittest from datetime import datetime, timedelta import sys sys.path.append(r"../..") from daymetpy import daymet_timeseries class TimeseriesTest(unittest.TestCase): def setUp(self): pass def test_ornl_df(self): ornl_lat, ornl_long = 35.9313167, -84.3104124 df =...
Update test to new package structure
Update test to new package structure
Python
agpl-3.0
khufkens/daymetpy
2feda27b60874de513224256c553dfee32e1a982
tests/lexer/test_lexer.py
tests/lexer/test_lexer.py
import pytest from tests.infrastructure.test_utils import lexer_single from thinglang.lexer.tokens.indent import LexicalIndent from thinglang.lexer.values.identifier import Identifier from thinglang.lexer.values.inline_text import InlineString UNTERMINATED_GROUPS = 'hello"', '"hello', 'hello`', '`hello', '"hello`', '...
import pytest from tests.infrastructure.test_utils import lexer_single from thinglang.lexer.operators.comparison import LexicalEquals from thinglang.lexer.tokens.indent import LexicalIndent from thinglang.lexer.values.identifier import Identifier from thinglang.lexer.values.inline_text import InlineString UNTERMINATE...
Add test for string escaping
Add test for string escaping
Python
mit
ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang
08d42200150f60e7d629911ee96a12021ae99206
build_yaml_macros.py
build_yaml_macros.py
import sublime import sublime_plugin import os from os import path from .src.build import build_yaml_macros class BuildYamlMacrosCommand(sublime_plugin.WindowCommand): def run(self, working_dir=None): if working_dir: os.chdir(working_dir) view = self.window.active_view(); sou...
import sublime import sublime_plugin import os from os import path from .src.build import build_yaml_macros class BuildYamlMacrosCommand(sublime_plugin.WindowCommand): def run(self, working_dir=None): if working_dir: os.chdir(working_dir) view = self.window.active_view(); sou...
Use with context manager to handle file access
Use with context manager to handle file access Currently, after the build completes the output file is not closed, and so it remains locked and is unable to be edited by other processes.
Python
mit
Thom1729/YAML-Macros
9a8544eaccde1420e6cbac7b4c5115155d6402f3
django_docutils/__about__.py
django_docutils/__about__.py
__title__ = 'django-docutils' __package_name__ = 'django_docutils' __description__ = 'Documentation Utilities (Docutils, reStructuredText) for django.' __version__ = '0.4.0' __author__ = 'Tony Narlock' __email__ = 'tony@git-pull.com' __license__ = 'BSD' __copyright__ = 'Copyright 2013-2015 Tony Narlock'
__title__ = 'django-docutils' __package_name__ = 'django_docutils' __description__ = 'Documentation Utilities (Docutils, reStructuredText) for django.' __version__ = '0.4.0' __author__ = 'Tony Narlock' __github__ = 'https://github.com/tony/django-docutils' __pypi__ = 'https://pypi.org/project/django-docutils/' __email_...
Add github + pypi to metadata
Add github + pypi to metadata
Python
mit
tony/django-docutils,tony/django-docutils
145749cc7ee4c67a494f0287850597740b7f002a
modules/module_karma.py
modules/module_karma.py
import re import sqlite3 def do_karma(bot, user, channel, karma): if karma[1] == '++': k = 1 else: k = -1 conn = sqlite3.connect('karma.db') c = conn.cursor() t = (karma[0],) c.execute('select * from karma where word=?', t) res = c.fetchone() if res != None: u ...
import re import sqlite3 def do_karma(bot, user, channel, karma): if karma[1] == '++': k = 1 else: k = -1 conn = sqlite3.connect('karma.db') c = conn.cursor() t = (karma[0],) c.execute('select * from karma where word=?', t) res = c.fetchone() if res != None: u ...
Add .tolower() when adding to DB to avoid potential issues
Add .tolower() when adding to DB to avoid potential issues
Python
bsd-3-clause
nigeljonez/newpyfibot
c491759a0f71479b4faa68a747ff149b78b109e0
tests/test_observatory.py
tests/test_observatory.py
""" test_heavy.py BlimPy """ from blimpy.ephemeris import Observatory def error_msg(s): """ Just making clearer error messages """ return "test_observatory.py: " + s def test_observatory_construction(): """ Constructor test """ obs = Observatory(telescope_id=0) assert obs.get_telescope_name() !=...
""" test_heavy.py BlimPy """ from blimpy.ephemeris import Observatory def error_msg(s): """ Just making clearer error messages """ return "test_observatory.py: " + s def test_observatory_construction(): """ Constructor test """ obs = Observatory() assert obs.get_telescope_name() != "Fake", error...
Increase test coverage for ephemris
Increase test coverage for ephemris
Python
bsd-3-clause
UCBerkeleySETI/blimpy,UCBerkeleySETI/blimpy
5683aa0d2674214050ed1ea97e528ba39e39b126
cosmos/cli.py
cosmos/cli.py
import os import json import click from cosmos import Data def validate_filename(ctx, param, value): if not os.path.exists(value): print('No such directory: {}'.format(value)) ctx.exit() ext = os.path.splitext(value)[1] if ext not in ['.json', '.geojson']: raise click.BadParamete...
import os import json import click from cosmos import Data def validate_filename(ctx, param, value): if os.path.dirname(value) and not os.path.isdir(os.path.dirname(value)): print('No such directory: {}'.format(value)) ctx.exit() ext = os.path.splitext(value)[1] if ext not in ['.json', '...
Fix for checking directory and short params.
Fix for checking directory and short params.
Python
mit
astrosat/cOSMos
e4fe21b1e1366a1676d2129575ee7c19f6fc6547
models.py
models.py
class Color(object): def __init__(self, r, g, b): self.r = r self.g = g self.b = b class Line(object): def __init__(self, name, api_code, bg_color, fg_color): self.name = name self.api_code = api_code self.bg_color = bg_color self.fg_color = fg_color ...
class Color(object): def __init__(self, r, g, b): self.r = r self.g = g self.b = b def __repr__(self): return '%s,%s,%s' % (self.r, self.g, self.b) __unicode__ = __repr__ class Line(object): def __init__(self, name, api_code, bg_color, fg_color): self.name = na...
Add string representation for colors
Add string representation for colors
Python
mit
kirberich/tube_status
e87e5b2fb0947d280c38a46f6f6e94808be9fa7a
txircd/modules/cmode_p.py
txircd/modules/cmode_p.py
from txircd.modbase import Mode class PrivateMode(Mode): def listOutput(self, command, data): if command != "LIST": return data cdata = data["cdata"] if "p" in cdata["channel"].mode and cdata["channel"].name not in data["user"].channels: cdata["name"] = "*" ...
from txircd.modbase import Mode class PrivateMode(Mode): def listOutput(self, command, data): if command != "LIST": return data if "cdata" not in data: return data cdata = data["cdata"] if "p" in cdata["channel"].mode and cdata["channel"].name not in data["us...
Fix LIST crashing on certain input
Fix LIST crashing on certain input
Python
bsd-3-clause
Heufneutje/txircd,ElementalAlchemist/txircd,DesertBus/txircd
d2da0b71c36f32305ef55e2cbbf2041eb7b06cf6
Project/tools/lib.py
Project/tools/lib.py
# # lib.py: utility functions for the Motebopok handlers # """This file takes the difficulties out of working with directories, and it also reduces clutter in at least one program.""" import os def newer(file1, file2): file1_creation = os.stat(file1).st_mtime file2_creation = os.stat(file2).st_mtime retur...
# # lib.py: utility functions for the Motebopok handlers # """This file takes the difficulties out of working with directories, and it also reduces clutter in at least one program.""" import os def newer(file1, file2): file1_modification = os.stat(file1).st_mtime file2_modification = os.stat(file2).st_mtime ...
Use modification, not creation times to determine relative newness.
Use modification, not creation times to determine relative newness.
Python
mit
holdenweb/nbtools,holdenweb/nbtools
87b051a4d97f54af16c37c118be654243c8b36cd
application.py
application.py
from paste.deploy import loadapp from waitress import serve from opreturnninja.config import config if __name__ == "__main__": app = loadapp('config:production.ini', relative_to='.') serve(app, host='0.0.0.0', port=config.PORT)
from paste.deploy import loadapp from waitress import serve from opreturnninja.config import config if __name__ == "__main__": print("Loading application.py") app = loadapp('config:production.ini', relative_to='.') serve(app, host='0.0.0.0', port=config.PORT)
Add a print statement; heroku not building :/
Add a print statement; heroku not building :/
Python
mit
XertroV/opreturn-ninja,XertroV/opreturn-ninja,XertroV/opreturn-ninja
89d6c81529d1f0f467a098934a670c57e463188f
cmcb/reddit.py
cmcb/reddit.py
import asyncio import functools import praw class AsyncRateRedditAPI: def __init__(self, client_id, client_secret, user_agent, username, password, loop=None): self._reddit = praw.Reddit( client_id=client_id, client_secret=client_secret, user_agent=user_agent, username...
import praw class AsyncRateRedditAPI: def __init__(self, client_id, client_secret, user_agent, username, password): self._reddit = praw.Reddit( client_id=client_id, client_secret=client_secret, user_agent=user_agent, username=username, password=password) async def...
Revert Reddit api to its synchonous state
Revert Reddit api to its synchonous state
Python
mit
festinuz/cmcb,festinuz/cmcb
c6d949cbb32e095e5859aa22d11aa1566f5bc63f
website/util/mimetype.py
website/util/mimetype.py
import os import mimetypes HERE = os.path.dirname(os.path.abspath(__file__)) MIMEMAP = os.path.join(HERE, 'mime.types') def get_mimetype(path, data=None): mimetypes.init([MIMEMAP]) mimetype, _ = mimetypes.guess_type(path) if mimetype is None and data is not None: try: import magic ...
import os import mimetypes HERE = os.path.dirname(os.path.abspath(__file__)) MIMEMAP = os.path.join(HERE, 'mime.types') def get_mimetype(path, file_contents=None): mimetypes.init([MIMEMAP]) mimetype, _ = mimetypes.guess_type(path) if mimetype is None and file_contents is not None: try: ...
Make better name for argument.
Make better name for argument.
Python
apache-2.0
mfraezz/osf.io,saradbowman/osf.io,danielneis/osf.io,reinaH/osf.io,amyshi188/osf.io,GageGaskins/osf.io,wearpants/osf.io,KAsante95/osf.io,billyhunt/osf.io,petermalcolm/osf.io,danielneis/osf.io,cldershem/osf.io,samanehsan/osf.io,abought/osf.io,GaryKriebel/osf.io,CenterForOpenScience/osf.io,erinspace/osf.io,dplorimer/osf,a...
b8c2376368290fa4fef103ba86d4f2ed164a3b7d
numscons/checkers/__init__.py
numscons/checkers/__init__.py
from blas_lapack_checkers import CheckCLAPACK, CheckCBLAS, CheckF77BLAS, CheckF77LAPACK from fft_checkers import CheckFFT from simple_check import NumpyCheckLibAndHeader from perflib import * from fortran import * from perflib_info import write_info import blas_lapack_checkers import fft_checkers import perflib imp...
from numscons.checkers.new.netlib_checkers import \ CheckCblas as CheckCBLAS, \ CheckF77Blas as CheckF77BLAS, \ CheckF77Lapack as CheckF77LAPACK from numscons.checkers.new.common import \ get_perflib_implementation from numscons.checkers.new.common import \ write_configuration_re...
Use the new framework for checkers.
Use the new framework for checkers.
Python
bsd-3-clause
cournape/numscons,cournape/numscons,cournape/numscons
f200d98547baef9ac2faa90d72857ffa0e64c721
IPython/nbconvert/exporters/python.py
IPython/nbconvert/exporters/python.py
"""Python script Exporter class""" #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------...
"""Python script Exporter class""" #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------...
Add MIME types to nbconvert exporters
Add MIME types to nbconvert exporters
Python
bsd-3-clause
cornhundred/ipywidgets,jupyter-widgets/ipywidgets,cornhundred/ipywidgets,SylvainCorlay/ipywidgets,SylvainCorlay/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,ipython/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,cornhundred/ipywidg...
fda1b41890ea338e992ddd8a23d9c6a497990ea2
fabfile/eg.py
fabfile/eg.py
# coding: utf-8 from __future__ import unicode_literals, print_function from fabric.api import task, local, run, lcd, cd, env, shell_env from fabtools.python import virtualenv from _util import PWD, VENV_DIR @task def mnist(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python...
# coding: utf-8 from __future__ import unicode_literals, print_function from fabric.api import task, local, run, lcd, cd, env, shell_env from fabtools.python import virtualenv from _util import PWD, VENV_DIR @task def mnist(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python...
Add fabric task for Quora example
Add fabric task for Quora example
Python
mit
spacy-io/thinc,explosion/thinc,explosion/thinc,spacy-io/thinc,spacy-io/thinc,explosion/thinc,explosion/thinc
c604ace9394cdc1c0c0a3002cbb3d90dd64695f3
examples/mnist-classifier.py
examples/mnist-classifier.py
#!/usr/bin/env python import cPickle import gzip import logging import os import sys import tempfile import urllib import lmj.tnn logging.basicConfig( stream=sys.stdout, format='%(levelname).1s %(asctime)s %(message)s', level=logging.INFO) URL = 'http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.p...
#!/usr/bin/env python import cPickle import gzip import logging import os import sys import tempfile import urllib import lmj.tnn logging.basicConfig( stream=sys.stdout, format='%(levelname).1s %(asctime)s %(message)s', level=logging.INFO) URL = 'http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.p...
Save mnist classifier model in a file named with the network topology.
Save mnist classifier model in a file named with the network topology.
Python
mit
lmjohns3/theanets,chrinide/theanets,devdoer/theanets
e5083fd56caa271afbdbad1c59009f7e1ea465b3
content/app.py
content/app.py
from flask import Flask from .extensions import envcfg, apierrors, applogging from .blueprints.status import blueprint as status_bp from .blueprints.content import blueprint as content_bp from .blueprints.swagger import blueprint as swagger_bp def create_app(): app = Flask('content') app.config.from_object('...
from flask import Flask, jsonify from botocore.exceptions import ClientError from .extensions import envcfg, apierrors, applogging from .blueprints.status import blueprint as status_bp from .blueprints.content import blueprint as content_bp from .blueprints.swagger import blueprint as swagger_bp def create_app(): ...
Return 404 when no content found.
Return 404 when no content found.
Python
bsd-3-clause
Zipmatch/zipmatch-content,Zipmatch/zipmatch-content
1b455898665ceedec330dea68e53ece4719b2898
cumulusci/utils/yaml/cumulusci_yml.py
cumulusci/utils/yaml/cumulusci_yml.py
from typing import IO, Text from re import compile, MULTILINE from logging import getLogger from io import StringIO import yaml NBSP = "\u00A0" pattern = compile(r"^\s*[\u00A0]+\s*", MULTILINE) logger = getLogger(__name__) def _replace_nbsp(origdata): counter = 0 def _replacer_func(matchobj): non...
from typing import IO, Text import re from logging import getLogger from io import StringIO import yaml NBSP = "\u00A0" pattern = re.compile(r"^\s*[\u00A0]+\s*", re.MULTILINE) logger = getLogger(__name__) def _replace_nbsp(origdata): counter = 0 def _replacer_func(matchobj): nonlocal counter ...
Improve error message and imports
Improve error message and imports
Python
bsd-3-clause
SalesforceFoundation/CumulusCI,SalesforceFoundation/CumulusCI
3d00536041d52900a4ace5304b5b07eba4c11efb
wmt/flask/names/models.py
wmt/flask/names/models.py
#from flask_security import UserMixin, RoleMixin from standard_names import StandardName from ..core import db class Name(db.Model): __tablename__ = 'names' __bind_key__ = 'names' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.Text) def __init__(self, name): self.name =...
from flask import url_for from standard_names import StandardName from ..core import db, JsonMixin class NameJsonSerializer(JsonMixin): __public_fields__ = set(['href', 'id', 'name', 'object', 'quantity', 'operators']) class Name(NameJsonSerializer, db.Model): __tablename__ = '...
Use the JsonMixin for the names model.
Use the JsonMixin for the names model.
Python
mit
mcflugen/wmt-rest,mcflugen/wmt-rest
2fac490ed8926bf04e396ded35340f880e9c49b6
wikilink/db/connection.py
wikilink/db/connection.py
from sqlalchemy import create_engine from sqlalchemy_utils import functions from sqlalchemy.orm import sessionmaker from .base import Base class Connection: def __init__(self, db, name, password, ip, port): if db == "postgresql": connection = "postgresql+psycopg2://" + name + ":" + password + "@" + ip + ...
from sqlalchemy import create_engine from sqlalchemy_utils import functions from sqlalchemy.orm import sessionmaker from .base import Base class Connection: def __init__(self, db, name, password, ip, port): if db == "postgresql": connection = "postgresql+psycopg2://" + name + ":" + password + "@" + ip + ...
Add exception for wrong type of db
Add exception for wrong type of db
Python
apache-2.0
tranlyvu/findLink,tranlyvu/find-link
d404b91cc7af75c343c78fe44273a8cff8aa5663
feincms/module/page/admin.py
feincms/module/page/admin.py
# ------------------------------------------------------------------------ # coding=utf-8 # ------------------------------------------------------------------------ from __future__ import absolute_import from django.conf import settings from django.contrib import admin from django.core.exceptions import ImproperlyCon...
# ------------------------------------------------------------------------ # coding=utf-8 # ------------------------------------------------------------------------ from __future__ import absolute_import from django.conf import settings from django.contrib import admin from django.core.exceptions import ImproperlyCon...
Add a note concerning FEINCMS_USE_PAGE_ADMIN
Add a note concerning FEINCMS_USE_PAGE_ADMIN
Python
bsd-3-clause
joshuajonah/feincms,matthiask/feincms2-content,feincms/feincms,nickburlett/feincms,nickburlett/feincms,feincms/feincms,matthiask/django-content-editor,matthiask/django-content-editor,matthiask/django-content-editor,michaelkuty/feincms,feincms/feincms,michaelkuty/feincms,matthiask/feincms2-content,nickburlett/feincms,mj...
a8599728ea4b306776b4ba8aa92e333671571e4d
tensorflow_text/python/keras/layers/__init__.py
tensorflow_text/python/keras/layers/__init__.py
# coding=utf-8 # Copyright 2021 TF.Text Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
# coding=utf-8 # Copyright 2021 TF.Text Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
Add missing symbols for tokenization layers
Add missing symbols for tokenization layers Tokenization layers are now exposed by adding them to the list of allowed symbols. Cheers
Python
apache-2.0
tensorflow/text,tensorflow/text,tensorflow/text
d9dce6f97019d688750c8143777d2c9e2acd4170
qtpy/QtOpenGLWidgets.py
qtpy/QtOpenGLWidgets.py
# ----------------------------------------------------------------------------- # Copyright © 2009- The Spyder Development Team # # Licensed under the terms of the MIT License # (see LICENSE.txt for details) # ----------------------------------------------------------------------------- """Provides QtOpenGLWidgets cla...
# ----------------------------------------------------------------------------- # Copyright © 2009- The Spyder Development Team # # Licensed under the terms of the MIT License # (see LICENSE.txt for details) # ----------------------------------------------------------------------------- """Provides QtOpenGLWidgets cla...
Fix wrong module name in error message
Fix wrong module name in error message
Python
mit
spyder-ide/qtpy
2021cdbe3304c91af03d9664e05c9bbc1a197f4d
python/ql/test/experimental/library-tests/frameworks/yaml/Decoding.py
python/ql/test/experimental/library-tests/frameworks/yaml/Decoding.py
import yaml from yaml import SafeLoader yaml.load(payload) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.load(payload, Loader=SafeLoader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.load(payload, Loader=yaml.BaseLoader) # $decodeInput=payload...
import yaml from yaml import SafeLoader yaml.load(payload) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.load(payload, SafeLoader) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML SPURIOUS: decodeMayExecuteInput yaml.load(payload, Loader=SafeLoader) #...
Add tests for more yaml loading functions
Python: Add tests for more yaml loading functions
Python
mit
github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql
b535dcc490f56a54b92443172ad0b5828bc5a540
rpcd/playbooks/roles/horizon_extensions/templates/_50_rackspace.py
rpcd/playbooks/roles/horizon_extensions/templates/_50_rackspace.py
DASHBOARD = 'rackspace' ADD_INSTALLED_APPS = [ 'rackspace', ] # If set to True, this dashboard will not be added to the settings. DISABLED = False
DASHBOARD = 'rackspace' ADD_INSTALLED_APPS = [ 'rackspace', ] ADD_ANGULAR_MODULES = ['horizon.dashboard.rackspace'] # If set to True, this dashboard will not be added to the settings. DISABLED = False
Fix enabled file installed from horizon-extensions
Fix enabled file installed from horizon-extensions Add the angularjs module containing the Rackspace Solutions panel code to the Horizon application so it works. Requires accompanying patch https://github.com/rcbops/horizon-extensions/pull/7 for the panel to work with this change. closes 891
Python
apache-2.0
cfarquhar/rpc-openstack,galstrom21/rpc-openstack,mancdaz/rpc-openstack,sigmavirus24/rpc-openstack,cloudnull/rpc-openstack,major/rpc-openstack,darrenchan/rpc-openstack,cfarquhar/rpc-openstack,mancdaz/rpc-openstack,git-harry/rpc-openstack,darrenchan/rpc-openstack,xeregin/rpc-openstack,prometheanfire/rpc-openstack,robb-ro...
3d5eaf13597bd7cab5dc09e1030b803701f0872f
genda/genders/models.py
genda/genders/models.py
from django.db import models from django.conf import settings class Gender(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name __repr__ = __str__ class UserToPronoun(models.Model): email_hash = models.CharField(max_length=32) user = models.ForeignK...
from django.db import models from django.conf import settings class Gender(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name __repr__ = lambda self: '<{}>'.format(self.__str__()) class UserToPronoun(models.Model): email_hash = models.CharField(max_le...
Correct __str__ & __repr__ implementations
Correct __str__ & __repr__ implementations
Python
mit
Mause/Genda,Mause/Genda
5354a39d62edc12cd5dbea6b1912bf6bdf846999
test_migrations/migrate_test/app/models.py
test_migrations/migrate_test/app/models.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # from modeltrans.fields import TranslationField class Category(models.Model): name = models.CharField(max_length=255) # i18n = TranslationField(fields=('name', )) class Meta: verbose_name_plural = 'cat...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # from modeltrans.fields import TranslationField class Category(models.Model): name = models.CharField(max_length=255) # i18n = TranslationField(fields=('name', ), virtual_fields=False) class Meta: verb...
Disable adding virtual fields during migration
Disable adding virtual fields during migration
Python
bsd-3-clause
zostera/django-modeltrans,zostera/django-modeltrans
c7514e73eff70514659db9ff27aaccf50e99c4c5
account_wallet/models/account_move.py
account_wallet/models/account_move.py
# © 2015 Laetitia Gangloff, Acsone SA/NV (http://www.acsone.eu) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class AccountInvoice(models.Model): _inherit = "account.move" account_wallet_type_id = fields.Many2one( comodel_name='account.wal...
# © 2015 Laetitia Gangloff, Acsone SA/NV (http://www.acsone.eu) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class AccountMove(models.Model): _inherit = "account.move" account_wallet_type_id = fields.Many2one( comodel_name='account.wallet...
Remove former methods as models have been merged
[14.0][IMP] account_wallet: Remove former methods as models have been merged
Python
agpl-3.0
acsone/acsone-addons,acsone/acsone-addons,acsone/acsone-addons
a3bf9240424700f21b1e89b4663ca4e5c12d78ef
django_yadt/utils.py
django_yadt/utils.py
from django.db import models from django.core.management.base import CommandError def get_variant(app_label, model_name, field_name, variant_name): model = models.get_model(app_label, model_name) if model is None: raise CommandError("%s.%s is not a valid model name" % ( app_label, ...
import os from django.db import models from django.core.management.base import CommandError from .fields import IMAGE_VARIANTS def get_variant(app_label, model_name, field_name, variant_name): model = models.get_model(app_label, model_name) if model is None: raise CommandError("%s.%s is not a valid ...
Add a utility for local installations to use the fallback mechanism too.
Add a utility for local installations to use the fallback mechanism too. Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@thread.com>
Python
bsd-3-clause
lamby/django-yadt,thread/django-yadt
b16bd59125fc5a800f5806f713fda3da4446d73c
pokemongo_bot/cell_workers/utils.py
pokemongo_bot/cell_workers/utils.py
# -*- coding: utf-8 -*- import struct from math import cos, asin, sqrt def distance(lat1, lon1, lat2, lon2): p = 0.017453292519943295 a = 0.5 - cos((lat2 - lat1) * p)/2 + cos(lat1 * p) * cos(lat2 * p) * (1 - cos((lon2 - lon1) * p)) / 2 return 12742 * asin(sqrt(a)) * 1000 def i2f(int): return struct.u...
# -*- coding: utf-8 -*- import struct from math import cos, asin, sqrt def distance(lat1, lon1, lat2, lon2): p = 0.017453292519943295 a = 0.5 - cos((lat2 - lat1) * p)/2 + cos(lat1 * p) * cos(lat2 * p) * (1 - cos((lon2 - lon1) * p)) / 2 return 12742 * asin(sqrt(a)) * 1000 def i2f(int): return struct.u...
Fix encoding error when printing messages
Fix encoding error when printing messages Some messages that will be printed will contain utf-8 chars, e.g. Pokestops in European locations.
Python
mit
joergpatz/PokemonGo-Bot,dtee/PokemonGo-Bot,lythien/pokemongo,codybaldwin/PokemonGo-Bot,dhluong90/PokemonGo-Bot,dtee/PokemonGo-Bot,Gobberwart/PokemonGo-Bot,tibotic/simple-pokemongo-bot,yahwes/PokemonGo-Bot,Gobberwart/PokemonGo-Bot,Gobberwart/PokemonGo-Bot,halsafar/PokemonGo-Bot,bbiiggppiigg/PokemonGo-Bot,heihachi/Pokemo...
a1f93a76782b0bf406a16d36f0f60aea8b855566
cogs/points.py
cogs/points.py
from discord.ext import commands from utils import * import discord import asyncio import sqlite3 from member import Member class Points: def __init__(self,bot): self.bot = bot #Test method to populate an array from discord -Infinite @commands.command() @commands.has_role('Leadership') @...
from discord.ext import commands from utils import * import discord import asyncio import sqlite3 from member import Member class Points: def __init__(self,bot): self.bot = bot #Test method to populate an array from discord -Infinite @commands.command() @commands.has_role('Leadership') @...
Fix getmembers command to get role instead of top role.
Fix getmembers command to get role instead of top role.
Python
agpl-3.0
freiheit/Bay-Oh-Woolph,dark-echo/Bay-Oh-Woolph
8603d5e83f1eeac84990cb5353b166dd35fa8140
cyder/base/eav/forms.py
cyder/base/eav/forms.py
from django import forms from django.core.exceptions import ValidationError from cyder.base.eav.models import Attribute class AttributeFormField(forms.CharField): def to_python(self, value): try: return Attribute.objects.get( name=value) except Attribute.DoesNotExist: ...
from django import forms from django.core.exceptions import ValidationError from cyder.base.eav.models import Attribute class AttributeFormField(forms.CharField): def to_python(self, value): try: return Attribute.objects.get( name=value) except Attribute.DoesNotExist: ...
Fix EAV creation form; fix form error bug
Fix EAV creation form; fix form error bug
Python
bsd-3-clause
drkitty/cyder,OSU-Net/cyder,OSU-Net/cyder,zeeman/cyder,akeym/cyder,OSU-Net/cyder,akeym/cyder,zeeman/cyder,zeeman/cyder,murrown/cyder,murrown/cyder,OSU-Net/cyder,drkitty/cyder,murrown/cyder,zeeman/cyder,drkitty/cyder,murrown/cyder,akeym/cyder,akeym/cyder,drkitty/cyder
b4c7a8d35d94f767154da44509a77010b585fe13
daiquiri/query/views.py
daiquiri/query/views.py
from django.views.generic import TemplateView from daiquiri.core.views import ModelPermissionMixin, AnonymousAccessMixin from daiquiri.core.utils import get_model_field_meta from .models import QueryJob, Example class QueryView(AnonymousAccessMixin, TemplateView): template_name = 'query/query.html' anonymou...
from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import TemplateView from daiquiri.core.views import ModelPermissionMixin, AnonymousAccessMixin from daiquiri.core.utils import get_model_field_meta from .models import QueryJob, Example class QueryView(AnonymousAccessMixin, Template...
Disable jobs overview for anonymous users
Disable jobs overview for anonymous users
Python
apache-2.0
aipescience/django-daiquiri,aipescience/django-daiquiri,aipescience/django-daiquiri
c6c06ab8197bfe3f007bab231536656abfcf0954
docs/conf.py
docs/conf.py
# -*- coding: utf-8 -*- import os import sphinx_rtd_theme import sys REPO_DIR = os.path.dirname(os.path.dirname(__file__)) sys.path.append(REPO_DIR) project = 'Ichnaea' copyright = '2013-2019, Mozilla' # The short X.Y version. version = '2.0' # The full version, including alpha/beta/rc tags. release = '2.0' auto...
# -*- coding: utf-8 -*- import os import sphinx_rtd_theme import sys from unittest import mock # Add repository root so we can import ichnaea things REPO_DIR = os.path.dirname(os.path.dirname(__file__)) sys.path.append(REPO_DIR) # Fake the shapely module so things will import sys.modules['shapely'] = mock.MagicMoc...
Add mock for shapely module
Add mock for shapely module Adding a mock for the shapely module allows ReadTheDocs to build the docs even though Shapely isn't installed.
Python
apache-2.0
mozilla/ichnaea,mozilla/ichnaea,mozilla/ichnaea,mozilla/ichnaea
c6447310063a1521d83a4f7fd0b4bc548d54835b
test/test_get_new.py
test/test_get_new.py
from __future__ import absolute_import, print_function from ..pyautoupdate.launcher import Launcher from .pytest_skipif import needinternet from .pytest_makevers import fixture_update_dir import pytest import os @pytest.mark.trylast @needinternet def test_check_vers_update(fixture_update_dir): package=fixture_u...
from __future__ import absolute_import, print_function from ..pyautoupdate.launcher import Launcher from .pytest_skipif import needinternet from .pytest_makevers import fixture_update_dir import pytest import os import sys @pytest.fixture("function") def create_zip(request): def teardown(): if os.path.i...
Add create_zip fixture to get_new test to cover more branches
Add create_zip fixture to get_new test to cover more branches
Python
lgpl-2.1
rlee287/pyautoupdate,rlee287/pyautoupdate
81246153033d38132903759cb7e33cf86c26a548
tests/test_attime.py
tests/test_attime.py
import datetime import time from graphite_api.render.attime import parseATTime from . import TestCase class AtTestCase(TestCase): def test_parse(self): for value in [ str(int(time.time())), '20140319', '20130319+1y', '20130319+1mon', '20130319+...
import datetime import time from graphite_api.render.attime import parseATTime from . import TestCase class AtTestCase(TestCase): def test_parse(self): for value in [ str(int(time.time())), '20140319', '20130319+1y', '20130319+1mon', '20130319+...
Make sure HH:MM values are allowed
Make sure HH:MM values are allowed
Python
apache-2.0
michaelrice/graphite-api,alphapigger/graphite-api,Knewton/graphite-api,vladimir-smirnov-sociomantic/graphite-api,hubrick/graphite-api,GeorgeJahad/graphite-api,absalon-james/graphite-api,raintank/graphite-api,winguru/graphite-api,DaveBlooman/graphite-api,absalon-james/graphite-api,alphapigger/graphite-api,raintank/graph...
21d45e38d07a413aeeb19e10a68e540d1f6d5851
core/forms.py
core/forms.py
# -*- encoding: UTF-8 -*- from core import settings as stCore from django import forms from django.conf import settings as st from django.contrib.flatpages.admin import FlatpageForm from django.contrib.sites.models import Site from django.forms.widgets import HiddenInput, MultipleHiddenInput class PageForm(FlatpageF...
# -*- encoding: UTF-8 -*- from core import settings as stCore from django import forms from django.conf import settings as st from flatpages_i18n.forms import FlatpageForm from django.contrib.sites.models import Site from django.forms.widgets import HiddenInput, MultipleHiddenInput class PageForm(FlatpageForm): ...
Remove last references to flatpage so it doesnt show up on admin page
Remove last references to flatpage so it doesnt show up on admin page
Python
agpl-3.0
tic-ull/portal-del-investigador,tic-ull/portal-del-investigador,tic-ull/portal-del-investigador,tic-ull/portal-del-investigador