commit
stringlengths
40
40
subject
stringlengths
4
1.73k
repos
stringlengths
5
127k
old_file
stringlengths
2
751
new_file
stringlengths
2
751
new_contents
stringlengths
1
8.98k
old_contents
stringlengths
0
6.59k
license
stringclasses
13 values
lang
stringclasses
23 values
d1aed83b46719422c3676a32e7bcfaa5829508b2
add additional test stubs
TeamRemote/remote-sublime,TeamRemote/remote-sublime
tests/test.py
tests/test.py
import sublime from unittest import TestCase version = sublime.version() class TestDiffListener(TestCase): def setUp(self): self.view = sublime.active_window().new_file() def tearDown(self): if self.view: self.view.set_scratch(True) self.view.window().run_command("close_file") def testOnModify(self): # put actual test here pass def testOnClose(self): # insert test here pass
import sublime from unittest import TestCase version = sublime.version() class TestDiffListener(TestCase): def setUp(self): self.view = sublime.active_window().new_file() def tearDown(self): if self.view: self.view.set_scratch(True) self.view.window().run_command("close_file") def TestOnModified(self): # put actual tests here pass
mit
Python
8a47a729a9805032a94b7ce5171609ef3b5cb90d
remove test_missevan
xyuanmu/you-get,xyuanmu/you-get
tests/test.py
tests/test.py
#!/usr/bin/env python import unittest from you_get.extractors import ( imgur, magisto, youtube, missevan, acfun ) class YouGetTests(unittest.TestCase): def test_imgur(self): imgur.download('http://imgur.com/WVLk5nD', info_only=True) def test_magisto(self): magisto.download( 'http://www.magisto.com/album/video/f3x9AAQORAkfDnIFDA', info_only=True ) def test_youtube(self): youtube.download( 'http://www.youtube.com/watch?v=pzKerr0JIPA', info_only=True ) youtube.download('http://youtu.be/pzKerr0JIPA', info_only=True) youtube.download( 'http://www.youtube.com/attribution_link?u=/watch?v%3DldAKIzq7bvs%26feature%3Dshare', # noqa info_only=True ) youtube.download( 'https://www.youtube.com/watch?v=Fpr4fQSh1cc', info_only=True ) def test_acfun(self): acfun.download('https://www.acfun.cn/v/ac11701912', info_only=True) if __name__ == '__main__': unittest.main()
#!/usr/bin/env python import unittest from you_get.extractors import ( imgur, magisto, youtube, missevan, acfun ) class YouGetTests(unittest.TestCase): def test_imgur(self): imgur.download('http://imgur.com/WVLk5nD', info_only=True) def test_magisto(self): magisto.download( 'http://www.magisto.com/album/video/f3x9AAQORAkfDnIFDA', info_only=True ) def test_missevan(self): missevan.download('https://m.missevan.com/sound/1285995', info_only=True) missevan.download_playlist( 'https://www.missevan.com/mdrama/drama/24130', info_only=True) missevan.download_playlist( 'https://www.missevan.com/albuminfo/203090', info_only=True) def test_youtube(self): youtube.download( 'http://www.youtube.com/watch?v=pzKerr0JIPA', info_only=True ) youtube.download('http://youtu.be/pzKerr0JIPA', info_only=True) youtube.download( 'http://www.youtube.com/attribution_link?u=/watch?v%3DldAKIzq7bvs%26feature%3Dshare', # noqa info_only=True ) youtube.download( 'https://www.youtube.com/watch?v=Fpr4fQSh1cc', info_only=True ) def test_acfun(self): acfun.download('https://www.acfun.cn/v/ac11701912', info_only=True) if __name__ == '__main__': unittest.main()
mit
Python
3e2fb3e91acbe5c0db4e6166364c9580715cd6dd
Fix logging
pybel/pybel,pybel/pybel,pybel/pybel
src/pybel/parser/modifiers/truncation.py
src/pybel/parser/modifiers/truncation.py
# -*- coding: utf-8 -*- """ Truncations ~~~~~~~~~~~ Truncations in the legacy BEL 1.0 specification are automatically translated to BEL 2.0 with HGVS nomenclature. :code:`p(HGNC:AKT1, trunc(40))` becomes :code:`p(HGNC:AKT1, var(p.40*))` and is represented with the following dictionary: .. code:: { FUNCTION: PROTEIN, NAMESPACE: 'HGNC', NAME: 'AKT1', VARIANTS: [ { KIND: HGVS, IDENTIFIER: 'p.40*' } ] } Unfortunately, the HGVS nomenclature requires the encoding of the terminal amino acid which is exchanged for a stop codon, and this information is not required by BEL 1.0. For this example, the proper encoding of the truncation at position also includes the information that the 40th amino acid in the AKT1 is Cys. Its BEL encoding should be :code:`p(HGNC:AKT1, var(p.Cys40*))`. Temporary support has been added to compile these statements, but it's recommended they are upgraded by reexamining the supporting text, or looking up the amino acid sequence. .. seealso:: - BEL 2.0 specification on `truncations <http://openbel.org/language/version_2.0/bel_specification_version_2.0.html#_variants_2>`_ - PyBEL module :py:class:`pybel.parser.modifiers.TruncationParser` """ import logging from pyparsing import pyparsing_common as ppc from ..baseparser import BaseParser from ..utils import nest, one_of_tags from ...constants import HGVS, IDENTIFIER, KIND, TRUNCATION_POSITION __all__ = [ 'truncation_tag', 'TruncationParser', ] log = logging.getLogger(__name__) truncation_tag = one_of_tags(tags=['trunc', 'truncation'], canonical_tag=HGVS, name=KIND) class TruncationParser(BaseParser): def __init__(self): self.language = truncation_tag + nest(ppc.integer(TRUNCATION_POSITION)) self.language.setParseAction(self.handle_trunc_legacy) super(TruncationParser, self).__init__(self.language) # FIXME this isn't correct HGVS nomenclature, but truncation isn't forward compatible without more information def handle_trunc_legacy(self, line, position, tokens): upgraded = 'p.{}*'.format(tokens[TRUNCATION_POSITION]) log.warning('trunc() is deprecated. Re-encode with reference terminal amino acid in HGVS: %s', line) tokens[IDENTIFIER] = upgraded del tokens[TRUNCATION_POSITION] return tokens
# -*- coding: utf-8 -*- """ Truncations ~~~~~~~~~~~ Truncations in the legacy BEL 1.0 specification are automatically translated to BEL 2.0 with HGVS nomenclature. :code:`p(HGNC:AKT1, trunc(40))` becomes :code:`p(HGNC:AKT1, var(p.40*))` and is represented with the following dictionary: .. code:: { FUNCTION: PROTEIN, NAMESPACE: 'HGNC', NAME: 'AKT1', VARIANTS: [ { KIND: HGVS, IDENTIFIER: 'p.40*' } ] } Unfortunately, the HGVS nomenclature requires the encoding of the terminal amino acid which is exchanged for a stop codon, and this information is not required by BEL 1.0. For this example, the proper encoding of the truncation at position also includes the information that the 40th amino acid in the AKT1 is Cys. Its BEL encoding should be :code:`p(HGNC:AKT1, var(p.Cys40*))`. Temporary support has been added to compile these statements, but it's recommended they are upgraded by reexamining the supporting text, or looking up the amino acid sequence. .. seealso:: - BEL 2.0 specification on `truncations <http://openbel.org/language/version_2.0/bel_specification_version_2.0.html#_variants_2>`_ - PyBEL module :py:class:`pybel.parser.modifiers.TruncationParser` """ import logging from pyparsing import pyparsing_common as ppc from ..baseparser import BaseParser from ..utils import nest, one_of_tags from ...constants import HGVS, IDENTIFIER, KIND, TRUNCATION_POSITION __all__ = [ 'truncation_tag', 'TruncationParser', ] log = logging.getLogger(__name__) truncation_tag = one_of_tags(tags=['trunc', 'truncation'], canonical_tag=HGVS, name=KIND) class TruncationParser(BaseParser): def __init__(self): self.language = truncation_tag + nest(ppc.integer(TRUNCATION_POSITION)) self.language.setParseAction(self.handle_trunc_legacy) super(TruncationParser, self).__init__(self.language) # FIXME this isn't correct HGVS nomenclature, but truncation isn't forward compatible without more information def handle_trunc_legacy(self, line, position, tokens): upgraded = 'p.{}*'.format(tokens[TRUNCATION_POSITION]) log.warning( 'trunc() is deprecated. Please look up reference terminal amino acid and encode with HGVS: {}'.format(line)) tokens[IDENTIFIER] = upgraded del tokens[TRUNCATION_POSITION] return tokens
mit
Python
fb213097e838ddfa40d9f71f1705d7af661cfbdf
Allow tests to be run with Python <2.6.
ask/python-github2
tests/unit.py
tests/unit.py
# -*- coding: latin-1 -*- import unittest from github2.issues import Issue from github2.client import Github class ReprTests(unittest.TestCase): """__repr__ must return strings, not unicode objects.""" def test_issue(self): """Issues can have non-ASCII characters in the title.""" i = Issue(title=u'abcdé') self.assertEqual(str, type(repr(i))) class RateLimits(unittest.TestCase): """ How should we handle actual API calls such that tests can run? Perhaps the library should support a ~/.python_github2.conf from which to get the auth? """ def test_delays(self): import datetime USERNAME = '' API_KEY = '' client = Github(username=USERNAME, api_token=API_KEY, requests_per_second=.5) client.users.show('defunkt') start = datetime.datetime.now() client.users.show('mojombo') end = datetime.datetime.now() delta = end - start delta_seconds = delta.days * 24 * 60 * 60 + delta.seconds self.assertTrue(delta_seconds >= 2, "Expected .5 reqs per second to require a 2 second delay between " "calls.")
# -*- coding: latin-1 -*- import unittest from github2.issues import Issue from github2.client import Github class ReprTests(unittest.TestCase): """__repr__ must return strings, not unicode objects.""" def test_issue(self): """Issues can have non-ASCII characters in the title.""" i = Issue(title=u'abcdé') self.assertEqual(str, type(repr(i))) class RateLimits(unittest.TestCase): """ How should we handle actual API calls such that tests can run? Perhaps the library should support a ~/.python_github2.conf from which to get the auth? """ def test_delays(self): import datetime USERNAME = '' API_KEY = '' client = Github(username=USERNAME, api_token=API_KEY, requests_per_second=.5) client.users.show('defunkt') start = datetime.datetime.now() client.users.show('mojombo') end = datetime.datetime.now() self.assertGreaterEqual((end - start).total_seconds(), 2.0, "Expected .5 reqs per second to require a 2 second delay between " "calls.")
bsd-3-clause
Python
1064c11ec4e8e24564408ca598e16e30e0eb6b7a
Support for django 1.x vs 2.x
aschn/drf-tracking
tests/urls.py
tests/urls.py
# coding=utf-8 from __future__ import absolute_import from django.conf.urls import url import django if django.VERSION[0] == 1: from django.conf.urls import include else: from django.urls import include from . import views as test_views from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'user', test_views.MockUserViewSet) urlpatterns = [ url(r'^no-logging$', test_views.MockNoLoggingView.as_view()), url(r'^logging$', test_views.MockLoggingView.as_view()), url(r'^logging-exception$', test_views.MockLoggingView.as_view()), url(r'^slow-logging$', test_views.MockSlowLoggingView.as_view()), url(r'^explicit-logging$', test_views.MockExplicitLoggingView.as_view()), url(r'^sensitive-fields-logging$', test_views.MockSensitiveFieldsLoggingView.as_view()), url(r'^invalid-cleaned-substitute-logging$', test_views.MockInvalidCleanedSubstituteLoggingView.as_view()), url(r'^custom-check-logging-deprecated$', test_views.MockCustomCheckLoggingViewDeprecated.as_view()), url(r'^custom-check-logging$', test_views.MockCustomCheckLoggingView.as_view()), url(r'^custom-check-logging-methods$', test_views.MockCustomCheckLoggingWithLoggingMethodsView.as_view()), url(r'^custom-check-logging-methods-fail$', test_views.MockCustomCheckLoggingWithLoggingMethodsFailView.as_view()), url(r'^custom-log-handler$', test_views.MockCustomLogHandlerView.as_view()), url(r'^errors-logging$', test_views.MockLoggingErrorsView.as_view()), url(r'^session-auth-logging$', test_views.MockSessionAuthLoggingView.as_view()), url(r'^token-auth-logging$', test_views.MockTokenAuthLoggingView.as_view()), url(r'^json-logging$', test_views.MockJSONLoggingView.as_view()), url(r'^multipart-logging$', test_views.MockMultipartLoggingView.as_view()), url(r'^streaming-logging$', test_views.MockStreamingLoggingView.as_view()), url(r'^validation-error-logging$', test_views.MockValidationErrorLoggingView.as_view()), url(r'^404-error-logging$', test_views.Mock404ErrorLoggingView.as_view()), url(r'^500-error-logging$', test_views.Mock500ErrorLoggingView.as_view()), url(r'^415-error-logging$', test_views.Mock415ErrorLoggingView.as_view()), url(r'^no-view-log$', test_views.MockNameAPIView.as_view()), url(r'^view-log$', test_views.MockNameViewSet.as_view({'get': 'list'})), url(r'^400-body-parse-error-logging$', test_views.Mock400BodyParseErrorLoggingView.as_view()), url(r'', include(router.urls)) ]
# coding=utf-8 from __future__ import absolute_import from django.conf.urls import url from django.urls import include, path from . import views as test_views from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'user', test_views.MockUserViewSet) urlpatterns = [ url(r'^no-logging$', test_views.MockNoLoggingView.as_view()), url(r'^logging$', test_views.MockLoggingView.as_view()), url(r'^logging-exception$', test_views.MockLoggingView.as_view()), url(r'^slow-logging$', test_views.MockSlowLoggingView.as_view()), url(r'^explicit-logging$', test_views.MockExplicitLoggingView.as_view()), url(r'^sensitive-fields-logging$', test_views.MockSensitiveFieldsLoggingView.as_view()), url(r'^invalid-cleaned-substitute-logging$', test_views.MockInvalidCleanedSubstituteLoggingView.as_view()), url(r'^custom-check-logging-deprecated$', test_views.MockCustomCheckLoggingViewDeprecated.as_view()), url(r'^custom-check-logging$', test_views.MockCustomCheckLoggingView.as_view()), url(r'^custom-check-logging-methods$', test_views.MockCustomCheckLoggingWithLoggingMethodsView.as_view()), url(r'^custom-check-logging-methods-fail$', test_views.MockCustomCheckLoggingWithLoggingMethodsFailView.as_view()), url(r'^custom-log-handler$', test_views.MockCustomLogHandlerView.as_view()), url(r'^errors-logging$', test_views.MockLoggingErrorsView.as_view()), url(r'^session-auth-logging$', test_views.MockSessionAuthLoggingView.as_view()), url(r'^token-auth-logging$', test_views.MockTokenAuthLoggingView.as_view()), url(r'^json-logging$', test_views.MockJSONLoggingView.as_view()), url(r'^multipart-logging$', test_views.MockMultipartLoggingView.as_view()), url(r'^streaming-logging$', test_views.MockStreamingLoggingView.as_view()), url(r'^validation-error-logging$', test_views.MockValidationErrorLoggingView.as_view()), url(r'^404-error-logging$', test_views.Mock404ErrorLoggingView.as_view()), url(r'^500-error-logging$', test_views.Mock500ErrorLoggingView.as_view()), url(r'^415-error-logging$', test_views.Mock415ErrorLoggingView.as_view()), url(r'^no-view-log$', test_views.MockNameAPIView.as_view()), url(r'^view-log$', test_views.MockNameViewSet.as_view({'get': 'list'})), url(r'^400-body-parse-error-logging$', test_views.Mock400BodyParseErrorLoggingView.as_view()), path(r'', include(router.urls)) ]
isc
Python
218c2f90b8b8475ca2cebdeb5e083c620abc25c0
Implement rudimentary support for width and height options.
ijks/textinator
textinator.py
textinator.py
import click from PIL import Image def scale(val, src, dst): """ Scale the given value from the scale of src to the scale of dst. """ return ((val - src[0]) / (src[1]-src[0])) * (dst[1]-dst[0]) + dst[0] def value_to_char(value, palette, value_range=(0, 256)): palette_range = (0, len(palette)) mapped = int(scale(value, value_range, palette_range)) return palette[mapped] @click.command() @click.argument('image', type=click.File('rb')) @click.argument('out', type=click.File('wt'), default='-', required=False) @click.option('-p', '--palette', default='█▓▒░ ', help="A custom palette for rendering images. Goes from dark to bright.") @click.option('-w', '--width', type=click.INT, help="Width of output. If height is not given, the image will be proportionally scaled.") @click.option('-h', '--height', type=click.INT, help="Height of output. If width is not given, the image will be proportionally scaled.") @click.option('--correct/--no-correct', default=True, help="Wether to account for the proportions of monospaced characters. On by default.") @click.option('--resample', default='nearest', type=click.Choice(['nearest', 'bilinear', 'bicubic', 'antialias']), help="Filter to use for resampling. Default is nearest.") @click.option('--newlines/--no-newlines', default=False, help="Wether to add a newline after each row.") def convert(image, out, width, height, palette, correct, resample): """ Converts an input image to a text representation. Writes to stdout by default. Optionally takes another file as a second output. Supports most filetypes, except JPEG. For that you need to install libjpeg. For more info see:\n http://pillow.readthedocs.org/installation.html#external-libraries """ if not width or height: width, height = 80, 24 if width and not height: height = width if height and not width: width = height original = Image.open(image) resized = original.copy() resized.thumbnail((height, width)) bw = resized.convert(mode="L") o_width, o_height = bw.size for y in range(o_height): line = '' for x in range(o_width): pixel = bw.getpixel((x, y)) line += value_to_char(pixel, palette) click.echo(line)
import click from PIL import Image def scale(val, src, dst): """ Scale the given value from the scale of src to the scale of dst. """ return ((val - src[0]) / (src[1]-src[0])) * (dst[1]-dst[0]) + dst[0] def value_to_char(value, palette, value_range=(0, 256)): palette_range = (0, len(palette)) mapped = int(scale(value, value_range, palette_range)) return palette[mapped] @click.command() @click.argument('image', type=click.File('rb')) @click.argument('out', type=click.File('wt'), default='-', required=False) @click.option('-p', '--palette', default='█▓▒░ ', help="A custom palette for rendering images. Goes from dark to bright.") @click.option('-w', '--width', type=click.INT, help="Width of output. If height is not given, the image will be proportionally scaled.") @click.option('-h', '--height', type=click.INT, help="Height of output. If width is not given, the image will be proportionally scaled.") @click.option('--correct/--no-correct', default=True, help="Wether to account for the proportions of monospaced characters. On by default.") @click.option('--resample', default='nearest', type=click.Choice(['nearest', 'bilinear', 'bicubic', 'antialias']), help="Filter to use for resampling. Default is nearest.") @click.option('--newlines/--no-newlines', default=False, help="Wether to add a newline after each row.") def convert(image, out, width, height, palette, correct, resample): """ Converts an input image to a text representation. Writes to stdout by default. Optionally takes another file as a second output. Supports most filetypes, except JPEG. For that you need to install libjpeg. For more info see:\n http://pillow.readthedocs.org/installation.html#external-libraries """ original = Image.open(image) width, height = original.size thumb = original.copy() thumb.thumbnail(80) bw = thumb.convert(mode="L") width, height = bw.size for y in range(height): line = '' for x in range(width): pixel = bw.getpixel((x, y)) line += value_to_char(pixel, palette) click.echo(line)
mit
Python
843ce4bf4b0264cdaca3f054bddc3218938dbc60
Create /var/log in tmproot
vityagi/azure-linux-extensions,soumyanishan/azure-linux-extensions,krkhan/azure-linux-extensions,bpramod/azure-linux-extensions,soumyanishan/azure-linux-extensions,Azure/azure-linux-extensions,andyliuliming/azure-linux-extensions,vityagi/azure-linux-extensions,krkhan/azure-linux-extensions,varunkumta/azure-linux-extensions,vityagi/azure-linux-extensions,Azure/azure-linux-extensions,jasonzio/azure-linux-extensions,bpramod/azure-linux-extensions,vityagi/azure-linux-extensions,varunkumta/azure-linux-extensions,Azure/azure-linux-extensions,andyliuliming/azure-linux-extensions,jasonzio/azure-linux-extensions,bpramod/azure-linux-extensions,Azure/azure-linux-extensions,andyliuliming/azure-linux-extensions,jasonzio/azure-linux-extensions,soumyanishan/azure-linux-extensions,vityagi/azure-linux-extensions,soumyanishan/azure-linux-extensions,bpramod/azure-linux-extensions,vityagi/azure-linux-extensions,jasonzio/azure-linux-extensions,bpramod/azure-linux-extensions,bpramod/azure-linux-extensions,krkhan/azure-linux-extensions,krkhan/azure-linux-extensions,varunkumta/azure-linux-extensions,bpramod/azure-linux-extensions,Azure/azure-linux-extensions,andyliuliming/azure-linux-extensions,Azure/azure-linux-extensions,varunkumta/azure-linux-extensions,vityagi/azure-linux-extensions,Azure/azure-linux-extensions,soumyanishan/azure-linux-extensions
VMEncryption/main/oscrypto/encryptstates/StripdownState.py
VMEncryption/main/oscrypto/encryptstates/StripdownState.py
#!/usr/bin/env python # # VM Backup extension # # Copyright 2015 Microsoft Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Requires Python 2.7+ # from OSEncryptionState import * class StripdownState(OSEncryptionState): def __init__(self, context): super(StripdownState, self).__init__('StripdownState', context) def should_enter(self): self.context.logger.log("Verifying if machine should enter stripdown state") if not super(StripdownState, self).should_enter(): return False self.context.logger.log("Performing enter checks for stripdown state") self.command_executor.ExecuteInBash('! [ -e "/tmp/tmproot" ]', True) self.command_executor.ExecuteInBash('! [ -e "/oldroot" ]', True) return True def enter(self): if not self.should_enter(): return self.context.logger.log("Entering stripdown state") self.command_executor.Execute('umount -a') self.command_executor.Execute('mkdir /tmp/tmproot', True) self.command_executor.Execute('mount -t tmpfs none /tmp/tmproot', True) self.command_executor.ExecuteInBash('for i in proc sys dev run usr var tmp root oldroot; do mkdir /tmp/tmproot/$i; done', True) self.command_executor.ExecuteInBash('for i in bin etc mnt sbin lib lib64 root; do cp -ax /$i /tmp/tmproot/; done', True) self.command_executor.ExecuteInBash('for i in bin sbin lib lib64; do cp -ax /usr/$i /tmp/tmproot/usr/; done', True) self.command_executor.ExecuteInBash('for i in lib local lock opt run spool tmp; do cp -ax /var/$i /tmp/tmproot/var/; done', True) self.command_executor.ExecuteInBash('mkdir /tmp/tmproot/var/log', True) self.command_executor.ExecuteInBash('cp -ax /var/log/azure /tmp/tmproot/var/log/', True) self.command_executor.Execute('mount --make-rprivate /', True) self.command_executor.Execute('pivot_root /tmp/tmproot /tmp/tmproot/oldroot', True) def should_exit(self): self.context.logger.log("Verifying if machine should exit stripdown state") return super(StripdownState, self).should_exit()
#!/usr/bin/env python # # VM Backup extension # # Copyright 2015 Microsoft Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Requires Python 2.7+ # from OSEncryptionState import * class StripdownState(OSEncryptionState): def __init__(self, context): super(StripdownState, self).__init__('StripdownState', context) def should_enter(self): self.context.logger.log("Verifying if machine should enter stripdown state") if not super(StripdownState, self).should_enter(): return False self.context.logger.log("Performing enter checks for stripdown state") self.command_executor.ExecuteInBash('! [ -e "/tmp/tmproot" ]', True) self.command_executor.ExecuteInBash('! [ -e "/oldroot" ]', True) return True def enter(self): if not self.should_enter(): return self.context.logger.log("Entering stripdown state") self.command_executor.Execute('umount -a') self.command_executor.Execute('mkdir /tmp/tmproot', True) self.command_executor.Execute('mount -t tmpfs none /tmp/tmproot', True) self.command_executor.ExecuteInBash('for i in proc sys dev run usr var tmp root oldroot; do mkdir /tmp/tmproot/$i; done', True) self.command_executor.ExecuteInBash('for i in bin etc mnt sbin lib lib64 root; do cp -ax /$i /tmp/tmproot/; done', True) self.command_executor.ExecuteInBash('for i in bin sbin lib lib64; do cp -ax /usr/$i /tmp/tmproot/usr/; done', True) self.command_executor.ExecuteInBash('for i in lib local lock opt run spool tmp; do cp -ax /var/$i /tmp/tmproot/var/; done', True) self.command_executor.ExecuteInBash('cp -ax /var/log/azure /tmp/tmproot/var/', True) self.command_executor.Execute('mount --make-rprivate /', True) self.command_executor.Execute('pivot_root /tmp/tmproot /tmp/tmproot/oldroot', True) def should_exit(self): self.context.logger.log("Verifying if machine should exit stripdown state") return super(StripdownState, self).should_exit()
apache-2.0
Python
d19fa3b085d691780bbdc7b8e5edf9e8b53906e6
Revert "Adding request context for proper url generation."
Faerbit/todo-backend-flask
todo/views.py
todo/views.py
from todo import app from flask import jsonify, request, url_for from flask import json from todo.database import db_session from todo.models import Entry @app.route("/", methods=["GET", "POST", "DELETE"]) def index(): if request.method == "POST": request_json = request.get_json() entry = Entry(request_json["title"]) db_session.add(entry) db_session.commit() return jsonify(construct_dict(entry)) else: if request.method == "DELETE": Entry.query.delete() db_session.commit() response = [] for entry in Entry.query.all(): response.append(construct_dict(entry)) return json.dumps(response) @app.route("/<int:entry_id>") def entry(entry_id): return jsonify(construct_dict(Entry.query.filter(Entry.id == entry_id).first())) def construct_dict(entry): return dict(title=entry.title, completed=entry.completed, url=url_for("entry", entry_id=entry.id)) @app.teardown_appcontext def shutdown_session(exception=None): db_session.remove()
from todo import app from flask import jsonify, request, url_for from flask import json from todo.database import db_session from todo.models import Entry @app.route("/", methods=["GET", "POST", "DELETE"]) def index(): if request.method == "POST": request_json = request.get_json() entry = Entry(request_json["title"]) db_session.add(entry) db_session.commit() return jsonify(construct_dict(entry, request)) else: if request.method == "DELETE": Entry.query.delete() db_session.commit() response = [] for entry in Entry.query.all(): response.append(construct_dict(entry, request)) return json.dumps(response) @app.route("/<int:entry_id>") def entry(entry_id): return jsonify(construct_dict(Entry.query.filter(Entry.id == entry_id).first(), request)) def construct_dict(entry, request): with request: return dict(title=entry.title, completed=entry.completed, url=url_for("entry", entry_id=entry.id)) @app.teardown_appcontext def shutdown_session(exception=None): db_session.remove()
mit
Python
d5b20ed2ffd69a3383c854bced310b391319601e
Fix auth bug
Vassius/ttrss-python
ttrss/auth.py
ttrss/auth.py
from requests.auth import AuthBase import requests import json from exceptions import raise_on_error class TTRAuth(AuthBase): def __init__(self, user, password): self.user = user self.password = password self.sid = None def response_hook(self, r, **kwargs): j = json.loads(r.content) if int(j['status']) == 0: return r self.sid = self._get_sid(r.request.url) r.request.deregister_hook('response', self.response_hook) j = json.loads(r.request.body) j.update({'sid': self.sid}) req = requests.Request('POST', r.request.url) req.data = json.dumps(j) _r = requests.Session().send(req.prepare()) raise_on_error(_r) return _r def __call__(self, r): r.register_hook('response', self.response_hook) data = json.loads(r.body) if 'sid' not in data: if self.sid is None: self.sid = self._get_sid(r.url) data.update({'sid': self.sid}) req = requests.Request('POST', r.url) req.data = json.dumps(data) return req.prepare() else: self.sid = data['sid'] return r def _get_sid(self, url): res = requests.post(url, data=json.dumps({ 'op': 'login', 'user': self.user, 'password': self.password })) raise_on_error(res) j = json.loads(res.content) return j['content']['session_id']
from requests.auth import AuthBase import requests import json from exceptions import raise_on_error class TTRAuth(AuthBase): def __init__(self, user, password): self.user = user self.password = password self.sid = None def response_hook(self, r, **kwargs): j = json.loads(r.content) if int(j['status']) == 0: return r self.sid = self._get_sid(r.request.url) r.request.deregister_hook('response', self.response_hook) j = json.loads(r.request.body) j.update({'sid': self.sid}) req = requests.Request('POST', r.request.url) req.data = json.dumps(j) _r = requests.Session().send(req.prepare()) raise_on_error(_r) return _r def __call__(self, r): r.register_hook('response', self.response_hook) if self.sid is None: self.sid = self._get_sid(r.url) data = json.loads(r.body) if 'sid' not in data: data.update({'sid': self.sid}) req = requests.Request('POST', r.url) req.data = json.dumps(data) return req.prepare() return r def _get_sid(self, url): res = requests.post(url, data=json.dumps({ 'op': 'login', 'user': self.user, 'password': self.password })) raise_on_error(res) j = json.loads(res.content) return j['content']['session_id']
mit
Python
88686c420f403b59a32bad637dd67e4f84dec46d
Fix issue
wikkiewikkie/elizabeth,lk-geimfari/elizabeth,lk-geimfari/church,lk-geimfari/mimesis,lk-geimfari/mimesis
elizabeth/__init__.py
elizabeth/__init__.py
# -*- coding: utf-8 -*- """ :copyright: (c) 2016 by Likid Geimfari <likid.geimfari@gmail.com>. :software_license: MIT, see LICENSES for more details. :repository: https://github.com/lk-geimfari/elizabeth :contributors: see CONTRIBUTING.md for more details. """ from elizabeth.core import * __version__ = '0.3.4' __author__ = 'Likid Geimfari' __all__ = [ 'Address', 'Business', 'ClothingSizes', 'Code', 'Datetime', 'Development', 'File', 'Food', 'Hardware', 'Internet', 'Network', 'Numbers', 'Path', 'Personal', 'Science', 'Text', 'Transport', 'Generic' ]
# -*- coding: utf-8 -*- """ :copyright: (c) 2016 by Likid Geimfari <likid.geimfari@gmail.com>. :software_license: MIT, see LICENSES for more details. :repository: https://github.com/lk-geimfari/elizabeth :contributors: https://github.com/lk-geimfari/elizabeth/blob/master/CONTRIBUTORS.md """ from elizabeth.core import * __version__ = '0.3.4' __author__ = 'Likid Geimfari' __all__ = [ 'Address', 'Business', 'ClothingSizes', 'Code', 'Datetime', 'Development', 'File', 'Food', 'Hardware', 'Internet', 'Network', 'Numbers', 'Path', 'Personal', 'Science', 'Text', 'Transport', 'Generic' ]
mit
Python
457550824bece74f1dd1a07eb7e6c484a4e53348
remove pyc
jacegem/lotto-store,jacegem/lotto-store,jacegem/lotto-store,jacegem/lotto-store
util/store.py
util/store.py
# -*- coding: utf-8 -*- ''' Created on 2016. 6. 28. @author: nw ''' from google.appengine.ext import ndb class Store(ndb.Model): ''' classdocs 클래스 설명 ''' key = ndb.StringProperty() RTLRID = ndb.StringProperty() RECORDNO = ndb.IntegerProperty()
# -*- coding: utf-8 -*- ''' Created on 2016. 6. 28. @author: nw ''' from google.appengine.ext import ndb class Store(ndb.Model): ''' classdocs 클래스 설명 ''' key = ndb.StringProperty() RTLRID = ndb.StringProperty() RECORDNO = ndb.IntegerProperty()
apache-2.0
Python
67254d140ec1b98bd60fa59a676ad11ebf276112
Fix up the test utility
Miceuz/rs485-moist-sensor,Miceuz/rs485-moist-sensor
utils/test.py
utils/test.py
#!/usr/bin/python """Waits for the sensor to appear on /dev/ttyUSB5, then reads moisture and temperature from it continuously""" import chirp_modbus from time import sleep import minimalmodbus ADDRESS = 1 minimalmodbus.TIMEOUT=0.5 # for baudrate in chirp_modbus.SoilMoistureSensor.baudrates: # print("Checking baudrate " + str(baudrate)) # minimalmodbus.BAUDRATE = baudrate # chirp_modbus.SoilMoistureSensor.scanBus(verbose=True, findOne=True) while True: try: sensor = chirp_modbus.SoilMoistureSensor(address=ADDRESS, serialport='/dev/ttyUSB5') # sensor.sensor.debug=True sensor.sensor.precalculate_read_size=False print( " Moisture=" + str(sensor.getMoisture()) + " Temperature=" + str(sensor.getTemperature())) sleep(1) except ValueError as e: print e print("Waiting...") sleep(0.3) except IOError as e: print e print("Waiting...") sleep(0.3)
#!/usr/bin/python """Waits for the sensor to appear on /dev/ttyUSB5, then reads moisture and temperature from it continuously""" import chirp_modbus from time import sleep import minimalmodbus ADDRESS = 1 minimalmodbus.TIMEOUT=0.5 # for baudrate in chirp_modbus.SoilMoistureSensor.baudrates: # print("Checking baudrate " + str(baudrate)) # minimalmodbus.BAUDRATE = baudrate # chirp_modbus.SoilMoistureSensor.scanBus(verbose=True, findOne=True) while True: try: sensor = chirp_modbus.SoilMoistureSensor(address=ADDRESS, serialport='/dev/ttyUSB5') # sensor.sensor.debug=True sensor.sensor.precalculate_read_size=False print( " Moisture=" + str(sensor.getMoisture()) + " Temperature=" + str(sensor.getTemperature())) sleep(1) except ValueError as e: print e print("Waiting...") sleep(0.3)
apache-2.0
Python
7ae8cd06fd299656858416b79d0b96ca380de84b
add os
20c/vaping,20c/vaping
vaping/cli.py
vaping/cli.py
from __future__ import absolute_import from __future__ import print_function import click import munge import munge.click import os # test direct imports import vaping import vaping.daemon class Context(munge.click.Context): app_name = 'vaping' config_class = vaping.Config def update_context(ctx, kwargs): ctx.update_options(kwargs) if not isinstance(ctx.config['vaping']['plugin_path'], list): raise ValueError('config item vaping.plugin_path must be a list') # set plugin search path to defined + home/plugins searchpath = ctx.config['vaping']['plugin_path'] if ctx.home: searchpath.append(os.path.join(ctx.home, 'plugins')) vaping.plugin.searchpath = searchpath @click.group() @click.version_option() @Context.options @Context.pass_context() def cli(ctx, **kwargs): """ Vaping """ update_context(ctx, kwargs) @cli.command() @click.version_option() @Context.options @Context.pass_context() @click.option('-d', '--no-fork', help='do not fork into background', is_flag=True, default=False) def start(ctx, **kwargs): """ start a vaping process """ update_context(ctx, kwargs) daemon = vaping.daemon.Vaping(ctx.config) if ctx.debug or kwargs['no_fork']: daemon.run() else: daemon.start() @cli.command() @click.version_option() @Context.options @Context.pass_context() def stop(ctx, **kwargs): """ start a vaping process """ update_context(ctx, kwargs) daemon = vaping.daemon.Vaping(ctx.config) daemon.stop()
from __future__ import absolute_import from __future__ import print_function import click import munge import munge.click # test direct imports import vaping import vaping.daemon class Context(munge.click.Context): app_name = 'vaping' config_class = vaping.Config def update_context(ctx, kwargs): ctx.update_options(kwargs) if not isinstance(ctx.config['vaping']['plugin_path'], list): raise ValueError('config item vaping.plugin_path must be a list') # set plugin search path to defined + home/plugins searchpath = ctx.config['vaping']['plugin_path'] if ctx.home: searchpath.append(os.path.join(ctx.home, 'plugins')) vaping.plugin.searchpath = searchpath @click.group() @click.version_option() @Context.options @Context.pass_context() def cli(ctx, **kwargs): """ Vaping """ update_context(ctx, kwargs) @cli.command() @click.version_option() @Context.options @Context.pass_context() @click.option('-d', '--no-fork', help='do not fork into background', is_flag=True, default=False) def start(ctx, **kwargs): """ start a vaping process """ update_context(ctx, kwargs) daemon = vaping.daemon.Vaping(ctx.config) if ctx.debug or kwargs['no_fork']: daemon.run() else: daemon.start() @cli.command() @click.version_option() @Context.options @Context.pass_context() def stop(ctx, **kwargs): """ start a vaping process """ update_context(ctx, kwargs) daemon = vaping.daemon.Vaping(ctx.config) daemon.stop()
apache-2.0
Python
ee77150df7db9d22e00f1ff0c34a88eb310fb26c
add experimental debug function
doctorzeb8/django-era,doctorzeb8/django-era,doctorzeb8/django-era
era/utils/__init__.py
era/utils/__init__.py
from .functools import unidec @unidec def o_O(fn, *args, **kw): import ipdb locals().update(fn.__globals__) closure = [x.cell_contents for x in fn.__closure__ or []] ipdb.set_trace() return fn(*args, **kw) __builtins__['o_O'] = o_O
mit
Python
4c6c0c14f05b2946e8ecafd8e3031fbf68ee222f
use Form instead of FlaskForm with flask_wtf
vug/personalwebapp,vug/personalwebapp
views/blog.py
views/blog.py
""" This Blueprint implements Blog related views. """ from flask import Blueprint, render_template, abort, request from flask_misaka import markdown from flask_login import login_required from flask_wtf import Form import wtforms from models import Post, Tag blog = Blueprint('blog', __name__) @blog.route('/') def blog_index(): all_posts = Post.query.all() all_posts = sorted(all_posts, key=lambda p: p.published_at, reverse=True) all_tags = Tag.query.all() all_tags = sorted(all_tags, key=lambda t: t.name) return render_template('blog_list.html', posts=all_posts, tags=all_tags) @blog.route('/post/<post_url>') def blog_post(post_url): post = Post.query.filter_by(url=post_url).first() if post is None: abort(404) md_text = post.content html = markdown(md_text, fenced_code=True, math=True) # https://flask-misaka.readthedocs.io/en/latest/ # http://misaka.61924.nl/# time_str = post.published_at.strftime('%Y-%m-%d %H:%M') return render_template('blog_post.html', title=post.title, content=html, posted_at=time_str, tags=post.tags) @blog.route('/tag/<tag_name>') def blog_tag(tag_name): tag = Tag.query.filter_by(name=tag_name).first() return render_template('blog_tag.html', tag=tag, posts=tag.posts) class BlogEditForm(Form): title = wtforms.StringField('Title', validators=[wtforms.validators.DataRequired()]) content = wtforms.TextAreaField('Content', validators=[wtforms.validators.DataRequired()]) submit = wtforms.SubmitField('Save') @blog.route('/new', methods=['GET', 'POST']) @login_required def new_post(): # Create a new post # move to edit of that post pass @blog.route('/edit/<post_url>', methods=['GET', 'POST']) @login_required def edit_post(post_url): if request.method == 'POST': form = BlogEditForm(request.form) return 'posted<br>request.form["title"]: {}<br>form.title: {}'.format(request.form['title'], form.title) post = Post.query.filter_by(url=post_url).first() form = BlogEditForm(title=post.title, content=post.content) return render_template('blog_edit.html', form=form, post=post)
""" This Blueprint implements Blog related views. """ from flask import Blueprint, render_template, abort, request from flask_misaka import markdown from flask_login import login_required from flask_wtf import FlaskForm import wtforms from models import Post, Tag blog = Blueprint('blog', __name__) @blog.route('/') def blog_index(): all_posts = Post.query.all() all_posts = sorted(all_posts, key=lambda p: p.published_at, reverse=True) all_tags = Tag.query.all() all_tags = sorted(all_tags, key=lambda t: t.name) return render_template('blog_list.html', posts=all_posts, tags=all_tags) @blog.route('/post/<post_url>') def blog_post(post_url): post = Post.query.filter_by(url=post_url).first() if post is None: abort(404) md_text = post.content html = markdown(md_text, fenced_code=True, math=True) # https://flask-misaka.readthedocs.io/en/latest/ # http://misaka.61924.nl/# time_str = post.published_at.strftime('%Y-%m-%d %H:%M') return render_template('blog_post.html', title=post.title, content=html, posted_at=time_str, tags=post.tags) @blog.route('/tag/<tag_name>') def blog_tag(tag_name): tag = Tag.query.filter_by(name=tag_name).first() return render_template('blog_tag.html', tag=tag, posts=tag.posts) class BlogEditForm(FlaskForm): title = wtforms.StringField('Title', validators=[wtforms.validators.DataRequired()]) content = wtforms.TextAreaField('Content', validators=[wtforms.validators.DataRequired()]) submit = wtforms.SubmitField('Save') @blog.route('/new', methods=['GET', 'POST']) @login_required def new_post(): # Create a new post # move to edit of that post pass @blog.route('/edit/<post_url>', methods=['GET', 'POST']) @login_required def edit_post(post_url): if request.method == 'POST': form = BlogEditForm(request.form) return 'posted<br>request.form["title"]: {}<br>form.title: {}'.format(request.form['title'], form.title) post = Post.query.filter_by(url=post_url).first() form = BlogEditForm(title=post.title, content=post.content) return render_template('blog_edit.html', form=form, post=post)
mit
Python
b9bae46996308c49554148ff547ae5efca72d90e
Switch to stable
Vauxoo/account-financial-tools,Vauxoo/account-financial-tools,Vauxoo/account-financial-tools
account_asset_management/__manifest__.py
account_asset_management/__manifest__.py
# Copyright 2009-2019 Noviat # Copyright 2019 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Assets Management", "version": "13.0.3.7.1", "license": "AGPL-3", "depends": ["account", "report_xlsx_helper"], "excludes": ["account_asset"], "development_status": "Production/Stable", "external_dependencies": {"python": ["python-dateutil"]}, "author": "Noviat, Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-financial-tools", "category": "Accounting & Finance", "data": [ "security/account_asset_security.xml", "security/ir.model.access.csv", "wizard/account_asset_compute.xml", "wizard/account_asset_remove.xml", "views/account_account.xml", "views/account_asset.xml", "views/account_asset_group.xml", "views/account_asset_profile.xml", "views/account_move.xml", "views/account_move_line.xml", "views/menuitem.xml", "data/cron.xml", "wizard/wiz_account_asset_report.xml", "wizard/wiz_asset_move_reverse.xml", ], }
# Copyright 2009-2019 Noviat # Copyright 2019 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Assets Management", "version": "13.0.3.7.1", "license": "AGPL-3", "depends": ["account", "report_xlsx_helper"], "excludes": ["account_asset"], "external_dependencies": {"python": ["python-dateutil"]}, "author": "Noviat, Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-financial-tools", "category": "Accounting & Finance", "data": [ "security/account_asset_security.xml", "security/ir.model.access.csv", "wizard/account_asset_compute.xml", "wizard/account_asset_remove.xml", "views/account_account.xml", "views/account_asset.xml", "views/account_asset_group.xml", "views/account_asset_profile.xml", "views/account_move.xml", "views/account_move_line.xml", "views/menuitem.xml", "data/cron.xml", "wizard/wiz_account_asset_report.xml", "wizard/wiz_asset_move_reverse.xml", ], }
agpl-3.0
Python
f0b2fa27656473b4c397f59074e96712ed9613eb
Bump version (#115)
VirusTotal/vt-py
vt/version.py
vt/version.py
"""Defines VT release version.""" __version__ = '0.16.0'
"""Defines VT release version.""" __version__ = '0.15.0'
apache-2.0
Python
c6cc632b015f7d4621c5d2dbb3fb70c6fe00c5e7
Add conference registration to urls
CTPUG/wafer,CarlFK/wafer,CarlFK/wafer,CarlFK/wafer,CarlFK/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer
wafer/urls.py
wafer/urls.py
from django.conf.urls import include, patterns, url from django.views.generic import RedirectView, TemplateView from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns = patterns( '', url(r'^$', TemplateView.as_view(template_name='wafer/index.html'), name='wafer_index'), url(r'^index.html$', RedirectView.as_view(url='/')), url('^contact.html', 'wafer.views.contact', name='wafer_contact'), (r'^accounts/', include('wafer.registration.urls')), (r'^users/', include('wafer.users.urls')), (r'^talks/', include('wafer.talks.urls')), (r'^sponsors/', include('wafer.sponsors.urls')), (r'^pages/', include('wafer.pages.urls')), (r'^register/', include('wafer.conf_registration.urls')), (r'^admin/', include(admin.site.urls)), ) # Serve media if settings.DEBUG: urlpatterns += patterns( '', url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), )
from django.conf.urls import include, patterns, url from django.views.generic import RedirectView, TemplateView from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns = patterns( '', url(r'^$', TemplateView.as_view(template_name='wafer/index.html'), name='wafer_index'), url(r'^index.html$', RedirectView.as_view(url='/')), url('^contact.html', 'wafer.views.contact', name='wafer_contact'), (r'^accounts/', include('wafer.registration.urls')), (r'^users/', include('wafer.users.urls')), (r'^talks/', include('wafer.talks.urls')), (r'^sponsors/', include('wafer.sponsors.urls')), (r'^pages/', include('wafer.pages.urls')), (r'^admin/', include(admin.site.urls)), ) # Serve media if settings.DEBUG: urlpatterns += patterns( '', url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), )
isc
Python
d205fcdd27048a166111d7c0077174ed73052310
Fix intervals unit test.
tskisner/pytoast,tskisner/pytoast
src/python/tests/intervals.py
src/python/tests/intervals.py
# Copyright (c) 2015-2017 by the parties listed in the AUTHORS file. # All rights reserved. Use of this source code is governed by # a BSD-style license that can be found in the LICENSE file. from ..mpi import MPI from .mpi import MPITestCase import sys import os import numpy as np import numpy.testing as nt from ..dist import * from ..tod.interval import * from ..tod.sim_interval import * class IntervalTest(MPITestCase): def setUp(self): self.outdir = "toast_test_output" if self.comm.rank == 0: if not os.path.isdir(self.outdir): os.mkdir(self.outdir) self.rate = 123.456 self.duration = 24 * 3601.23 self.gap = 3600.0 self.start = 5432.1 self.first = 10 self.nint = 3 def test_regular(self): start = MPI.Wtime() intrvls = regular_intervals(self.nint, self.start, self.first, self.rate, self.duration, self.gap) goodsamp = self.nint * ( int(self.duration * self.rate) + 1 ) check = 0 for it in intrvls: print(it.first," ",it.last," ",it.start," ",it.stop) check += it.last - it.first + 1 nt.assert_equal(check, goodsamp) stop = MPI.Wtime() elapsed = stop - start #print('Proc {}: test took {:.4f} s'.format( MPI.COMM_WORLD.rank, elapsed ))
# Copyright (c) 2015-2017 by the parties listed in the AUTHORS file. # All rights reserved. Use of this source code is governed by # a BSD-style license that can be found in the LICENSE file. from ..mpi import MPI from .mpi import MPITestCase import sys import os import numpy as np import numpy.testing as nt from ..dist import * from ..tod.interval import * from ..tod.sim_interval import * class IntervalTest(MPITestCase): def setUp(self): self.outdir = "toast_test_output" if self.comm.rank == 0: if not os.path.isdir(self.outdir): os.mkdir(self.outdir) self.rate = 123.456 self.duration = 24 * 3601.23 self.gap = 3600.0 self.start = 5432.1 self.first = 10 self.nint = 3 def test_regular(self): start = MPI.Wtime() intrvls = regular_intervals(self.nint, self.start, self.first, self.rate, self.duration, self.gap) goodsamp = self.nint * ( int(0.5 + self.duration * self.rate) + 1 ) check = 0 for it in intrvls: print(it.first," ",it.last," ",it.start," ",it.stop) check += it.last - it.first + 1 nt.assert_equal(check, goodsamp) stop = MPI.Wtime() elapsed = stop - start #print('Proc {}: test took {:.4f} s'.format( MPI.COMM_WORLD.rank, elapsed ))
bsd-2-clause
Python
7624b72d5d7bb08e38ffa40e8606d581de124d1d
Update lookupAndStoreTweets.py docs: Update lookupAndStoreTweets.py
MichaelCurrin/twitterverse,MichaelCurrin/twitterverse
app/utils/insert/lookupAndStoreTweets.py
app/utils/insert/lookupAndStoreTweets.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Lookup and Store Tweets utility. """ import argparse import os import sys # Allow imports to be done when executing this file directly. sys.path.insert(0, os.path.abspath(os.path.join( os.path.dirname(__file__), os.path.pardir, os.path.pardir) )) from lib import tweets from lib.twitter import auth # TODO: Use the sytem category and campaign as set in app.conf file. def main(): """ Command-line interface to lookup and store Tweets. """ parser = argparse.ArgumentParser( description="""Lookup and Store Tweets utility. Fetches a tweet from the Twitter API given its GUID. Stores or updates the author Profile and Tweet in the db.""" ) parser.add_argument( 'tweetGUIDs', metavar='TWEET_GUID', nargs='+', help="""List of one or more Tweet GUIDs to lookup, separated by spaces. The Tweet 'GUID' in the local db is equivalent to the Tweet 'ID' on the Twitter API.""") parser.add_argument( '-u', '--update-all-fields', action='store_true', help="""If supplied, update all fields when updating an existing local Tweet record. Otherwise, the default behavior is to only update the favorite and retweet counts of the record.""" ) args = parser.parse_args() APIConn = auth.getAppOnlyConnection() tweets.lookupTweetGuids( APIConn, args.tweetGUIDs, onlyUpdateEngagements=not(args.update_all_fields) ) if __name__ == '__main__': main()
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Lookup and Store Tweets utility. """ import argparse import os import sys # Allow imports to be done when executing this file directly. appDir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir)) sys.path.insert(0, appDir) from lib import tweets from lib.twitter import auth def main(): """ Command-line interface to lookup and store Tweets. """ parser = argparse.ArgumentParser( description="""Lookup and Store Tweets utility. Fetches a tweet from the Twitter API given its GUID. Stores or updates the author Profile and Tweet in the db.""" ) parser.add_argument( 'tweetGUIDs', metavar='TWEET_GUID', nargs='+', help="""List of one or more Tweet GUIDs to lookup, separated by spaces. The Tweet 'GUID' in the local db is equivalent to the Tweet 'ID' on the Twitter API.""") parser.add_argument( '-u', '--update-all-fields', action='store_true', help="""If supplied, update all fields when updating an existing local Tweet record. Otherwise, the default behavior is to only update the favorite and retweet counts of the record.""" ) args = parser.parse_args() APIConn = auth.getAppOnlyConnection() tweets.lookupTweetGuids( APIConn, args.tweetGUIDs, onlyUpdateEngagements=not(args.update_all_fields) ) if __name__ == '__main__': main()
mit
Python
5c5119febc2a1f2ab4157895f5fe336adedc5807
correct path for selftest
jswoboda/GeoDataPython,jswoboda/GeoDataPython
Test/test.py
Test/test.py
#!/usr/bin/env python3 """ self-test for GeoDataPython """ from os.path import dirname,join from numpy.testing import assert_allclose,run_module_suite # from load_isropt import load_risromti path=dirname(__file__) def test_risr(): isrfn = join(path,'data','ran120219.004.hdf5') omtifn = join(path,'data','OMTIdata.h5') risr,omti = load_risromti(isrfn,omtifn) assert_allclose(risr.data['ne'][[36,136],[46,146]], [119949930314.93805,79983425500.702927]) assert_allclose(omti.data['optical'][[32,41],[22,39]], [ 603.03568232, 611.20040632]) if __name__ == '__main__': run_module_suite()
#!/usr/bin/env python3 """ self-test for GeoDataPython """ from numpy.testing import assert_allclose,run_module_suite # from load_isropt import load_risromti def test_risr(): isrfn = 'data/ran120219.004.hdf5' omtifn = 'data/OMTIdata.h5' risr,omti = load_risromti(isrfn,omtifn) assert_allclose(risr.data['ne'][[36,136],[46,146]], [119949930314.93805,79983425500.702927]) assert_allclose(omti.data['optical'][[32,41],[22,39]], [ 603.03568232, 611.20040632]) #test_risr() run_module_suite()
mit
Python
8918a4296ce3d7100578c4adce3cf39a37719173
update help button to use font awesome and be disabled if no help
xgds/xgds_core,xgds/xgds_core,xgds/xgds_core
xgds_core/templatetags/help_button.py
xgds_core/templatetags/help_button.py
#__BEGIN_LICENSE__ # Copyright (c) 2015, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. # All rights reserved. # # The xGDS platform is licensed under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software distributed # under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR # CONDITIONS OF ANY KIND, either express or implied. See the License for the # specific language governing permissions and limitations under the License. #__END_LICENSE__ from django import template from django.core.urlresolvers import reverse from django.utils.safestring import mark_safe register = template.Library() @register.simple_tag(name='help_button') def help_button(help_content_path, help_title): try: url = reverse('help_popup', kwargs={'help_content_path':help_content_path, 'help_title':str(help_title)}) result = "<a href='#' onclick='help.openPopup(\"" + url + "\")' class='help_button btn btn-primary fa fa-question-circle-o fa-lg' role='button'></a>" return mark_safe(result) except: # if the url is not found disable it result = "<a href='#' class='help_button btn btn-primary fa fa-question-circle-o fa-lg disabled' role='button' disabled></a>" return mark_safe(result)
#__BEGIN_LICENSE__ # Copyright (c) 2015, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. # All rights reserved. # # The xGDS platform is licensed under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software distributed # under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR # CONDITIONS OF ANY KIND, either express or implied. See the License for the # specific language governing permissions and limitations under the License. #__END_LICENSE__ from django import template from django.core.urlresolvers import reverse from django.utils.safestring import mark_safe register = template.Library() @register.simple_tag(name='help_button') def help_button(help_content_path, help_title): try: url = reverse('help_popup', kwargs={'help_content_path':help_content_path, 'help_title':str(help_title)}) result = "<a href='#' onclick='help.openPopup(\"" + url + "\")' class='help_button'><i class='fa fa-question-circle-o fa-lg' aria-hidden='true'></i></a>" return mark_safe(result) except: # if the url is not found do not include the help button return ""
apache-2.0
Python
a2f9ecc391a4e77b22f857d26e8ffc7741e92b4a
fix default for provider_service
jermowery/xos,jermowery/xos,cboling/xos,jermowery/xos,xmaruto/mcord,xmaruto/mcord,jermowery/xos,xmaruto/mcord,cboling/xos,cboling/xos,xmaruto/mcord,cboling/xos,cboling/xos
xos/core/xoslib/methods/volttenant.py
xos/core/xoslib/methods/volttenant.py
from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.reverse import reverse from rest_framework import serializers from rest_framework import generics from core.models import * from django.forms import widgets from cord.models import VOLTTenant, VOLTService from plus import PlusSerializerMixin from xos.apibase import XOSListCreateAPIView, XOSRetrieveUpdateDestroyAPIView, XOSPermissionDenied if hasattr(serializers, "ReadOnlyField"): # rest_framework 3.x ReadOnlyField = serializers.ReadOnlyField else: # rest_framework 2.x ReadOnlyField = serializers.Field def get_default_volt_service(): volt_services = VOLTService.get_service_objects().all() if volt_services: return volt_services[0].id return None class VOLTTenantIdSerializer(serializers.ModelSerializer, PlusSerializerMixin): id = ReadOnlyField() service_specific_id = serializers.CharField() vlan_id = serializers.CharField() provider_service = serializers.PrimaryKeyRelatedField(queryset=VOLTService.get_service_objects().all(), default=get_default_volt_service) humanReadableName = serializers.SerializerMethodField("getHumanReadableName") class Meta: model = VOLTTenant fields = ('humanReadableName', 'id', 'provider_service', 'service_specific_id', 'vlan_id' ) def getHumanReadableName(self, obj): return obj.__unicode__() class VOLTTenantList(XOSListCreateAPIView): queryset = VOLTTenant.get_tenant_objects().select_related().all() serializer_class = VOLTTenantIdSerializer method_kind = "list" method_name = "volttenant" class VOLTTenantDetail(XOSRetrieveUpdateDestroyAPIView): queryset = VOLTTenant.get_tenant_objects().select_related().all() serializer_class = VOLTTenantIdSerializer method_kind = "detail" method_name = "volttenant"
from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.reverse import reverse from rest_framework import serializers from rest_framework import generics from core.models import * from django.forms import widgets from cord.models import VOLTTenant, VOLTService from plus import PlusSerializerMixin from xos.apibase import XOSListCreateAPIView, XOSRetrieveUpdateDestroyAPIView, XOSPermissionDenied if hasattr(serializers, "ReadOnlyField"): # rest_framework 3.x ReadOnlyField = serializers.ReadOnlyField else: # rest_framework 2.x ReadOnlyField = serializers.Field def get_default_volt_service(): volt_services = VOLTService.get_service_objects().all() if volt_services: return volt_services[0].id return None class VOLTTenantIdSerializer(serializers.ModelSerializer, PlusSerializerMixin): id = ReadOnlyField() service_specific_id = serializers.CharField() vlan_id = serializers.CharField() provider_service = serializers.PrimaryKeyRelatedField(queryset=VOLTService.get_service_objects().all(), default=get_default_volt_service()) humanReadableName = serializers.SerializerMethodField("getHumanReadableName") class Meta: model = VOLTTenant fields = ('humanReadableName', 'id', 'provider_service', 'service_specific_id', 'vlan_id' ) def getHumanReadableName(self, obj): return obj.__unicode__() class VOLTTenantList(XOSListCreateAPIView): queryset = VOLTTenant.get_tenant_objects().select_related().all() serializer_class = VOLTTenantIdSerializer method_kind = "list" method_name = "volttenant" class VOLTTenantDetail(XOSRetrieveUpdateDestroyAPIView): queryset = VOLTTenant.get_tenant_objects().select_related().all() serializer_class = VOLTTenantIdSerializer method_kind = "detail" method_name = "volttenant"
apache-2.0
Python
8d29e6bfbf3b85bb4471b5cd41be180bf9fcda4f
support REST query by service_specific_id and vlan_id
jermowery/xos,xmaruto/mcord,cboling/xos,jermowery/xos,cboling/xos,jermowery/xos,xmaruto/mcord,cboling/xos,xmaruto/mcord,cboling/xos,jermowery/xos,cboling/xos,xmaruto/mcord
xos/core/xoslib/methods/volttenant.py
xos/core/xoslib/methods/volttenant.py
from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.reverse import reverse from rest_framework import serializers from rest_framework import generics from core.models import * from django.forms import widgets from cord.models import VOLTTenant, VOLTService from plus import PlusSerializerMixin from xos.apibase import XOSListCreateAPIView, XOSRetrieveUpdateDestroyAPIView, XOSPermissionDenied if hasattr(serializers, "ReadOnlyField"): # rest_framework 3.x ReadOnlyField = serializers.ReadOnlyField else: # rest_framework 2.x ReadOnlyField = serializers.Field def get_default_volt_service(): volt_services = VOLTService.get_service_objects().all() if volt_services: return volt_services[0].id return None class VOLTTenantIdSerializer(serializers.ModelSerializer, PlusSerializerMixin): id = ReadOnlyField() service_specific_id = serializers.CharField() vlan_id = serializers.CharField() provider_service = serializers.PrimaryKeyRelatedField(queryset=VOLTService.get_service_objects().all(), default=get_default_volt_service) humanReadableName = serializers.SerializerMethodField("getHumanReadableName") class Meta: model = VOLTTenant fields = ('humanReadableName', 'id', 'provider_service', 'service_specific_id', 'vlan_id' ) def getHumanReadableName(self, obj): return obj.__unicode__() class VOLTTenantList(XOSListCreateAPIView): serializer_class = VOLTTenantIdSerializer method_kind = "list" method_name = "volttenant" def get_queryset(self): queryset = VOLTTenant.get_tenant_objects().select_related().all() service_specific_id = self.request.QUERY_PARAMS.get('service_specific_id', None) if service_specific_id is not None: queryset = queryset.filter(service_specific_id=service_specific_id) vlan_id = self.request.QUERY_PARAMS.get('vlan_id', None) if vlan_id is not None: ids = [x.id for x in queryset if x.get_attribute("vlan_id", None)==vlan_id] queryset = queryset.filter(id__in=ids) return queryset class VOLTTenantDetail(XOSRetrieveUpdateDestroyAPIView): serializer_class = VOLTTenantIdSerializer queryset = VOLTTenant.get_tenant_objects().select_related().all() method_kind = "detail" method_name = "volttenant"
from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.reverse import reverse from rest_framework import serializers from rest_framework import generics from core.models import * from django.forms import widgets from cord.models import VOLTTenant, VOLTService from plus import PlusSerializerMixin from xos.apibase import XOSListCreateAPIView, XOSRetrieveUpdateDestroyAPIView, XOSPermissionDenied if hasattr(serializers, "ReadOnlyField"): # rest_framework 3.x ReadOnlyField = serializers.ReadOnlyField else: # rest_framework 2.x ReadOnlyField = serializers.Field def get_default_volt_service(): volt_services = VOLTService.get_service_objects().all() if volt_services: return volt_services[0].id return None class VOLTTenantIdSerializer(serializers.ModelSerializer, PlusSerializerMixin): id = ReadOnlyField() service_specific_id = serializers.CharField() vlan_id = serializers.CharField() provider_service = serializers.PrimaryKeyRelatedField(queryset=VOLTService.get_service_objects().all(), default=get_default_volt_service) humanReadableName = serializers.SerializerMethodField("getHumanReadableName") class Meta: model = VOLTTenant fields = ('humanReadableName', 'id', 'provider_service', 'service_specific_id', 'vlan_id' ) def getHumanReadableName(self, obj): return obj.__unicode__() class VOLTTenantList(XOSListCreateAPIView): queryset = VOLTTenant.get_tenant_objects().select_related().all() serializer_class = VOLTTenantIdSerializer method_kind = "list" method_name = "volttenant" class VOLTTenantDetail(XOSRetrieveUpdateDestroyAPIView): queryset = VOLTTenant.get_tenant_objects().select_related().all() serializer_class = VOLTTenantIdSerializer method_kind = "detail" method_name = "volttenant"
apache-2.0
Python
ebbe67666e113345a6f96edcd514ff8a1854485d
Bump version to 1.1
duointeractive/django-fabtastic
fabtastic/__init__.py
fabtastic/__init__.py
VERSION = '1.1'
VERSION = '1.0'
bsd-3-clause
Python
4be7f694220ee969683f07b982f8fcbe61971a04
Add comment to explain the length of the scripts taken into account in DuplicateScripts
ucsb-cs-education/hairball,jemole/hairball,thsunmy/hairball,jemole/hairball,ucsb-cs-education/hairball,thsunmy/hairball
hairball/plugins/duplicate.py
hairball/plugins/duplicate.py
"""This module provides plugins for basic duplicate code detection.""" from hairball.plugins import HairballPlugin class DuplicateScripts(HairballPlugin): """Plugin that keeps track of which scripts have been used more than once whithin a project.""" def __init__(self): super(DuplicateScripts, self).__init__() self.total_duplicate = 0 self.list_duplicate = [] def finalize(self): """Output the duplicate scripts detected.""" if self.total_duplicate > 0: print("%d duplicate scripts found" % self.total_duplicate) for duplicate in self.list_duplicate: print duplicate def analyze(self, scratch): """Run and return the results from the DuplicateChecks plugin. Only takes into account scripts with more than 3 blocks""" scripts_set = set() for script in self.iter_scripts(scratch): blocks_list = [] for name, _, _ in self.iter_blocks(script.blocks): blocks_list.append(name) blocks_tuple = tuple(blocks_list) if blocks_tuple in scripts_set: if len(blocks_list)>3: self.total_duplicate += 1 self.list_duplicate.append(blocks_list) else: scripts_set.add(blocks_tuple)
"""This module provides plugins for basic duplicate code detection.""" from hairball.plugins import HairballPlugin class DuplicateScripts(HairballPlugin): """Plugin that keeps track of which scripts have been used more than once whithin a project.""" def __init__(self): super(DuplicateScripts, self).__init__() self.total_duplicate = 0 self.list_duplicate = [] def finalize(self): """Output the duplicate scripts detected.""" if self.total_duplicate > 0: print("%d duplicate scripts found" % self.total_duplicate) for duplicate in self.list_duplicate: print duplicate def analyze(self, scratch): """Run and return the results from the DuplicateChecks plugin.""" scripts_set = set() for script in self.iter_scripts(scratch): blocks_list = [] for name, _, _ in self.iter_blocks(script.blocks): blocks_list.append(name) blocks_tuple = tuple(blocks_list) if blocks_tuple in scripts_set: if len(blocks_list)>3: self.total_duplicate += 1 self.list_duplicate.append(blocks_list) else: scripts_set.add(blocks_tuple)
bsd-2-clause
Python
091445f20eca624112ab0660791b5858e268080d
add missing Ap_rst
Nic30/HWToolkit
hdl_toolkit/interfaces/all.py
hdl_toolkit/interfaces/all.py
from hdl_toolkit.interfaces.std import BramPort, \ BramPort_withoutClk, Ap_hs, Ap_clk, Ap_rst_n, Ap_none, Ap_vld,\ Ap_rst from hdl_toolkit.interfaces.amba import Axi4, Axi4_xil, \ AxiLite, AxiLite_xil, AxiStream, AxiStream_withoutSTRB, AxiStream_withUserAndStrb, AxiStream_withUserAndNoStrb allInterfaces = [Axi4, Axi4_xil, AxiLite, AxiLite_xil, BramPort, BramPort_withoutClk, AxiStream_withUserAndStrb, AxiStream, AxiStream_withUserAndNoStrb, AxiStream_withoutSTRB, Ap_hs, Ap_clk, Ap_rst, Ap_rst_n, Ap_vld, Ap_none ]
from hdl_toolkit.interfaces.std import BramPort, \ BramPort_withoutClk, Ap_hs, Ap_clk, Ap_rst_n, Ap_none, Ap_vld from hdl_toolkit.interfaces.amba import Axi4, Axi4_xil, \ AxiLite, AxiLite_xil, AxiStream, AxiStream_withoutSTRB, AxiStream_withUserAndStrb, AxiStream_withUserAndNoStrb allInterfaces = [Axi4, Axi4_xil, AxiLite, AxiLite_xil, BramPort, BramPort_withoutClk, AxiStream_withUserAndStrb, AxiStream, AxiStream_withUserAndNoStrb, AxiStream_withoutSTRB, Ap_hs, Ap_clk, Ap_rst_n, Ap_vld, Ap_none ]
mit
Python
15996286496d913c25290362ba2dba2d349bd5f6
Fix bug of invoking /bin/sh on several OSs
snippits/qemu_image,snippits/qemu_image,snippits/qemu_image
imageManagerUtils/settings.py
imageManagerUtils/settings.py
# Copyright (c) 2017, MIT Licensed, Medicine Yeh # This file helps to read settings from bash script into os.environ import os import sys import subprocess # This path is the location of the caller script MAIN_SCRIPT_PATH = os.path.dirname(os.path.abspath(sys.argv[0])) # Set up the path to settings.sh settings_path = os.path.join(MAIN_SCRIPT_PATH, 'settings.sh') if not os.path.isfile(settings_path): print('Cannot find settings.sh in ' + MAIN_SCRIPT_PATH) exit(1) # This is a tricky way to read bash envs in the script env_str = subprocess.check_output('source {} && env'.format(settings_path), shell=True, executable='/bin/bash') # Transform to list of python strings (utf-8 encodings) env_str = env_str.decode('utf-8').split('\n') # Transform from a list to a list of pairs and filter out invalid formats env_list = [kv.split('=') for kv in env_str if len(kv.split('=')) == 2] # Transform from a list to a dictionary env_dict = {kv[0]: kv[1] for kv in env_list} # Update the os.environ globally os.environ.update(env_dict)
# Copyright (c) 2017, MIT Licensed, Medicine Yeh # This file helps to read settings from bash script into os.environ import os import sys import subprocess # This path is the location of the caller script MAIN_SCRIPT_PATH = os.path.dirname(os.path.abspath(sys.argv[0])) # Set up the path to settings.sh settings_path = os.path.join(MAIN_SCRIPT_PATH, 'settings.sh') if not os.path.isfile(settings_path): print('Cannot find settings.sh in ' + MAIN_SCRIPT_PATH) exit(1) # This is a tricky way to read bash envs in the script env_str = subprocess.check_output('source {} && env'.format(settings_path), shell=True) # Transform to list of python strings (utf-8 encodings) env_str = env_str.decode('utf-8').split('\n') # Transform from a list to a list of pairs and filter out invalid formats env_list = [kv.split('=') for kv in env_str if len(kv.split('=')) == 2] # Transform from a list to a dictionary env_dict = {kv[0]: kv[1] for kv in env_list} # Update the os.environ globally os.environ.update(env_dict)
mit
Python
44514aa5d70af10a14fd90a77fe57d7af01d538e
add automated email workflow improvements: 1) don't use extra_models, now renamed to queries 2) use new date_filter construct where appropriate
magfest/attendee_tournaments,magfest/attendee_tournaments
attendee_tournaments/automated_emails.py
attendee_tournaments/automated_emails.py
from attendee_tournaments import * AutomatedEmail.queries[AttendeeTournament] = lambda session: session.query(AttendeeTournament).all() AutomatedEmail(AttendeeTournament, 'Your tournament application has been received', 'tournament_app_received.txt', lambda app: app.status == c.NEW) AutomatedEmail(AttendeeTournament, 'Your tournament application has been approved', 'tournament_app_accepted.txt', lambda app: app.status == c.ACCEPTED) AutomatedEmail(AttendeeTournament, 'Your tournament application has been declined', 'tournament_app_declined.txt', lambda app: app.status == c.DECLINED)
from attendee_tournaments import * AutomatedEmail.extra_models[AttendeeTournament] = lambda session: session.query(AttendeeTournament).all() AutomatedEmail(AttendeeTournament, 'Your tournament application has been received', 'tournament_app_received.txt', lambda app: app.status == c.NEW) AutomatedEmail(AttendeeTournament, 'Your tournament application has been approved', 'tournament_app_accepted.txt', lambda app: app.status == c.ACCEPTED) AutomatedEmail(AttendeeTournament, 'Your tournament application has been declined', 'tournament_app_declined.txt', lambda app: app.status == c.DECLINED)
agpl-3.0
Python
fead22592dfe644cb1684888ed8d8b422b1fb101
Update views.py
ebridge2/FNGS_website,ebridge2/FNGS_website,ebridge2/FNGS_website,ebridge2/FNGS_website,02agarwalt/FNGS_website,02agarwalt/FNGS_website,02agarwalt/FNGS_website
fngs/analyze/views.py
fngs/analyze/views.py
from django.http import HttpResponse, Http404 from django.shortcuts import render, get_object_or_404 from django.views import generic from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.core.urlresolvers import reverse_lazy from .models import Submission from .forms import SubmissionForm from ndmg.scripts.ndmg_func_pipeline import ndmg_func_pipeline as fngs_pipeline from ndmg.scripts.ndmg_dwi_pipeline import ndmg_dwi_pipeline as ndmg_pipeline from django.conf import settings import time import importlib import imp from ndmg.utils import utils as mgu from threading import Thread from multiprocessing import Process import os import re def index(request): return render(request, 'analyze/index.html') def submit_job(request): form = SubmissionForm(request.POST or None, request.FILES or None) if form.is_valid(): submission = form.save(commit=False) submission.creds_file = request.FILES['creds_file'] submission.save() logfile = submission.jobdir + "log.txt" p = Process(target=submitstuff, args=(submission, logfile)) p.daemon=True p.start() p.join() messages = open(logfile, 'r').readlines() os.system("rm " + logfile) context = { "messages": messages } return render(request, 'analyze/index.html', context) context = { "form": form, } return render(request, 'analyze/create_submission.html', context) def submitstuff(submission, logfile): if submission.state == 'participant': cmd = "ndmg_cloud participant --bucket " + submission.bucket + " --bidsdir " + submission.bidsdir + " --jobdir " + submission.jobdir + " --credentials " + submission.creds_file.url + " --modality " + submission.modality + " --stc " + submission.slice_timing if submission.state == 'group': cmd = "ndmg_cloud group --bucket " + submission.bucket + " --bidsdir " + submission.bidsdir + " --jobdir " + submission.jobdir + " --credentials " + submission.creds_file.url + " --modality " + submission.modality + " --dataset " + submission.datasetname if submission.state == 'status': cmd = "ndmg_cloud status --jobdir " + submission.jobdir + " --credentials " + submission.creds_file.url if submission.state == 'kill': cmd = "ndmg_cloud kill --jobdir " + submission.jobdir + " --credentials " + submission.creds_file.url cmd = cmd + " > " + logfile os.system(cmd)
from django.http import HttpResponse, Http404 from django.shortcuts import render, get_object_or_404 from django.views import generic from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.core.urlresolvers import reverse_lazy from .models import Submission from .forms import SubmissionForm from ndmg.scripts.ndmg_func_pipeline import ndmg_func_pipeline as fngs_pipeline from ndmg.scripts.ndmg_dwi_pipeline import ndmg_dwi_pipeline as ndmg_pipeline from django.conf import settings import time import importlib import imp from ndmg.utils import utils as mgu from threading import Thread from multiprocessing import Process import os import re def index(request): return render(request, 'analyze/index.html') def submit_job(request): form = SubmissionForm(request.POST or None, request.FILES or None) if form.is_valid(): submission = form.save(commit=False) submission.creds_file = request.FILES['creds_file'] submission.save() logfile = submission.jobdir + "log.txt" p = Process(target=submitstuff, args=(submission, logfile)) p.daemon=True p.start() p.join() messages = open(logfile, 'r').readlines() os.system("rm " + logfile) context = { "messages": messages } return render(request, 'analyze/index.html', context) context = { "form": form, } return render(request, 'analyze/create_submission.html', context) def submitstuff(submission, logfile): if submission.state == 'participant': cmd = "ndmg_cloud participant --bucket " + submission.bucket + " --bidsdir " + submission.bidsdir + " --jobdir " + submission.jobdir + " --credentials " + submission.creds_file.url + " --modality " + submission.modality + " --stc " + submission.slice_timing if submission.state == 'group': cmd = "ndmg_cloud group --bucket " + submission.bucket + " --bidsdir " + submission.bidsdir + " --jobdir " + submission.jobdir + " --credentials " + submission.creds_file.url + " --modality " + submission.modality + " --dataset " + submission.datasetname if submission.state == 'status': cmd = "ndmg_cloud status --jobdir " + submission.jobdir + " --credentials " + submission.creds_file.url if submission.state == 'kill': cmd = "ndmg_cloud kill --jobdir " + submission.jobdir + " --credentials " + submission.creds_file.url cmd = cmd + " >&! " + logfile os.system(cmd)
apache-2.0
Python
5a46276585aaaae76f00095b7166a4ddf52ad335
fix log formatting (#2427)
Azure/WALinuxAgent,Azure/WALinuxAgent
azurelinuxagent/common/osutil/systemd.py
azurelinuxagent/common/osutil/systemd.py
# # Copyright 2018 Microsoft Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Requires Python 2.6+ and Openssl 1.0+ # import os import re from azurelinuxagent.common.osutil import get_osutil from azurelinuxagent.common.utils import shellutil def _get_os_util(): if _get_os_util.value is None: _get_os_util.value = get_osutil() return _get_os_util.value _get_os_util.value = None def is_systemd(): """ Determine if systemd is managing system services; the implementation follows the same strategy as, for example, sd_booted() in libsystemd, or /usr/sbin/service """ return os.path.exists("/run/systemd/system/") def get_version(): # the output is similar to # $ systemctl --version # systemd 245 (245.4-4ubuntu3) # +PAM +AUDIT +SELINUX +IMA +APPARMOR +SMACK +SYSVINIT +UTMP etc # return shellutil.run_command(['systemctl', '--version']) def get_unit_file_install_path(): """ e.g. /lib/systemd/system """ return _get_os_util().get_systemd_unit_file_install_path() def get_agent_unit_name(): """ e.g. walinuxagent.service """ return _get_os_util().get_service_name() + ".service" def get_agent_unit_file(): """ e.g. /lib/systemd/system/walinuxagent.service """ return os.path.join(get_unit_file_install_path(), get_agent_unit_name()) def get_agent_drop_in_path(): """ e.g. /lib/systemd/system/walinuxagent.service.d """ return os.path.join(get_unit_file_install_path(), "{0}.d".format(get_agent_unit_name())) def get_unit_property(unit_name, property_name): output = shellutil.run_command(["systemctl", "show", unit_name, "--property", property_name]) # Output is similar to # # systemctl show walinuxagent.service --property CPUQuotaPerSecUSec # CPUQuotaPerSecUSec=50ms match = re.match("[^=]+=(?P<value>.+)", output) if match is None: raise ValueError("Can't find property {0} of {1}".format(property_name, unit_name)) return match.group('value')
# # Copyright 2018 Microsoft Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Requires Python 2.6+ and Openssl 1.0+ # import os import re from azurelinuxagent.common.osutil import get_osutil from azurelinuxagent.common.utils import shellutil def _get_os_util(): if _get_os_util.value is None: _get_os_util.value = get_osutil() return _get_os_util.value _get_os_util.value = None def is_systemd(): """ Determine if systemd is managing system services; the implementation follows the same strategy as, for example, sd_booted() in libsystemd, or /usr/sbin/service """ return os.path.exists("/run/systemd/system/") def get_version(): # the output is similar to # $ systemctl --version # systemd 245 (245.4-4ubuntu3) # +PAM +AUDIT +SELINUX +IMA +APPARMOR +SMACK +SYSVINIT +UTMP etc # return shellutil.run_command(['systemctl', '--version']) def get_unit_file_install_path(): """ e.g. /lib/systemd/system """ return _get_os_util().get_systemd_unit_file_install_path() def get_agent_unit_name(): """ e.g. walinuxagent.service """ return _get_os_util().get_service_name() + ".service" def get_agent_unit_file(): """ e.g. /lib/systemd/system/walinuxagent.service """ return os.path.join(get_unit_file_install_path(), get_agent_unit_name()) def get_agent_drop_in_path(): """ e.g. /lib/systemd/system/walinuxagent.service.d """ return os.path.join(get_unit_file_install_path(), "{0}.d".format(get_agent_unit_name())) def get_unit_property(unit_name, property_name): output = shellutil.run_command(["systemctl", "show", unit_name, "--property", property_name]) # Output is similar to # # systemctl show walinuxagent.service --property CPUQuotaPerSecUSec # CPUQuotaPerSecUSec=50ms match = re.match("[^=]+=(?P<value>.+)", output) if match is None: raise ValueError("Can't find property {0} of {1}", property_name, unit_name) # pylint: disable=W0715 return match.group('value')
apache-2.0
Python
bcd1e5124efda816ff60b79112a99e19f6846960
clean the test-build
simbuerg/benchbuild,simbuerg/benchbuild
benchbuild/projects/benchbuild/python.py
benchbuild/projects/benchbuild/python.py
from benchbuild.project import wrap from benchbuild.projects.benchbuild.group import BenchBuildGroup from benchbuild.utils.compiler import lt_clang, lt_clang_cxx from benchbuild.utils.downloader import Wget from benchbuild.utils.run import run from plumbum import local from benchbuild.utils.cmd import make, tar from os import path class Python(BenchBuildGroup): """ python benchmarks """ NAME = 'python' DOMAIN = 'compilation' VERSION = '3.4.3' src_dir = "Python-{0}".format(VERSION) SRC_FILE = src_dir + ".tar.xz" src_uri = "https://www.python.org/ftp/python/{0}/".format(VERSION) \ + SRC_FILE def download(self): Wget(self.src_uri, self.SRC_FILE) tar("xfJ", self.SRC_FILE) def configure(self): clang = lt_clang(self.cflags, self.ldflags, self.compiler_extension) clang_cxx = lt_clang_cxx(self.cflags, self.ldflags, self.compiler_extension) with local.cwd(self.src_dir): configure = local["./configure"] with local.env(CC=str(clang), CXX=str(clang_cxx)): run(configure["--disable-shared", "--without-gcc"]) def build(self): with local.cwd(self.src_dir): run(make) def run_tests(self, experiment): wrap(path.join(self.src_dir, "python"), experiment) with local.cwd(self.src_dir): run(make["-i", "test"])
from benchbuild.project import wrap from benchbuild.projects.benchbuild.group import BenchBuildGroup from benchbuild.utils.compiler import lt_clang, lt_clang_cxx from benchbuild.utils.downloader import Wget from benchbuild.utils.run import run from plumbum import local from benchbuild.utils.cmd import make, tar from os import path class Python(BenchBuildGroup): """ python benchmarks """ NAME = 'python' DOMAIN = 'compilation' VERSION = '3.4.3' src_dir = "Python-{0}".format(VERSION) SRC_FILE = src_dir + ".tar.xz" src_uri = "https://www.python.org/ftp/python/{0}/".format(VERSION) \ + SRC_FILE def download(self): Wget(self.src_uri, self.SRC_FILE) tar("xfJ", self.SRC_FILE) def configure(self): clang = lt_clang(self.cflags, self.ldflags, self.compiler_extension) clang_cxx = lt_clang_cxx(self.cflags, self.ldflags, self.compiler_extension) with local.cwd(self.src_dir): configure = local["./configure"] with local.env(CC=str(clang), CXX=str(clang_cxx)): run(configure["--disable-shared", "--without-gcc"]) def build(self): with local.cwd(self.src_dir): run(make) def run_tests(self, experiment): exp = wrap(path.join(self.src_dir, "python"), experiment) with local.cwd(self.src_dir): run(make["TESTPYTHON=" + str(exp), "-i", "test"])
mit
Python
0f673f5c3bb4fbeda582ad6b42933a36b1279186
Remove wildcard import from test_dynd
cpcloud/blaze,LiaoPan/blaze,ContinuumIO/blaze,maxalbert/blaze,jdmcbr/blaze,jcrist/blaze,cowlicks/blaze,xlhtc007/blaze,maxalbert/blaze,jdmcbr/blaze,cpcloud/blaze,cowlicks/blaze,nkhuyu/blaze,LiaoPan/blaze,alexmojaki/blaze,nkhuyu/blaze,ChinaQuants/blaze,xlhtc007/blaze,scls19fr/blaze,caseyclements/blaze,dwillmer/blaze,ContinuumIO/blaze,alexmojaki/blaze,scls19fr/blaze,ChinaQuants/blaze,dwillmer/blaze,jcrist/blaze,caseyclements/blaze
blaze/compute/tests/test_dynd_compute.py
blaze/compute/tests/test_dynd_compute.py
from __future__ import absolute_import, division, print_function import pytest dynd = pytest.importorskip('dynd') from dynd import nd from blaze.compute.core import compute from blaze import symbol def eq(a, b): return nd.as_py(a) == nd.as_py(b) n = symbol('n', '3 * 5 * int') nx = nd.array([[ 1, 2, 3, 4, 5], [11, 22, 33, 44, 55], [21, 22, 23, 24, 25]], type=str(n.dshape)) rec = symbol('s', '3 * var * {name: string, amount: int}') recx = nd.array([[('Alice', 1), ('Bob', 2)], [('Charlie', 3)], [('Dennis', 4), ('Edith', 5), ('Frank', 6)]], type=str(rec.dshape)) def test_symbol(): assert eq(compute(n, nx), nx) def test_slice(): assert eq(compute(n[0], nx), nx[0]) assert eq(compute(n[0, :3], nx), nx[0, :3]) def test_first_last(): assert eq(compute(n[0], nx), nx[0]) assert eq(compute(n[-1], nx), nx[-1]) def test_field(): assert eq(compute(rec.amount, recx), recx.amount) def test_arithmetic(): # assert eq(compute(n + 1, nx), nx + 1) assert eq(compute(rec.amount + 1, recx), recx.amount + 1) assert eq(compute(-rec.amount, recx), 0-recx.amount)
from __future__ import absolute_import, division, print_function import pytest dynd = pytest.importorskip('dynd') from dynd import nd from blaze.compute.core import compute from blaze.expr import * from blaze.compute.dynd import * def eq(a, b): return nd.as_py(a) == nd.as_py(b) n = symbol('n', '3 * 5 * int') nx = nd.array([[ 1, 2, 3, 4, 5], [11, 22, 33, 44, 55], [21, 22, 23, 24, 25]], type=str(n.dshape)) rec = symbol('s', '3 * var * {name: string, amount: int}') recx = nd.array([[('Alice', 1), ('Bob', 2)], [('Charlie', 3)], [('Dennis', 4), ('Edith', 5), ('Frank', 6)]], type=str(rec.dshape)) def test_symbol(): assert eq(compute(n, nx), nx) def test_slice(): assert eq(compute(n[0], nx), nx[0]) assert eq(compute(n[0, :3], nx), nx[0, :3]) def test_first_last(): assert eq(compute(n[0], nx), nx[0]) assert eq(compute(n[-1], nx), nx[-1]) def test_field(): assert eq(compute(rec.amount, recx), recx.amount) def test_arithmetic(): # assert eq(compute(n + 1, nx), nx + 1) assert eq(compute(rec.amount + 1, recx), recx.amount + 1) assert eq(compute(-rec.amount, recx), 0-recx.amount)
bsd-3-clause
Python
8cf8e7c968232fe999e4dfc20541be4ff96fcee1
Add user-supplied arguments in log_handler
watonyweng/neutron,Metaswitch/calico-neutron,takeshineshiro/neutron,virtualopensystems/neutron,adelina-t/neutron,vivekanand1101/neutron,watonyweng/neutron,JioCloud/neutron,waltBB/neutron_read,CiscoSystems/neutron,javaos74/neutron,aristanetworks/neutron,JianyuWang/neutron,swdream/neutron,dhanunjaya/neutron,openstack/neutron,apporc/neutron,eayunstack/neutron,cloudbase/neutron-virtualbox,vijayendrabvs/ssl-neutron,sasukeh/neutron,sajuptpm/neutron-ipam,skyddv/neutron,cloudbase/neutron-virtualbox,infobloxopen/neutron,cernops/neutron,gopal1cloud/neutron,Stavitsky/neutron,mandeepdhami/neutron,zhhf/charging,suneeth51/neutron,yamahata/neutron,mahak/neutron,aristanetworks/neutron,cloudbase/neutron,gkotton/neutron,chitr/neutron,MaximNevrov/neutron,paninetworks/neutron,vijayendrabvs/hap,suneeth51/neutron,jumpojoy/neutron,virtualopensystems/neutron,Stavitsky/neutron,shahbazn/neutron,silenci/neutron,asgard-lab/neutron,CiscoSystems/neutron,yamahata/tacker,Juniper/neutron,neoareslinux/neutron,vijayendrabvs/hap,leeseulstack/openstack,barnsnake351/neutron,leeseuljeong/leeseulstack_neutron,miyakz1192/neutron,yanheven/neutron,blueboxgroup/neutron,waltBB/neutron_read,vbannai/neutron,JioCloud/neutron,SmartInfrastructures/neutron,glove747/liberty-neutron,adelina-t/neutron,wenhuizhang/neutron,alexandrucoman/vbox-neutron-agent,huntxu/neutron,projectcalico/calico-neutron,vveerava/Openstack,vveerava/Openstack,rdo-management/neutron,bgxavier/neutron,vivekanand1101/neutron,neoareslinux/neutron,miyakz1192/neutron,mmnelemane/neutron,klmitch/neutron,zhhf/charging,yamahata/neutron,Juniper/neutron,jerryz1982/neutron,dims/neutron,gopal1cloud/neutron,rdo-management/neutron,cisco-openstack/neutron,beagles/neutron_hacking,chitr/neutron,bigswitch/neutron,dhanunjaya/neutron,takeshineshiro/neutron,mahak/neutron,jacknjzhou/neutron,yamahata/neutron,sebrandon1/neutron,apporc/neutron,Juniper/contrail-dev-neutron,wolverineav/neutron,yamahata/tacker,eonpatapon/neutron,mattt416/neutron,leeseuljeong/leeseulstack_neutron,mmnelemane/neutron,Juniper/contrail-dev-neutron,vveerava/Openstack,sajuptpm/neutron-ipam,cernops/neutron,cisco-openstack/neutron,javaos74/neutron,bigswitch/neutron,zhhf/charging,barnsnake351/neutron,leeseuljeong/leeseulstack_neutron,mattt416/neutron,leeseulstack/openstack,yamahata/tacker,pnavarro/neutron,vbannai/neutron,virtualopensystems/neutron,yanheven/neutron,MaximNevrov/neutron,swdream/neutron,noironetworks/neutron,noironetworks/neutron,JianyuWang/neutron,shahbazn/neutron,leeseulstack/openstack,sasukeh/neutron,vbannai/neutron,Juniper/contrail-dev-neutron,yuewko/neutron,sajuptpm/neutron-ipam,mandeepdhami/neutron,jacknjzhou/neutron,silenci/neutron,eayunstack/neutron,gkotton/neutron,Juniper/neutron,SamYaple/neutron,alexandrucoman/vbox-neutron-agent,magic0704/neutron,blueboxgroup/neutron,vijayendrabvs/hap,openstack/neutron,paninetworks/neutron,CiscoSystems/neutron,mahak/neutron,blueboxgroup/neutron,SamYaple/neutron,vijayendrabvs/ssl-neutron,igor-toga/local-snat,glove747/liberty-neutron,projectcalico/calico-neutron,bgxavier/neutron,huntxu/neutron,igor-toga/local-snat,eonpatapon/neutron,antonioUnina/neutron,antonioUnina/neutron,asgard-lab/neutron,jumpojoy/neutron,NeCTAR-RC/neutron,NeCTAR-RC/neutron,redhat-openstack/neutron,sebrandon1/neutron,gkotton/neutron,jerryz1982/neutron,vijayendrabvs/ssl-neutron,openstack/neutron,dims/neutron,wenhuizhang/neutron,redhat-openstack/neutron,cloudbase/neutron,beagles/neutron_hacking,klmitch/neutron,infobloxopen/neutron,skyddv/neutron,yuewko/neutron,wolverineav/neutron,Metaswitch/calico-neutron,pnavarro/neutron,beagles/neutron_hacking,magic0704/neutron,SmartInfrastructures/neutron
neutron/openstack/common/log_handler.py
neutron/openstack/common/log_handler.py
# Copyright 2013 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import logging from oslo.config import cfg from neutron.openstack.common import notifier class PublishErrorsHandler(logging.Handler): def emit(self, record): if ('neutron.openstack.common.notifier.log_notifier' in cfg.CONF.notification_driver): return notifier.api.notify(None, 'error.publisher', 'error_notification', notifier.api.ERROR, dict(error=record.getMessage()))
# Copyright 2013 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import logging from oslo.config import cfg from neutron.openstack.common import notifier class PublishErrorsHandler(logging.Handler): def emit(self, record): if ('neutron.openstack.common.notifier.log_notifier' in cfg.CONF.notification_driver): return notifier.api.notify(None, 'error.publisher', 'error_notification', notifier.api.ERROR, dict(error=record.msg))
apache-2.0
Python
29f5e0a9b3d441f4fbc31055e319da4f37d9f40b
add import_regulomedb.py
perGENIE/pergenie,perGENIE/pergenie,perGENIE/pergenie-web,perGENIE/pergenie,perGENIE/pergenie-web,perGENIE/pergenie-web,perGENIE/pergenie-web,knmkr/perGENIE,knmkr/perGENIE,perGENIE/pergenie,perGENIE/pergenie-web,knmkr/perGENIE,knmkr/perGENIE,knmkr/perGENIE,perGENIE/pergenie-web,perGENIE/pergenie,knmkr/perGENIE
pergenie/lib/mongo/import_regulomedb.py
pergenie/lib/mongo/import_regulomedb.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import pymongo path_to_regulomedb = '/Users/numa/Dropbox/py/perGENIE/pergenie/data/large_dbs/regulomedb/RegulomeDB.dbSNP132.Category1.txt' def import_regulomedb(): print >>sys.stderr, 'Importing ...' with pymongo.MongoClient() as c: db = c['pergenie'] regulomedb = db['regulomedb'] # Ensure old collections does not exist if regulomedb.find_one(): db.drop_collection(regulomedb) assert regulomedb.count() == 0 with open(path_to_regulomedb, 'rb') as fin: for line in fin: chrom, pos, rs, anotation, score = line.strip().split('\t') chrom = chrom.replace('chr', '') assert (chrom in [str(i+1) for i in range(22)] + ['X', 'Y']) # no MT ? assert rs.startswith('rs') rs = int(rs.replace('rs', '')) anotation = anotation.split(',') record = dict(chrom=chrom, pos=int(pos), rs=rs, anotation=anotation, score=score) regulomedb.insert(record) print >>sys.stderr, 'count: {}'.format(regulomedb.count()) print >>sys.stderr, 'Creating indices...' regulomedb.create_index([('rs', pymongo.ASCENDING)]) regulomedb.create_index([('chrom', pymongo.ASCENDING), ('pos', pymongo.ASCENDING)]) print >>sys.stderr, 'done.' if __name__ == '__main__': import_regulomedb()
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import pymongo path_to_23adnme_snps = '/Users/numa/Dropbox/py/perGENIE/pergenie/data/large_dbs/23andme-api/snps.data' # FIX to path of yours. def import_23andme_snps(): print >>sys.stderr, 'Importing 23andMe SNPs...' with pymongo.MongoClient() as c: db = c['pergenie'] andme_snps = db['andme_snps'] # Ensure old collections does not exist if andme_snps.find_one(): db.drop_collection(andme_snps) assert andme_snps.count() == 0 with open(path_to_23adnme_snps, 'rb') as fin: for line in fin: # Skip header lines if line.startswith('#'): continue if line.startswith('index'): continue index, snp, chrom, pos = line.strip().split('\t') rs = int(snp.replace('rs', '')) if snp.startswith('rs') else None # Insert record as {'index': 0, , 'snp': 'rs41362547', 'rs': 41362547, 'chrom': 'MT', 'pos': 10044} record = dict(index=int(index), snp=snp, rs=rs, chrom=chrom, pos=int(pos)) andme_snps.insert(record) print >>sys.stderr, 'count: {}'.format(andme_snps.count()) print >>sys.stderr, 'Creating indices...' andme_snps.create_index([('index', pymongo.ASCENDING)]) andme_snps.create_index([('rs', pymongo.ASCENDING)]) # andme_snps.create_index([('chrom', pymongo.ASCENDING), ('pos', pymongo.ASCENDING)]) print >>sys.stderr, 'done.' if __name__ == '__main__': import_23andme_snps()
agpl-3.0
Python
38da9b42558d59b5858d18e5b2c9a26d5d8fd23b
Update email.py
delitamakanda/socialite,delitamakanda/socialite,delitamakanda/socialite
app/email.py
app/email.py
from threading import Thread from flask.ext.mail import Message from flask import render_template, current_app from . import mail from .decorators import async @async def send_async_email(app, msg): with app.app_context(): mail.send(msg) def send_email(to, subject, template, **kwargs): app = current_app._get_current_object() msg = Message(app.config['MAIL_SUBJECT_PREFIX'] + subject, sender=app.config['MAIL_SENDER'], recipients=[to]) msg.body = render_template(template + '.txt', **kwargs) msg.html = render_template(template + '.html', **kwargs) thr = Thread(target=send_async_email, args=[app, msg]) thr.start() return thr def follower_notification(followed, follower): send_email("Socialite %s is now following you!" %s follower.nickname, current_app.config['ADMIN'], [followed.email], render_template("mail/follower_email.txt"), render_template("mail/follower_email.html"))
from threading import Thread from flask.ext.mail import Message from flask import render_template, current_app from . import mail from .decorators import async @async def send_async_email(app, msg): with app.app_context(): mail.send(msg) def send_email(to, subject, template, **kwargs): app = current_app._get_current_object() msg = Message(app.config['MAIL_SUBJECT_PREFIX'] + subject, sender=app.config['MAIL_SENDER'], recipients=[to]) msg.body = render_template(template + '.txt', **kwargs) msg.html = render_template(template + '.html', **kwargs) thr = Thread(target=send_async_email, args=[app, msg]) thr.start() return thr def follower_notification(followed, follower): send_email("Socialite %s is now following you!" %s follower.nickname, current_app.config['ADMIN'], [followed.email], render_template("mail/follower_email.txt"), render_template("mail/follower_email.html"))
mit
Python
ac92075762ea9fecb9732a1328524f18d321f4a6
Add basic chat functions
tuxxy/SMIRCH
app/views.py
app/views.py
from app import app, db from flask import request, json from api import Teli from models import User, DID import re teli = Teli(app.config['TELI_TOKEN'], app.config['TELI_DID']) @app.route('/', methods=['POST']) def main(): # subscribe <nick> message = request.form.get('message').split(' ') sender = User.query.filter_by(user_phone=request.form.get('source')).first() if sender is None: if message[0].lower() == '@subscribe' and len(message) >= 2: return subscribe_user(message, request.form.get('source')) else: teli.send_sms(int(request.form.get('source')), "Subscribe to the Mojave SMS IRC by texting '@subscribe <nick>'") return json.dumps({'status': 'Call received'}) else: elif message[0].lower() == '@unsub': return unsub_user(sender) elif message[0].lower() == '@resub': return resub_user(sender) elif message[0].lower() == '@help': return send_help(sender) return json.dumps({'status': 'Call received'}) def subscribe_user(message, src): nick = re.sub('[^A-Za-z0-9_-]+', '', message[1]) if len(nick) >= 2: # Grab the first available DID did = DID.query.filter_by(user_id=None).first() if did: new_user = User(nick, src, did) db.session.add(new_user) db.session.commit() teli.send_sms(int(new_user.user_phone), "Welcome to Mojave SMS IRC for DEFCON 24!\nWritten by @__tux for the Mojave!\nText '@help' for commands.", src=int(new_user.did.number)) return json.dumps({'status': 'Call received'}) def unsub_user(user): user.is_subbed = False if not user.is_admin: user.did = None # Release the DID for others, unless you're an admin db.session.add(user) db.session.commit() return json.dumps({'status': 'Call received'}) def resub_user(user): # Admins get to keep their DID if not user.is_admin: did = DID.query.filter_by(user=None).first() if did is None: teli.send_sms(int(user.user_phone), "This chat is full, try again later.") return json.dumps({'status': 'Call received'}) else: user.did = did user.is_subbed = True teli.send_sms(int(user.user_phone), "Rejoined chat!") return json.dumps({'status': 'Call received'}) def send_help(user): teli.send_sms(int(user.user_phone), "@help - Displays this menu\n@<nick> <message> - Private message user\n@unsub - Unsubs from chat\n@resub - Resubscribes to chat\n@about - Displays info about the software") return json.dumps({'status': 'Call received'}) def relay_sms(message, sender): if sender.is_subbed: for user in User.query.filter_by(is_subbed=True): # Don't send the sender the same message if sender != user: message = ' '.join(message) teli.send_sms(int(user.user_phone), "<{}> {}".format(nick, message), src=int(user.did.number)) else: teli.send_sms(int(sender.user_phone), "You are not subscribed. Text 'subscribe' to rejoin the chat.", src=int(sender.did.number)) return json.dumps({'status': 'Call received'})
from app import app, db from flask import request, json from api import Teli from models import User, DID import re teli = Teli(app.config['TELI_TOKEN'], app.config['TELI_DID']) @app.route('/', methods=['POST']) def main(): # subscribe <nick> message = request.form.get('message').split(' ') if message[0].lower() == 'subscribe' and len(message) >= 2: return subscribe_user(message, request.form.get('source')) return json.dumps({'status': 'Call received'}) def subscribe_user(message, src): nick = re.sub('[^A-Za-z0-9_-]+', '', message[1]) if len(nick) >= 2: # Grab the first available DID did = DID.query.filter_by(user_id=None).first() if did: new_user = User(nick, src, did) db.session.add(new_user) db.session.commit() teli.send_sms( int(new_user.user_phone), "Welcome to Mojave SMS IRC for DEFCON 24!\nWritten by @__tux for the Mojave!", src=int(new_user.did.number)) return json.dumps({'status': 'Call received'})
agpl-3.0
Python
22ae4b9e0ce5c9d1ac37a2dc2d225c2855b7f9f1
Save votes to redis
Arcana/pubstomp.hu,Arcana/pubstomp.hu,Arcana/pubstomp.hu
app/views.py
app/views.py
from uuid import uuid4 from flask import render_template, request, make_response from app import app, babel, redis @babel.localeselector def get_locale(): if hasattr(request, 'locale'): if request.locale in app.config['LOCALES'] and request.locale: return request.locale else: return request.accept_languages.best_match(app.config['LOCALES']) @app.route('/') @app.route('/<locale>') def index_with_locale(locale=None): request.locale = locale response = make_response(render_template('index.html')) if 'u' not in request.cookies: response.set_cookie('u', str(uuid4())[:13]) return response @app.route('/poll', methods=['PUT']) def submit_poll_response(): if 'u' in request.cookies: redis.set(request.cookies['u'], request.form['value']) return '', 204 else: return '', 400
from flask import render_template, request from app import app, babel @babel.localeselector def get_locale(): if hasattr(request, 'locale'): if request.locale in app.config['LOCALES'] and request.locale: return request.locale else: return request.accept_languages.best_match(app.config['LOCALES']) @app.route('/') @app.route('/<locale>') def index_with_locale(locale=None): request.locale = locale return render_template('index.html') @app.route('/poll', methods=['PUT']) def submit_poll_response(): return '', 204
mit
Python
7a22663a66749ef7f86a78575fb915b66ed02f73
Update views to frontend
chrisfrederickson/firepi,chrisfrederickson/firepi,chrisfrederickson/firepi,chrisfrederickson/firepi
app/views.py
app/views.py
from app import app, chamber from app.auth import google, whitelist_required, admin_required from flask import request, url_for, redirect, flash, session, jsonify, render_template @app.route('/') def home(): return render_template('index.html') @app.route('/read') @whitelist_required def read_temp(): try: temp = chamber.read_temp() except: return 'Fail! Temp read error.' return str(temp) @app.route('/set') @admin_required def set_temp(): try: temp = float(request.args.get('temp')) except: return 'Fail! Invalid argument' try: chamber.set_temp(temp) except: return 'Fail! Temp set error' return 'Success!' @app.route('/login') def login(): return google.authorize(callback=url_for('oauth_authorized', _external=True)) @app.route('/logout') def logout(): session.pop('google_token', None) return redirect(url_for('home')) @app.route('/oauth-authorized') def oauth_authorized(): resp = google.authorized_response() if resp is None: if resp is None: # User denied request to sign in return redirect(url_for('home')) session['google_token'] = (resp['access_token'], '') me = google.get('userinfo') return redirect(url_for('home', token=resp['access_token']))
from app import app, tempchamber from app.auth import google, whitelist_required, admin_required from flask import request, url_for, redirect, flash, session, jsonify chamber = tempchamber.TempChamber() @app.route('/') def home(): if 'google_token' in session: me = google.get('userinfo') return jsonify({"data": me.data}) return 'No user data' @app.route('/read') @whitelist_required def read_temp(): try: temp = chamber.read_temp() except: return 'Fail! Temp read error.' return str(temp) @app.route('/set') @admin_required def set_temp(): try: temp = float(request.args.get('temp')) except: return 'Fail! Invalid argument' try: chamber.set_temp(temp) except: return 'Fail! Temp set error' return 'Success!' @app.route('/login') def login(): return google.authorize(callback=url_for('oauth_authorized', _external=True)) @app.route('/logout') def logout(): session.pop('google_token', None) return redirect(url_for('home')) @app.route('/oauth-authorized') def oauth_authorized(): resp = google.authorized_response() if resp is None: if resp is None: # User denied request to sign in return redirect(url_for('home')) session['google_token'] = (resp['access_token'], '') me = google.get('userinfo') return redirect(url_for('home'))
mit
Python
a31428a7bd18a1c9f551276b08b1334352fb552b
debug = false
copelco/Durham-Open-Data-Catalog,copelco/Durham-Open-Data-Catalog,copelco/Durham-Open-Data-Catalog
OpenDataCatalog/settings_production.py
OpenDataCatalog/settings_production.py
from settings import * DEBUG = False SITE_ROOT = '' LOGIN_URL = SITE_ROOT + "/accounts/login/" # Theme info # LOCAL_STATICFILE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), # '../../ODC-overlay/static')) # LOCAL_TEMPLATE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), # '../../ODC-overlay/templates')) # ReCatchpa stuff RECAPTCHA_PUBLIC_KEY = '6LfU8t8SAAAAAJKrpalcrjlSA6zf9SIJaMBbz33s' RECAPTCHA_PRIVATE_KEY = '' # Twitter stuff TWITTER_USER = None # AWS Credentials for Warehouse stuff AWS_ACCESS_KEY = None AWS_SECRET_KEY = None # Contacts # mx_host = 'mycity.gov' ADMINS = ( ('Colin', 'copelco@caktusgroup.com'), ) CONTACT_EMAILS = ['copelco@caktusgroup.com'] DEFAULT_FROM_EMAIL = 'OpenData Site <noreply@example.com>' EMAIL_SUBJECT_PREFIX = '[OpenDataCatalog - MYCITY] ' SERVER_EMAIL = 'OpenData Team <info@example.com>' MANAGERS = ( ('Colin', 'copelco@caktusgroup.com'), ) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'opendata', # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } INSTALLED_APPS += ( 'gunicorn', ) # Make this unique, and don't share it with anybody. SECRET_KEY = 'insecure'
import os from settings import * SITE_ROOT = '' LOGIN_URL = SITE_ROOT + "/accounts/login/" # Theme info # LOCAL_STATICFILE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), # '../../ODC-overlay/static')) # LOCAL_TEMPLATE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), # '../../ODC-overlay/templates')) # ReCatchpa stuff RECAPTCHA_PUBLIC_KEY = '6LfU8t8SAAAAAJKrpalcrjlSA6zf9SIJaMBbz33s' RECAPTCHA_PRIVATE_KEY = '' # Twitter stuff TWITTER_USER = None # AWS Credentials for Warehouse stuff AWS_ACCESS_KEY = None AWS_SECRET_KEY = None # Contacts # mx_host = 'mycity.gov' ADMINS = ( ('Colin', 'copelco@caktusgroup.com'), ) CONTACT_EMAILS = ['copelco@caktusgroup.com'] DEFAULT_FROM_EMAIL = 'OpenData Site <noreply@example.com>' EMAIL_SUBJECT_PREFIX = '[OpenDataCatalog - MYCITY] ' SERVER_EMAIL = 'OpenData Team <info@example.com>' MANAGERS = ( ('Colin', 'copelco@caktusgroup.com'), ) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'opendata', # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } INSTALLED_APPS += ( 'gunicorn', ) # Make this unique, and don't share it with anybody. SECRET_KEY = 'insecure'
mit
Python
f55a7bffd1cd6a75aa7e5151d4cd564826ab08b2
Remove unused code
rollbar/pyrollbar
rollbar/contrib/starlette/middleware.py
rollbar/contrib/starlette/middleware.py
import sys from starlette.requests import Request from starlette.types import Receive, Scope, Send import rollbar from .requests import store_current_request from rollbar.contrib.asgi import ASGIMiddleware from rollbar.lib._async import RollbarAsyncError, try_report class StarletteMiddleware(ASGIMiddleware): async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: try: store_current_request(scope, receive) await self.app(scope, receive, send) except Exception: if scope['type'] == 'http': request = Request(scope, receive, send) # Consuming the request body in Starlette middleware is problematic # See: https://github.com/encode/starlette/issues/495#issuecomment-494008175 # Uncomment line below if you know the risk # await request.body() exc_info = sys.exc_info() try: await try_report(exc_info, request) except RollbarAsyncError: rollbar.report_exc_info(exc_info, request) raise
import logging import sys from starlette.requests import Request from starlette.types import Receive, Scope, Send import rollbar from .requests import store_current_request from rollbar.contrib.asgi import ASGIMiddleware from rollbar.lib._async import RollbarAsyncError, try_report log = logging.getLogger(__name__) class StarletteMiddleware(ASGIMiddleware): async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: try: store_current_request(scope, receive) await self.app(scope, receive, send) except Exception: if scope['type'] == 'http': request = Request(scope, receive, send) # Consuming the request body in Starlette middleware is problematic # See: https://github.com/encode/starlette/issues/495#issuecomment-494008175 # Uncomment line below if you know the risk # await request.body() exc_info = sys.exc_info() try: await try_report(exc_info, request) except RollbarAsyncError: rollbar.report_exc_info(exc_info, request) raise
mit
Python
e93a87f451b1e2a11b0393fa8ed048f19203eafc
bump to 0.19.0
dmpetrov/dataversioncontrol,efiop/dvc,efiop/dvc,dataversioncontrol/dvc,dataversioncontrol/dvc,dmpetrov/dataversioncontrol
dvc/__init__.py
dvc/__init__.py
""" DVC ---- Make your data science projects reproducible and shareable. """ import os import warnings VERSION_BASE = '0.19.0' __version__ = VERSION_BASE PACKAGEPATH = os.path.abspath(os.path.dirname(__file__)) HOMEPATH = os.path.dirname(PACKAGEPATH) VERSIONPATH = os.path.join(PACKAGEPATH, 'version.py') if os.path.exists(os.path.join(HOMEPATH, 'setup.py')): # dvc is run directly from source without installation or # __version__ is called from setup.py if os.getenv('APPVEYOR_REPO_TAG', '').lower() != 'true' \ and os.getenv('TRAVIS_TAG', '') == '': # Dynamically update version try: import git repo = git.Repo(HOMEPATH) sha = repo.head.object.hexsha short_sha = repo.git.rev_parse(sha, short=6) dirty = '.mod' if repo.is_dirty() else '' __version__ = '{}+{}{}'.format(__version__, short_sha, dirty) # Write a helper file, that will be installed with the package # and will provide a true version of the installed dvc with open(VERSIONPATH, 'w+') as fd: fd.write('# AUTOGENERATED by dvc/__init__.py\n') fd.write('version = "{}"\n'.format(__version__)) except Exception: pass else: # Remove version.py so that it doesn't get into the release if os.path.exists(VERSIONPATH): os.unlink(VERSIONPATH) else: # dvc was installed with pip or something. Hopefully we have our # auto-generated version.py to help us provide a true version try: from dvc.version import version __version__ = version except Exception: pass VERSION = __version__ # Ignore numpy's runtime warnings: https://github.com/numpy/numpy/pull/432. # We don't directly import numpy, but our dependency networkx does, causing # these warnings in some environments. Luckily these warnings are benign and # we can simply ignore them so that they don't show up when you are using dvc. warnings.filterwarnings("ignore", message="numpy.dtype size changed") warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
""" DVC ---- Make your data science projects reproducible and shareable. """ import os import warnings VERSION_BASE = '0.18.15' __version__ = VERSION_BASE PACKAGEPATH = os.path.abspath(os.path.dirname(__file__)) HOMEPATH = os.path.dirname(PACKAGEPATH) VERSIONPATH = os.path.join(PACKAGEPATH, 'version.py') if os.path.exists(os.path.join(HOMEPATH, 'setup.py')): # dvc is run directly from source without installation or # __version__ is called from setup.py if os.getenv('APPVEYOR_REPO_TAG', '').lower() != 'true' \ and os.getenv('TRAVIS_TAG', '') == '': # Dynamically update version try: import git repo = git.Repo(HOMEPATH) sha = repo.head.object.hexsha short_sha = repo.git.rev_parse(sha, short=6) dirty = '.mod' if repo.is_dirty() else '' __version__ = '{}+{}{}'.format(__version__, short_sha, dirty) # Write a helper file, that will be installed with the package # and will provide a true version of the installed dvc with open(VERSIONPATH, 'w+') as fd: fd.write('# AUTOGENERATED by dvc/__init__.py\n') fd.write('version = "{}"\n'.format(__version__)) except Exception: pass else: # Remove version.py so that it doesn't get into the release if os.path.exists(VERSIONPATH): os.unlink(VERSIONPATH) else: # dvc was installed with pip or something. Hopefully we have our # auto-generated version.py to help us provide a true version try: from dvc.version import version __version__ = version except Exception: pass VERSION = __version__ # Ignore numpy's runtime warnings: https://github.com/numpy/numpy/pull/432. # We don't directly import numpy, but our dependency networkx does, causing # these warnings in some environments. Luckily these warnings are benign and # we can simply ignore them so that they don't show up when you are using dvc. warnings.filterwarnings("ignore", message="numpy.dtype size changed") warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
apache-2.0
Python
4ee58acb7e9a35be0514d1a4189fbc6c4a53baa5
update http example
ubolonton/twisted-csp
example/http.py
example/http.py
import csp from twisted.web.client import getPage def request(url): channel = csp.Channel(1) def ok(value): csp.put_then_callback(channel, (value, None), csp.no_op) def error(failure): csp.put_then_callback(channel, (None, failure), csp.no_op) getPage(url).addCallback(ok).addErrback(error) return channel def main(): for url, dt in ( ("http://www.google.com/search?q=csp", 0.01), # too little time ("http://www.google.come/search?q=csp", 10), # wrong domain name ("http://www.google.com/search?q=csp", 10), ): print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" print url, dt, "seconds" c = request(url) t = csp.timeout(dt) value, chan = yield csp.alts([c, t]) if chan is c: result, error = value if error: print "Uhm, not good" print error else: print "Here" print result[:500] + "..." elif chan is t: print "Timeout"
import csp from twisted.web.client import getPage def request(url): return csp.channelify(getPage(url)) def main(): def timeout_channel(seconds): c = csp.Channel() def _t(): yield csp.wait(seconds) yield c.put(None) csp.go(_t()) return c c = request("http://www.google.com/search?q=csp") t = timeout_channel(10) chan = yield csp.select(c, t) if chan is c: result, error = yield c.take() if error: print "Uhm, not good" print error else: print "Here" print result elif chan is t: print "Timeout"
epl-1.0
Python
32c35a39fa14aecf91747727ee8b54bb60027b48
add function to parse fixer_io
anshulc95/exch
exch/helpers.py
exch/helpers.py
""" helper functions to gather the currency rates """ from urllib.parse import urlencode import requests from decimal import Decimal, getcontext getcontext().prec = 2 def fixer(base, target, value=1, date='latest'): """get currency exchange rate from fixer.io in JSON""" main_api = 'http://api.fixer.io/{}?'.format(date) url = main_api + urlencode({'base':base}) json_data = requests.get(url).json() return round(json_data['rates'][target] * value, 2) def google_finance_converter(base, target, value): """ parse the Google Finance Converter html to extract the value""" pass
mit
Python
6f421c97a0b5d08c5d8d76330ddda89a4bb78a73
Update seo_meta.py
eghuro/crawlcheck
src/checker/plugin/checkers/seo_meta.py
src/checker/plugin/checkers/seo_meta.py
from common import PluginType, getSoup from yapsy.IPlugin import IPlugin import logging class MetaTagValidator(IPlugin): category = PluginType.CHECKER id = "seometa" contentTypes = ["text/html"] __defects = {"seo:multidsc": "Multiple description meta tags found", "seo:nodsc": "No description meta tag found", "seo:multikeys": "Multiple keywords meta tags found", "seo:nokeys": "No keywords meta tags found"} __severity = 0.4 def __init__(self): self.__journal = None def setJournal(self, journal): self.__journal = journal def __classify(self, head, name, idno, zero, multi): foo = head.find_all('meta', {'name': name}) if len(foo) > 1: clas = multi dsc = str(len(foo)) elif len(foo) == 0: clas = zero dsc = "" else: return self.__journal.foundDefect(idno, clas, MetaTagValidator.__defects[clas], dsc, MetaTagValidator.__severity) def check(self, transaction): """Pusti validator, ulozi chyby. """ for html in getSoup(transaction).find_all('html', limit=1): for head in html.find_all('head', limit=1): self.__classify(head, 'description', transaction.idno, "seo:nodsc", "seo:multidsc") self.__classify(head, 'keywords', transaction.idno, "seo:nokeys", "seo:multikeys") return
from common import PluginType, getSoup from yapsy.IPlugin import IPlugin import logging class MetaTagValidator(IPlugin): category = PluginType.CHECKER id = "seometa" contentTypes = ["text/html"] __defects = {"seo:multidsc": "Multiple description meta tags found", "seo:nodsc": "No description meta tag found", "seo:multikeys": "Multiple keywords meta tags found", "seo:nokeys": "No keywords meta tags found"} __severity = 0.8 def __init__(self): self.__journal = None def setJournal(self, journal): self.__journal = journal def __classify(self, head, name, idno, zero, multi): foo = head.find_all('meta', {'name': name}) if len(foo) > 1: clas = multi dsc = str(len(foo)) elif len(foo) == 0: clas = zero dsc = "" else: return self.__journal.foundDefect(idno, clas, MetaTagValidator.__defects[clas], dsc, MetaTagValidator.__severity) def check(self, transaction): """Pusti validator, ulozi chyby. """ for html in getSoup(transaction).find_all('html', limit=1): for head in html.find_all('head', limit=1): self.__classify(head, 'description', transaction.idno, "seo:nodsc", "seo:multidsc") self.__classify(head, 'keywords', transaction.idno, "seo:nokeys", "seo:multikeys") return
mit
Python
48e4b347dcbef03efc889c227895c4f2b66e0838
Improve test names.
raphaeldore/analyzr,raphaeldore/analyzr
analyzr/test/test_networkdiscoverer.py
analyzr/test/test_networkdiscoverer.py
import unittest from analyzr.constants import topports from analyzr.core import NetworkToolFacade, Fingerprinter from analyzr.networkdiscoverer import NetworkDiscoverer class NetworkToolMock(NetworkToolFacade): pass class FingerprinterMock(Fingerprinter): pass class InitConfig(unittest.TestCase): def setUp(self): fingerprinters = [FingerprinterMock("abc", "whatever", None)] self.network_tool = NetworkToolMock(fingerprinters) self.config = {"ports": None, "networks": None, "discovery_mode": None} def get_network_discoverer(self): return NetworkDiscoverer(self.network_tool, self.config) def test_given_no_ports_to_scan_then_uses_default_ports(self): network_discoverer = self.get_network_discoverer() self.assertEqual(network_discoverer.ports_to_scan, topports) def test_given_config_with_no_ports_to_scan_then_uses_default_ports(self): self.config.pop("ports") network_discoverer = self.get_network_discoverer() self.assertEqual(network_discoverer.ports_to_scan, topports) def test_given_no_networks_to_scan_then_uses_default_networks(self): network_discoverer = self.get_network_discoverer() self.assertEqual(network_discoverer.networks_to_scan, network_discoverer.private_ipv4_space) def test_given_config_with_no_networks_to_scan_then_uses_default_networks(self): self.config.pop("networks") network_discoverer = self.get_network_discoverer() self.assertEqual(network_discoverer.networks_to_scan, network_discoverer.private_ipv4_space) def test_given_no_discovery_mode_then_default_discovery_mode_used(self): network_discoverer = self.get_network_discoverer() self.assertEqual(network_discoverer.discovery_mode, "all") def test_given_config_with_no_discory_mode_then_default_descovery_mode_used(self): self.config.pop("discovery_mode") network_discoverer = self.get_network_discoverer() self.assertEqual(network_discoverer.discovery_mode, "all") # TODO: Tester que les valeurs sont bien affectés. if __name__ == '__main__': unittest.main()
import unittest from analyzr.constants import topports from analyzr.core import NetworkToolFacade, Fingerprinter from analyzr.networkdiscoverer import NetworkDiscoverer class NetworkToolMock(NetworkToolFacade): pass class FingerprinterMock(Fingerprinter): pass class InitConfig(unittest.TestCase): def setUp(self): fingerprinters = [FingerprinterMock("abc", "whatever", None)] self.network_tool = NetworkToolMock(fingerprinters) self.config = {"ports": None, "networks": None, "discovery_mode": None} def get_network_discoverer(self): return NetworkDiscoverer(self.network_tool, self.config) def test_when_no_ports_given_then_default_ports_used(self): network_discoverer = self.get_network_discoverer() self.assertEqual(network_discoverer.ports_to_scan, topports) def test_when_config_does_not_have_ports_key_then_default_ports_used(self): self.config.pop("ports") network_discoverer = self.get_network_discoverer() self.assertEqual(network_discoverer.ports_to_scan, topports) def test_when_no_networks_given_then_default_networks_used(self): network_discoverer = self.get_network_discoverer() self.assertEqual(network_discoverer.networks_to_scan, network_discoverer.private_ipv4_space) def test_when_config_does_not_have_networks_key_then_default_networks_used(self): self.config.pop("networks") network_discoverer = self.get_network_discoverer() self.assertEqual(network_discoverer.networks_to_scan, network_discoverer.private_ipv4_space) def test_when_no_discovery_mode_given_then_default_default_discovery_mode_used(self): network_discoverer = self.get_network_discoverer() self.assertEqual(network_discoverer.discovery_mode, "all") def test_when_config_does_not_have_discovery_mode_key_then_default_descovery_mode_all_used(self): self.config.pop("discovery_mode") network_discoverer = self.get_network_discoverer() self.assertEqual(network_discoverer.discovery_mode, "all") # TODO: Tester que les valeurs sont bien affectés. if __name__ == '__main__': unittest.main()
mit
Python
1bae18a57bbda31ff14b8689d0dfaa205596456b
Move setting of CALACCESS_WEBSITE_ENV before initial django db migration
california-civic-data-coalition/django-calaccess-downloads-website,california-civic-data-coalition/django-calaccess-downloads-website,california-civic-data-coalition/django-calaccess-downloads-website
fabfile/chef.py
fabfile/chef.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import collections from app import migrate, collectstatic from configure import ConfigTask, copyconfig from fabric.api import sudo, task, env from fabric.contrib.project import rsync_project from fabric.colors import green @task(task_class=ConfigTask) def bootstrap(): """ Install Chef and use it to install the app on an EC2 instance. """ # Prepare node to use secrets from our configuration file rendernodejson() # Install chef and run it installchef() cook() # Copy local env to new instance copyconfig() # Set the CALACCESS_WEBSITE_ENV var when the virtualenv is activated. # Otherwise the Django project will default to DEV. sudo("echo 'export CALACCESS_WEBSITE_ENV=%s' >> " "/apps/calaccess/bin/activate" % env.config_section) # Fire up the Django project migrate() collectstatic() # Done deal print(green("Success!")) print("Visit the app at %s" % env.EC2_HOST) @task(task_class=ConfigTask) def installchef(): """ Install all the dependencies to run a Chef cookbook """ # Update apt-get sudo('apt-get update', pty=True) # Install Chef sudo('curl -L https://www.chef.io/chef/install.sh | sudo bash', pty=True) @task(task_class=ConfigTask) def rendernodejson(): """ Render chef's node.json file from a template """ template = open("./chef/node.json.template", "r").read() data = json.loads( template % env, object_pairs_hook=collections.OrderedDict ) with open('./chef/node.json', 'w') as f: json.dump(data, f, indent=4, separators=(',', ': ')) @task(task_class=ConfigTask) def cook(): """ Update Chef cookbook and execute it. """ sudo('mkdir -p /etc/chef') sudo('chown ubuntu -R /etc/chef') rsync_project("/etc/chef/", "./chef/") sudo('cd /etc/chef && /usr/bin/chef-solo -c solo.rb -j node.json', pty=True)
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import collections from app import migrate, collectstatic from configure import ConfigTask, copyconfig from fabric.api import sudo, task, env from fabric.contrib.project import rsync_project from fabric.colors import green @task(task_class=ConfigTask) def bootstrap(): """ Install Chef and use it to install the app on an EC2 instance. """ # Prepare node to use secrets from our configuration file rendernodejson() # Install chef and run it installchef() cook() # Copy local env to new instance copyconfig() # Fire up the Django project migrate() collectstatic() sudo("echo 'export CALACCESS_WEBSITE_ENV=%s' >> " "/apps/calaccess/bin/activate" % env.config_section) # Done deal print(green("Success!")) print("Visit the app at %s" % env.EC2_HOST) @task(task_class=ConfigTask) def installchef(): """ Install all the dependencies to run a Chef cookbook """ # Update apt-get sudo('apt-get update', pty=True) # Install Chef sudo('curl -L https://www.chef.io/chef/install.sh | sudo bash', pty=True) @task(task_class=ConfigTask) def rendernodejson(): """ Render chef's node.json file from a template """ template = open("./chef/node.json.template", "r").read() data = json.loads( template % env, object_pairs_hook=collections.OrderedDict ) with open('./chef/node.json', 'w') as f: json.dump(data, f, indent=4, separators=(',', ': ')) @task(task_class=ConfigTask) def cook(): """ Update Chef cookbook and execute it. """ sudo('mkdir -p /etc/chef') sudo('chown ubuntu -R /etc/chef') rsync_project("/etc/chef/", "./chef/") sudo('cd /etc/chef && /usr/bin/chef-solo -c solo.rb -j node.json', pty=True)
mit
Python
ebf9c923388b8ea013785791b4c5031760987d4b
fix generate_process_flowchart
vicalloy/django-lb-workflow,vicalloy/django-lb-workflow,vicalloy/django-lb-workflow
lbworkflow/views/flowchart.py
lbworkflow/views/flowchart.py
from django.http import HttpResponse from django.template import Context from django.template import Template from lbworkflow.models import Process try: import pygraphviz as pgv except ImportError: pass def generate_process_flowchart(process): file_template = """ strict digraph { rankdir=TB; graph [ratio="auto" label="{{ name }}" labelloc=t ]; node [shape = ellipse]; edge [fontsize=14] {% for transition in transitions %} "{{ transition.input_activity.name }}" -> "{{ transition.output_activity.name }}" [label="{{ transition.name }} {% if transition.get_condition_descn %}: {% endif %} {{ transition.get_condition_descn }}"] ; {% endfor %} } """ # NOQA transitions = process.transition_set.all() request = Context({'name': process.name, 'transitions': transitions}) t = Template(file_template) G = pgv.AGraph(string=t.render(request)) return G def render_dot_graph(graph): image_data = graph.draw(format='png', prog='dot') return HttpResponse(image_data, content_type="image/png") def process_flowchart(request, wf_code): process = Process.objects.get(code=wf_code) G = generate_process_flowchart(process) return render_dot_graph(G)
from django.http import HttpResponse from django.template import Context from django.template import Template from lbworkflow.models import Process try: import pygraphviz as pgv except ImportError: pass def generate_process_flowchart(process): file_template = """ strict digraph { rankdir=TB; graph [ratio="auto" label="{{name}}" labelloc=t ]; node [shape = ellipse]; edge [fontsize=14] {% for transition in transitions %} "{{ transition.input.name }}" -> "{{ transition.output.name }}" [label="{{ transition.name }} {%if transition.get_condition_descn %}: {%endif%} flow_note transition.get_condition_descn"] ; {% endfor %} } """ # NOQA transitions = process.transition_set.all() request = Context({'name': process.name, 'transitions': transitions}) t = Template(file_template) G = pgv.AGraph(string=t.render(request)) return G def render_dot_graph(graph): image_data = graph.draw(format='png', prog='dot') return HttpResponse(image_data, content_type="image/png") def process_flowchart(request, wf_code): process = Process.objects.get(code=wf_code) G = generate_process_flowchart(process) return render_dot_graph(G)
mit
Python
30e7567ae6d8fe407b8360425ebcd46b4633a852
Update fetchWeather.py
siskulous/PiAwake,siskulous/PiAwake
fetchWeather.py
fetchWeather.py
#!/usr/bin/python import json, requests, commands url='http://forecast.weather.gov/MapClick.php' params = dict( lat = 37.9752, lon = -100.8642, FcstType = 'json' ) resp = requests.get(url=url, params=params) data = json.loads(resp.text) #weather=data['location']['areaDescription']+' Weather...' weather="Garden City Kansas Weather... " for i in range(0,3): weather+=data['time']['startPeriodName'][i] + ': ' weather+=data['data']['text'][i] commands.getstatusoutput('flite -o /tmp/weather.wav "' + weather + '"')
#!/usr/bin/python import json, requests, commands url='http://forecast.weather.gov/MapClick.php' params = dict( lat = 37.9752, lon = -100.8642, FcstType = 'json' ) resp = requests.get(url=url, params=params) data = json.loads(resp.text) #weather=data['location']['areaDescription']+' Weather...' weather="Garden City Kansas Weather... " for i in range(0,3): weather+=data['time']['startPeriodName'][i] + ': ' weather+=data['data']['text'][i] commands.getstatusoutput('pico2wave -w /tmp/weather.wav "' + weather + '"')
mit
Python
7efbb0c4edbe572b03495c8403d56d2230dc97db
Tag new release: 3.1.14
Floobits/floobits-sublime,Floobits/floobits-sublime
floo/version.py
floo/version.py
PLUGIN_VERSION = '3.1.14' # The line above is auto-generated by tag_release.py. Do not change it manually. try: from .common import shared as G assert G except ImportError: from common import shared as G G.__VERSION__ = '0.11' G.__PLUGIN_VERSION__ = PLUGIN_VERSION
PLUGIN_VERSION = '3.1.13' # The line above is auto-generated by tag_release.py. Do not change it manually. try: from .common import shared as G assert G except ImportError: from common import shared as G G.__VERSION__ = '0.11' G.__PLUGIN_VERSION__ = PLUGIN_VERSION
apache-2.0
Python
8fd6d943c73a5d9772b598923893d6501a4ed343
Bump minor build
gogetdata/ggd-cli,gogetdata/ggd-cli
ggd/__init__.py
ggd/__init__.py
__version__ = "0.0.9"
__version__ = "0.0.8"
mit
Python
c027e671d1a47d485755b748f2dffc202c704ff8
Update goodreads API to `show original_publication_year`
avinassh/Reddit-GoodReads-Bot
goodreadsapi.py
goodreadsapi.py
#!/usr/bin/env python import re from xml.parsers.expat import ExpatError import requests import xmltodict from settings import goodreads_api_key def get_goodreads_ids(comment_msg): # receives goodreads url # returns the id using regex regex = r'goodreads.com/book/show/(\d+)' return set(re.findall(regex, comment_msg)) def get_book_details_by_id(goodreads_id): api_url = 'http://goodreads.com/book/show/{0}?format=xml&key={1}' r = requests.get(api_url.format(goodreads_id, goodreads_api_key)) try: book_data = xmltodict.parse(r.content)['GoodreadsResponse']['book'] except (TypeError, KeyError, ExpatError): return False keys = ['title', 'average_rating', 'ratings_count', 'description', 'num_pages'] book = {} for k in keys: book[k] = book_data.get(k) try: work = book_data['work'] book['publication_year'] = work['original_publication_year']['#text'] except KeyError: book['publication_year'] = book_data.get('publication_year') if type(book_data['authors']['author']) == list: authors = [author['name'] for author in book_data['authors']['author']] authors = ', '.join(authors) else: authors = book_data['authors']['author']['name'] book['authors'] = authors return book
#!/usr/bin/env python import re from xml.parsers.expat import ExpatError import requests import xmltodict from settings import goodreads_api_key def get_goodreads_ids(comment_msg): # receives goodreads url # returns the id using regex regex = r'goodreads.com/book/show/(\d+)' return set(re.findall(regex, comment_msg)) def get_book_details_by_id(goodreads_id): api_url = 'http://goodreads.com/book/show/{0}?format=xml&key={1}' r = requests.get(api_url.format(goodreads_id, goodreads_api_key)) try: book_data = xmltodict.parse(r.content)['GoodreadsResponse']['book'] except (TypeError, KeyError, ExpatError): return False keys = ['title', 'average_rating', 'ratings_count', 'description', 'num_pages', 'publication_year'] book = {} for k in keys: book[k] = book_data.get(k) if type(book_data['authors']['author']) == list: authors = [author['name'] for author in book_data['authors']['author']] authors = ', '.join(authors) else: authors = book_data['authors']['author']['name'] book['authors'] = authors return book
mit
Python
59b015bb3e45497b7ec86bf1799e8442a30b65da
Exit method. - (New) Added exit method.
dacuevas/PMAnalyzer,dacuevas/PMAnalyzer,dacuevas/PMAnalyzer,dacuevas/PMAnalyzer
py/PMUtil.py
py/PMUtil.py
# PMUtil.py # Phenotype microarray utility functions # # Author: Daniel A Cuevas # Created on 27 Jan 2015 # Updated on 20 Aug 2015 from __future__ import absolute_import, division, print_function import sys import time import datetime def timeStamp(): '''Return time stamp''' t = time.time() fmt = '[%Y-%m-%d %H:%M:%S]' return datetime.datetime.fromtimestamp(t).strftime(fmt) def printStatus(msg): '''Print status message''' print('{} {}'.format(timeStamp(), msg), file=sys.stderr) sys.stderr.flush() def exitScript(num=1): '''Exit script''' sys.exit(num)
# PMUtil.py # Phenotype microarray utility functions # # Author: Daniel A Cuevas # Created on 27 Jan. 2015 # Updated on 27 Jan. 2015 from __future__ import absolute_import, division, print_function import sys import time import datetime def timeStamp(): '''Return time stamp''' t = time.time() fmt = '[%Y-%m-%d %H:%M:%S]' return datetime.datetime.fromtimestamp(t).strftime(fmt) def printStatus(msg): '''Print status message''' print('{} {}'.format(timeStamp(), msg), file=sys.stderr) sys.stderr.flush()
mit
Python
a8976ff1c3bdc177ca72becf48c4278f963d2627
Add Publications class to initialisation
nestauk/gtr
gtr/__init__.py
gtr/__init__.py
__all__ = [ "gtr.services.funds.Funds", "gtr.services.organisations.Organisations", "gtr.services.persons.Persons", "gtr.services.projects.Projects", "gtr.services.publications.Publications" ] __version__ = "0.1.0" from gtr.services.base import _Service from gtr.services.funds import Funds from gtr.services.organisations import Organisations from gtr.services.persons import Persons from gtr.services.projects import Projects from gtr.services.publications import Publications
__all__ = [ "gtr.services.funds.Funds", "gtr.services.organisations.Organisations", "gtr.services.persons.Persons", "gtr.services.projects.Projects" ] __version__ = "0.1.0" from gtr.services.base import _Service from gtr.services.funds import Funds from gtr.services.organisations import Organisations from gtr.services.persons import Persons from gtr.services.projects import Projects
apache-2.0
Python
036ec4468bf6431bd137417f51fb182dd990cb80
read json file as OrderedDicts
phaustin/nws_parse,phaustin/nws_parse
read_json.py
read_json.py
""" example read for json file """ import json from collections import OrderedDict filename = 'testdata/bondurant.json' with open(filename,'r') as f: week_list = json.load(f,object_pairs_hook=OrderedDict) # # print valid forecast periods for each week # for week in week_list: print(week['valid']) # # print temperatures for week3 (index starts at 0) # temps = week_list[2]['temps'] print(temps)
""" example read for json file """ import json filename = 'testdata/bondurant.json' with open(filename,'r') as f: week_list = json.load(f) # # print valid forecast periods for each week # for week in week_list: print(week['valid']) # # print temperatures for week3 (index starts at 0) # temps = week_list[2]['temps'] print(temps)
cc0-1.0
Python
05d4427f3998180a9e9caa192ddadd7bb5e8ccdd
remove extra spaces
sdpython/pyquickhelper,sdpython/pyquickhelper,sdpython/pyquickhelper,sdpython/pyquickhelper
src/pyquickhelper/pycode/code_helper.py
src/pyquickhelper/pycode/code_helper.py
""" @file @brief Various function to clean the code. """ import os from ..sync.synchelper import explore_folder def remove_extra_spaces(filename): """ removes extra spaces in a filename, replace the file in place @param filename file name @return number of removed extra spaces """ try: with open(filename, "r") as f : lines = f.readlines() except PermissionError as e : raise PermissionError (filename) from e lines2 = [ _.rstrip(" \r\n") for _ in lines ] last = len(lines2)-1 while last >= 0 and len(lines2[last]) == 0 : last -= 1 last+=1 lines2 = lines2[:last] diff = len("".join(lines)) - len("\n".join(lines2)) if diff != 0: with open(filename,"w") as f : f.write("\n".join(lines2)) return diff def remove_extra_spaces_folder(folder, extensions = (".py",".rst")): """ removes extra files in a folder for specific file extensions @param folder folder to explore @param extensions list of file extensions to process @return the list of modified files """ files = explore_folder(folder)[1] mod = [ ] for f in files : ext = os.path.splitext(f)[-1] if ext in extensions: d = remove_extra_spaces(f) if d != 0 : mod.append(f) return mod
""" @file @brief Various function to clean the code. """ import os from ..sync.synchelper import explore_folder def remove_extra_spaces(filename): """ removes extra spaces in a filename, replace the file in place @param filename file name @return number of removed extra spaces """ try: with open(filename, "r") as f : lines = f.readlines() except PermissionError as e : raise PermissionError (filename) from e lines2 = [ _.rstrip(" \r\n") for _ in lines ] last = len(lines2)-1 while last >= 0 and len(lines2[last]) == 0 : last -= 1 last+=1 lines2 = lines2[:last] diff = len("".join(lines)) - len("\n".join(lines2)) if diff != 0: with open(filename,"w") as f : f.write("\n".join(lines2)) return diff def remove_extra_spaces_folder(folder, extensions = (".py",".rst")): """ removes extra files in a folder for specific file extensions @param folder folder to explore @param extensions list of file extensions to process @return the list of modified files """ files = explore_folder(folder)[1] mod = [ ] for f in files : ext = os.path.splitext(f)[-1] if ext in extensions: d = remove_extra_spaces(f) if d != 0 : mod.append(f) return mod
mit
Python
da7e82efccb8ace8d3473a553da896a51bdd3b24
Bump version to 0.2.6
amplify-education/python-hcl2
hcl2/version.py
hcl2/version.py
"""Place of record for the package version""" __version__ = "0.2.6" __git_hash__ = "GIT_HASH"
"""Place of record for the package version""" __version__ = "0.2.5" __git_hash__ = "GIT_HASH"
mit
Python
c8049c01d2900a2cb1662edec390d35fe6fc706c
Remove unneeded SourcecodeCompiler object
SOM-st/PySOM,SOM-st/PySOM,smarr/PySOM,smarr/PySOM
src/som/compiler/sourcecode_compiler.py
src/som/compiler/sourcecode_compiler.py
import os from rlib.streamio import open_file_as_stream from rlib.string_stream import StringStream from som.compiler.class_generation_context import ClassGenerationContext from som.interp_type import is_ast_interpreter if is_ast_interpreter(): from som.compiler.ast.parser import Parser else: from som.compiler.bc.parser import Parser def compile_class_from_file(path, filename, system_class, universe): fname = path + os.sep + filename + ".som" try: input_file = open_file_as_stream(fname, "r") try: parser = Parser(input_file, fname, universe) result = _compile(parser, system_class, universe) finally: input_file.close() except OSError: raise IOError() cname = result.get_name() cnameC = cname.get_embedded_string() if filename != cnameC: from som.vm.universe import error_println error_println("File name %s does not match class name %s." % (filename, cnameC)) universe.exit(1) return result def compile_class_from_string(stream, system_class, universe): parser = Parser(StringStream(stream), "$str", universe) result = _compile(parser, system_class, universe) return result def _compile(parser, system_class, universe): cgc = ClassGenerationContext(universe) result = system_class parser.classdef(cgc) if not system_class: result = cgc.assemble() else: cgc.assemble_system_class(result) return result
import os from rlib.streamio import open_file_as_stream from rlib.string_stream import StringStream from som.compiler.class_generation_context import ClassGenerationContext from som.interp_type import is_ast_interpreter if is_ast_interpreter(): from som.compiler.ast.parser import Parser else: from som.compiler.bc.parser import Parser def compile_class_from_file(path, filename, system_class, universe): return _SourcecodeCompiler().compile(path, filename, system_class, universe) def compile_class_from_string(stmt, system_class, universe): return _SourcecodeCompiler().compile_class_string(stmt, system_class, universe) class _SourcecodeCompiler(object): def __init__(self): self._parser = None def compile(self, path, filename, system_class, universe): fname = path + os.sep + filename + ".som" try: input_file = open_file_as_stream(fname, "r") try: self._parser = Parser(input_file, fname, universe) result = self._compile(system_class, universe) finally: input_file.close() except OSError: raise IOError() cname = result.get_name() cnameC = cname.get_embedded_string() if filename != cnameC: from som.vm.universe import error_println error_println("File name %s does not match class name %s." % (filename, cnameC)) universe.exit(1) return result def compile_class_string(self, stream, system_class, universe): self._parser = Parser(StringStream(stream), "$str", universe) result = self._compile(system_class, universe) return result def _compile(self, system_class, universe): cgc = ClassGenerationContext(universe) result = system_class self._parser.classdef(cgc) if not system_class: result = cgc.assemble() else: cgc.assemble_system_class(result) return result
mit
Python
1e4276ea4311284835803e081566fc9ffc57191a
add time in UTC to generated manifest
rs-makino/buildpack-test,createmultimedia/heroku-buildpack-php,dzuelke/heroku-buildpack-php,emeth-/heroku-buildpack-php,jayelkaake/heroku-buildpack-magento,flant/heroku-buildpack-php,dzuelke/heroku-buildpack-php,thecsea/heroku-buildpack-php-with-ioncube,createmultimedia/heroku-buildpack-php,rikur/heroku-buildpack-php,alzheic/heroku-buildpack-aop,alzheic/heroku-buildpack-aop,puteulanus/heroku-buildpack-php,flant/heroku-buildpack-php,jopereyral/heroku-buildpack-php,heroku/heroku-buildpack-php,rs-makino/buildpack-test,martijngastkemper/heroku-buildpack-php,rs-makino/buildpack-test,heroku/heroku-buildpack-php,rikur/heroku-buildpack-php,rs-makino/buildpack-test,a2service/heroku-buildpack-php,rs-makino/buildpack-test,martijngastkemper/heroku-buildpack-php,thecsea/heroku-buildpack-php-with-ioncube,0ppy/sample-buildpack,rikur/heroku-buildpack-php,0ppy/sample-buildpack,dzuelke/heroku-buildpack-php,puteulanus/heroku-buildpack-php,jopereyral/heroku-buildpack-php,rs-makino/buildpack-test,flant/heroku-buildpack-php,thecsea/heroku-buildpack-php-with-ioncube,jopereyral/heroku-buildpack-php,puteulanus/heroku-buildpack-php,heroku/heroku-buildpack-php,alzheic/heroku-buildpack-aop,emeth-/heroku-buildpack-php,rikur/heroku-buildpack-php,emeth-/heroku-buildpack-php,a2service/heroku-buildpack-php,a2service/heroku-buildpack-php,emeth-/heroku-buildpack-php,0ppy/sample-buildpack,jayelkaake/heroku-buildpack-magento,createmultimedia/heroku-buildpack-php,jayelkaake/heroku-buildpack-magento,heroku/heroku-buildpack-php
support/build/_util/include/manifest.py
support/build/_util/include/manifest.py
import os, sys, json, re, datetime require = { "heroku-sys/"+os.getenv("STACK"): "^1.0.0", "heroku/installer-plugin": "^1.0.0", } engine=re.match('heroku-sys-(\w+)-extension', sys.argv[1]) if engine: require["heroku-sys/"+engine.group(1)] = sys.argv.pop(5) manifest = { "type": sys.argv[1], "name": sys.argv[2], "version": sys.argv[3], "require": require, "conflict": dict(item.split(":") for item in sys.argv[5:]), "dist": { "type": "heroku-sys-tar", "url": "https://"+os.getenv("S3_BUCKET")+"."+os.getenv("S3_REGION", "s3")+".amazonaws.com/"+os.getenv("S3_PREFIX")+"/"+sys.argv[4] }, "time": datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") } if not sys.stdin.isatty(): manifest["replace"] = dict(item.rstrip("\n").split(" ") for item in tuple(sys.stdin)) json.dump(manifest, sys.stdout, sort_keys=True)
import os, sys, json, re require = { "heroku-sys/"+os.getenv("STACK"): "^1.0.0", "heroku/installer-plugin": "^1.0.0", } engine=re.match('heroku-sys-(\w+)-extension', sys.argv[1]) if engine: require["heroku-sys/"+engine.group(1)] = sys.argv.pop(5) manifest = { "type": sys.argv[1], "name": sys.argv[2], "version": sys.argv[3], "require": require, "conflict": dict(item.split(":") for item in sys.argv[5:]), "dist": { "type": "heroku-sys-tar", "url": "https://"+os.getenv("S3_BUCKET")+"."+os.getenv("S3_REGION", "s3")+".amazonaws.com/"+os.getenv("S3_PREFIX")+"/"+sys.argv[4] } } if not sys.stdin.isatty(): manifest["replace"] = dict(item.rstrip("\n").split(" ") for item in tuple(sys.stdin)) json.dump(manifest, sys.stdout, sort_keys=True)
mit
Python
63a26cbf76a3d0135f5b67dd10cc7f383ffa7ebf
Change authenticate_credentials method to raise an exception if the account is disabled
City-of-Helsinki/django-helusers,City-of-Helsinki/django-helusers
helusers/jwt.py
helusers/jwt.py
from django.conf import settings from rest_framework import exceptions from rest_framework_jwt.authentication import JSONWebTokenAuthentication from rest_framework_jwt.settings import api_settings from .user_utils import get_or_create_user def patch_jwt_settings(): """Patch rest_framework_jwt authentication settings from allauth""" defaults = api_settings.defaults defaults['JWT_PAYLOAD_GET_USER_ID_HANDLER'] = ( __name__ + '.get_user_id_from_payload_handler') if 'allauth.socialaccount' not in settings.INSTALLED_APPS: return from allauth.socialaccount.models import SocialApp try: app = SocialApp.objects.get(provider='helsinki') except SocialApp.DoesNotExist: return defaults['JWT_SECRET_KEY'] = app.secret defaults['JWT_AUDIENCE'] = app.client_id # Disable automatic settings patching for now because it breaks Travis. # patch_jwt_settings() class JWTAuthentication(JSONWebTokenAuthentication): def authenticate_credentials(self, payload): user = super().authenticate_credentials(payload) if user and not user.is_active: msg = _('User account is disabled.') raise exceptions.AuthenticationFailed(msg) return get_or_create_user(payload) def get_user_id_from_payload_handler(payload): return payload.get('sub')
from django.conf import settings from rest_framework_jwt.authentication import JSONWebTokenAuthentication from rest_framework_jwt.settings import api_settings from .user_utils import get_or_create_user def patch_jwt_settings(): """Patch rest_framework_jwt authentication settings from allauth""" defaults = api_settings.defaults defaults['JWT_PAYLOAD_GET_USER_ID_HANDLER'] = ( __name__ + '.get_user_id_from_payload_handler') if 'allauth.socialaccount' not in settings.INSTALLED_APPS: return from allauth.socialaccount.models import SocialApp try: app = SocialApp.objects.get(provider='helsinki') except SocialApp.DoesNotExist: return defaults['JWT_SECRET_KEY'] = app.secret defaults['JWT_AUDIENCE'] = app.client_id # Disable automatic settings patching for now because it breaks Travis. # patch_jwt_settings() class JWTAuthentication(JSONWebTokenAuthentication): def authenticate_credentials(self, payload): return get_or_create_user(payload) def get_user_id_from_payload_handler(payload): return payload.get('sub')
bsd-2-clause
Python
9ccd957dfde79db677c7ae19e0a271d69921f0b4
bump version
hopshadoop/hops-util-py,hopshadoop/hops-util-py
hops/version.py
hops/version.py
__version__ = '1.6.5'
__version__ = '1.6.4'
apache-2.0
Python
754e08288be17db63747592fd5ce1d70a6fb154e
bump version
hopshadoop/hops-util-py,hopshadoop/hops-util-py
hops/version.py
hops/version.py
__version__ = '2.7.7'
__version__ = '2.7.6'
apache-2.0
Python
ae21b9796abb1511d3af2cdd0c87f8d90386093c
Update inftp.py
ldmoray/dotfiles,ldmoray/dotfiles
bin/inftp.py
bin/inftp.py
__author__ = 'Lenny Morayniss' ''' This project is licensed under the terms of the MIT license. Copyright Lenny Morayniss 2015 ''' import argparse from ftplib import FTP_TLS import os import time def upload(ftp, filename): ext = os.path.splitext(filename)[1] if ext in (".txt", ".htm", ".html"): ftp.storlines("STOR " + filename, open(filename)) else: ftp.storbinary("STOR " + filename, open(filename, "rb"), 1024) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Copy files over ftp on loop') parser.add_argument('address', action='store') parser.add_argument('--user', action='store') parser.add_argument('--password', action='store') parser.add_argument('filename', action='store') args = parser.parse_args() ftps = FTP_TLS(args.address) while True: ftps.login(args.user, args.password) ftps.prot_p() upload(ftps, args.filename) ftps.prot_c() ftps.quit() time.sleep(300)
__author__ = 'Lenny Morayniss' ''' This project is licensed under the terms of the MIT license. Copyright Lenny Morayiss 2015 ''' import argparse from ftplib import FTP_TLS import os import time def upload(ftp, filename): ext = os.path.splitext(filename)[1] if ext in (".txt", ".htm", ".html"): ftp.storlines("STOR " + filename, open(filename)) else: ftp.storbinary("STOR " + filename, open(filename, "rb"), 1024) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Copy files over ftp on loop') parser.add_argument('address', action='store') parser.add_argument('--user', action='store') parser.add_argument('--password', action='store') parser.add_argument('filename', action='store') args = parser.parse_args() ftps = FTP_TLS(args.address) while True: ftps.login(args.user, args.password) ftps.prot_p() upload(ftps, args.filename) ftps.prot_c() ftps.quit() time.sleep(300)
mit
Python
764f8d9d7818076555cde5fcad29f3052b523771
Add more search fields to autocomplete
KlubJagiellonski/pola-backend,KlubJagiellonski/pola-backend,KlubJagiellonski/pola-backend,KlubJagiellonski/pola-backend
company/autocomplete_light_registry.py
company/autocomplete_light_registry.py
import autocomplete_light from .models import Company class CompanyAutocomplete(autocomplete_light.AutocompleteModelBase): search_fields = ['name', 'official_name', 'common_name'] model = Company autocomplete_light.register(CompanyAutocomplete)
import autocomplete_light from .models import Company class CompanyAutocomplete(autocomplete_light.AutocompleteModelBase): search_fields = ['^name'] model = Company autocomplete_light.register(CompanyAutocomplete)
bsd-3-clause
Python
e0b8866d3b1b6a9fc896d511227523391a1501f4
Update binstar-push.py
rmcgibbo/python-appveyor-conda-example,rmcgibbo/python-appveyor-conda-example
continuous-integration/binstar-push.py
continuous-integration/binstar-push.py
import os import glob import subprocess import traceback token = os.environ['BINSTAR_TOKEN'] cmd = ['binstar', '-t', token, 'upload', '--force'] cmd.extend(glob.glob('*.tar.bz2')) try: subprocess.check_call(cmd) except subprocess.CalledProcessError: traceback.print_exc()
import os import glob import subprocess import traceback token = os.environ['BINSTAR_TOKEN'] cmd = ['anaconda_server', '-t', token, 'upload', '--force'] cmd.extend(glob.glob('*.tar.bz2')) try: subprocess.check_call(cmd) except subprocess.CalledProcessError: traceback.print_exc()
cc0-1.0
Python
805e6be1687622cd70e6475708d0e5d8b53f8132
Update docs
eeue56/PyChat.js,eeue56/PyChat.js
pychatjs/server/user_server.py
pychatjs/server/user_server.py
class UsernameInUseException(Exception): pass class User(object): """ Class used to hold a user and the user server """ def __init__(self, server, name=None): if name is None: name = server.temp_name self.name = name self.server = server def __str__(self): return str(self.name) def _to_json(self): """ Gets a dict of this object's properties so that it can be used to send a dump to the client """ return self.__dict__ def release_name(self): """ release the username from the user server """ self.server.release_name(self.name) def change_name(self, username): """ changes the username to given username, throws exception if username used """ self.release_name() try: self.server.register_name(username) except UsernameInUseException: logging.log(', '.join(self.server.registered_names)) self.server.register_name(self.name) raise self.name = username class UserServer(object): """ User server used to manage names """ def __init__(self, names=None): if names is None: names = ['a', 'b', 'c', 'd', 'e'] self.temp_names = names self.registered_names = [] @property def temp_name(self): """ gets the top temp name """ return self.temp_names.pop(0) def is_username_used(self, username): """ checks if username is used """ return username in self.registered_names def register_name(self, username): """ register a name """ if self.is_username_used(username): raise UsernameInUseException('Username {username} already in use!'.format(username=username)) self.registered_names.append(username) def release_name(self, username): """ release a name and add it to the temp list """ self.temp_names.append(username) if self.is_username_used(username): self.registered_names.remove(username)
class UsernameInUseException(Exception): pass class User(object): def __init__(self, server, name=None): if name is None: name = server.temp_name self.name = name self.server = server def __str__(self): return str(self.name) def _to_json(self): return self.__dict__ def release_name(self): self.server.release_name(self.name) def change_name(self, username): self.release_name() try: self.server.register_name(username) except UsernameInUseException: logging.log(', '.join(self.server.registered_names)) self.server.register_name(self.name) raise self.name = username class UserServer(object): def __init__(self, names=None): if names is None: names = ['a', 'b', 'c', 'd', 'e'] self.temp_names = names self.registered_names = [] @property def temp_name(self): return self.temp_names.pop(0) def is_username_used(self, username): return username in self.registered_names def register_name(self, username): if self.is_username_used(username): raise UsernameInUseException('Username {username} already in use!'.format(username=username)) self.registered_names.append(username) def release_name(self, username): self.temp_names.append(username) if self.is_username_used(username): self.registered_names.remove(username)
bsd-3-clause
Python
0b1499e87e5a2bdaadc13811378e869e13c9c3db
Update chat.py
CodeGuild-co/wtc,CodeGuild-co/wtc,CodeGuild-co/wtc
blog/chat.py
blog/chat.py
# A simple chat server using websockets # Uses a slight modification to the protocol I'm using to write a different # application # Modifications: # No rooms # Uses Facebook to authenticate from flask import Flask, session, escape, request, redirect from flask_socketio import SocketIO, emit from blog.util import render_template, app from os import getenv from urllib.request import urlopen from json import loads as loadjson socketio = SocketIO(app) fb_appid = getenv('FB_APPID') fb_secret = getenv('FB_SECRET') @app.route('/chat') def chat(): #if 'accesskey' not in session: # if 'error_reason' in request.args: # return 'You must login via Facebook to use our chat!' # elif 'code' in request.args: # resp = '' # with urlopen('https://graph.facebook.com/v2.3/oauth/access_token?client_id=%s&redirect_uri=http://wtc.codeguild.co/chat&client_secret=%s&code=%s' % (fb_appid, fb_secret, request.args['code'])) as r: # resp = r.read() # j = loadjson(resp.decode("utf-8")) # if 'access_token' in j: # session['accesskey'] = j['access_token'] # return render_template('chat.html') # else: # return 'An error has occured, please try again later' # else: # return redirect('https://www.facebook.com/dialog/oauth?client_id=%s&redirect_uri=http://wtc.codeguild.co/chat&response_type=code' % fb_appid) return render_template('chat.html') @socketio.on('message') def handle_message(json): emit('message', { 'room': 'willcoates', 'msg': escape('%s: %s' % (session['displayname'], json['msg'])), 'role': 'message' }, broadcast=True, include_self=False) emit('message', { 'room': 'willcoates', 'msg': escape('%s' % json['msg']), 'role': 'mymessage' }) @socketio.on('connect') def connect(): #if 'accesskey' not in session: # return False #resp = '' #with urlopen('https://graph.facebook.com/v2.3/me?client_id=%s&client_secret=%s&accses_token=%s' % (fb_appid, fb_secret, session['accesskey'])) as r: # resp = r.read() #j = loadjson(resp.decode("utf-8")) session['displayname'] = 'TestUser' #j['name'] emit('message', { 'room': 'broadcast', 'msg': 'Welcome to Will Coates\' Chat', 'role': 'notice' }) emit('message', { 'room': 'willcoates', 'msg': escape('%s has joined the chat!' % session['displayname']), 'role': 'notice' }, broadcast=True) return True @socketio.on('disconnect') def disconnect(): emit('message', { 'room': 'willcoates', 'msg': escape('%s has left the chat!' % session['displayname']), 'role': 'notice' }, broadcast=True, include_self=False)
# A simple chat server using websockets # Uses a slight modification to the protocol I'm using to write a different # application # Modifications: # No rooms # Uses Facebook to authenticate from flask import Flask, session, escape, request, redirect from flask_socketio import SocketIO, emit from blog.util import render_template, app from os import getenv from urllib.request import urlopen from json import loads as loadjson socketio = SocketIO(app) fb_appid = getenv('FB_APPID') fb_secret = getenv('FB_SECRET') @app.route('/chat') def chat(): #if 'accesskey' not in session: # if 'error_reason' in request.args: # return 'You must login via Facebook to use our chat!' # elif 'code' in request.args: # resp = '' # with urlopen('https://graph.facebook.com/v2.3/oauth/access_token?client_id=%s&redirect_uri=http://wtc.codeguild.co/chat&client_secret=%s&code=%s' % (fb_appid, fb_secret, request.args['code'])) as r: # resp = r.read() # j = loadjson(resp.decode("utf-8")) # if 'access_token' in j: # session['accesskey'] = j['access_token'] # return render_template('chat.html') # else: # return 'An error has occured, please try again later' # else: # return redirect('https://www.facebook.com/dialog/oauth?client_id=%s&redirect_uri=http://wtc.codeguild.co/chat&response_type=code' % fb_appid) return render_template('chat.html') @socketio.on('message') def handle_message(json): emit('message', { 'room': 'willcoates', 'msg': escape('%s: %s' % (session['displayname'], json['msg'])), 'role': 'message' }, broadcast=True, include_self=False) emit('message', { 'room': 'willcoates', 'msg': escape('%s' % json['msg']), 'role': 'mymessage' }) @socketio.on('connect') def connect(): #if 'accesskey' not in session: # return False #resp = '' #with urlopen('https://graph.facebook.com/v2.3/me?client_id=%s&client_secret=%s&accses_token=%s' % (fb_appid, fb_secret, session['accesskey'])) as r: # resp = r.read() #j = loadjson(resp.decode("utf-8")) session['displayname'] = 'TestUser' #j['name'] emit('message', { 'room': 'broadcast', 'msg': 'Welcome to Will Coates\' Chat', 'role': 'notice' }) emit('message', { 'room': 'willcoates', 'msg': escape('%s has joined the chat!' % session['displayname']), 'role': 'notice' }, broadcast=True, include_self=False) return True @socketio.on('disconnect') def disconnect(): emit('message', { 'room': 'willcoates', 'msg': escape('%s has left the chat!' % session['displayname']), 'role': 'notice' }, broadcast=True, include_self=False)
mit
Python
a06010fcb2f4424d085da1487a6666867a8cbf5b
Remove add_view and add form for the hole admin
globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service
dbaas/maintenance/admin/maintenance.py
dbaas/maintenance/admin/maintenance.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django_services import admin from ..models import Maintenance from ..service.maintenance import MaintenanceService from ..forms import MaintenanceForm class MaintenanceAdmin(admin.DjangoServicesAdmin): service_class = MaintenanceService search_fields = ("scheduled_for", "description", "maximum_workers", 'status') list_display = ("scheduled_for", "description", "maximum_workers", 'status') fields = ( "description", "scheduled_for", "main_script", "rollback_script", "host_query","maximum_workers", "status", "celery_task_id",) save_on_top = True readonly_fields = ('status', 'celery_task_id') form = MaintenanceForm def change_view(self, request, object_id, form_url='', extra_context=None): maintenance = Maintenance.objects.get(id=object_id) if maintenance.celery_task_id: self.readonly_fields = self.fields return super(MaintenanceAdmin, self).change_view(request, object_id, form_url, extra_context=extra_context)
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django_services import admin from ..models import Maintenance from ..service.maintenance import MaintenanceService class MaintenanceAdmin(admin.DjangoServicesAdmin): service_class = MaintenanceService search_fields = ("scheduled_for", "description", "maximum_workers", 'status') list_display = ("scheduled_for", "description", "maximum_workers", 'status') fields = ( "description", "scheduled_for", "main_script", "rollback_script", "host_query","maximum_workers", "status", "celery_task_id",) save_on_top = True readonly_fields = ('status', 'celery_task_id') def change_view(self, request, object_id, form_url='', extra_context=None): maintenance = Maintenance.objects.get(id=object_id) if maintenance.celery_task_id: self.readonly_fields = self.fields return super(MaintenanceAdmin, self).change_view(request, object_id, form_url, extra_context=extra_context) def add_view(self, request, form_url='', extra_context=None): return super(MaintenanceAdmin, self).add_view(request, form_url, extra_context)
bsd-3-clause
Python
67643dd792967523fa7c12fb380274237e30c34d
Update trainLSTM-noATTN.py
svobodam/Deep-Learning-Text-Summariser,svobodam/Deep-Learning-Text-Summariser,svobodam/Deep-Learning-Text-Summariser
runScripts/trainLSTM-noATTN.py
runScripts/trainLSTM-noATTN.py
# Original script developed by Harshal Priyadarshi https://github.com/harpribot # Edited for purpose of this project. # Script to initiate training process of the LSTM network with attention disabled. # Import required libraries; Point system directory back to parent folder to allow import files below: import os import sys sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..')) from Models import lstmSimple from PreProcessingScript import checkpoint print("LSTM Network training process initiated with attention disabled...") # Get the review summary file try: docSum_file = 'Data/rewsum.csv' print("Source data loaded.") except NameError: raise ValueError("No source data found. Please check if 'Data/rewsum.csv' exists!") # Initialise Checkpointer to ensure checkpointing, No. of steps per checkpoint: 100 checkpointSys = checkpoint.checkpointSys('simple', 'lstm', 'noAttention') checkpointSys.steps_per_checkpoint(100) checkpointSys.steps_per_prediction(100) # Do using LSTM cell - with attention mechanism disabled out_file = 'Results/Simple-LSTM/NoAttention/no-attention.csv' checkpointSys.set_result_location(out_file) lstm_net = lstmSimple.LstmSimple(docSum_file, checkpointSys, attention=False) #Set the parameters for the model and training. #parameter train_batch_size: The batch size of examples used for batch training #parameter test_batch_size: The batch size of test examples used for testing #parameter memory_dim: The length of the hidden vector produced by the encoder #parameter learning_rate: The learning rate for Stochastic Gradient Descent lstm_net.set_parameters(train_batch_size=128, test_batch_size=128, memory_dim=128, learning_rate=0.05) lstm_net.begin_session() lstm_net.form_model_graph() lstm_net.fit() lstm_net.predict() lstm_net.store_test_predictions()
# Original script developed by Harshal Priyadarshi https://github.com/harpribot # Edited for purpose of this project. # Script to initiate training process of the LSTM network with attention disabled. # Import required libraries; Point system directory back to parent folder to allow import files below: import os import sys sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..')) from Models import lstmSimple from PreProcessingScript import checkpoint print("LSTM Network training process initiated with attention disabled...") # Get the review summary file try: docSum_file = 'Data/rewsum.csv' print("Source data loaded.") except NameError: raise ValueError("No source data found. Please check if 'Data/rewsum.csv' exists!") # Initialise Checkpointer to ensure checkpointing, No. of steps per checkpoint: 100 checkpointSys = checkpoint.checkpointSys('simple', 'lstm', 'noAttention') checkpointSys.steps_per_checkpoint(100) checkpointSys.steps_per_prediction(100) # Do using LSTM cell - with attention mechanism disabled out_file = 'Results/Simple-LSTM/NoAttention/no-attention.csv' checkpointSys.set_result_location(out_file) lstm_net = lstmSimple.LstmSimple(docSum_file, checkpointSys, attention=True) #Set the parameters for the model and training. #parameter train_batch_size: The batch size of examples used for batch training #parameter test_batch_size: The batch size of test examples used for testing #parameter memory_dim: The length of the hidden vector produced by the encoder #parameter learning_rate: The learning rate for Stochastic Gradient Descent lstm_net.set_parameters(train_batch_size=128, test_batch_size=128, memory_dim=128, learning_rate=0.05) lstm_net.begin_session() lstm_net.form_model_graph() lstm_net.fit() lstm_net.predict() lstm_net.store_test_predictions()
mit
Python
81b4344d3f1882ff65308273b87395cae2d6cc6c
Disable OpenBSD service module on 5.0, it won't work reliably there.
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
salt/modules/openbsdservice.py
salt/modules/openbsdservice.py
''' The service module for OpenBSD ''' import os # XXX enable/disable support would be nice def __virtual__(): ''' Only work on OpenBSD ''' if __grains__['os'] == 'OpenBSD' and os.path.exists('/etc/rc.d/rc.subr'): v = map(int, __grains__['kernelrelease'].split('.')) # The -f flag, used to force a script to run even if disabled, # was added after the 5.0 release. if v[0] > 5 or (v[0] == 5 and v[1] > 0): return 'service' return False def start(name): ''' Start the specified service CLI Example:: salt '*' service.start <service name> ''' cmd = '/etc/rc.d/{0} -f start'.format(name) return not __salt__['cmd.retcode'](cmd) def stop(name): ''' Stop the specified service CLI Example:: salt '*' service.stop <service name> ''' cmd = '/etc/rc.d/{0} -f stop'.format(name) return not __salt__['cmd.retcode'](cmd) def restart(name): ''' Restart the named service CLI Example:: salt '*' service.restart <service name> ''' cmd = '/etc/rc.d/{0} -f restart'.format(name) return not __salt__['cmd.retcode'](cmd) def status(name): ''' Return the status for a service, returns a bool whether the service is running. CLI Example:: salt '*' service.status <service name> ''' cmd = '/etc/rc.d/{0} -f check'.format(name) return not __salt__['cmd.retcode'](cmd)
''' The service module for OpenBSD ''' import os # XXX enable/disable support would be nice def __virtual__(): ''' Only work on OpenBSD ''' if __grains__['os'] == 'OpenBSD' and os.path.exists('/etc/rc.d/rc.subr'): return 'service' return False def start(name): ''' Start the specified service CLI Example:: salt '*' service.start <service name> ''' cmd = '/etc/rc.d/{0} -f start'.format(name) return not __salt__['cmd.retcode'](cmd) def stop(name): ''' Stop the specified service CLI Example:: salt '*' service.stop <service name> ''' cmd = '/etc/rc.d/{0} -f stop'.format(name) return not __salt__['cmd.retcode'](cmd) def restart(name): ''' Restart the named service CLI Example:: salt '*' service.restart <service name> ''' cmd = '/etc/rc.d/{0} -f restart'.format(name) return not __salt__['cmd.retcode'](cmd) def status(name): ''' Return the status for a service, returns a bool whether the service is running. CLI Example:: salt '*' service.status <service name> ''' cmd = '/etc/rc.d/{0} -f check'.format(name) return not __salt__['cmd.retcode'](cmd)
apache-2.0
Python
6f822cf46957d038588e7a71eb91f8ca9f9c95f1
Use get_minion_path to get default dir.
goliatone/minions
scaffolder/commands/install.py
scaffolder/commands/install.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from optparse import make_option from optparse import OptionParser from scaffolder import get_minion_path from scaffolder.core.template import TemplateManager from scaffolder.core.commands import BaseCommand class InstallCommand(BaseCommand): option_list = BaseCommand.option_list + ( make_option( "-t", "--target", dest="target_dir", default=get_minion_path('weaver'), help='Project Templates directory.', metavar="TEMPLATES_DIR" ), ) def __init__(self, name, help='', aliases=(), stdout=None, stderr=None): help = 'install: Installs a Project Template.' parser = OptionParser( version=self.get_version(), option_list=self.get_option_list(), usage='\n %prog {0} ACTION [OPTIONS]'.format(name) ) aliases = ('tmp',) BaseCommand.__init__(self, name, parser=parser, help=help, aliases=aliases) def run(self, *args, **options): src = args[0] tgt = options.get('target_dir') manager = TemplateManager() manager.install(src=src, dest=tgt)
#!/usr/bin/env python # -*- coding: utf-8 -*- from optparse import make_option from optparse import OptionParser from scaffolder.core.template import TemplateManager from scaffolder.core.commands import BaseCommand class InstallCommand(BaseCommand): option_list = BaseCommand.option_list + ( make_option( "-t", "--target", dest="target_dir", default='~/.cookiejar', help='Project Templates directory.', metavar="TEMPLATES_DIR" ), ) def __init__(self, name, help='', aliases=(), stdout=None, stderr=None): help = 'install: Installs a Project Template.' parser = OptionParser( version=self.get_version(), option_list=self.get_option_list(), usage='\n %prog {0} ACTION [OPTIONS]'.format(name) ) aliases = ('tmp',) BaseCommand.__init__(self, name, parser=parser, help=help, aliases=aliases) def run(self, *args, **options): src = args[0] tgt = options.get('target_dir') manager = TemplateManager() manager.install(src=src, dest=tgt)
mit
Python
c0682d5d53d3f136485f952dfa82e0dc44df89ae
change release_url
cf-platform-eng/bosh-azure-template,cf-platform-eng/bosh-azure-template
bootstrap.py
bootstrap.py
#!/usr/bin/env python import urllib2 import json import apt import tarfile import sys from distutils import dir_util from os import chdir from os import symlink from subprocess import call # install packages package_list = [ "python-pip", "build-essential", "tmux", "ruby2.0", "ruby2.0-dev", "libxml2-dev", "libsqlite3-dev", "libxslt1-dev", "libpq-dev", "libmysqlclient-dev", "zlibc", "zlib1g-dev", "openssl", "libxslt1-dev", "libssl-dev", "libreadline6", "libreadline6-dev", "libyaml-dev", "sqlite3", "libffi-dev"] print "Updating apt cache" cache = apt.cache.Cache() cache.update(raise_on_error=False) cache.open(None) for package in package_list: pkg = cache[package] if not pkg.is_installed: pkg.mark_install(auto_inst=True) try: cache.commit() except Exception as arg: print >> sys.stderr, "Sorry, package installation failed [{err}]".format( err=str(arg)) import pip pip_packages = ['jinja2', 'azure', 'azure-mgmt', 'click'] for package in pip_packages: pip.main(['install', package]) release_url = 'https://s3-us-west-2.amazonaws.com/bosh-azure-releases/latest.tgz' res = urllib2.urlopen(release_url) code = res.getcode() length = int(res.headers["Content-Length"]) # content-length if code is 200: CHUNK = 16 * 1024 filename = '/tmp/archive.tgz' with open(filename, 'wb') as temp: while True: chunk = res.read(CHUNK) if not chunk: break temp.write(chunk) print "Download complete." tfile = tarfile.open(filename, 'r:gz') tfile.extractall(".") dir_util.copy_tree(".", "../..") symlink('/usr/local/lib/python2.7/dist-packages/azure/mgmt', '../../azure/mgmt') chdir("../..") index_file = "index-{0}.yml".format(sys.argv[1].lower()) gamma_cmd = "./gamma.py --index {0}".format(index_file) # start tmux, running deploy_bosh_and_releases call("tmux new -d -s shared '{0}'".format(gamma_cmd), shell=True) call("./gotty -c gamma:{0} -t --tls-crt '.gotty.crt' --tls-key '.gotty.key' -p '443' tmux attach -d -t shared &".format(sys.argv[2]), shell=True)
#!/usr/bin/env python import urllib2 import json import apt import tarfile import sys from distutils import dir_util from os import chdir from os import symlink from subprocess import call # install packages package_list = [ "python-pip", "build-essential", "tmux", "ruby2.0", "ruby2.0-dev", "libxml2-dev", "libsqlite3-dev", "libxslt1-dev", "libpq-dev", "libmysqlclient-dev", "zlibc", "zlib1g-dev", "openssl", "libxslt1-dev", "libssl-dev", "libreadline6", "libreadline6-dev", "libyaml-dev", "sqlite3", "libffi-dev"] print "Updating apt cache" cache = apt.cache.Cache() cache.update(raise_on_error=False) cache.open(None) for package in package_list: pkg = cache[package] if not pkg.is_installed: pkg.mark_install(auto_inst=True) try: cache.commit() except Exception as arg: print >> sys.stderr, "Sorry, package installation failed [{err}]".format( err=str(arg)) import pip pip_packages = ['jinja2', 'azure', 'azure-mgmt', 'click'] for package in pip_packages: pip.main(['install', package]) gh_url = 'https://s3-us-west-2.amazonaws.com/bosh-azure-releases/latest.tgz' req = urllib2.Request(gh_url) headers = req.headers = { 'Content-Type': 'application/json' } # upload the release asset handler = urllib2.urlopen(req) release = json.loads(handler.read()) release_url = release['assets'][0]['browser_download_url'] res = urllib2.urlopen(release_url) code = res.getcode() length = int(res.headers["Content-Length"]) # content-length if code is 200: CHUNK = 16 * 1024 filename = '/tmp/archive.tgz' with open(filename, 'wb') as temp: while True: chunk = res.read(CHUNK) if not chunk: break temp.write(chunk) print "Download complete." tfile = tarfile.open(filename, 'r:gz') tfile.extractall(".") dir_util.copy_tree(".", "../..") symlink('/usr/local/lib/python2.7/dist-packages/azure/mgmt', '../../azure/mgmt') chdir("../..") index_file = "index-{0}.yml".format(sys.argv[1].lower()) gamma_cmd = "./gamma.py --index {0}".format(index_file) # start tmux, running deploy_bosh_and_releases call("tmux new -d -s shared '{0}'".format(gamma_cmd), shell=True) call("./gotty -c gamma:{0} -t --tls-crt '.gotty.crt' --tls-key '.gotty.key' -p '443' tmux attach -d -t shared &".format(sys.argv[2]), shell=True)
apache-2.0
Python
6a111c64c50ffe6daa387034ef8fc3ad3e90fc75
Move import to the top of the page.
genenetwork/genenetwork2,DannyArends/genenetwork2,pjotrp/genenetwork2,zsloan/genenetwork2,pjotrp/genenetwork2,DannyArends/genenetwork2,pjotrp/genenetwork2,DannyArends/genenetwork2,DannyArends/genenetwork2,DannyArends/genenetwork2,pjotrp/genenetwork2,pjotrp/genenetwork2,DannyArends/genenetwork2,zsloan/genenetwork2,zsloan/genenetwork2,genenetwork/genenetwork2,genenetwork/genenetwork2,zsloan/genenetwork2,genenetwork/genenetwork2
test/requests/main_web_functionality.py
test/requests/main_web_functionality.py
from __future__ import print_function import re import requests from lxml.html import parse from link_checker import check_page from requests.exceptions import ConnectionError def check_home(url): doc = parse(url).getroot() search_button = doc.cssselect("#btsearch") assert(search_button[0].value == "Search") print("OK") def check_search_page(host): data = dict( species="mouse" , group="BXD" , type="Hippocampus mRNA" , dataset="HC_M2_0606_P" , search_terms_or="" , search_terms_and="MEAN=(15 16) LRS=(23 46)") result = requests.get(host+"/search", params=data) found = result.text.find("/show_trait?trait_id=1435395_s_at&dataset=HC_M2_0606_P") assert(found >= 0) print("OK") check_traits_page(host, "/show_trait?trait_id=1435395_s_at&dataset=HC_M2_0606_P") def check_traits_page(host, traits_url): doc = parse(host+traits_url).getroot() traits_form = doc.forms[1] assert(traits_form.fields["corr_dataset"] == "HC_M2_0606_P") print("OK") check_page(host, host+traits_url) def check_main_web_functionality(args_obj, parser): print("") print("Checking main web functionality...") host = args_obj.host check_home(host) check_search_page(host)
from __future__ import print_function import re import requests from lxml.html import parse from requests.exceptions import ConnectionError def check_home(url): doc = parse(url).getroot() search_button = doc.cssselect("#btsearch") assert(search_button[0].value == "Search") print("OK") def check_search_page(host): data = dict( species="mouse" , group="BXD" , type="Hippocampus mRNA" , dataset="HC_M2_0606_P" , search_terms_or="" , search_terms_and="MEAN=(15 16) LRS=(23 46)") result = requests.get(host+"/search", params=data) found = result.text.find("/show_trait?trait_id=1435395_s_at&dataset=HC_M2_0606_P") assert(found >= 0) print("OK") check_traits_page(host, "/show_trait?trait_id=1435395_s_at&dataset=HC_M2_0606_P") def check_traits_page(host, traits_url): from link_checker import check_page doc = parse(host+traits_url).getroot() traits_form = doc.forms[1] assert(traits_form.fields["corr_dataset"] == "HC_M2_0606_P") print("OK") check_page(host, host+traits_url) def check_main_web_functionality(args_obj, parser): print("") print("Checking main web functionality...") host = args_obj.host check_home(host) check_search_page(host)
agpl-3.0
Python
ae47decb69b71f227ccb6caa0047c7a471161bc4
Allow running jacquard/cli.py directly
prophile/jacquard,prophile/jacquard
jacquard/cli.py
jacquard/cli.py
import sys import pathlib import argparse import configparser import pkg_resources from jacquard.storage import open_engine from jacquard.users import get_settings def argument_parser(): parser = argparse.ArgumentParser(description="Split testing server") parser.add_argument( '-v', '--verbose', help="enable verbose output", action='store_true', ) parser.add_argument( '-c', '--config', help="config file", type=pathlib.Path, default=pathlib.Path('config.cfg'), ) parser.set_defaults(func=None) subparsers = parser.add_subparsers(metavar='subcommand') for entry_point in pkg_resources.iter_entry_points('jacquard.commands'): command = entry_point.load()() command_help = getattr(entry_point, 'help', entry_point.name) subparser = subparsers.add_parser( entry_point.name, help=command_help, description=command_help, ) subparser.set_defaults(func=command.handle) command.add_arguments(subparser) return parser def load_config(config_file): parser = configparser.ConfigParser() with config_file.open('r') as f: parser.read_file(f) # Get storage engine engine = open_engine( engine=parser.get('storage', 'engine'), url=parser.get('storage', 'url'), ) return { 'storage': engine, } def main(args=sys.argv[1:]): parser = argument_parser() options = parser.parse_args(args) if options.func is None: parser.print_usage() return # Parse options config = load_config(options.config) # Run subcommand options.func(config, options) if '__name__' == '__main__': main()
import sys import pathlib import argparse import configparser import pkg_resources from jacquard.storage import open_engine from jacquard.users import get_settings def argument_parser(): parser = argparse.ArgumentParser(description="Split testing server") parser.add_argument( '-v', '--verbose', help="enable verbose output", action='store_true', ) parser.add_argument( '-c', '--config', help="config file", type=pathlib.Path, default=pathlib.Path('config.cfg'), ) parser.set_defaults(func=None) subparsers = parser.add_subparsers(metavar='subcommand') for entry_point in pkg_resources.iter_entry_points('jacquard.commands'): command = entry_point.load()() command_help = getattr(entry_point, 'help', entry_point.name) subparser = subparsers.add_parser( entry_point.name, help=command_help, description=command_help, ) subparser.set_defaults(func=command.handle) command.add_arguments(subparser) return parser def load_config(config_file): parser = configparser.ConfigParser() with config_file.open('r') as f: parser.read_file(f) # Get storage engine engine = open_engine( engine=parser.get('storage', 'engine'), url=parser.get('storage', 'url'), ) return { 'storage': engine, } def main(args=sys.argv[1:]): parser = argument_parser() options = parser.parse_args(args) if options.func is None: parser.print_usage() return # Parse options config = load_config(options.config) # Run subcommand options.func(config, options)
mit
Python
6bf998fa9ae7f0edaddfbeca1ef7e5f9e764ee66
print bug
snurkabill/pydeeplearn,Warvito/pydeeplearn,Warvito/pydeeplearn,mihaelacr/pydeeplearn,snurkabill/pydeeplearn
code/test.py
code/test.py
# this file is made to see how theano works and the speedup # it gives you on GPU versus a normal implementation on CPU (ran on my computer) import theano import theano.tensor as T from theano import function, shared import numpy as np import time x = T.matrix('x', dtype=theano.config.floatX) y = T.matrix('y', dtype=theano.config.floatX) sc = shared(np.zeros((10, 10), dtype = theano.config.floatX), name='sc') mydot = function( [x,y], updates=( (sc, T.dot(x,y)), )) # We need to declare the variables shared to run on GPU a = np.ones((10000, 10000), dtype = theano.config.floatX) * 40.0 b = np.ones((10000, 10000), dtype = theano.config.floatX) * 23.0 print "go" before = time.time() mydot(a,b) print sc.get_value().sum() print time.time() - before
# this file is made to see how theano works and the speedup # it gives you on GPU versus a normal implementation on CPU (ran on my computer) import theano import theano.tensor as T from theano import function, shared import numpy as np import time x = T.matrix('x', dtype=theano.config.floatX) y = T.matrix('y', dtype=theano.config.floatX) sc = shared(np.zeros((10, 10), dtype = theano.config.floatX), name='sc') mydot = function( [x,y], updates=( (sc, T.dot(x,y)), )) # We need to declare the variables shared to run on GPU a = np.ones((10000, 10000), dtype = theano.config.floatX) * 40.0 b = np.ones((10000, 10000), dtype = theano.config.floatX) * 23.0 print "go" mydot(a,b) print sc.get_value().sum() before = time.time() print time.time() - before
bsd-3-clause
Python
9853ae44908156e29115f5c9859bbd2c7a756bd9
fix typo in init
griffy/sikwidgets,griffy/sikwidgets
sikwidgets/widgets/__init__.py
sikwidgets/widgets/__init__.py
instantiable_widget_class_names = [ "Button", "CheckBox", "Image", "Label", "List", "MenuButton", "RadioButton", "Tab", "Table", "TextField", "Tooltip", "Tree" ] from widget import Widget from page import Page from button import Button from check_box import CheckBox from image import Image from label import Label from list import List, ListRow from menu import Menu, MenuButton from radio_button import RadioButton from scrollable_widget import ScrollableWidget from tab import Tab from table import Table, TableColumn, TableRow, TableCell from text_field import TextField from tooltip import Tooltip from tree import Tree
instantiable_widget_class_names = [ "Button", "Checkbox", "Image", "Label", "List", "MenuButton", "RadioButton", "Tab", "Table", "TextField", "Tooltip", "Tree" ] from widget import Widget from page import Page from button import Button from checkbox import Checkbox from image import Image from label import Label from list import List, ListRow from menu import Menu, MenuButton from radio_button import RadioButton from scrollable_widget import ScrollableWidget from tab import Tab from table import Table, TableColumn, TableRow, TableCell from text_field import TextField from tooltip import Tooltip from tree import Tree
mit
Python
5e42bde844eb6c7260a4415e512646d061137640
bump version
mikepatrick/robotframework-requests,bulkan/robotframework-requests,bulkan/robotframework-requests,oleduc/robotframework-requests
src/RequestsLibrary/version.py
src/RequestsLibrary/version.py
VERSION = '0.4.5'
VERSION = '0.4.4'
mit
Python
95d9bb3a9500d80b5064c5fb4d5bd7b30406d1ae
Fix update remote to ConanCenter and grpc to highest buildable/supported version
jinq0123/grpc_cb_core,jinq0123/grpc_cb_core,jinq0123/grpc_cb_core
conanfile.py
conanfile.py
from conans import ConanFile, CMake class GrpccbConan(ConanFile): name = "grpc_cb_core" version = "0.2" license = "Apache-2.0" url = "https://github.com/jinq0123/grpc_cb_core" description = "C++ gRPC core library with callback interface." settings = "os", "compiler", "build_type", "arch" options = {"shared": [True, False]} default_options = "shared=False" requires = "grpc/1.44.0@", generators = "cmake", "premake" # The builtin premake generator exports_sources = "src*", "include*", "CMakeLists.txt" def build(self): cmake = CMake(self) self.run('cmake %s %s' % (self.source_folder, cmake.command_line)) self.run("cmake --build . %s" % cmake.build_config) def package(self): self.copy("include/*") self.copy("*.lib", dst="lib", keep_path=False) self.copy("*.dll", dst="bin", keep_path=False) self.copy("*.dylib*", dst="lib", keep_path=False) self.copy("*.so", dst="lib", keep_path=False) self.copy("*.a", dst="lib", keep_path=False) def package_info(self): self.cpp_info.libs = ["grpc_cb_core"]
from conans import ConanFile, CMake class GrpccbConan(ConanFile): name = "grpc_cb_core" version = "0.2" license = "Apache-2.0" url = "https://github.com/jinq0123/grpc_cb_core" description = "C++ gRPC core library with callback interface." settings = "os", "compiler", "build_type", "arch" options = {"shared": [True, False]} default_options = "shared=False" requires = "grpc/1.17.2@inexorgame/stable", generators = "cmake", "Premake" # A custom generator: PremakeGen/0.1@memsharded/testing build_requires = "PremakeGen/0.1@memsharded/testing" exports_sources = "src*", "include*", "CMakeLists.txt" def build(self): cmake = CMake(self) self.run('cmake %s %s' % (self.source_folder, cmake.command_line)) self.run("cmake --build . %s" % cmake.build_config) def package(self): self.copy("include/*") self.copy("*.lib", dst="lib", keep_path=False) self.copy("*.dll", dst="bin", keep_path=False) self.copy("*.dylib*", dst="lib", keep_path=False) self.copy("*.so", dst="lib", keep_path=False) self.copy("*.a", dst="lib", keep_path=False) def package_info(self): self.cpp_info.libs = ["grpc_cb_core"]
apache-2.0
Python
c13a12e6355423d6756b8b514942596c31b0e3a9
Make cmake-unit, cmake-linter-cmake and style-linter-cmake normal deps
polysquare/cmake-module-common
conanfile.py
conanfile.py
from conans import ConanFile from conans.tools import download, unzip import os VERSION = "0.0.7" class CMakeModuleCommonConan(ConanFile): name = "cmake-module-common" version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION) generators = "cmake" url = "http://github.com/polysquare/cmake-module-common" license = "MIT" requires = ("cmake-unit/master@smspillaz/cmake-unit", "cmake-linter-cmake/master@smspillaz/cmake-linter-cmake", "style-linter-cmake/master@smspillaz/style-linter-cmake") def source(self): zip_name = "cmake-module-common.zip" download("https://github.com/polysquare/" "cmake-module-common/archive/{version}.zip" "".format(version="v" + VERSION), zip_name) unzip(zip_name) os.unlink(zip_name) def package(self): self.copy(pattern="Find*.cmake", dst="", src="cmake-module-common-" + VERSION, keep_path=True) self.copy(pattern="*.cmake", dst="cmake/cmake-module-common", src="cmake-module-common-" + VERSION, keep_path=True)
from conans import ConanFile from conans.tools import download, unzip import os VERSION = "0.0.7" class CMakeModuleCommonConan(ConanFile): name = "cmake-module-common" version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION) generators = "cmake" url = "http://github.com/polysquare/cmake-module-common" license = "MIT" def source(self): zip_name = "cmake-module-common.zip" download("https://github.com/polysquare/" "cmake-module-common/archive/{version}.zip" "".format(version="v" + VERSION), zip_name) unzip(zip_name) os.unlink(zip_name) def package(self): self.copy(pattern="Find*.cmake", dst="", src="cmake-module-common-" + VERSION, keep_path=True) self.copy(pattern="*.cmake", dst="cmake/cmake-module-common", src="cmake-module-common-" + VERSION, keep_path=True)
mit
Python
f39fc5c07421ddf27b3b921806fafcdb2c2ee3ed
Use WCSSUB_CELESTIAL
Alex-Ian-Hamilton/sunpy,dpshelio/sunpy,Alex-Ian-Hamilton/sunpy,dpshelio/sunpy,dpshelio/sunpy,Alex-Ian-Hamilton/sunpy
sunpy/coordinates/wcs_utils.py
sunpy/coordinates/wcs_utils.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, division import astropy.wcs.utils from astropy.wcs import WCSSUB_CELESTIAL from .frames import * __all__ = ['solar_wcs_frame_mapping'] def solar_wcs_frame_mapping(wcs): """ This function registers the coordinates frames to their FITS-WCS coordinate type values in the `astropy.wcs.utils.wcs_to_celestial_frame` registry. """ # SunPy Map adds some extra attributes to the WCS object. # We check for them here, and default to None. dateobs = wcs.wcs.dateobs if wcs.wcs.dateobs else None hglon = None hglat = None dsun = None if hasattr(wcs, 'heliographic_longitude'): hglon = wcs.heliographic_longitude if hasattr(wcs, 'heliographic_latitude'): hglat = wcs.heliographic_latitude if hasattr(wcs, 'dsun'): dsun = wcs.dsun # First we try the Celestial sub, which rectifies the order. # It will return any thing matching ??LN*, ??LT* wcss = wcs.sub([WCSSUB_CELESTIAL]) xcoord = wcss.wcs.ctype[0][0:4] ycoord = wcss.wcs.ctype[1][0:4] if xcoord == 'HPLN' and ycoord == 'HPLT': return Helioprojective(dateobs=dateobs, L0=hglon, B0=hglat, D0=dsun) if xcoord == 'HGLN' and ycoord == 'HGLT': return HeliographicStonyhurst(dateobs=dateobs) if xcoord == 'CRLN' and ycoord == 'CRLT': return HeliographicCarrington(dateobs=dateobs) # Now we try for heliocentric without the sub. xcoord = wcs.wcs.ctype[0][0:4] ycoord = wcs.wcs.ctype[1][0:4] if xcoord == 'SOLX' and ycoord == 'SOLY': return Heliocentric(dateobs=dateobs, L0=hglon, B0=hglat, D0=dsun) astropy.wcs.utils.WCS_FRAME_MAPPINGS.append([solar_wcs_frame_mapping]) # The following is a patch for wcsaxes 0.6 and lower: try: import wcsaxes.wcs_utils if hasattr(wcsaxes.wcs_utils, 'WCS_FRAME_MAPPINGS'): wcsaxes.wcs_utils.WCS_FRAME_MAPPINGS.append([solar_wcs_frame_mapping]) except ImportError: pass
# -*- coding: utf-8 -*- from __future__ import absolute_import, division import astropy.wcs.utils from .frames import * __all__ = ['solar_wcs_frame_mapping'] def solar_wcs_frame_mapping(wcs): """ This function registers the coordinates frames to their FITS-WCS coordinate type values in the `astropy.wcs.utils.wcs_to_celestial_frame` registry. """ xcoord = wcs.wcs.ctype[0][0:4] ycoord = wcs.wcs.ctype[1][0:4] dateobs = wcs.wcs.dateobs if wcs.wcs.dateobs else None hglon = None hglat = None dsun = None if hasattr(wcs, 'heliographic_longitude'): hglon = wcs.heliographic_longitude if hasattr(wcs, 'heliographic_latitude'): hglat = wcs.heliographic_latitude if hasattr(wcs, 'dsun'): dsun = wcs.dsun if xcoord == 'HPLN' and ycoord == 'HPLT': return Helioprojective(dateobs=dateobs, L0=hglon, B0=hglat, D0=dsun) if xcoord == 'HGLN' and ycoord == 'HGLT': return HeliographicStonyhurst(dateobs=dateobs) if xcoord == 'CRLN' and ycoord == 'CRLT': return HeliographicCarrington(dateobs=dateobs) if xcoord == 'SOLX' and ycoord == 'SOLY': return Heliocentric(dateobs=dateobs, L0=hglon, B0=hglat, D0=dsun) astropy.wcs.utils.WCS_FRAME_MAPPINGS.append([solar_wcs_frame_mapping]) # The following is a patch for wcsaxes 0.6 and lower: try: import wcsaxes.wcs_utils if hasattr(wcsaxes.wcs_utils, 'WCS_FRAME_MAPPINGS'): wcsaxes.wcs_utils.WCS_FRAME_MAPPINGS.append([solar_wcs_frame_mapping]) except ImportError: pass
bsd-2-clause
Python
b315778e1717dce8c6d5e493c0c7851f65aee25f
Add blank line above @classmethod joke2k/faker#552
joke2k/faker,danhuss/faker,joke2k/faker
faker/providers/automotive/__init__.py
faker/providers/automotive/__init__.py
# coding=utf-8 localized = True from .. import BaseProvider from string import ascii_uppercase import re class Provider(BaseProvider): license_formats = () @classmethod def license_plate(cls): temp = re.sub(r'\?', lambda x: cls.random_element(ascii_uppercase), cls.random_element(cls.license_formats)) return cls.numerify(temp)
# coding=utf-8 localized = True from .. import BaseProvider from string import ascii_uppercase import re class Provider(BaseProvider): license_formats = () @classmethod def license_plate(cls): temp = re.sub(r'\?', lambda x: cls.random_element(ascii_uppercase), cls.random_element(cls.license_formats)) return cls.numerify(temp)
mit
Python
32dcc7384613870b95dc8b55c42381050b12d6a5
update test block ordering
praekelt/molo-freebasics,praekelt/molo-freebasics,praekelt/molo-freebasics,praekelt/molo-freebasics
freebasics/tests/test_env_variables.py
freebasics/tests/test_env_variables.py
from django.test import TestCase, RequestFactory from molo.core.tests.base import MoloTestCaseMixin from freebasics.views import HomeView from freebasics.templatetags import freebasics_tags class EnvTestCase(TestCase, MoloTestCaseMixin): def setUp(self): self.mk_main() def test_block_ordering(self): with self.settings(BLOCK_POSITION_BANNER=1, BLOCK_POSITION_LATEST=2, BLOCK_POSITION_QUESTIONS=3, BLOCK_POSITION_SECTIONS=4): factory = RequestFactory() request = factory.get('/') request.site = self.site home = HomeView() home.request = request context = home.get_context_data() self.assertEquals(context['blocks'][0], ( 'blocks/sections.html', 4)) self.assertEquals(context['blocks'][1], ( 'blocks/questions.html', 2)) self.assertEquals(context['blocks'][2], ('blocks/latest.html', 3)) self.assertEquals(context['blocks'][3], ('blocks/banners.html', 4)) def test_css_vars(self): with self.settings(CUSTOM_CSS_BLOCK_TEXT_TRANSFORM="lowercase", CUSTOM_CSS_ACCENT_2="red"): styles = freebasics_tags.custom_css(context='') self.assertEquals(styles['accent_2'], 'red') self.assertEquals(styles['text_transform'], 'lowercase') def test_custom_css(self): response = self.client.get('/') self.assertContains(response, 'Free Basics Custom CSS') self.assertContains(response, '.fb-body .base-bcolor') self.assertContains(response, '.fb-body .block-heading') self.assertContains(response, '.section-nav__items')
from django.test import TestCase, RequestFactory from molo.core.tests.base import MoloTestCaseMixin from freebasics.views import HomeView from freebasics.templatetags import freebasics_tags class EnvTestCase(TestCase, MoloTestCaseMixin): def setUp(self): self.mk_main() def test_block_ordering(self): with self.settings(BLOCK_POSITION_BANNER=1, BLOCK_POSITION_LATEST=3, BLOCK_POSITION_QUESTIONS=4, BLOCK_POSITION_SECTIONS=7): factory = RequestFactory() request = factory.get('/') request.site = self.site home = HomeView() home.request = request context = home.get_context_data() self.assertEquals(context['blocks'][0], ( 'blocks/sections.html', 7)) self.assertEquals(context['blocks'][1], ( 'blocks/questions.html', 4)) self.assertEquals(context['blocks'][2], ('blocks/latest.html', 3)) self.assertEquals(context['blocks'][3], ('blocks/banners.html', 1)) def test_css_vars(self): with self.settings(CUSTOM_CSS_BLOCK_TEXT_TRANSFORM="lowercase", CUSTOM_CSS_ACCENT_2="red"): styles = freebasics_tags.custom_css(context='') self.assertEquals(styles['accent_2'], 'red') self.assertEquals(styles['text_transform'], 'lowercase') def test_custom_css(self): response = self.client.get('/') self.assertContains(response, 'Free Basics Custom CSS') self.assertContains(response, '.fb-body .base-bcolor') self.assertContains(response, '.fb-body .block-heading') self.assertContains(response, '.section-nav__items')
bsd-2-clause
Python
f94580bad7e0d6df6bb92b34d153ade658d59c01
Print output in test_debug__library_versions
pfmoore/pip,pradyunsg/pip,sbidoul/pip,pradyunsg/pip,pfmoore/pip,pypa/pip,sbidoul/pip,pypa/pip
tests/functional/test_debug.py
tests/functional/test_debug.py
import pytest from pip._internal.commands.debug import create_vendor_txt_map from pip._internal.utils import compatibility_tags @pytest.mark.parametrize('expected_text', [ 'sys.executable: ', 'sys.getdefaultencoding: ', 'sys.getfilesystemencoding: ', 'locale.getpreferredencoding: ', 'sys.platform: ', 'sys.implementation:', '\'cert\' config value: ', 'REQUESTS_CA_BUNDLE: ', 'CURL_CA_BUNDLE: ', 'pip._vendor.certifi.where(): ', 'pip._vendor.DEBUNDLED: ', 'vendored library versions:', ]) def test_debug(script, expected_text): """ Check that certain strings are present in the output. """ args = ['debug'] result = script.pip(*args, allow_stderr_warning=True) stdout = result.stdout assert expected_text in stdout def test_debug__library_versions(script): """ Check the library versions normal output. """ args = ['debug'] result = script.pip(*args, allow_stderr_warning=True) print(result.stdout) vendored_versions = create_vendor_txt_map() for name, value in vendored_versions.items(): assert '{}=={}'.format(name, value) in result.stdout @pytest.mark.parametrize( 'args', [ [], ['--verbose'], ] ) def test_debug__tags(script, args): """ Check the compatible tag output. """ args = ['debug'] + args result = script.pip(*args, allow_stderr_warning=True) stdout = result.stdout tags = compatibility_tags.get_supported() expected_tag_header = 'Compatible tags: {}'.format(len(tags)) assert expected_tag_header in stdout show_verbose_note = '--verbose' not in args assert ( '...\n [First 10 tags shown. Pass --verbose to show all.]' in stdout ) == show_verbose_note @pytest.mark.parametrize( 'args, expected', [ (['--python-version', '3.7'], "(target: version_info='3.7')"), ] ) def test_debug__target_options(script, args, expected): """ Check passing target-related options. """ args = ['debug'] + args result = script.pip(*args, allow_stderr_warning=True) stdout = result.stdout assert 'Compatible tags: ' in stdout assert expected in stdout
import pytest from pip._internal.commands.debug import create_vendor_txt_map from pip._internal.utils import compatibility_tags @pytest.mark.parametrize('expected_text', [ 'sys.executable: ', 'sys.getdefaultencoding: ', 'sys.getfilesystemencoding: ', 'locale.getpreferredencoding: ', 'sys.platform: ', 'sys.implementation:', '\'cert\' config value: ', 'REQUESTS_CA_BUNDLE: ', 'CURL_CA_BUNDLE: ', 'pip._vendor.certifi.where(): ', 'pip._vendor.DEBUNDLED: ', 'vendored library versions:', ]) def test_debug(script, expected_text): """ Check that certain strings are present in the output. """ args = ['debug'] result = script.pip(*args, allow_stderr_warning=True) stdout = result.stdout assert expected_text in stdout def test_debug__library_versions(script): """ Check the library versions normal output. """ args = ['debug'] result = script.pip(*args, allow_stderr_warning=True) stdout = result.stdout vendored_versions = create_vendor_txt_map() for name, value in vendored_versions.items(): assert '{}=={}'.format(name, value) in stdout @pytest.mark.parametrize( 'args', [ [], ['--verbose'], ] ) def test_debug__tags(script, args): """ Check the compatible tag output. """ args = ['debug'] + args result = script.pip(*args, allow_stderr_warning=True) stdout = result.stdout tags = compatibility_tags.get_supported() expected_tag_header = 'Compatible tags: {}'.format(len(tags)) assert expected_tag_header in stdout show_verbose_note = '--verbose' not in args assert ( '...\n [First 10 tags shown. Pass --verbose to show all.]' in stdout ) == show_verbose_note @pytest.mark.parametrize( 'args, expected', [ (['--python-version', '3.7'], "(target: version_info='3.7')"), ] ) def test_debug__target_options(script, args, expected): """ Check passing target-related options. """ args = ['debug'] + args result = script.pip(*args, allow_stderr_warning=True) stdout = result.stdout assert 'Compatible tags: ' in stdout assert expected in stdout
mit
Python
306e6939c5b369f4a4ef4bb4d16948dc1f027f53
Update for PYTHON 985: MongoClient properties now block until connected.
ajdavis/pymongo-mockup-tests
tests/test_initial_ismaster.py
tests/test_initial_ismaster.py
# Copyright 2015 MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time from mockupdb import MockupDB, wait_until from pymongo import MongoClient from tests import unittest class TestInitialIsMaster(unittest.TestCase): def test_initial_ismaster(self): server = MockupDB() server.run() self.addCleanup(server.stop) start = time.time() client = MongoClient(server.uri) self.addCleanup(client.close) # A single ismaster is enough for the client to be connected. self.assertFalse(client.nodes) server.receives('ismaster').ok(ismaster=True) wait_until(lambda: client.nodes, 'update nodes', timeout=1) # At least 10 seconds before next heartbeat. server.receives('ismaster').ok(ismaster=True) self.assertGreaterEqual(time.time() - start, 10) if __name__ == '__main__': unittest.main()
# Copyright 2015 MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time from mockupdb import MockupDB, wait_until from pymongo import MongoClient from tests import unittest class TestInitialIsMaster(unittest.TestCase): def test_initial_ismaster(self): server = MockupDB() server.run() self.addCleanup(server.stop) start = time.time() client = MongoClient(server.uri) self.addCleanup(client.close) # A single ismaster is enough for the client to be connected. self.assertIsNone(client.address) server.receives('ismaster').ok() wait_until(lambda: client.address is not None, 'update address', timeout=1) # At least 10 seconds before next heartbeat. server.receives('ismaster').ok() self.assertGreaterEqual(time.time() - start, 10) if __name__ == '__main__': unittest.main()
apache-2.0
Python
f0b26198bc3c0e3937db334af3c99643481a3d91
change from file
tongpa/tgext.pylogservice
tgext/pylogservice/__init__.py
tgext/pylogservice/__init__.py
from tg import config from tg import hooks from tg.configuration import milestones import logging log = logging.getLogger('tgext.pylogservice') # This is the entry point of your extension, will be called # both when the user plugs the extension manually or through tgext.pluggable # What you write here has the same effect as writing it into app_cfg.py # So it is possible to plug other extensions you depend on. def plugme(configurator, options=None): if options is None: options = {} log.info('Setting up tgext.pylogservice extension...') milestones.config_ready.register(SetupExtension(configurator)) # This is required to be compatible with the # tgext.pluggable interface return dict(appid='tgext.pylogservice') # Most of your extension initialization should probably happen here, # where it's granted that .ini configuration file has already been loaded # in tg.config but you can still register hooks or other milestones. class SetupExtension(object): def __init__(self, configurator): self.configurator = configurator def __call__(self): log.info('>>> Public files path is %s' % config['paths']['static_files']) hooks.register('startup', self.on_startup) def echo_wrapper_factory(handler, config): def echo_wrapper(controller, environ, context): log.info('Serving: %s' % context.request.path) return handler(controller, environ, context) return echo_wrapper # Application Wrappers are much like easier WSGI Middleware # that get a TurboGears context and return a Response object. self.configurator.register_wrapper(echo_wrapper_factory) def on_startup(self): log.info('tgext.pylogservice + Application Running!') from .logdbhandler import LogDBHandler
from tg import config from tg import hooks from tg.configuration import milestones import logging log = logging.getLogger('tgext.pylogservice') # This is the entry point of your extension, will be called # both when the user plugs the extension manually or through tgext.pluggable # What you write here has the same effect as writing it into app_cfg.py # So it is possible to plug other extensions you depend on. def plugme(configurator, options=None): if options is None: options = {} log.info('Setting up tgext.pylogservice extension...') milestones.config_ready.register(SetupExtension(configurator)) # This is required to be compatible with the # tgext.pluggable interface return dict(appid='tgext.pylogservice') # Most of your extension initialization should probably happen here, # where it's granted that .ini configuration file has already been loaded # in tg.config but you can still register hooks or other milestones. class SetupExtension(object): def __init__(self, configurator): self.configurator = configurator def __call__(self): log.info('>>> Public files path is %s' % config['paths']['static_files']) hooks.register('startup', self.on_startup) def echo_wrapper_factory(handler, config): def echo_wrapper(controller, environ, context): log.info('Serving: %s' % context.request.path) return handler(controller, environ, context) return echo_wrapper # Application Wrappers are much like easier WSGI Middleware # that get a TurboGears context and return a Response object. self.configurator.register_wrapper(echo_wrapper_factory) def on_startup(self): print 'Application Running!' log.info('+ Application Running!') from .logdbhandler import LogDBHandler
mit
Python
ace177c6d83209eac6038fb4b3cc4b0c392e1cf4
Integrate LLVM at llvm/llvm-project@4e5c44964a7f
tensorflow/runtime,tensorflow/runtime,tensorflow/runtime,tensorflow/runtime
third_party/llvm/workspace.bzl
third_party/llvm/workspace.bzl
"""Provides the repository macro to import LLVM.""" load("//third_party:repo.bzl", "tfrt_http_archive") def repo(name): """Imports LLVM.""" LLVM_COMMIT = "4e5c44964a7f3ecbe93cd69bdbcbbcf2a5f52c28" LLVM_SHA256 = "13cd6f2bbd749d5386f133dc44b0707e7f780149a91cf56e05b8a730103122d8" tfrt_http_archive( name = name, build_file = "//third_party/llvm:BUILD", sha256 = LLVM_SHA256, strip_prefix = "llvm-project-" + LLVM_COMMIT, urls = [ "https://storage.googleapis.com/mirror.tensorflow.org/github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT), "https://github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT), ], )
"""Provides the repository macro to import LLVM.""" load("//third_party:repo.bzl", "tfrt_http_archive") def repo(name): """Imports LLVM.""" LLVM_COMMIT = "be199527205dc8a8c7febc057ad6be90fac15547" LLVM_SHA256 = "b43318ef35679dd1b6cb6c4cf1cd5888ac4530fb4149128e345cade0b6628e88" tfrt_http_archive( name = name, build_file = "//third_party/llvm:BUILD", sha256 = LLVM_SHA256, strip_prefix = "llvm-project-" + LLVM_COMMIT, urls = [ "https://storage.googleapis.com/mirror.tensorflow.org/github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT), "https://github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT), ], )
apache-2.0
Python
df73a47311c8527ee6a5bd7b461d9ffd44d2ff17
Switch repo tests query to be a (somewhat) faster join (#391)
getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus
zeus/api/resources/repository_tests.py
zeus/api/resources/repository_tests.py
from datetime import timedelta from sqlalchemy.sql import func from zeus.config import db from zeus.constants import Result, Status from zeus.models import Repository, TestCase, Job from zeus.utils import timezone from .base_repository import BaseRepositoryResource from ..schemas import TestCaseStatisticsSchema testcases_schema = TestCaseStatisticsSchema(many=True) class RepositoryTestsResource(BaseRepositoryResource): def get(self, repo: Repository): """ Return a list of testcases for the given repository. """ runs_failed = ( func.count(TestCase.result) .filter(TestCase.result == Result.failed) .label("runs_failed") ) query = ( db.session.query( TestCase.hash, TestCase.name, func.count(TestCase.hash).label("runs_total"), runs_failed, func.avg(TestCase.duration).label("avg_duration"), ) .join(Job, Job.id == TestCase.job_id) .filter( Job.repository_id == repo.id, Job.date_finished >= timezone.now() - timedelta(days=14), Job.status == Status.finished, ) .group_by(TestCase.hash, TestCase.name) .order_by(runs_failed.desc()) ) return self.paginate_with_schema(testcases_schema, query)
from datetime import timedelta from sqlalchemy.sql import func from zeus.config import db from zeus.constants import Result, Status from zeus.models import Repository, TestCase, Job from zeus.utils import timezone from .base_repository import BaseRepositoryResource from ..schemas import TestCaseStatisticsSchema testcases_schema = TestCaseStatisticsSchema(many=True) class RepositoryTestsResource(BaseRepositoryResource): def get(self, repo: Repository): """ Return a list of testcases for the given repository. """ runs_failed = ( func.count(TestCase.result) .filter(TestCase.result == Result.failed) .label("runs_failed") ) query = ( db.session.query( TestCase.hash, TestCase.name, func.count(TestCase.hash).label("runs_total"), runs_failed, func.avg(TestCase.duration).label("avg_duration"), ) .filter( TestCase.job_id.in_( db.session.query(Job.id) .filter( Job.repository_id == repo.id, Job.date_finished >= timezone.now() - timedelta(days=14), Job.status == Status.finished, ) .limit(10000) .subquery() ) ) .group_by(TestCase.hash, TestCase.name) .order_by(runs_failed.desc()) ) return self.paginate_with_schema(testcases_schema, query)
apache-2.0
Python
af7d139391fc797e1fa5a6540f0589e5b0c2a1c0
Bump version to 4.1.0.13.dev2
MAECProject/python-maec
maec/version.py
maec/version.py
# Copyright (c) 2015, The MITRE Corporation. All rights reserved. # See LICENSE.txt for complete terms. __version__ = "4.1.0.13.dev2"
# Copyright (c) 2015, The MITRE Corporation. All rights reserved. # See LICENSE.txt for complete terms. __version__ = "4.1.0.13.dev1"
bsd-3-clause
Python
af5e90cb544e2e37819302f5750084fc17f7ee12
Remove sdbus++ template search workaround
openbmc/phosphor-inventory-manager,openbmc/phosphor-inventory-manager
make_example.py
make_example.py
#!/usr/bin/env python import os import sys import yaml import subprocess if __name__ == '__main__': genfiles = { 'server-cpp': lambda x: '%s.cpp' % x, 'server-header': lambda x: os.path.join( os.path.join(*x.split('.')), 'server.hpp') } with open(os.path.join('example', 'interfaces.yaml'), 'r') as fd: interfaces = yaml.load(fd.read()) for i in interfaces: for process, f in genfiles.iteritems(): dest = f(i) parent = os.path.dirname(dest) if parent and not os.path.exists(parent): os.makedirs(parent) with open(dest, 'w') as fd: subprocess.call([ 'sdbus++', '-r', os.path.join('example', 'interfaces'), 'interface', process, i], stdout=fd) # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
#!/usr/bin/env python import os import sys import yaml import subprocess class SDBUSPlus(object): def __init__(self, path): self.path = path def __call__(self, *a, **kw): args = [ os.path.join(self.path, 'sdbus++'), '-t', os.path.join(self.path, 'templates') ] subprocess.call(args + list(a), **kw) if __name__ == '__main__': sdbusplus = None for p in os.environ.get('PATH', "").split(os.pathsep): if os.path.exists(os.path.join(p, 'sdbus++')): sdbusplus = SDBUSPlus(p) break if sdbusplus is None: sys.stderr.write('Cannot find sdbus++\n') sys.exit(1) genfiles = { 'server-cpp': lambda x: '%s.cpp' % x, 'server-header': lambda x: os.path.join( os.path.join(*x.split('.')), 'server.hpp') } with open(os.path.join('example', 'interfaces.yaml'), 'r') as fd: interfaces = yaml.load(fd.read()) for i in interfaces: for process, f in genfiles.iteritems(): dest = f(i) parent = os.path.dirname(dest) if parent and not os.path.exists(parent): os.makedirs(parent) with open(dest, 'w') as fd: sdbusplus( '-r', os.path.join('example', 'interfaces'), 'interface', process, i, stdout=fd) # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
apache-2.0
Python
1e07e9424a1ac69e1e660e6a6f1e58bba15472c1
Implement saving and loading the observer tau
sbird/vw_spectra
make_spectra.py
make_spectra.py
# -*- coding: utf-8 -*- import halospectra as hs import randspectra as rs import sys snapnum=sys.argv[1] sim=sys.argv[2] #base="/n/hernquistfs1/mvogelsberger/projects/GFM/Production/Cosmo/Cosmo"+str(sim)+"_V6/L25n512/output/" #savedir="/n/home11/spb/scratch/Cosmo/Cosmo"+str(sim)+"_V6_512/snapdir_"+str(snapnum).rjust(3,'0') base="/home/spb/data/Cosmo/Cosmo"+str(sim)+"_V6/L25n256" savedir="/home/spb/scratch/Cosmo/Cosmo"+str(sim)+"_V6/snapdir_"+str(snapnum).rjust(3,'0') #halo = hs.HaloSpectra(snapnum, base,3, savefile="halo_spectra_DLA.hdf5", savedir=savedir) halo = rs.RandSpectra(snapnum, base,numlos=10000,savedir=savedir, savefile="rand_spectra.hdf5") #halo.get_observer_tau("Si",2) halo.get_tau("H",1,1) #halo.get_col_density("Z",-1) #halo.get_col_density("H",-1) halo.save_file()
# -*- coding: utf-8 -*- import halospectra as hs import randspectra as rs import sys snapnum=sys.argv[1] sim=sys.argv[2] #base="/n/hernquistfs1/mvogelsberger/projects/GFM/Production/Cosmo/Cosmo"+str(sim)+"_V6/L25n512/output/" #savedir="/n/home11/spb/scratch/Cosmo/Cosmo"+str(sim)+"_V6_512/snapdir_"+str(snapnum).rjust(3,'0') base="/home/spb/data/Cosmo/Cosmo"+str(sim)+"_V6/L25n256" savedir="/home/spb/scratch/Cosmo/Cosmo"+str(sim)+"_V6/snapdir_"+str(snapnum).rjust(3,'0') #halo = hs.HaloSpectra(snapnum, base,3, savefile="halo_spectra_DLA.hdf5", savedir=savedir) halo = rs.RandSpectra(snapnum, base,numlos=3000,savedir=savedir, savefile="rand_spectra_DLA.hdf5") halo.get_tau("Si",2,2) halo.get_tau("H",1,1) halo.get_col_density("Z",-1) halo.get_col_density("H",-1) halo.save_file()
mit
Python
d4905477b812213da2333103c9fdd789151ae2d8
Allow core config updated (#26398)
balloob/home-assistant,GenericStudent/home-assistant,qedi-r/home-assistant,sander76/home-assistant,qedi-r/home-assistant,balloob/home-assistant,lukas-hetzenecker/home-assistant,mezz64/home-assistant,pschmitt/home-assistant,leppa/home-assistant,w1ll1am23/home-assistant,sdague/home-assistant,postlund/home-assistant,aronsky/home-assistant,FreekingDean/home-assistant,aronsky/home-assistant,adrienbrault/home-assistant,sander76/home-assistant,sdague/home-assistant,Danielhiversen/home-assistant,toddeye/home-assistant,FreekingDean/home-assistant,pschmitt/home-assistant,balloob/home-assistant,tboyce021/home-assistant,jawilson/home-assistant,postlund/home-assistant,nkgilley/home-assistant,partofthething/home-assistant,rohitranjan1991/home-assistant,Teagan42/home-assistant,soldag/home-assistant,kennedyshead/home-assistant,jawilson/home-assistant,Teagan42/home-assistant,toddeye/home-assistant,titilambert/home-assistant,turbokongen/home-assistant,rohitranjan1991/home-assistant,leppa/home-assistant,turbokongen/home-assistant,robbiet480/home-assistant,mKeRix/home-assistant,nkgilley/home-assistant,home-assistant/home-assistant,rohitranjan1991/home-assistant,tboyce1/home-assistant,mezz64/home-assistant,Danielhiversen/home-assistant,tboyce021/home-assistant,tchellomello/home-assistant,lukas-hetzenecker/home-assistant,kennedyshead/home-assistant,mKeRix/home-assistant,adrienbrault/home-assistant,mKeRix/home-assistant,tboyce1/home-assistant,partofthething/home-assistant,Cinntax/home-assistant,Cinntax/home-assistant,tboyce1/home-assistant,home-assistant/home-assistant,joopert/home-assistant,titilambert/home-assistant,soldag/home-assistant,mKeRix/home-assistant,tboyce1/home-assistant,robbiet480/home-assistant,GenericStudent/home-assistant,tchellomello/home-assistant,joopert/home-assistant,w1ll1am23/home-assistant
homeassistant/components/websocket_api/permissions.py
homeassistant/components/websocket_api/permissions.py
"""Permission constants for the websocket API. Separate file to avoid circular imports. """ from homeassistant.const import ( EVENT_COMPONENT_LOADED, EVENT_SERVICE_REGISTERED, EVENT_SERVICE_REMOVED, EVENT_STATE_CHANGED, EVENT_THEMES_UPDATED, EVENT_CORE_CONFIG_UPDATE, ) from homeassistant.components.persistent_notification import ( EVENT_PERSISTENT_NOTIFICATIONS_UPDATED, ) from homeassistant.components.lovelace import EVENT_LOVELACE_UPDATED from homeassistant.helpers.area_registry import EVENT_AREA_REGISTRY_UPDATED from homeassistant.helpers.device_registry import EVENT_DEVICE_REGISTRY_UPDATED from homeassistant.helpers.entity_registry import EVENT_ENTITY_REGISTRY_UPDATED from homeassistant.components.frontend import EVENT_PANELS_UPDATED # These are events that do not contain any sensitive data # Except for state_changed, which is handled accordingly. SUBSCRIBE_WHITELIST = { EVENT_COMPONENT_LOADED, EVENT_CORE_CONFIG_UPDATE, EVENT_PANELS_UPDATED, EVENT_PERSISTENT_NOTIFICATIONS_UPDATED, EVENT_SERVICE_REGISTERED, EVENT_SERVICE_REMOVED, EVENT_STATE_CHANGED, EVENT_THEMES_UPDATED, EVENT_AREA_REGISTRY_UPDATED, EVENT_DEVICE_REGISTRY_UPDATED, EVENT_ENTITY_REGISTRY_UPDATED, EVENT_LOVELACE_UPDATED, }
"""Permission constants for the websocket API. Separate file to avoid circular imports. """ from homeassistant.const import ( EVENT_COMPONENT_LOADED, EVENT_SERVICE_REGISTERED, EVENT_SERVICE_REMOVED, EVENT_STATE_CHANGED, EVENT_THEMES_UPDATED, ) from homeassistant.components.persistent_notification import ( EVENT_PERSISTENT_NOTIFICATIONS_UPDATED, ) from homeassistant.components.lovelace import EVENT_LOVELACE_UPDATED from homeassistant.helpers.area_registry import EVENT_AREA_REGISTRY_UPDATED from homeassistant.helpers.device_registry import EVENT_DEVICE_REGISTRY_UPDATED from homeassistant.helpers.entity_registry import EVENT_ENTITY_REGISTRY_UPDATED from homeassistant.components.frontend import EVENT_PANELS_UPDATED # These are events that do not contain any sensitive data # Except for state_changed, which is handled accordingly. SUBSCRIBE_WHITELIST = { EVENT_COMPONENT_LOADED, EVENT_PANELS_UPDATED, EVENT_PERSISTENT_NOTIFICATIONS_UPDATED, EVENT_SERVICE_REGISTERED, EVENT_SERVICE_REMOVED, EVENT_STATE_CHANGED, EVENT_THEMES_UPDATED, EVENT_AREA_REGISTRY_UPDATED, EVENT_DEVICE_REGISTRY_UPDATED, EVENT_ENTITY_REGISTRY_UPDATED, EVENT_LOVELACE_UPDATED, }
apache-2.0
Python
1b224e868011c7fb9e20cabaed26fb029355d04d
Add the member name to the description in tracking.
MJB47/Jokusoramame,MJB47/Jokusoramame,MJB47/Jokusoramame
joku/cogs/tracking.py
joku/cogs/tracking.py
""" NSA-tier presence tracking. """ import datetime import time import discord from discord import Status from discord.ext import commands from joku.bot import Context from joku.cogs._common import Cog class Tracking(Cog): async def on_message(self, message: discord.Message): author = message.author # type: discord.Member # update their last message in redis await self.bot.redis.update_last_message(author) # and their last seen await self.bot.redis.update_last_seen(author) async def on_member_update(self, before: discord.Member, after: discord.Member): # check to see if their after status is online and their before was not online if after.status is Status.online and before.status is not Status.online: await self.bot.redis.update_last_seen(after) @commands.command() async def tracking(self, ctx: Context, *, member: discord.Member=None): """ Shows the last seen information for a member. """ if member is None: member = ctx.message.author data = await self.bot.redis.get_presence_data(member) em = discord.Embed(title="National Security Agency") em.set_thumbnail(url=member.avatar_url) if data is None: em.description = "**No tracking data for this user was found.**" else: em.description = "**Tracking data for {}**".format(member.name) # float bugs if int(data["last_seen"]) == 0: if member.status == Status.online: await ctx.bot.redis.update_last_seen(member) last_seen = datetime.datetime.fromtimestamp(time.time()) else: last_seen = "Unknown" else: last_seen = datetime.datetime.fromtimestamp(data["last_seen"]) if int(data["last_message"]) == 0: last_message = "Unknown" else: last_message = datetime.datetime.fromtimestamp(data["last_message"]) em.add_field(name="Last seen", value=last_seen.isoformat(), inline=False) em.add_field(name="Last message", value=last_message.isoformat(), inline=False) await ctx.send(embed=em) setup = Tracking.setup
""" NSA-tier presence tracking. """ import datetime import time import discord from discord import Status from discord.ext import commands from joku.bot import Context from joku.cogs._common import Cog class Tracking(Cog): async def on_message(self, message: discord.Message): author = message.author # type: discord.Member # update their last message in redis await self.bot.redis.update_last_message(author) # and their last seen await self.bot.redis.update_last_seen(author) async def on_member_update(self, before: discord.Member, after: discord.Member): # check to see if their after status is online and their before was not online if after.status is Status.online and before.status is not Status.online: await self.bot.redis.update_last_seen(after) @commands.command() async def tracking(self, ctx: Context, *, member: discord.Member=None): """ Shows the last seen information for a member. """ if member is None: member = ctx.message.author data = await self.bot.redis.get_presence_data(member) em = discord.Embed(title="National Security Agency") em.set_thumbnail(url=member.avatar_url) if data is None: em.description = "**No tracking data for this user was found.**" else: # float bugs if int(data["last_seen"]) == 0: if member.status == Status.online: await ctx.bot.redis.update_last_seen(member) last_seen = datetime.datetime.fromtimestamp(time.time()) else: last_seen = "Unknown" else: last_seen = datetime.datetime.fromtimestamp(data["last_seen"]) if int(data["last_message"]) == 0: last_message = "Unknown" else: last_message = datetime.datetime.fromtimestamp(data["last_message"]) em.add_field(name="Last seen", value=last_seen.isoformat(), inline=False) em.add_field(name="Last message", value=last_message.isoformat(), inline=False) await ctx.send(embed=em) setup = Tracking.setup
mit
Python
0e6cf0f032ca8b8c48282eb16d8e1751c869494b
update error message validation
clach04/json-rpc,lorehov/json-rpc
jsonrpc/exceptions.py
jsonrpc/exceptions.py
import six class JSONRPCError(object): """ Error for JSON-RPC communication. When a rpc call encounters an error, the Response Object MUST contain the error member with a value that is a Object with the following members: code: A Number that indicates the error type that occurred. This MUST be an integer. message: A String providing a short description of the error. The message SHOULD be limited to a concise single sentence. data: A Primitive or Structured value that contains additional information about the error. This may be omitted. The value of this member is defined by the Server (e.g. detailed error information, nested errors etc.). The error codes from and including -32768 to -32000 are reserved for pre-defined errors. Any code within this range, but not defined explicitly below is reserved for future use. The error codes are nearly the same as those suggested for XML-RPC at the following url: http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php """ def __init__(self, code=None, message=None, data=None): self._dict = dict() self.code = code self.message = message self.data = data def __get_code(self): return self._dict["code"] def __set_code(self, value): if not isinstance(value, six.integer_types): raise ValueError("Error code should be integer") self._dict["code"] = value code = property(__get_code, __set_code) def __get_message(self): return self._dict["message"] def __set_message(self, value): if not isinstance(value, six.string_types): raise ValueError("Error message should be string") self._dict["message"] = value message = property(__get_message, __set_message) class JSONRPCParseError(JSONRPCError): """ Parse Error. Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text. """ code = -32700 message = "Parse error" class JSONRPCInvalidRequest(JSONRPCError): """ Invalid Request. The JSON sent is not a valid Request object. """ code = -32600 message = "Invalid Request" class JSONRPCMethodNotFound(JSONRPCError): """ Method not found. The method does not exist / is not available. """ code = -32601 message = "Method not found" class JSONRPCInvalidParams(JSONRPCError): """ Invalid params. Invalid method parameter(s). """ code = -32602 message = "Invalid params" class JSONRPCInternalError(JSONRPCError): """ Internal error. Internal JSON-RPC error. """ code = -32603 message = "Internal error" class JSONRPCServerError(JSONRPCError): """ Server error. Reserved for implementation-defined server-errors. """ code = -32000 message = "Server error"
import six class JSONRPCError(object): """ Error for JSON-RPC communication. When a rpc call encounters an error, the Response Object MUST contain the error member with a value that is a Object with the following members: code: A Number that indicates the error type that occurred. This MUST be an integer. message: A String providing a short description of the error. The message SHOULD be limited to a concise single sentence. data: A Primitive or Structured value that contains additional information about the error. This may be omitted. The value of this member is defined by the Server (e.g. detailed error information, nested errors etc.). The error codes from and including -32768 to -32000 are reserved for pre-defined errors. Any code within this range, but not defined explicitly below is reserved for future use. The error codes are nearly the same as those suggested for XML-RPC at the following url: http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php """ def __init__(self, code=None, message=None, data=None): self._dict = dict() self.code = code #self.message = message or self.message #self.data = data def __get_code(self): return self._dict["code"] def __set_code(self, value): if not isinstance(value, six.integer_types): raise ValueError("Error code should be integer") self._dict["code"] = value code = property(__get_code, __set_code) class JSONRPCParseError(JSONRPCError): """ Parse Error. Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text. """ code = -32700 message = "Parse error" class JSONRPCInvalidRequest(JSONRPCError): """ Invalid Request. The JSON sent is not a valid Request object. """ code = -32600 message = "Invalid Request" class JSONRPCMethodNotFound(JSONRPCError): """ Method not found. The method does not exist / is not available. """ code = -32601 message = "Method not found" class JSONRPCInvalidParams(JSONRPCError): """ Invalid params. Invalid method parameter(s). """ code = -32602 message = "Invalid params" class JSONRPCInternalError(JSONRPCError): """ Internal error. Internal JSON-RPC error. """ code = -32603 message = "Internal error" class JSONRPCServerError(JSONRPCError): """ Server error. Reserved for implementation-defined server-errors. """ code = -32000 message = "Server error"
mit
Python
d8405b54d7fd2634582585bd420be0636d804eee
Bump version to 7.0.0a3
genialis/resolwe,jberci/resolwe,genialis/resolwe,jberci/resolwe
resolwe/__about__.py
resolwe/__about__.py
"""Central place for package metadata.""" # NOTE: We use __title__ instead of simply __name__ since the latter would # interfere with a global variable __name__ denoting object's name. __title__ = 'resolwe' __summary__ = 'Open source enterprise dataflow engine in Django' __url__ = 'https://github.com/genialis/resolwe' # Semantic versioning is used. For more information see: # https://packaging.python.org/en/latest/distributing/#semantic-versioning-preferred __version__ = '7.0.0a3' __author__ = 'Genialis d.o.o.' __email__ = 'dev-team@genialis.com' __license__ = 'Apache License (2.0)' __copyright__ = '2015-2018, ' + __author__ __all__ = ( '__title__', '__summary__', '__url__', '__version__', '__author__', '__email__', '__license__', '__copyright__', )
"""Central place for package metadata.""" # NOTE: We use __title__ instead of simply __name__ since the latter would # interfere with a global variable __name__ denoting object's name. __title__ = 'resolwe' __summary__ = 'Open source enterprise dataflow engine in Django' __url__ = 'https://github.com/genialis/resolwe' # Semantic versioning is used. For more information see: # https://packaging.python.org/en/latest/distributing/#semantic-versioning-preferred __version__ = '7.0.0a2' __author__ = 'Genialis d.o.o.' __email__ = 'dev-team@genialis.com' __license__ = 'Apache License (2.0)' __copyright__ = '2015-2018, ' + __author__ __all__ = ( '__title__', '__summary__', '__url__', '__version__', '__author__', '__email__', '__license__', '__copyright__', )
apache-2.0
Python
0511ad666a22375afe14b89e94828d1bf3c746b7
Add a way to handle multiple regex expression. (Used to exclude file, directory or path
funilrys/A-John-Shots
a_john_shots/regex.py
a_john_shots/regex.py
#!/usr/bin/env python # python-regex - A simple implementation ot the python.re package # Copyright (C) 2017 Funilrys - Nissar Chababy <contact at funilrys dot com> # # 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 your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Original Version: https://github.com/funilrys/python-regex from re import compile, search class Regex(object): """A simple implementation ot the python.re package""" def __init__(self, data, regex, return_data=False, group=0): super(Regex, self).__init__() self.data = data self.regex = regex self.return_data = return_data self.group = group def match(self): """Used to get exploitable result of re.search""" if type(self.data) is list: result = [] for item in self.regex: to_match = compile(item) local_result = to_match.search(self.data) if self.return_data and local_result is not None: result.append(local_result.group(self.group)) elif self.return_data == False and local_result is not None: return True if self.return_data and result: return result return False elif isinstance(self.data,str) and isinstance(self.regex,str): toMatch = compile(self.regex) result = toMatch.search(self.data) if self.return_data and result is not None: return result.group(self.group).strip() elif self.return_data == False and result is not None: return True return False return None
!/usr/bin/env python # python-regex - A simple implementation ot the python.re package # Copyright (C) 2017 Funilrys - Nissar Chababy <contact at funilrys dot com> # # 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 your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Original Version: https://github.com/funilrys/python-regex from re import compile, search class Regex(object): """A simple implementation ot the python.re package""" def __init__(self, data, regex, return_data=False, group=0): super(Regex, self).__init__() self.data = data self.regex = regex self.return_data = return_data self.group = group def match(self): """Used to get exploitable result of re.search""" toMatch = compile(self.regex) result = toMatch.search(self.data) if self.return_data and result is not None: return result.group(self.group).strip() elif self.return_data == False and result is not None: return True else: return False
mit
Python
43bcd715a6008151a8856ecc25a3382a8df54532
fix type in id__in refrences
lampwins/stackstorm-netbox
actions/lib/action.py
actions/lib/action.py
from st2actions.runners.pythonrunner import Action import requests __all__ = [ 'NetboxBaseAction' ] class NetboxBaseAction(Action): """Base Action for all Netbox API based actions """ def __init__(self, config): super(NetboxBaseAction, self).__init__(config) def get(self, endpoint_uri, **kwargs): """Make a get request to the API URI passed in """ self.logger.debug("Calling base get with kwargs: {}".format(kwargs)) if self.config['use_https']: url = 'https://' else: url = 'http://' url = url + self.config['hostname'] + endpoint_uri headers = { 'Authorization': 'Token ' + self.config['api_token'], 'Accept': 'application/json' } # transform `in__id` if present if kwargs.get('id__in'): kwargs['id__in'] = ','.join(kwargs['id__in']) self.logger.debug('id__in fransformed to {}'.format(kwargs['id__in'])) r = requests.get(url, verify=self.config['ssl_verify'], headers=headers, params=kwargs) return {'raw': r.json()}
from st2actions.runners.pythonrunner import Action import requests __all__ = [ 'NetboxBaseAction' ] class NetboxBaseAction(Action): """Base Action for all Netbox API based actions """ def __init__(self, config): super(NetboxBaseAction, self).__init__(config) def get(self, endpoint_uri, **kwargs): """Make a get request to the API URI passed in """ self.logger.debug("Calling base get with kwargs: {}".format(kwargs)) if self.config['use_https']: url = 'https://' else: url = 'http://' url = url + self.config['hostname'] + endpoint_uri headers = { 'Authorization': 'Token ' + self.config['api_token'], 'Accept': 'application/json' } # transform `in__id` if present if kwargs.get('in__id'): kwargs['in__id'] = ','.join(kwargs['in__id']) self.logger.debug('in__id fransformed to {}'.format(kwargs['in__id'])) r = requests.get(url, verify=self.config['ssl_verify'], headers=headers, params=kwargs) return {'raw': r.json()}
mit
Python
b2b1cbebd26e82d7570e21f275fd279143125de7
Fix version in docs conf.
SectorLabs/pytest-benchmark,ionelmc/pytest-benchmark,aldanor/pytest-benchmark,thedrow/pytest-benchmark
docs/conf.py
docs/conf.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode', 'sphinxcontrib.napoleon' ] if os.getenv('SPELLCHECK'): extensions += 'sphinxcontrib.spelling', spelling_show_suggestions = True spelling_lang = 'en_US' source_suffix = '.rst' master_doc = 'index' project = u'pytest-benchmark' year = u'2014-2015' author = u'Ionel Cristian M\u0103rie\u0219' copyright = '{0}, {1}'.format(year, author) version = release = u'2.4.1' import sphinx_py3doc_enhanced_theme html_theme = "sphinx_py3doc_enhanced_theme" html_theme_path = [sphinx_py3doc_enhanced_theme.get_html_theme_path()] pygments_style = 'trac' templates_path = ['.'] html_use_smartypants = True html_last_updated_fmt = '%b %d, %Y' html_split_index = True html_sidebars = { '**': ['searchbox.html', 'globaltoc.html', 'sourcelink.html'], } html_short_title = '%s-%s' % (project, version) html_theme_options = { 'githuburl': 'https://github.com/ionelmc/pytest-benchmark/' }
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode', 'sphinxcontrib.napoleon' ] if os.getenv('SPELLCHECK'): extensions += 'sphinxcontrib.spelling', spelling_show_suggestions = True spelling_lang = 'en_US' source_suffix = '.rst' master_doc = 'index' project = u'pytest-benchmark' year = u'2014-2015' author = u'Ionel Cristian M\u0103rie\u0219' copyright = '{0}, {1}'.format(year, author) version = release = u'0.1.0' import sphinx_py3doc_enhanced_theme html_theme = "sphinx_py3doc_enhanced_theme" html_theme_path = [sphinx_py3doc_enhanced_theme.get_html_theme_path()] pygments_style = 'trac' templates_path = ['.'] html_use_smartypants = True html_last_updated_fmt = '%b %d, %Y' html_split_index = True html_sidebars = { '**': ['searchbox.html', 'globaltoc.html', 'sourcelink.html'], } html_short_title = '%s-%s' % (project, version) html_theme_options = { 'githuburl': 'https://github.com/ionelmc/pytest-benchmark/' }
bsd-2-clause
Python
a2d49d61718ac9c772ae620d26fdb2af13284f0b
update copyright year
desec-io/desec-stack,desec-io/desec-stack,desec-io/desec-stack,desec-io/desec-stack
docs/conf.py
docs/conf.py
try: import sphinx_rtd_theme except ImportError: sphinx_rtd_theme = None # Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # # import os # import sys # sys.path.insert(0, os.path.abspath('.')) # -- Project information ----------------------------------------------------- project = 'deSEC DNS API' copyright = '2021, deSEC e.V., Individual Contributors' author = 'deSEC e.V., Individual Contributors' # -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # if sphinx_rtd_theme: html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] else: html_theme = "default" # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] master_doc = 'index' if sphinx_rtd_theme: html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] else: html_theme = "default" html_static_path = ['_static'] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'deSEC.tex', u'deSEC DNS API Documentation', u'deSEC e.V., Individual Contributors', 'manual'), ]
try: import sphinx_rtd_theme except ImportError: sphinx_rtd_theme = None # Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # # import os # import sys # sys.path.insert(0, os.path.abspath('.')) # -- Project information ----------------------------------------------------- project = 'deSEC DNS API' copyright = '2020, deSEC e.V., Individual Contributors' author = 'deSEC e.V., Individual Contributors' # -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # if sphinx_rtd_theme: html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] else: html_theme = "default" # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] master_doc = 'index' if sphinx_rtd_theme: html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] else: html_theme = "default" html_static_path = ['_static'] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'deSEC.tex', u'deSEC DNS API Documentation', u'deSEC e.V., Individual Contributors', 'manual'), ]
mit
Python
3cd945aba394f1b094fa2e219a6f3db1704a770f
Change how we filter merges a bit.
Fifty-Nine/github_ebooks
Scraper.py
Scraper.py
from github import Github, GithubException import re tag_mutex = re.compile(r'^([\w\- ]+):(.*)$', re.UNICODE) class Scraper: def __init__(self, db): self.db = db api_key = db.getConfigValue('api_key') self.gh = Github(api_key) self.gh.per_page = 10 def _filterCommit(self, message): message = message.strip() return \ len(message) > 0 and \ message.find('Initial commit') < 0 and \ not message.startswith('Merge') and \ not tag_mutex.match(message) and \ message.find('#') < 0 def scrapeRepo(self, repo_name): return self._scrapeRepo(self.gh.get_repo(repo_name)) def _scrapeRepo(self, repo): count = 0 try: for commit in repo.get_commits(): sha = commit.sha message = commit.commit.message.strip() message = ' '.join(filter(self._filterCommit, message.split('\n'))) if len(message) > 0: print message self.db.addCommit(sha, message) count += 1 except GithubException as e: if e.status != 409 or e.message != u'Git Repository is empty.': raise e return count def scrapeUser(self, user_name): return self._scrapeUser(self.gh.get_user(user_name)) def _scrapeUser(self, user): count = 0 for repo in user.get_repos(): count += self._scrapeRepo(repo) return count def scrape(self, search): repos = self.gh.legacy_search_repos(keyword=search) count = 0 for repo in repos: count += self._scrapeRepo(repo) return count
from github import Github, GithubException from random import randint class Scraper: def __init__(self, db): self.db = db api_key = db.getConfigValue('api_key') self.gh = Github(api_key) self.gh.per_page = 10 def _filterCommit(self, message): message = message.strip() return \ len(message) > 0 and \ message.find('Initial commit') < 0 and \ message.find('Merge pull request') < 0 and \ not message.startswith('Signed-off-by') and \ message.find('#') < 0 def scrapeRepo(self, repo_name): return self._scrapeRepo(self.gh.get_repo(repo_name)) def _scrapeRepo(self, repo): count = 0 try: for commit in repo.get_commits(): sha = commit.sha message = commit.commit.message.strip() message = ' '.join(filter(self._filterCommit, message.split('\n'))) if len(message) > 0: print message self.db.addCommit(sha, message) count += 1 except GithubException as e: if e.status != 409 or e.message != u'Git Repository is empty.': raise e return count def scrapeUser(self, user_name): return self._scrapeUser(self.gh.get_user(user_name)) def _scrapeUser(self, user): count = 0 for repo in user.get_repos(): count += self._scrapeRepo(repo) return count def scrape(self, search): repos = self.gh.legacy_search_repos(keyword=search) count = 0 for repo in repos: count += self._scrapeRepo(repo) return count
mit
Python
fe651b4ef790d9e2c3d180347aaf7be103325102
update to 0.6.20
wjo1212/aliyun-log-python-sdk
aliyun/log/version.py
aliyun/log/version.py
__version__ = '0.6.20' USER_AGENT = 'log-python-sdk-v-' + __version__ API_VERSION = '0.6.0'
__version__ = '0.6.19' USER_AGENT = 'log-python-sdk-v-' + __version__ API_VERSION = '0.6.0'
mit
Python