commit
stringlengths
40
40
subject
stringlengths
1
3.25k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
old_contents
stringlengths
0
26.3k
lang
stringclasses
3 values
proba
float64
0
1
diff
stringlengths
0
7.82k
5a5900a5c0ab1e0ac41469770e3775faf482c21e
write TagField basic
tags/fields.py
tags/fields.py
Python
0.000004
@@ -0,0 +1,1201 @@ +#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0Afrom django.db.models.fields import CharField%0Afrom django.utils.translation import ugettext_lazy as _%0A%0Afrom tags.models import Tag%0A%0A%0Aclass TagField(CharField):%0A def __init__(self,%0A verbose_name=_(u'Tags'),%0A max_length=4000,%0A blank=True,%0A null=True,%0A help_text=_(u'A comma-separated list of tags.'),%0A **kwargs):%0A kwargs%5B'max_length'%5D = max_length%0A kwargs%5B'blank'%5D = blank%0A kwargs%5B'null'%5D = null%0A kwargs%5B'verbose_name'%5D = verbose_name%0A kwargs%5B'help_text'%5D = help_text%0A self.max_length = max_length%0A self.blank = blank%0A self.null = null%0A self.verbose_name = verbose_name%0A self.help_text = help_text%0A CharField.__init__(self, **kwargs)%0A%0A def pre_save(self, model_instance, add):%0A str_tags = getattr(model_instance, self.name)%0A if str_tags:%0A tags = set(str_tags.split(','))%0A for tag in tags:%0A Tag.objects.get_or_create(name=tag)%0A return ','.join(tags)%0A return super(TagField, self).pre_save(model_instance, add)%0A
11d2f5e649ef5c5aedec9723894cd29c1d4d81f4
Add missing migration
froide/document/migrations/0027_alter_document_content_hash.py
froide/document/migrations/0027_alter_document_content_hash.py
Python
0.0002
@@ -0,0 +1,434 @@ +# Generated by Django 3.2.4 on 2021-07-07 20:08%0A%0Afrom django.db import migrations, models%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('document', '0026_auto_20210603_1617'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterField(%0A model_name='document',%0A name='content_hash',%0A field=models.CharField(blank=True, editable=False, max_length=40, null=True),%0A ),%0A %5D%0A
36e3cb292b24d5940efed635c49bf5bb62007edb
Create __init__.py
acupoints/__init__.py
acupoints/__init__.py
Python
0.000011
@@ -0,0 +1 @@ +%0A
41631175c7aae124f7504f068d9c2f8cf1c9e617
Add exception to describe errors in configuration processing
plugins/configuration/configurationtype/configuration_error.py
plugins/configuration/configurationtype/configuration_error.py
Python
0
@@ -0,0 +1,1295 @@ +#!/usr/bin/env python%0A#-*- coding: utf-8 -*-%0A%0A#This software is distributed under the Creative Commons license (CC0) version 1.0. A copy of this license should have been distributed with this software.%0A#The license can also be read online: %3Chttps://creativecommons.org/publicdomain/zero/1.0/%3E. If this online license differs from the license provided with this software, the license provided with this software should be applied.%0A%0A%22%22%22%0ADefines a class of exceptions used to denote a false state of being for%0Aconfiguration.%0A%22%22%22%0A%0Aclass ConfigurationError(Exception):%0A%09%22%22%22%0A%09This exception denotes that something went wrong in the configuration.%0A%0A%09It is mostly a marker class, but also provides the type of configuration in%0A%09which something went wrong.%0A%09%22%22%22%0A%0A%09def __init__(self, message, configuration_type):%0A%09%09%22%22%22%0A%09%09Creates a new ConfigurationError.%0A%0A%09%09:param message: The message describing the error that occurred.%0A%09%09:param configuration_type: The configuration type with which the error%0A%09%09occurred.%0A%09%09%22%22%22%0A%09%09#Prepend the configuration type before the error message.%0A%09%09super(ConfigurationError, self).__init__(%22%7Bconfiguration_type%7D: %7Bmessage%7D%22.format(configuration_type=configuration_type, message=message))%0A%09%09self.configuration_type = configuration_type #Also store it here for debugging purposes.
a857273666cb616e1c019bedff81d3014070c896
increase Proofread of Henochbuch
scripts/online_scripts/150916_increase_proofread_Henochbuch.py
scripts/online_scripts/150916_increase_proofread_Henochbuch.py
Python
0
@@ -0,0 +1,481 @@ +# -*- coding: utf-8 -*-%0A__author__ = 'eso'%0Aimport sys%0Asys.path.append('../../')%0Afrom tools.catscan import CatScan%0Aimport re%0Aimport requests%0Aimport pywikibot%0Afrom pywikibot import proofreadpage%0A%0Asite = pywikibot.Site()%0A%0Afor i in range(455, 474):%0A page = pywikibot.proofreadpage.ProofreadPage(site, 'Seite:Riessler Altjuedisches Schrifttum ausserhalb der Bibel %7B%7D.jpg'.format(i))%0A print(page.status)%0A page._full_header.user = 'THEbotIT'%0A page.proofread()%0A page.save()%0A
29179bd9a9aa1dafa2dce08dee0339fd5d320238
add similar processes to test config, one of them matching name, and the other exe
src/collectors/processmemory/test/testprocessmemory.py
src/collectors/processmemory/test/testprocessmemory.py
#!/usr/bin/python # coding=utf-8 ################################################################################ from test import CollectorTestCase from test import get_collector_config from test import unittest from mock import patch, Mock from diamond.collector import Collector from processmemory import ProcessMemoryCollector ################################################################################ class TestProcessMemoryCollector(CollectorTestCase): TEST_CONFIG = { 'interval': 10, 'process': { 'postgres': { 'exe': '^\/usr\/lib\/postgresql\/+d.+d\/bin\/postgres', 'name': ['postgres', 'pg'], }, 'foo': { 'exe': '^foobar', }, } } def setUp(self): config = get_collector_config('ProcessMemoryCollector', self.TEST_CONFIG) self.collector = ProcessMemoryCollector(config, None) @patch.object(Collector, 'publish') def test(self, publish_mock): process_info_list = [ # postgres processes {'exe': '/usr/lib/postgresql/9.1/bin/postgres', 'name': 'postgres', 'pid': 1427, 'rss': 9875456, 'vms': 106852352}, {'name': 'postgres: writer process ', 'pid': 1445, 'rss': 1753088, 'vms': 106835968}, {'name': 'postgres: wal writer process ', 'pid': 1446, 'rss': 1503232, 'vms': 106835968}, {'name': 'postgres: autovacuum launcher process ', 'pid': 1447, 'rss': 3989504, 'vms': 109023232}, {'name': 'postgres: stats collector process ', 'pid': 1448, 'rss': 2400256, 'vms': 75829248}, # postgres-y process {'name': 'posgre: not really', 'pid': 9999, 'rss': 999999999999, 'vms': 999999999999, }, ] class ProcessMock: def __init__(self, pid, name, rss, vms, exe=None): self.pid = pid self.name = name self.rss = rss self.vms = vms if exe is not None: self.exe = exe def get_memory_info(self): class MemInfo: def __init__(self, rss, vms): self.rss = rss self.vms = vms return MemInfo(self.rss, self.vms) process_iter_mock = (ProcessMock( pid=x['pid'], name=x['name'], rss=x['rss'], vms=x['vms'], exe=x['exe']) if 'exe' in x else ProcessMock(pid=x['pid'], name=x['name'], rss=x['rss'], vms=x['vms'], exe='') for x in process_info_list) with patch('psutil.process_iter', return_value=process_iter_mock): self.collector.collect() self.assertPublished(publish_mock, 'postgres.rss', 9875456+1753088+1503232+3989504+2400256) self.assertPublished(publish_mock, 'postgres.vms', 106852352+106835968+106835968+109023232+ 75829248) self.assertPublished(publish_mock, 'foo.rss', 0) self.assertPublished(publish_mock, 'foo.vms', 0) ################################################################################ if __name__ == "__main__": unittest.main()
Python
0
@@ -747,32 +747,168 @@ %0A %7D,%0A + 'bar': %7B%0A 'name': '%5Ebar',%0A %7D,%0A 'barexe': %7B%0A 'exe': 'bar$'%0A %7D%0A %7D%0A %7D%0A @@ -897,24 +897,24 @@ %7D%0A %7D%0A - %7D%0A%0A d @@ -2188,32 +2188,358 @@ %0A %7D,%0A + # bar process%0A %7B'name': 'bar',%0A 'exe': '/usr/bin/foo',%0A 'pid': 9998,%0A 'rss': 1,%0A 'vms': 1%0A %7D,%0A %7B'exe': '/usr/bin/bar',%0A 'name': '',%0A 'pid': 9998,%0A 'rss': 10,%0A 'vms': 10,%0A %7D,%0A %5D%0A%0A @@ -4124,18 +4124,79 @@ k, ' -foo.vm +bar.rss', 1)%0A self.assertPublished(publish_mock, 'barexe.rs s', +1 0)%0A%0A
1d75b7e0bd0c498b5ea2c32c4e98a278ca2aed1b
make sitelockdown generic
src/python/expedient/common/middleware/sitelockdown.py
src/python/expedient/common/middleware/sitelockdown.py
Python
0
@@ -0,0 +1,1241 @@ +'''%0A@author jnaous%0A'''%0Afrom django.conf import settings%0Afrom django.http import HttpResponseRedirect%0Afrom utils import RegexMatcher%0A%0Aclass SiteLockDown(RegexMatcher):%0A %22%22%22%0A This middleware class will force almost every request coming from%0A Django to be authenticated, or it will redirect the user to a login%0A page. Some urls can be excluded by specifying their regexes in the%0A C%7BSITE_LOCKDOWN_EXCEPTIONS%7D tuple in the settings.%0A %0A Hints from: http://davyd.livejournal.com/262859.html%0A %22%22%22%0A def __init__(self):%0A super(SiteLockDown, self).__init__(%22SITE_LOCKDOWN_EXCEPTIONS%22)%0A %0A def process_request (self, request):%0A try:%0A request.django_root%0A except AttributeError:%0A request.django_root = ''%0A%0A login_url = settings.LOGIN_URL + '?next=%25s' %25 request.path%0A%0A if request.path.startswith(request.django_root):%0A path = request.path%5Blen(request.django_root):%5D%0A else:%0A return HttpResponseRedirect (login_url)%0A %0A if not request.user.is_authenticated () and not %5C%0A (path == settings.LOGIN_URL or%0A self.matches(path)%0A ):%0A return HttpResponseRedirect (login_url)%0A%0A return None%0A
4f8fff9fb2da7bbdab68a0a4c02b51d00410e8c4
Add synthtool scripts (#3765)
java-automl/google-cloud-automl/synth.py
java-automl/google-cloud-automl/synth.py
Python
0.000001
@@ -0,0 +1,1225 @@ +# Copyright 2018 Google LLC%0A#%0A# Licensed under the Apache License, Version 2.0 (the %22License%22);%0A# you may not use this file except in compliance with the License.%0A# You may obtain a copy of the License at%0A#%0A# http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS,%0A# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A# See the License for the specific language governing permissions and%0A# limitations under the License.%0A%0A%22%22%22This script is used to synthesize generated parts of this library.%22%22%22%0A%0Aimport synthtool as s%0Aimport synthtool.gcp as gcp%0A%0Agapic = gcp.GAPICGenerator()%0Acommon_templates = gcp.CommonTemplates()%0A%0Alibrary = gapic.java_library(%0A service='automl',%0A version='v1beta1',%0A config_path='artman_automl_v1beta1.yaml',%0A artman_output_name='')%0A%0As.copy(library / 'gapic-google-cloud-automl-v1beta1/src', 'src')%0As.copy(library / 'grpc-google-cloud-automl-v1beta1/src', '../../google-api-grpc/grpc-google-cloud-automl-v1beta1/src')%0As.copy(library / 'proto-google-cloud-automl-v1beta1/src', '../../google-api-grpc/proto-google-cloud-automl-v1beta1/src')%0A
c7987bde28992ef0ae8cae9fca500730b2fcea15
Add url rewriter for eztv
flexget/plugins/urlrewrite_eztv.py
flexget/plugins/urlrewrite_eztv.py
Python
0
@@ -0,0 +1,1913 @@ +from __future__ import unicode_literals, division, absolute_import%0Aimport re%0Aimport logging%0Afrom urlparse import urlparse, urlunparse%0Afrom requests import RequestException%0A%0Afrom flexget import plugin%0Afrom flexget.event import event%0Afrom flexget.plugins.plugin_urlrewriting import UrlRewritingError%0Afrom flexget.utils import requests%0Afrom flexget.utils.soup import get_soup%0A%0Alog = logging.getLogger('eztv')%0A%0AEZTV_MIRRORS = %5B%0A ('http', 'eztv.it'),%0A ('https', 'eztv-proxy.net'),%0A ('http', 'eztv.come.in')%5D%0A%0A%0Aclass UrlRewriteEztv(object):%0A %22%22%22Eztv url rewriter.%22%22%22%0A%0A def url_rewritable(self, task, entry):%0A return urlparse(entry%5B'url'%5D).netloc == 'eztv.it'%0A%0A def url_rewrite(self, task, entry):%0A url = entry%5B'url'%5D%0A for (scheme, netloc) in EZTV_MIRRORS:%0A try:%0A _, _, path, params, query, fragment = urlparse(url)%0A url = urlunparse((scheme, netloc, path, params, query, fragment))%0A page = requests.get(url).content%0A except RequestException as e:%0A log.debug('Eztv mirror %60%25s%60 seems to be down', url)%0A continue%0A break%0A%0A if not page:%0A raise UrlRewritingError('No mirrors found for url %25s' %25 entry%5B'url'%5D)%0A%0A log.debug('Eztv mirror %60%25s%60 chosen', url)%0A try:%0A soup = get_soup(page)%0A mirrors = soup.find('a', attrs=%7B'class': re.compile(r'download_%5Cd')%7D)%0A if not mirrors:%0A raise UrlRewritingError('Unable to locate download link from url %25s'%0A %25 url)%0A entry%5B'urls'%5D = %5Bm.get('href') for m in mirrors%5D%0A entry%5B'url'%5D = mirrors%5B0%5D.get('href')%0A except Exception as e:%0A raise UrlRewritingError(e)%0A%0A%0A@event('plugin.register')%0Adef register_plugin():%0A plugin.register(UrlRewriteEztv, 'eztv', groups=%5B'urlrewriter'%5D, api_ver=2)%0A
dc48c6068f04d007ab5ab318cd73783ae83464be
Fix error when trying a crash on a signature without proposed new signature
FTB/Signatures/CrashSignature.py
FTB/Signatures/CrashSignature.py
''' Crash Signature Represents a crash signature as specified in https://wiki.mozilla.org/Security/CrashSignatures @author: Christian Holler (:decoder) @license: This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. @contact: choller@mozilla.com ''' import json import difflib from FTB.Signatures import JSONHelper from FTB.Signatures.Symptom import Symptom, TestcaseSymptom, StackFramesSymptom import FTB.Signatures class CrashSignature(): def __init__(self, rawSignature): ''' Constructor @type rawSignature: string @param rawSignature: A JSON-formatted string representing the crash signature ''' # For now, we store the original raw signature and hand it out for # conversion to String. This is fine as long as our Signature object # is immutable. Later, we should implement a method that actually # serializes this object back to JSON as it is. # self.rawSignature = rawSignature self.symptoms = [] try: obj = json.loads(rawSignature) except ValueError, e: raise RuntimeError("Invalid JSON: %s" % e) # Get the symptoms objects (mandatory) if "symptoms" in obj: symptoms = JSONHelper.getArrayChecked(obj, "symptoms", True) if len(symptoms) == 0: raise RuntimeError("Signature must have at least one symptom.") for rawSymptomsObj in symptoms: self.symptoms.append(Symptom.fromJSONObject(rawSymptomsObj)) else: raise RuntimeError('Missing mandatory top-level key "symptoms".') # Get some optional lists self.platforms = JSONHelper.getArrayChecked(obj, "platforms") self.operatingSystems = JSONHelper.getArrayChecked(obj, "operatingSystems") self.products = JSONHelper.getArrayChecked(obj, "products") @staticmethod def fromFile(signatureFile): with open(signatureFile, 'r') as sigFd: return CrashSignature(sigFd.read()) def __str__(self): return self.rawSignature def matches(self, crashInfo): ''' Match this signature against the given crash information @type crashInfo: CrashInfo @param crashInfo: The crash info to match the signature against @rtype: bool @return: True if the signature matches, False otherwise ''' if self.platforms != None and not crashInfo.platform in self.platforms: return False if self.operatingSystems != None and not crashInfo.os in self.operatingSystems: return False if self.products != None and not crashInfo.product in self.products: return False for symptom in self.symptoms: if not symptom.matches(crashInfo): return False return True def matchRequiresTest(self): ''' Check if the signature requires a testcase to match. This method can be used to avoid attaching a testcase to the crashInfo before matching, avoiding unnecessary I/O on testcase files. @rtype: bool @return: True if the signature requires a testcase to match ''' for symptom in self.symptoms: if isinstance(symptom, TestcaseSymptom): return True return False def getDistance(self, crashInfo): distance = 0 for symptom in self.symptoms: if isinstance(symptom, StackFramesSymptom): symptomDistance = symptom.diff(crashInfo)[0] if symptomDistance != None: distance += symptomDistance else: # If we can't find the distance, assume worst-case distance += len(symptom.functionNames) else: if not symptom.matches(crashInfo): distance +=1 return distance def fit(self, crashInfo): sigObj = {} sigSymptoms = [] sigObj['symptoms'] = sigSymptoms if self.platforms: sigObj['platforms'] = self.platforms if self.operatingSystems: sigObj['operatingSystems'] = self.operatingSystems if self.products: sigObj['products'] = self.products symptomsDiff = self.getSymptomsDiff(crashInfo) for symptomDiff in symptomsDiff: if symptomDiff['offending']: if 'proposed' in symptomDiff: sigSymptoms.append(symptomDiff['proposed'].jsonobj) else: sigSymptoms.append(symptomDiff['symptom'].jsonobj) if not sigSymptoms: return None return CrashSignature(json.dumps(sigObj, indent=2)) def getSymptomsDiff(self, crashInfo): symptomsDiff = [] for symptom in self.symptoms: if symptom.matches(crashInfo): symptomsDiff.append({ 'offending' : False, 'symptom' : symptom }) else: # Special-case StackFramesSymptom because we would like to get a fine-grained # view on the offending parts *inside* that symptom. By calling matchWithDiff, # we annotate internals of the symptom with distance information to display. if isinstance(symptom, StackFramesSymptom): proposedSymptom = symptom.diff(crashInfo)[1] if proposedSymptom: symptomsDiff.append({ 'offending' : True, 'symptom' : symptom, 'proposed' : proposedSymptom }) continue symptomsDiff.append({ 'offending' : True, 'symptom' : symptom }) return symptomsDiff def getSignatureUnifiedDiffTuples(self, crashInfo): diffTuples = [] newRawCrashSignature = self.fit(crashInfo) oldLines = self.rawSignature.splitlines() newLines = newRawCrashSignature.rawSignature.splitlines() context = max(len(oldLines),len(newLines)) signatureDiff = difflib.unified_diff(oldLines, newLines, n=context) for diffLine in signatureDiff: if diffLine.startswith('+++') or diffLine.startswith('---') or diffLine.startswith('@@') or not diffLine.strip(): continue diffTuples.append((diffLine[0],diffLine[1:])) return diffTuples
Python
0.000002
@@ -6367,16 +6367,75 @@ wLines = + %5B%5D%0A if newRawCrashSignature:%0A newLines = newRawC
c60b152573ccfe01997f3d970968180ac82af8ba
Add forgotten migration
bluebottle/funding_stripe/migrations/0014_auto_20190916_1645.py
bluebottle/funding_stripe/migrations/0014_auto_20190916_1645.py
Python
0.000004
@@ -0,0 +1,491 @@ +# -*- coding: utf-8 -*-%0A# Generated by Django 1.11.15 on 2019-09-16 14:45%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations, models%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('funding_stripe', '0013_auto_20190913_1458'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterField(%0A model_name='stripepayoutaccount',%0A name='document_type',%0A field=models.CharField(blank=True, max_length=20),%0A ),%0A %5D%0A
7d6932a07caed84c424f62ab8d980fde7eddeaed
Create lc375.py
LeetCode/lc375.py
LeetCode/lc375.py
Python
0.000001
@@ -0,0 +1,578 @@ +class Solution(object):%0A def getMoneyAmount(self, n):%0A %22%22%22%0A :type n: int%0A :rtype: int%0A %22%22%22%0A dp = %5B%5B0 for x in range(n+1)%5D for y in range(n+1)%5D%0A for i in range(2,n+1):%0A for x in range(n):%0A if x + i %3E n:%0A break%0A dp%5Bx%5D%5Bx+i%5D = x+1 + dp%5Bx+1%5D%5Bx+i%5D%0A for j in range(x+1, x+i):%0A tmp = max(dp%5Bx%5D%5Bj%5D, dp%5Bj+1%5D%5Bx+i%5D) + (j+1)%0A if tmp %3C dp%5Bx%5D%5Bx+i%5D:%0A dp%5Bx%5D%5Bx+i%5D = tmp%0A print(dp%5B0%5D)%0A return dp%5B0%5D%5Bn%5D%0A
74d718b19ec49c0ca4c724533af1ec725003adef
remove emtry transtion of region
cities_light/management/commands/region_missing_translations.py
cities_light/management/commands/region_missing_translations.py
Python
0.001989
@@ -0,0 +1,445 @@ +from django.core.management.base import BaseCommand%0A%0A%0Aclass Command(BaseCommand):%0A%0A def handle(self, *args, **options):%0A from cities_light import Region%0A for item in Region.published.all():%0A if not item.translations.all():%0A obj = item.translate(item.default_language)%0A obj.name = %22no region name given%22%0A obj.display_name = %22no region name given%22%0A obj.save()
b09bfaa7a9f9bed7f3d19176cd67b83031347872
Largest prime factor
p3.py
p3.py
Python
0.999936
@@ -0,0 +1,673 @@ +# Find the largest prime factor of a positive (composite) number%0A%0Adef prime_factors(n):%0A factors = %5B%5D%0A d = 2%0A while n %3E 1:%0A while n %25 d == 0:%0A factors.append(d)%0A n /= d%0A d = d + 1%0A return factors%0A%0Apfs = prime_factors(600851475143)%0Alargest_prime_factor = max(pfs) %0Alargest_prime_factor # output: 6857%0A%0A# Optimize: increase factor with 2 every step%0A%0An = input(%22the evil big number: %22)%0AlastFactor = 1%0Awhile n %25 2 == 0:%0A lastFactor = 2%0A n = n / 2%0Aif lastFactor != 2:%0A lastFactor = 1%0Afactor = 3%0Awhile n %3E 1:%0A while n %25 factor == 0:%0A lastFactor = factor%0A n = n / factor%0A factor = factor + 2%0AlastFactor%0A
1fff4fb083e2ac0dad8d8a3ac59fc68ef2939073
required drilldown*s* not singular
cubes/backends/mixpanel/store.py
cubes/backends/mixpanel/store.py
# -*- coding=utf -*- from ...model import * from ...browser import * from ...stores import Store from ...errors import * from .mixpanel import * from string import capwords DIMENSION_COUNT_LIMIT = 100 time_dimension_md = { "name": "time", "levels": ["year", "month", "day", "hour"], "hierarchies": [ {"name":"mdh", "levels": ["year", "month", "day", "hour"]} ], "info": { "is_date": True } } _time_dimension = create_dimension(time_dimension_md) class MixpanelModelProvider(ModelProvider): def cube(self, name): """Creates a mixpanel cube with following variables: * `name` – cube name * `measures` – cube measures: `total` and `uniques` * `required_dimensions` – list of required dimension names * `mappings` – mapping of corrected dimension names Dimensions are Mixpanel's properties where ``$`` character is replaced by the underscore ``_`` character. """ result = self.store.request(["events", "properties", "top"], {"event":name, "limit":DIMENSION_COUNT_LIMIT}) if not result: raise NoSuchCubeError(name) names = result.keys() # Replace $ with underscore _ dims = ["time"] mappings = {} for dim_name in result.keys(): fixed_name = dim_name.replace("$", "_") if fixed_name != dim_name: mappings[fixed_name] = dim_name dims.append(fixed_name) measures = attribute_list(["total", "unique"]) for m in measures: m.aggregations = ['identity'] cube = Cube(name=name, measures=measures, required_dimensions=dims, store=self.store_name, mappings=mappings) # TODO: this is new (remove this comment) cube.category = self.store.category # TODO: required_drilldown might be a cube's attribute (fixed_dd?) cube.info = { "required_drilldown": "time", "category": cube.category } return cube def dimension(self, name): if name == "time": return _time_dimension level = Level(name, attribute_list([name])) dim = Dimension(name, levels=[level]) return dim def list_cubes(self): result = self.store.request(["events", "names"], {"type":"general", }) cubes = [] for name in result: label = capwords(name.replace("_", " ")) cube = { "name": name, "label": label, "category": self.store.category, "info": { "category": self.store.category } } cubes.append(cube) return cubes class MixpanelStore(Store): def __init__(self, api_key, api_secret, category=None): self.mixpanel = Mixpanel(api_key, api_secret) self.category = category or "Mixpanel" def model_provider_name(self): return "mixpanel" def request(self, *args, **kwargs): """Performs a mixpanel HTTP request. Raises a BackendError when mixpanel returns `error` in the response.""" response = self.mixpanel.request(*args, **kwargs) if "error" in response: raise BackendError("Mixpanel request error: %s" % response["error"]) return response
Python
0.99897
@@ -1946,16 +1946,17 @@ rilldown +s might b @@ -2049,25 +2049,28 @@ rilldown +s %22: +%5B %22time%22 +%5D ,%0A
e20002febd14a2f6d31b43ee85d57bfa26c745e5
test game/board.py
yaranullin/game/tests/board.py
yaranullin/game/tests/board.py
Python
0
@@ -0,0 +1,1792 @@ +# yaranullin/game/tests/board.py%0A#%0A# Copyright (c) 2012 Marco Scopesi %3Cmarco.scopesi@gmail.com%3E%0A#%0A# Permission to use, copy, modify, and distribute this software for any%0A# purpose with or without fee is hereby granted, provided that the above%0A# copyright notice and this permission notice appear in all copies.%0A#%0A# THE SOFTWARE IS PROVIDED %22AS IS%22 AND THE AUTHOR DISCLAIMS ALL WARRANTIES%0A# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF%0A# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR%0A# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES%0A# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN%0A# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF%0A# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.%0A%0Aimport unittest%0Aimport sys%0A%0Aif __name__ == '__main__':%0A sys.path.insert(0, %22.%22)%0A%0Afrom yaranullin.game.board import Board%0A%0A%0Aclass TestBoard(unittest.TestCase):%0A%0A def setUp(self):%0A self.size = (100, 200)%0A self.name = 'Test dungeon'%0A self.board = Board(self.name, self.size)%0A%0A def test_create_pawn(self):%0A pos = 3, 4%0A size = 5, 6%0A pawn = self.board.create_pawn('Dragon', 35, pos, size)%0A self.assertIn(pawn.name, self.board.pawns)%0A self.assertIs(pawn, self.board.pawns%5Bpawn.name%5D)%0A self.assertIn(pawn, self.board.initiatives)%0A%0A def del_pawn(self):%0A pos = 3, 4%0A size = 5, 6%0A self.board.create_pawn('Dragon', 35, pos, size)%0A pawn = self.board.del_pawn('Dragon')%0A self.assertNotIn(pawn.name, self.board.pawns)%0A self.assertIsNot(pawn, self.board.pawns%5Bpawn.name%5D)%0A self.assertNotIn(pawn, self.board.initiatives)%0A%0A%0A%0Aif __name__ == '__main__':%0A unittest.main()%0A
d3f556b6d7da2c67fc9dcc6b7d73a0d1b76d278c
Add tests for valid recipes
tests/functional_tests/test_valid_recipes.py
tests/functional_tests/test_valid_recipes.py
Python
0.000001
@@ -0,0 +1,1032 @@ +import os%0A%0Aimport pytest%0A%0Afrom conda_verify import utils%0Afrom conda_verify.exceptions import RecipeError%0Afrom conda_verify.verify import Verify%0A%0A%0A@pytest.fixture%0Adef recipe_dir():%0A return os.path.join(os.path.dirname(__file__), 'test-recipes')%0A%0A%0A@pytest.fixture%0Adef verifier():%0A recipe_verifier = Verify()%0A return recipe_verifier%0A%0A%0Adef test_valid_recipe_named_icu(recipe_dir, verifier):%0A recipe = os.path.join(recipe_dir, 'icu')%0A metadata = utils.render_metadata(recipe, None)%0A%0A try:%0A verifier.verify_recipe(pedantic=False, rendered_meta=metadata,%0A recipe_dir=recipe)%0A except RecipeError as error:%0A pytest.fail(error)%0A%0A%0Adef test_valid_test_file(recipe_dir, verifier):%0A recipe = os.path.join(recipe_dir, 'valid_test_file')%0A metadata = utils.render_metadata(recipe, None)%0A%0A try:%0A verifier.verify_recipe(pedantic=False, rendered_meta=metadata,%0A recipe_dir=recipe)%0A except RecipeError as error:%0A pytest.fail(error)%0A
40f4bc4602da9f66c08a6ee7dcdb3af71e891441
Create Python1.py
Python1.py
Python1.py
Python
0.999934
@@ -0,0 +1,84 @@ +#!/usr/bin/env python%0Adef main():%0A%09print('hello world')%0Aprint '------------'%0Amain()%0A
1de7573b08274646d961e7a667ed48aff5ca2932
return export path from Rule.do_build()
peru/rule.py
peru/rule.py
import os import subprocess from .cache import compute_key from .error import PrintableError class Rule: def __init__(self, name, build_command, export): self.name = name self.build_command = build_command self.export = export def cache_key(self, resolver, input_tree): return compute_key({ "input_tree": input_tree, "build": self.build_command, "export": self.export, }) def do_build(self, path): if not self.build_command: return try: subprocess.check_call(self.build_command, shell=True, cwd=path) except subprocess.CalledProcessError as e: raise PrintableError("Error in build command: " + str(e)) def get_tree(self, cache, resolver, input_tree): key = self.cache_key(resolver, input_tree) if key in cache.keyval: return cache.keyval[key] with cache.tmp_dir() as tmp_dir: cache.export_tree(input_tree, tmp_dir) self.do_build(tmp_dir) export_dir = tmp_dir if self.export: export_dir = os.path.join(tmp_dir, self.export) if not os.path.exists(export_dir): raise RuntimeError( "export dir '{}' doesn't exist".format(self.export)) tree = cache.import_tree(export_dir) cache.keyval[key] = tree return tree
Python
0
@@ -492,22 +492,86 @@ -if not +%22%22%22Executes the rule and returns the exported directory.%22%22%22%0A if self.bu @@ -599,28 +599,17 @@ -return%0A try:%0A + @@ -688,16 +688,20 @@ + + except s @@ -735,16 +735,20 @@ r as e:%0A + @@ -813,143 +813,136 @@ e))%0A -%0A + -def get_tree(self, cache, resolver, input_tree):%0A key = self.cache_key(resolver, input_tree)%0A if key in cache.keyval + if self.export:%0A export_path = os.path.join(path, self.export)%0A if not os.path.exists(export_path) :%0A @@ -955,161 +955,248 @@ + -return cache.keyval%5Bkey%5D%0A%0A with cache.tmp_dir() as tmp_dir:%0A cache.export_tree(input_tree, tmp_dir)%0A self.do_build(tmp_dir)%0A + raise PrintableError(%0A %22export path for rule '%7B%7D' does not exist: %7B%7D%22.format(%0A self.name, export_path))%0A if not os.path.isdir(export_path):%0A raise PrintableError(%0A @@ -1207,56 +1207,114 @@ + %22 export -_dir = tmp_dir%0A if self.export: + path for rule '%7B%7D' is not a directory: %7B%7D%22%0A .format(self.name, export_path)) %0A @@ -1322,27 +1322,30 @@ - +return export_ dir = os @@ -1340,203 +1340,364 @@ ort_ -dir = os.path.join(tmp_dir, self.export)%0A if not os.path.exists(export_dir):%0A raise RuntimeError(%0A %22export dir '%7B%7D' doesn't exist%22.format(self.export) +path%0A else:%0A return path%0A%0A def get_tree(self, cache, resolver, input_tree):%0A key = self.cache_key(resolver, input_tree)%0A if key in cache.keyval:%0A return cache.keyval%5Bkey%5D%0A%0A with cache.tmp_dir() as tmp_dir:%0A cache.export_tree(input_tree, tmp_dir)%0A export_dir = self.do_build(tmp_dir )%0A
729bed3fd3e7bd3ecabda3ab25525019f3f83661
Add py-imageio for python3 (#8553)
var/spack/repos/builtin/packages/py-imageio/package.py
var/spack/repos/builtin/packages/py-imageio/package.py
Python
0.000001
@@ -0,0 +1,2135 @@ +##############################################################################%0A# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.%0A# Produced at the Lawrence Livermore National Laboratory.%0A#%0A# This file is part of Spack.%0A# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.%0A# LLNL-CODE-647188%0A#%0A# For details, see https://github.com/spack/spack%0A# Please also see the NOTICE and LICENSE files for our notice and the LGPL.%0A#%0A# This program is free software; you can redistribute it and/or modify%0A# it under the terms of the GNU Lesser General Public License (as%0A# published by the Free Software Foundation) version 2.1, February 1999.%0A#%0A# This program is distributed in the hope that it will be useful, but%0A# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF%0A# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and%0A# conditions of the GNU Lesser General Public License for more details.%0A#%0A# You should have received a copy of the GNU Lesser General Public%0A# License along with this program; if not, write to the Free Software%0A# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA%0A##############################################################################%0Afrom spack import *%0A%0A%0Aclass PyImageio(PythonPackage):%0A %22%22%22 Imageio is a Python library that provides an easy interface%0A to read and write a wide range of image data, including animated%0A images, video, volumetric data, and scientific formats. It is%0A cross-platform, runs on Python 2.7 and 3.4+, and is easy to install.%22%22%22%0A%0A homepage = %22http://imageio.github.io/%22%0A url = %22https://pypi.io/packages/source/i/imageio/imageio-2.3.0.tar.gz%22%0A%0A version('2.3.0', '4722c4e1c366748abcb18729881cffb8')%0A%0A # TODO: Add variants for plugins, and optional dependencies%0A%0A # Fix for python 2 if needed.%0A depends_on('py-numpy', type=('build', 'run'))%0A depends_on('py-pillow', type=('build', 'run'))%0A depends_on('python@2.7:2.8,3.4:', type=('build', 'run'))%0A depends_on('py-setuptools', type='build')%0A depends_on('ffmpeg', type='run')%0A
1cb2855054c40e6de7c6f9bf8efb7c8331009ca8
add new package (#24702)
var/spack/repos/builtin/packages/py-iso8601/package.py
var/spack/repos/builtin/packages/py-iso8601/package.py
Python
0
@@ -0,0 +1,554 @@ +# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other%0A# Spack Project Developers. See the top-level COPYRIGHT file for details.%0A#%0A# SPDX-License-Identifier: (Apache-2.0 OR MIT)%0A%0Afrom spack import *%0A%0A%0Aclass PyIso8601(PythonPackage):%0A %22%22%22Simple module to parse ISO 8601 dates%22%22%22%0A%0A homepage = %22https://pyiso8601.readthedocs.io/en/latest/%22%0A pypi = %22iso8601/iso8601-0.1.14.tar.gz%22%0A%0A version('0.1.14', sha256='8aafd56fa0290496c5edbb13c311f78fa3a241f0853540da09d9363eae3ebd79')%0A%0A depends_on('py-setuptools', type='build')%0A
ace0f80344519a747a71e09faca46c05594dd0d9
Add examples/req_rep.py
examples/req_rep.py
examples/req_rep.py
Python
0
@@ -0,0 +1,1795 @@ +#!env/bin/python%0A%0A%22%22%22%0AExample txzmq client.%0A%0A examples/req_rep.py --method=connect --endpoint=ipc:///tmp/req_rep_sock --mode=req%0A%0A examples/req_rep.py --method=bind --endpoint=ipc:///tmp/req_rep_sock --mode=rep%0A%22%22%22%0Aimport os%0Aimport socket%0Aimport sys%0Aimport time%0Aimport zmq%0Afrom optparse import OptionParser%0A%0Afrom twisted.internet import reactor%0A%0Arootdir = os.path.realpath(os.path.join(os.path.dirname(sys.argv%5B0%5D), '..'))%0Asys.path.insert(0, rootdir)%0Aos.chdir(rootdir)%0A%0Afrom txzmq import ZmqEndpoint, ZmqFactory, ZmqREQConnection, ZmqREPConnection%0A%0A%0Aparser = OptionParser(%22%22)%0Aparser.add_option(%22-m%22, %22--method%22, dest=%22method%22, help=%220MQ socket connection: bind%7Cconnect%22)%0Aparser.add_option(%22-e%22, %22--endpoint%22, dest=%22endpoint%22, help=%220MQ Endpoint%22)%0Aparser.add_option(%22-M%22, %22--mode%22, dest=%22mode%22, help=%22Mode: req%7Crep%22)%0Aparser.set_defaults(method=%22connect%22, endpoint=%22ipc:///tmp/txzmq-pc-demo%22)%0A%0A(options, args) = parser.parse_args()%0A%0Azf = ZmqFactory()%0Ae = ZmqEndpoint(options.method, options.endpoint)%0A%0Aif options.mode == %22req%22:%0A s = ZmqREQConnection(zf, e)%0A%0A def produce():%0A # data = %5Bstr(time.time()), socket.gethostname()%5D%0A data = str(time.time())%0A%0A print %22Requesting %25r%22 %25 data%0A try:%0A d = s.sendMsg(data)%0A%0A def doPrint(reply):%0A print(%22Got reply: %25s%22 %25 (reply))%0A%0A d.addCallback(doPrint)%0A%0A except zmq.error.Again:%0A print %22Skipping, no pull consumers...%22%0A%0A reactor.callLater(1, produce)%0A%0A reactor.callWhenRunning(reactor.callLater, 1, produce)%0Aelse:%0A s = ZmqREPConnection(zf, e)%0A%0A def doPrint(messageId, message):%0A print %22Replying to %25s, %25r%22 %25 (messageId, message)%0A s.reply(messageId, %22%25s %25r %22 %25 (messageId, message))%0A%0A s.gotMessage = doPrint%0A%0Areactor.run()%0A
05a2a8115ae5bcab8e4980520327120111ca260a
Fix dupe add logic re: unreleased
fabric/changelog.py
fabric/changelog.py
import docutils import ipdb class issue(docutils.nodes.Element): @property def type(self): return self['type_'] @property def backported(self): return self['backported'] @property def number(self): return self.get('number', None) class release(docutils.nodes.Element): @property def number(self): return self['number'] def get_line(obj): # 1.2.7 -> 1.2 return '.'.join(obj.number.split('.')[:-1]) def construct_releases(entries): # Walk from back to front, consuming entries & copying them into # per-release buckets as releases are encountered. Store releases in order. releases = [] lines = {'unreleased': []} for obj in reversed(entries): # The 'actual' intermediate object we want to focus on is wrapped first # in a LI, then a P. focus = obj[0][0] # Releases 'eat' the entries in their line's list and get added to the # final data structure. They also inform new release-line 'buffers'. if isinstance(focus, release): line = get_line(focus) # New release line/branch detected. Create it & dump unreleased into # this new release. if line not in lines: lines[line] = [] releases.append({ 'obj': focus, 'entries': lines['unreleased'] }) lines['unreleased'] = [] # Existing line -> empty out its bucket into new release else: releases.append({ 'obj': focus, 'entries': lines[line] }) lines[line] = [] # Entries get copied into release line buckets as follows: # * Everything goes into 'unreleased' so it can be used in new lines. # * Bugfixes (but not support or feature entries) go into all release # lines, not just 'unreleased'. # * However, support/feature entries marked as 'backport' go into all # release lines as well, on the assumption that they were released to # all active branches. else: # Handle rare-but-valid non-issue-attached line items, which are # always bugs. if not isinstance(focus, issue): focus = issue(type_='bug', nodelist=[focus], backported=False) # Add all to unreleased, add bugs to others too lines['unreleased'].append(focus) if focus.type == 'bug' or focus.backported: for line in lines: lines[line].append(focus) # Entries not yet released get special 'release' entries (that lack an # actual release object). # FIXME: this isn't actually feasible because, due to no ability to mark # lines extinct, ALL lines get their own 'unreleased' release. #for line, items in lines.iteritems(): # number = "%s.X" % line # if line == 'unreleased': # line = number = 'master' # nodelist = [ # docutils.nodes.strong(text='Unreleased (%s)' % line), # docutils.nodes.reference( # text="Fabric %s" % number, # refuri="https://github.com/fabric/fabric/tree/%s" % line, # classes=['changelog-release'] # ) # ] # releases.append({ # 'obj': release(number=number, date=None, nodelist=nodelist), # 'entries': items # }) return releases def construct_nodes(releases): nodes = [] # Reverse the list again so the final display is newest on top for d in reversed(releases): if not d['entries']: continue release = d['obj'] entries = [ docutils.nodes.list_item('', docutils.nodes.paragraph('', *x['nodelist']) ) for x in d['entries'] ] # Release header # TODO: create actual header node, durr nodes.extend(docutils.nodes.paragraph('', release['nodelist'])) # Entry list list_ = docutils.nodes.bullet_list('', *entries) nodes.append(list_) return nodes def generate_changelog(app, doctree): # This seems to be the cleanest way to tell what a not-fully-parsed # document's 'name' is. Also lol @ not fully implementing dict protocol. source = doctree.children[0] if 'changelog' not in source.get('names', []): return # Second item inside main document is the 'modern' changelog bullet-list # object, whose children are the nodes we care about. changelog = source.children.pop(1) # Walk + parse into release mapping releases = construct_releases(changelog.children) # Construct new set of nodes to replace the old, and we're done source.children[1:1] = construct_nodes(releases) def setup(app): #app.connect('doctree-resolved', generate_changelog) app.connect('doctree-read', generate_changelog)
Python
0
@@ -2419,99 +2419,25 @@ # -Add all to unreleased, add bugs to others too%0A lines%5B'unreleased'%5D.append(focus) +Bugs go errywhere %0A @@ -2566,24 +2566,155 @@ pend(focus)%0A + # Non-bugs only go into unreleased (next release)%0A else:%0A lines%5B'unreleased'%5D.append(focus)%0A%0A # Entrie
3ed611cebed6c9283b5668a7c237deae265fdd64
create fedex_cir_import.py
fedex_cir_import.py
fedex_cir_import.py
Python
0
@@ -0,0 +1,3471 @@ +import os, pdb, psycopg2%0A%0A%0Aprint 'begin script - fedex_cir_import.py'%0A%0Apath = '/usr/local/cirdata/'%0Aimported = '/usr/local/cirdata/imported/'%0AphoenixDB = psycopg2.connect(%22dbname='database' user='user' host='host' password='password'%22)%0A %0A%0Afor file in os.listdir(path):%0A current = os.path.join(path, file)%0A if os.path.isfile(current):%0A ediNumber = ''%0A invoiceDate = ''%0A invoiceNumber = ''%0A accountNumber = ''%0A numberAirbills = ''%0A invoiceAmount = ''%0A fileTotal = ''%0A%0A rowOn = False%0A nextLineLast = False%0A data = open(current, %22rb%22)%0A for line in data:%0A %0A #print line%0A if 'Contact' in line:%0A ediNumber = line.split(':')%5B2%5D.replace('%5Cr%5Cn','').replace(' ','')%0A %0A if 'Address' in line:%0A invoiceDate = line.split(':')%5B2%5D.replace('%5Cr%5Cn','').replace(' ','')%0A invoiceDate = invoiceDate%5B6:%5D+'-'+invoiceDate%5B:-8%5D+'-'+invoiceDate%5B3:-5%5D%0A %0A if 'Customer Nbr' in line:%0A rowOn = True%0A%0A if rowOn == True and 'Customer Nbr' not in line:%0A%0A if line == '%5Cr%5Cn':%0A nextLineLast = True%0A else:%0A if nextLineLast == False: %0A try:%0A invoiceNumber = line.split()%5B1%5D.replace('%5Cr%5Cn','')%0A accountNumber = line.split()%5B0%5D.replace('%5Cr%5Cn','').zfill(9)%0A numberAirbills = line.split()%5B2%5D.replace('%5Cr%5Cn','')%0A invoiceAmount = line.split()%5B3%5D.replace('%5Cr%5Cn','')%0A except: %0A pass %0A %0A%0A cursorPhoenix = phoenixDB.cursor()%0A insertText = %22%22%22insert into configmgr_fedexcir (edi_number, invoice_date, account_number, invoice_number, number_of_airbills, invoice_amount, file_name) values ('%25s', '%25s', '%25s', %25s, %25s, '%25s', '%25s')%22%22%22 %25 (ediNumber, invoiceDate, accountNumber, invoiceNumber, numberAirbills, invoiceAmount, file)%0A%0A try:%0A if rowOn == True and nextLineLast == False:%0A print file, fileTotal, ediNumber, invoiceDate, accountNumber, invoiceNumber, numberAirbills, invoiceAmount%0A cursorPhoenix.execute(%22%22%22select * from configmgr_fedexcir where edi_number = '%25s' and invoice_date = '%25s' and account_number = '%25s' and invoice_number = '%25s' %22%22%22 %25 (ediNumber, invoiceDate, accountNumber, invoiceNumber))%0A results = cursorPhoenix.fetchone()%0A %0A if results is None:%0A cursorPhoenix.execute(insertText)%0A phoenixDB.commit() %0A except:%0A print 'insert failed: ' + insertText%0A%0A if nextLineLast == True and line != '%5Cr%5Cn':%0A rowOn = False%0A fileTotal = line.split()%5B2%5D.replace('%5Cr%5Cn','')%0A cursorPhoenix = phoenixDB.cursor()%0A updateString = %22%22%22update configmgr_fedexcir set file_total = '%25s' where file_name = '%25s' %22%22%22 %25 (fileTotal, file)%0A %0A cursorPhoenix.execute(updateString)%0A phoenixDB.commit() %0A %0A os.rename(os.path.join(path, file), os.path.join(imported, file))%0A%0Aprint 'end script - fedex_cir_import.py'%0A
513df9e9ce48c7877244d5c9ad1dcf220d368386
Add findexposurehist to finde exposure dist for each country.
findexposurehist.py
findexposurehist.py
Python
0
@@ -0,0 +1,1833 @@ +from __future__ import division%0A%0Aimport ConfigParser%0Aimport csv%0Aimport time%0Aimport datetime%0A%0Aimport matplotlib; matplotlib.use('Agg')%0Aimport matplotlib.pyplot as plt%0Aimport numpy as np%0Aimport scipy as sp%0Aimport scipy.stats as spstats%0A%0Aimport exposure%0Aimport util%0A%0Adef main():%0A %0A # Read config%0A config = ConfigParser.RawConfigParser()%0A config.read('app.config')%0A exp_id = str(datetime.datetime.now().strftime('%25Y-%25m-%25d %25H:%25M:%25S'))%0A print 'Running findexposurehist/%25s' %25 exp_id%0A %0A # Read data file, save country codes and country-video pairs%0A filename = 'data/%25s' %25 config.get('data', 'filename')%0A data = util.VideoData.from_csv(filename)%0A %0A # Plot and save exposure histograms%0A results = find_pair_stats(data, exp_id)%0A%0Adef find_pair_stats(data, exp_id):%0A countries = data.countries%0A for country in countries:%0A exposures = %5B%5D%0A for target in countries:%0A if target == country:%0A continue%0A # Find video exposure%0A h = data.country_lookup.tok2id%5Bcountry%5D%0A t = data.country_lookup.tok2id%5Btarget%5D%0A exposures.append(exposure.symmetric(data.counts%5Bt,:%5D, data.counts%5Bh,:%5D))%0A # Plot%0A util.create_result_dir('findexposurehist', exp_id)%0A fdtitle = %7B'fontsize':10%7D%0A fdaxis = %7B'fontsize':8%7D%0A %0A f = plt.figure(figsize=(3.3125, 3.3125))%0A plt.show()%0A plt.hist(exposures, bins=20)%0A hx = plt.xlabel('Video Exposure', fontdict=fdaxis)%0A hy = plt.ylabel('Count', fontdict=fdaxis)%0A ht = plt.title('Exposure Histogram (%25s)' %25 country, fontdict=fdtitle)%0A plt.tick_params('both', labelsize='7')%0A plt.tight_layout()%0A f.savefig('results/findexposurehist/%25s/exposurehist-%25s.eps' %25 (exp_id, country))%0A%0Aif __name__ == '__main__':%0A main()%0A
539098d24cb671fe30543917928404a8de0f02e5
make video using ffmpeg
fisspy/makemovie.py
fisspy/makemovie.py
Python
0.000001
@@ -0,0 +1,1526 @@ +%22%22%22%0AMakevideo%0A%0AUsing the ffmpeg make a movie file from images%0A%22%22%22%0Afrom __future__ import absolute_import, division, print_function%0Aimport numpy as np%0Aimport subprocess as sp%0Aimport platform%0Afrom matplotlib.pyplot import imread%0Afrom shutil import copy2%0Aimport os%0A%0A__author__=%22J. Kang: jhkang@astro.snu.ac.kr%22%0A__email__=%22jhkang@astro.snu.ac.kr%22%0A__date__=%22Nov 08 2016%22%0A%0Adef makevideo(imgstr,fpsi,movie_name='video.mp4'):%0A os_name=platform.system()%0A if os_name == 'Windows':%0A FFMPEG_BIN = %22ffmpeg.exe%22%0A else:%0A FFMPEG_BIN = %22ffmpeg%22%0A %0A exten=movie_name.split('.')%5B1%5D%0A if exten == 'mp4':%0A codec='libx264'%0A elif exten == 'avi':%0A codec='libxvid'%0A elif exten == 'mov':%0A codec='mpeg4'%0A else:%0A codec=''%0A %0A n=len(imgstr)%0A if n == 0:%0A raise ValueError('Image list has no element!')%0A %0A fps=str(fpsi)%0A img=imread(imgstr%5B0%5D)%0A size=img.shape%0A xsize=size%5B0%5D%0A ysize=size%5B1%5D%0A %0A if np.mod(xsize*ysize,2) == 0:%0A raise ValueError(%22The size of the image shuld be even numbers.%22)%0A %0A newname=np.arange(n)%0A newname=np.char.add('_',newname.astype(str))%0A newname=np.char.add(newname,'.png')%0A %0A for i in range(n):%0A copy2(imgstr%5Bi%5D,newname%5Bi%5D)%0A %0A %0A cmd=%5BFFMPEG_BIN,%0A '-i', '_%25d.png'%0A '-y',%0A '-s',str(xsize)+'x'+str(ysize),%0A '-pix_fmt','yuv420p',%0A '-r',fps,%0A '-c:v',codec,%0A 'q:v 1',movie_name%5D%0A %0A pipe = sp.Popen(cmd,stdin=sp.PIPE,stderr=sp.PIPE)
ef20713c0b4b7378fe91aae095258452d01e81ba
Create 1.py
basics/action/QWidgetAction/1.py
basics/action/QWidgetAction/1.py
Python
0.000007
@@ -0,0 +1,551 @@ +class SelectionSetsView(QTableView):%0A def _onContextMenu(self, widget, pos):%0A menu = QtGui.QMenu()%0A colorAction = menu.addAction(%22Edit Color%22)%0A colorAction.triggered.connect(partial(self._editColor, widget, pos))%0A colorWidgetAction = QtGui.QWidgetAction(menu)%0A cbg = ColoredButtonGroup(6)%0A cbg.currentColorChosen.connect(widget.colorize)%0A colorWidgetAction.setDefaultWidget(cbg)%0A menu.addAction(colorWidgetAction)%0A widget.addActionsTo(menu)%0A menu.exec_(widget.mapToGlobal(pos))%0A
5ed5a0af116e9ac64ca7cf5a8be68997d44a21c9
Version bump to 1.0.1
mezzanine/__init__.py
mezzanine/__init__.py
__version__ = "1.0.0"
Python
0
@@ -13,11 +13,11 @@ = %221.0. -0 +1 %22%0A
51b72ace0e0041199c596074718c2f8b22f5de71
Create stripmanager.py
stripmanager.py
stripmanager.py
Python
0.000001
@@ -0,0 +1,1215 @@ +import time%0Afrom neopixel import *%0Aimport datamanager%0A%0A# LED strip configuration:%0ALED_COUNT = 60 # Number of LED pixels.%0ALED_PIN = 18 # GPIO pin connected to the pixels (must support PWM!).%0ALED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz)%0ALED_DMA = 5 # DMA channel to use for generating signal (try 5)%0ALED_BRIGHTNESS = 255 # Set to 0 for darkest and 255 for brightest%0ALED_INVERT = False # True to invert the signal (when using NPN transistor level shift)%0A%0Astrip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS)%0Astrip.begin()%0A%0A%0Adef fill_strip_percentage(perc):%0A limit = int(60*perc)%0A for i in range(limit):%0A strip.setPixelColor(i, 0)%0A for i in range(limit):%0A delta = float(255)*(float(i)/60.0)%0A strip.setPixelColorRGB(i, int(delta), int(255-delta), 0)%0A strip.show()%0A time.sleep(0.2)%0A%0Aif __name__ == '__main__':%0A old_perc = 0.0%0A while True:%0A progress = datamanager.get_sprint_progress()%0A perc = float(progress)/100.0%0A if not old_perc == perc:%0A old_perc = perc%0A fill_strip_percentage(perc)%0A time.sleep(600)%0A
a19aff3173a85ca8b0035873c3a6315d3dbedba4
Create main.py
gateway/src/main.py
gateway/src/main.py
Python
0.000001
@@ -0,0 +1,217 @@ +#!/usr/bin/env python%0A#Gateway main script.%0A#Communicate with end devices via LoRa.%0A#Communicate with server via MQTT(hbmqtt) and HTTP POST.%0A#Save data in the sqlite database.%0A#Parse JSON from MQTT and LoRa protocol.%0A
754a717c8abc0f6b2683071684420240ff0aef17
add heap
ds/heap.py
ds/heap.py
Python
0.000005
@@ -0,0 +1,1408 @@ +class BinHeap:%0A def __init__(self):%0A self.heap_list = %5B0%5D%0A self.size = 0%0A%0A def siftup(self, i):%0A while i // 2 %3E 0:%0A if self.heap_list%5Bi%5D %3C self.heap_list%5Bi//2%5D:%0A self.heap_list%5Bi//2%5D, self.heap_list%5Bi%5D = self.heap_list%5Bi%5D, self.heap_list%5Bi//2%5D%0A i = i // 2%0A%0A def insert(self, k):%0A self.heap_list.append(k)%0A self.size += 1%0A self.siftup(self.size)%0A%0A def siftdown(self, i):%0A while (i*2) %3C= self.size:%0A mc = self.min_child(i)%0A if self.heap_list%5Bi%5D %3E self.heap_list%5Bmc%5D:%0A self.heap_list%5Bi%5D, self.heap_list%5Bmc%5D = self.heap_list%5Bmc%5D, self.heap_list%5Bi%5D%0A i = mc%0A%0A def min_child(self, i):%0A if i*2+1 %3E self.size:%0A return i * 2%0A else:%0A if self.heap_list%5Bi*2%5D %3C self.heap_list%5Bi*2+1%5D:%0A return i*2%0A else:%0A return i*2+1%0A%0A def pop(self):%0A v = self.heap_list%5B1%5D%0A self.heap_list%5B1%5D = self.heap_list%5Bself.size%5D%0A self.size -= 1%0A self.heap_list.pop()%0A self.siftdown(1)%0A return v%0A%0A def build_heap(self, L):%0A i = len(L) // 2%0A self.size = len(L)%0A self.heap_list = %5B0%5D + L%0A while i %3E 0:%0A self.siftdown(i)%0A i -= 1%0A%0A%0Aif '__main__' == __name__:%0A heap = BinHeap()%0A L = %5B9, 6, 5, 3, 2%5D%0A heap.build_heap(L)%0A
58c604a8574ade75aecbd80314004a9539e80c84
Add ?wv command for encouraging action
plugins/volunteers.py
plugins/volunteers.py
Python
0
@@ -0,0 +1,262 @@ +__commands__ = '''%0A ?wv %5Bname%5D - congratulates people on their public sprited gesture%0A'''%0A%0A%0Adef plugin(bot):%0A bot.hear(r'%5E%5C?wv$', %22Well volunteered!%22)%0A bot.hear(r'%5E%5C?wv%5Cs(.+)$', lambda response: %22Well volunteered %25s!%22 %25 response.match.group(1).strip())%0A
b15d6bf7a8dede16394cc8455d5096066f15e964
Update module.py
module/module.py
module/module.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2009-2012: # Gabes Jean, naparuba@gmail.com # Gerhard Lausser, Gerhard.Lausser@consol.de # Gregory Starck, g.starck@gmail.com # Hartmut Goebel, h.goebel@goebel-consult.de # # This file is part of Shinken. # # Shinken is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Shinken is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Shinken. If not, see <http://www.gnu.org/licenses/>. # This module imports hosts and services configuration from a MySQL Database # Queries for getting hosts and services are pulled from shinken-specific.cfg configuration file. import os # Try to import the Libcloud API from pprint import pprint try: from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver except ImportError: Provider = get_driver = None from shinken.basemodule import BaseModule from shinken.log import logger properties = { 'daemons': ['arbiter'], 'type': 'aws_import', 'external': False, 'phases': ['configuration'], } # called by the plugin manager to get a broker def get_instance(plugin): logger.debug("[AWS Importer Module]: Get AWS importer instance for plugin %s" % plugin.get_name()) if not Provider: raise Exception('Missing module libcloud. Please install it from http://libcloud.apache.org/index.html') # Beware : we must have RAW string here, not unicode! api_key = str(plugin.api_key.strip()) secret = str(plugin.secret.strip()) default_template = getattr(plugin, 'default_template', '') ignore_tag = getattr(plugin, 'ignore_tag', None) regions = getattr(plugin, 'regions', 'ec2_us_east').split(',') poller_tag = getattr(plugin, 'poller_tag', None) instance = AWS_importer_arbiter(plugin, api_key, secret, default_template, ignore_tag,regions,poller_tag) return instance # Retrieve hosts from AWS API class AWS_importer_arbiter(BaseModule): def __init__(self, mod_conf, api_key, secret, default_template, ignore_tag, regions, poller_tag): BaseModule.__init__(self, mod_conf) self.api_key = api_key self.secret = secret self.default_template = default_template self.ignore_tag = ignore_tag self.regions = regions self.poller_tag = poller_tag self.cons = [] # Called by Arbiter to say 'let's prepare yourself guy' def init(self): logger.debug("[AWS Importer Module]: Try to open a AWS connection") for region in self.regions: self.cons.append(get_driver(getattr(Provider, region.upper()))(self.api_key, self.secret)) logger.info("[AWS Importer Module]: Connection opened") # Main function that is called in the CONFIGURATION phase def get_objects(self): # Create variables for result r = {'hosts' : []} # Ok get all! nodes = [] try: for conn in self.cons: nodes.extend(conn.list_nodes()) except Exception, exp: logger.error("[AWS Importer Module]: Error during the node listing '%s'" % exp) raise hosts = r['hosts'] for n in nodes: h = {} # The templates we will use to really configure the VM tags = [] if self.default_template: tags.append(self.default_template) tags.append('EC2') # Append the instance id to the name since AWS allows for Name to be duplicated across instances h['host_name'] = unicode(n.name + "_" + n.id) # Now the network part, try to get some :) try: h['_EC2_PRIVATE_IP'] = unicode(n.private_ips[0]) except IndexError: h['_EC2_PRIVATE_IP'] = u'' try: h['_EC2_PUBLIC_IP'] = unicode(n.public_ips[0]) except IndexError: h['_EC2_PUBLIC_IP'] = u'' # If hope your public ip is ok, becaue we will use it as address :) h['address'] = h['_EC2_PUBLIC_IP'] # Ok massive macro setup, but if possible in a clean way for (k, v) in n.extra.iteritems(): prop = '_EC2_'+k.upper() if isinstance(v, list): try: h[prop] = ','.join(filter(None,v)) except TypeError: logger.debug(k + " is not a simple list: " + str(v)) elif isinstance(v, dict): h[prop] = ','.join(['%s:%s' % (i, j) for (i,j) in v.iteritems()]) else: h[prop] = unicode(v) # Special hooks # We take the "use" tag as a use parameter if k == 'tags' and 'use' in v: if v['use'] == self.ignore_tag: break else: tags.append(v['use']) # Also put as template the instance type if k == 'instancetype': tags.append(v) else: # The tag order is not the good, precise data are on the end, we want them # first tags.reverse() h['use'] = ','.join(tags) if self.poller_tag == 'availabilityzone': h['poller_tag'] = h['_EC2_AVAILABILITY'] elif self.poller_tag == 'region': h['poller_tag'] = h['_EC2_AVAILABILITY'][:-1].replace('-','_').upper() hosts.append(h) print "Discovered hosts" pprint(hosts) logger.info("[AWS Importer Module]: Returning to Arbiter %d hosts" % len(r['hosts'])) return r
Python
0.000001
@@ -4422,16 +4422,28 @@ %5D = u''%0A + %0A @@ -4453,74 +4453,183 @@ # -If hope your public ip is ok, becaue we will use it as address :)%0A +use public ip, else fall back to private one%0A if h%5B'_EC2_PUBLIC_IP'%5D:%0A h%5B'address'%5D = h%5B'_EC2_PUBLIC_IP'%5D%0A elif h%5B'_EC2_PRIVATE_IP'%5D:%0A @@ -4656,35 +4656,37 @@ = h%5B'_EC2_P -UBLIC +RIVATE _IP'%5D%0A +%0A
2d1fd9c81ca9f17270ecef6505830cb798632091
initialize graph test file.
test_simple_graph.py
test_simple_graph.py
Python
0
@@ -0,0 +1,480 @@ +#!/usr/bin/env python%0Afrom __future__ import print_function%0Afrom __future__ import unicode_literals%0A%0A%0Adef test_init(self):%0A return%0A%0A%0Adef test_nodes():%0A return nodes%0A%0A%0Adef test_edges():%0A return edges%0A%0A%0Adef test_add_node(value):%0A return%0A%0A%0Adef test_add_edge(value1, value2):%0A return%0A%0A%0Adef test_del_node(value):%0A return%0A%0A%0Adef test_has_node(value):%0A return%0A%0A%0Adef test_neighbors(value):%0A return neighbors%0A%0A%0Adef test_adjecent(value, value2):%0A return condition%0A
87eab562e847d7cdde7867c41453b10add376fba
Add test script
test_madoka.py
test_madoka.py
Python
0.000001
@@ -0,0 +1,2394 @@ +# -*- coding: utf-8 -*-%0Afrom nose.tools import eq_, ok_%0Aimport madoka%0Aimport os%0A%0A%0Aclass Test_madoka(object):%0A%0A def test_inc(self):%0A sketch = madoka.Sketch()%0A sketch.inc('mami', 3)%0A eq_(1, sketch.get('mami', 3))%0A sketch.inc('mami', 3)%0A eq_(2, sketch.get('mami', 3))%0A%0A def test_add(self):%0A sketch = madoka.Sketch()%0A sketch.add('mami', 3, 2)%0A eq_(2, sketch.get('mami', 3))%0A sketch.add('mami', 3, 8)%0A eq_(10, sketch.get('mami', 3))%0A%0A def test_set(self):%0A sketch = madoka.Sketch()%0A sketch.set('mami', 3, 14)%0A eq_(14, sketch.get('mami', 3))%0A%0A def test_clear(self):%0A sketch = madoka.Sketch()%0A sketch.set('mami', 3, 14)%0A sketch.clear()%0A eq_(0, sketch.get('mami', 3))%0A%0A def test_create(self):%0A sketch = madoka.Sketch()%0A sketch.create(max_value=4)%0A sketch.set('mami', 3, 100)%0A eq_(15, sketch.get('mami', 3))%0A%0A def test_copy(self):%0A sketch = madoka.Sketch()%0A sketch.set('mami', 3, 14)%0A%0A new_sketch = madoka.Sketch()%0A new_sketch.copy(sketch)%0A eq_(14, new_sketch.get('mami', 3))%0A%0A def test_merge(self):%0A sketch = madoka.Sketch()%0A sketch.set('mami', 3, 14)%0A%0A new_sketch = madoka.Sketch()%0A new_sketch.set('mami', 3, 14)%0A%0A new_sketch.merge(sketch)%0A eq_(28, new_sketch.get('mami', 3))%0A%0A def test_filter(self):%0A sketch = madoka.Sketch()%0A sketch.set('mami', 3, 3)%0A sketch.filter(lambda x: x**2)%0A eq_(9, sketch.get('mami', 3))%0A%0A def test_inner_product(self):%0A sketch = madoka.Sketch()%0A sketch.set('mami', 3, 2)%0A sketch.set('homura', 3, 1)%0A sketch.set('kyouko', 3, 2)%0A sketch.set('sayaka', 3, 2)%0A%0A new_sketch = madoka.Sketch()%0A new_sketch.set('mami', 3, 2)%0A new_sketch.set('kyouko', 3, 3)%0A new_sketch.set('sayaka', 3, 10)%0A%0A eq_(30, new_sketch.inner_product(sketch))%0A%0A def test_save_and_load(self):%0A try:%0A filename = 'test.madoka'%0A sketch = madoka.Sketch()%0A sketch.set('mami', 3, 14)%0A sketch.save(filename)%0A ok_(os.path.exists(filename))%0A%0A sketch = madoka.Sketch()%0A sketch.load(filename)%0A eq_(14, sketch.get('mami', 3))%0A finally:%0A os.remove(filename)%0A
100c2bb05d002c5b07e0d6ae4a242346e1362c2b
Create condition.py
colino/condition.py
colino/condition.py
Python
0
@@ -0,0 +1,598 @@ +from __future__ import (absolute_import, division,%0A print_function, unicode_literals)%0A%0Aclass Condition(object):%0A%0A def __init__(self, condition_model):%0A # used for holding objects like compiled reges%0A self.init_context = %7B%7D%0A # variables referenced by condition%0A self.variables = set()%0A # the condition python code%0A self.code = self.compile(condition_model)%0A %0A def compile(self, condition_model):%0A %22%22%22create a valid python expression from a condition model%22%22%22%0A # TODO recursice descent into model, one method for class%0A pass%0A
cf6172353ad5f73185b8de0d60510a0713aa9895
Transform omorfi tagged text into finnpos format.
bin/omorfi2finnpos.py
bin/omorfi2finnpos.py
Python
0
@@ -0,0 +1,3013 @@ +from sys import stdin, argv, stderr%0Afrom re import findall%0A%0Adef get_lemma(string, convert_type):%0A if convert_type == 'ftb':%0A word_id_strs = findall('%5C%5BWORD_ID=%5B%5E%5C%5D%5D*%5C%5D', string)%0A lemma_parts = %5B word_id_str%5B9:%5D%5B:-1%5D for word_id_str in word_id_strs %5D%0A return '#'.join(lemma_parts)%0A else:%0A return string%5B:string.find('%5Ct')%5D%0A%0Adef get_label(string, convert_type):%0A if convert_type == 'ftb':%0A # Remove everything up to the start of the last lemma.%0A string = string%5Bstring.rfind('%5BWORD_ID=') + len('%5BWORD_ID='):%5D%0A %0A # Remove the last lemma.%0A label = string%5Bstring.find('%5D') + 1:%5D%0A%0A # Add sub label separators.%0A label = label.replace('%5D%5B','%5D%7C%5B')%0A%0A sub_labels = label.split('%7C')%0A%0A sub_labels = filter(lambda x: x.find(%22STYLE=%22) == -1, sub_labels)%0A sub_labels = filter(lambda x: x.find(%22DRV=%22) == -1, sub_labels)%0A %0A label = '%7C'.join(sub_labels)%0A%0A return label%0A%0A else:%0A return string%5Bstring.find('%5Ct'):%5D%0A%0Adef convert(ifile, convert_type):%0A wf = ''%0A labels = ''%0A lemmas = %5B%5D%0A%0A for line in ifile:%0A line = line.strip()%0A%0A if line == '' and wf != '':%0A lemmas = list(set(lemmas))%0A print('%25s%5Ct%25s%5Ct%25s%5Ct%25s%5Ct%25s' %25 (wf, '_', '_', labels, str(lemmas)))%0A%0A wf, labels, lemmas = '', '', %5B%5D%0A %0A elif line == '':%0A continue%0A%0A elif (convert_type == 'ftb' and %0A line == 'OMORFI_VERSION_%E2%89%A5_14_%C2%A9_GNU_GPL_V3'):%0A print('')%0A entry = ''%0A%0A elif convert_type == 'tdt' and line.find('%3CEND%3E') != -1:%0A print('')%0A entry = ''%0A%0A else:%0A if convert_type == 'ftb':%0A wf, analysis = line.split('%5Ct')%0A%0A if analysis == '+?':%0A labels = '_'%0A else:%0A label = get_label(analysis, convert_type)%0A lemma = get_lemma(analysis, convert_type)%0A %0A if labels != '':%0A labels += ' '%0A %0A labels += label%0A lemmas.append((label, lemma))%0A else:%0A wf, lemma, label = line.split('%5Ct')%0A%0A lemma = lemma.replace('%7C','')%0A%0A if label == '+?':%0A labels = '_'%0A%0A else:%0A if labels != '':%0A labels += ' '%0A %0A labels += label%0A lemmas.append((label, lemma))%0A%0Aif __name__=='__main__':%0A%0A convert_type = 'ftb'%0A%0A if len(argv) == 2:%0A convert_type = argv%5B1%5D%0A elif len(argv) != 1:%0A stderr.write('USE: cat indata %7C %25s (ftb%7Ctdt) %3E outdata%5Cn' %25 argv%5B0%5D)%0A exit(1)%0A %0A if not convert_type in %5B'ftb','tdt'%5D:%0A stderr.write('Unknown conversion type %25s. Should be ftb or tdt.' %25 %0A convert_type)%0A exit(1)%0A%0A convert(stdin, convert_type)%0A
723a7ef13c34bf6e292377db9849753d34b4d0d1
add new helper to display completion on learner dashboard
openedx/core/djangoapps/appsembler/html_certificates/helpers.py
openedx/core/djangoapps/appsembler/html_certificates/helpers.py
Python
0.000001
@@ -0,0 +1,2126 @@ +%22%22%22%0AAppsembler Helpers to improve course info in learner dashboard.%0AWe should remove this after Maple, since all the info is in the new course_home_api.%0A%22%22%22%0A%0Aimport beeline%0A%0Afrom xmodule.modulestore.django import modulestore%0Afrom common.djangoapps.student.helpers import cert_info%0Afrom lms.djangoapps.course_blocks.api import get_course_blocks%0A%0A%0A@beeline.traced('html_certificates.get_course_blocks_completion_summary')%0Adef get_course_blocks_completion_summary(course_key, user):%0A %22%22%22%0A Returns an object with the number of complete units, incomplete units, and units that contain gated content%0A for the given course. The complete and incomplete counts only reflect units that are able to be completed by%0A the given user. If a unit contains gated content, it is not counted towards the incomplete count.%0A The object contains fields: complete_count, incomplete_count, locked_count%0A %22%22%22%0A if not user.id:%0A return %7B%7D%0A%0A beeline.add_context_field('username', user.username)%0A beeline.add_context_field('course_key', course_key)%0A%0A store = modulestore()%0A course_usage_key = store.make_course_usage_key(course_key)%0A block_data = get_course_blocks(user, course_usage_key, allow_start_dates_in_future=True, include_completion=True)%0A%0A complete_count, incomplete_count, locked_count = 0, 0, 0%0A for section_key in block_data.get_children(course_usage_key): # pylint: disable=too-many-nested-blocks%0A for subsection_key in block_data.get_children(section_key):%0A for unit_key in block_data.get_children(subsection_key):%0A complete = block_data.get_xblock_field(unit_key, 'complete', False)%0A contains_gated_content = block_data.get_xblock_field(unit_key, 'contains_gated_content', False)%0A if contains_gated_content:%0A locked_count += 1%0A elif complete:%0A complete_count += 1%0A else:%0A incomplete_count += 1%0A%0A return %7B%0A 'complete_count': complete_count,%0A 'incomplete_count': incomplete_count,%0A 'locked_count': locked_count%0A %7D%0A
898e1692ed87890cf77a7534e3c51afed112a131
add a top-level __init__.py with imports of the main classes
pyreaclib/__init__.py
pyreaclib/__init__.py
Python
0.000008
@@ -0,0 +1,578 @@ +%22%22%22%0Apyreaclib is a python module that interprets the nuclear reaction rates%0Acataloged by the JINA ReacLib project:%0A%0Ahttps://groups.nscl.msu.edu/jina/reaclib/db/%0A%0AIt provides both interactive access to the rates, for use in Jupyter%0Anotebooks as well as methods for writing python and Fortran nuclear%0Areaction networks, including the the righthand side and Jacobian%0Aroutines.%0A%22%22%22%0A%0A__version__ = %221.0%22%0A%0Afrom pyreaclib.networks import %5C%0A RateCollection, %5C%0A Composition, %5C%0A Explorer, %5C%0A PythonNetwork, %5C%0A BaseFortranNetwork, %5C%0A BoxLibNetwork, %5C%0A SundialsNetwork%0A
a7a20eacc94f1bca2baf5c37632f116e34f2f079
Create data_cleansed.py
data_cleansed.py
data_cleansed.py
Python
0
@@ -0,0 +1,853 @@ +# Data Cleansing%0Aimport pandas as pd%0Adf = pd.DataFrame()%0A# 1. Explore data: df.head(), df.tail(), df.info(), df.describe()%0A# Check NULL values totals: df.isna().sum()%0A# 2. Drop NaValues: df.dropna(inplace=True)%0A# 3. Deal with Duplicates: df.duplicated().value_counts()%0A''' A general rule of thumb is to ignore the duplicate values if they are less %0Athan 0.5%25. This is because, if the proportion is very low, duplicate values can %0Aalso be because of chance. If it is higher than 0.5%25, you can check if the %0Aconsecutive values are duplicate. If the consecutive values are duplicate, you can %0Adrop them.'''%0Adf.loc%5B(df%5B'col_1'%5D.diff() != 0) %7C %0A (df%5B'col_2'%5D.diff() != 0) %7C %0A (df%5B'col_3'%5D.diff() != 0) %7C%0A (df%5B'col_4'%5D.diff() != 0)%0A %5D%0A# 4. Row count: df.shape%5B0%5D%0A# 5. Deal with outliers: df%5B'returns'%5D = df%5B'close'%5D.pct_change()%0A
d90bb9ddfbac20fa9ae7d7ecf37064cb8a86b26e
add algorithm which choose the node with largest degree to query
degree_largest.py
degree_largest.py
Python
0.000001
@@ -0,0 +1,1395 @@ +from random import sample,random,choice%0Afrom core import Algorithm%0Afrom egraphs import FBEgoGraph%0A%0Aclass DegreeLargest(Algorithm):%0A%0A def update_graph(self, start_node, new_node):%0A g = self.sampled_graph%0A start_id = g.vs%5B'name'%5D.index(start_node)%0A if new_node%5B'name'%5D not in g.vs%5B'name'%5D:%0A g.add_vertex(**new_node)%0A index = g.vs%5B'name'%5D.index(new_node%5B'name'%5D)%0A g.add_edge(start_id,index)%0A else:%0A index = g.vs%5B'name'%5D.index(new_node%5B'name'%5D)%0A if g.get_eid(start_id, index, directed=False, error=False) == -1:%0A g.add_edge(start_id,index)%0A%0A def degree_largest(self):%0A full_degree = self.sampled_graph.vs%5B'degree'%5D%0A sample_degree = self.sampled_graph.degree()%0A difference = %5Bx1 - x2 for (x1, x2) in zip(full_degree, sample_degree)%5D%0A return difference.index(max(difference))%0A%0A def run(self,k):%0A n_attribute = len(self.sampled_graph.vertex_attributes())-2%0A i = 0%0A%0A while i %3C k:%0A query_node = self.sampled_graph.vs%5B'name'%5D%5Bself.degree_largest()%5D%0A query_result = self.egraph.query_node(query_node,n_attribute)%0A self.update_graph(query_node,query_result)%0A i += 1%0A%0Aif __name__ == %22__main__%22:%0A fbego_graph = FBEgoGraph('data/egofb.txt')%0A fuck_rj = RandomJump(fbego_graph)%0A print fuck_rj.validate()
7b4f3784f3c27e861b2b741fe2a02c82a97e8fb9
change storage test file name
blockchain_storage/tests.py
blockchain_storage/tests.py
Python
0.000001
@@ -0,0 +1,334 @@ +import hashlib%0Aimport leveldb%0A%0Adatabase = leveldb.LevelDB('/home/operator/PycharmProjects/CrAB/db', create_if_missing=False)%0Ahash = hashlib.sha256('data'.encode())%0Aprint('hash: ', hash.digest())%0Adatabase.Put(hashlib.sha256('data'.encode()).digest(), 'something'.encode())%0Aprint(database.Get(hashlib.sha256('data'.encode()).digest()))%0A
40ad674ae170347ed69b19434241438bb09e473d
Define decorator for requiring login
app/decorators.py
app/decorators.py
Python
0.000001
@@ -0,0 +1,296 @@ +from functools import wraps%0A%0Afrom flask import redirect, session, url_for%0A%0Adef login_required(f):%0A @wraps(f)%0A def wrapper(*args, **kwargs):%0A if session.get('logged_in', False):%0A return f(*args, **kwargs)%0A return redirect(url_for('public.login'))%0A return wrapper%0A
bb90850d95998fec515e6581de049562494fa484
Allow a debug param to be passed that keeps the script from running automatically.
boto/pyami/startup.py
boto/pyami/startup.py
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/ # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. # import os, sys import boto import ConfigParser from boto.utils import find_class class Startup: def read_metadata(self): self.config = ConfigParser.RawConfigParser() self.config.read(os.path.expanduser('~pyami/metadata.ini')) def get_instance_data(self, name): try: val = self.config.get('Instance', name) except: val = None return val def get_user_data(self, name): try: val = self.config.get('User', name) except: val = None return val def get_script(self): script_name = self.get_user_data('script_name') if script_name: c = boto.connect_s3(self.get_user_data('aws_access_key_id'), self.get_user_data('aws_secret_access_key')) script_name = script_name + '.py' script_bucket = self.get_user_data('script_bucket') if not script_bucket: script_bucket = self.get_user_data('bucket_name') bucket = c.get_bucket(script_bucket) script = bucket.get_key(script_name) print 'Fetching %s.%s' % (bucket.name, script.name) script_path = os.path.join(self.get_user_data('working_dir'), script_name) script.get_contents_to_filename(script_path) self.module_name = self.get_user_data('script_name') sys.path.append(self.get_user_data('working_dir')) else: self.module_name = self.get_user_data('module_name') def run_script(self): if self.module_name: cls = find_class(self.module_name, self.get_user_data('class_name')) s = cls(self.config) s.run() def main(self): self.read_metadata() self.get_script() self.run_script() if __name__ == "__main__": su = Startup() su.main()
Python
0
@@ -2722,32 +2722,102 @@ n_script(self):%0A + debug = self.get_user_data('debug')%0A if not debug:%0A if self. @@ -2825,24 +2825,28 @@ odule_name:%0A + @@ -2901,32 +2901,36 @@ + + self.get_user_da @@ -2959,16 +2959,20 @@ + s = cls( @@ -2984,16 +2984,20 @@ config)%0A +
789af47e06a559287562affe49d450c27c1d3ed1
handle anonymous users
src/sentry/debug/middleware.py
src/sentry/debug/middleware.py
from __future__ import absolute_import import json import re import threading from debug_toolbar.middleware import DebugToolbarMiddleware from debug_toolbar.toolbar import DebugToolbar from django.utils.encoding import force_text # Inherit from DebugToolbarMiddleware because of DJDT monkey patching class DebugMiddleware(threading.local, DebugToolbarMiddleware): _body_regexp = re.compile(re.escape('</body>'), flags=re.IGNORECASE) def __init__(self): threading.local.__init__(self) def show_toolbar(self, request): # TODO(dcramer): support VPN via INTERNAL_IPS + ipaddr maps if not request.user.is_active_superuser(): return False if 'text/html' not in request.META.get('HTTP_ACCEPT', '*/*'): return False return True def process_request(self, request): # Decide whether the toolbar is active for this request. if not self.show_toolbar(request): self.toolbar = None return self.toolbar = toolbar = DebugToolbar(request) # Activate instrumentation ie. monkey-patch. for panel in toolbar.enabled_panels: panel.enable_instrumentation() # Run process_request methods of panels like Django middleware. response = None for panel in toolbar.enabled_panels: response = panel.process_request(request) if response: break return response def process_view(self, request, view_func, view_args, view_kwargs): toolbar = getattr(self, 'toolbar', None) if not toolbar: return # Run process_view methods of panels like Django middleware. response = None for panel in toolbar.enabled_panels: response = panel.process_view(request, view_func, view_args, view_kwargs) if response: break def process_response(self, request, response): toolbar = getattr(self, 'toolbar', None) if not toolbar: return response # Run process_response methods of panels like Django middleware. for panel in reversed(toolbar.enabled_panels): new_response = panel.process_response(request, response) if new_response: response = new_response # Deactivate instrumentation ie. monkey-unpatch. This must run # regardless of the response. Keep 'return' clauses below. # (NB: Django's model for middleware doesn't guarantee anything.) for panel in reversed(toolbar.enabled_panels): panel.disable_instrumentation() # Collapse the toolbar by default if SHOW_COLLAPSED is set. if toolbar.config['SHOW_COLLAPSED'] and 'djdt' not in request.COOKIES: response.set_cookie('djdt', 'hide', 864000) content = force_text(response.content, encoding='utf-8') if 'text/html' not in response['Content-Type']: if 'application/json' in response['Content-Type']: content = json.dumps(json.loads(content), indent=2) response['Content-Type'] = 'text/html' response.content = '<body><h1>Debugger</h1><pre>{}</pre></body>'.format(content) # Insert the toolbar in the response. bits = self._body_regexp.split(content) if len(bits) > 1: bits[-2] += toolbar.render_toolbar() print(bits) response.content = '</body>'.join(bits) response['Content-Length'] = len(response.content) return response
Python
0.000004
@@ -604,16 +604,89 @@ dr maps%0A + if not request.user.is_authenticated():%0A return False%0A
f608e18aa9fa2d13ce5a08f63ab44b942678ff5d
convert avg_face_maker from ipynb to .py and commit
avg_face_maker.py
avg_face_maker.py
Python
0.000004
@@ -0,0 +1,986 @@ +%22%22%22Create an average face from a list of faces%22%22%22%0A%0Aimport numpy as np%0Aimport cv2%0Aimport sqlite3%0Aimport json%0A%0Aconn = sqlite3.connect(%22face.db%22)%0Ac = conn.cursor()%0A%0Afaces_data = c.execute(%22SELECT * FROM (SELECT * FROM faces) as t1 inner join (select rowid, instagram_id from images) as t2 on t1.image_table_id = t2.rowid%22).fetchall()%0A%0Aids_and_rois = %5B(x%5B10%5D, x%5B2%5D) for x in faces_data%5D%0Acropped_faces = np.zeros((640,640))%0Afor ig_id, face_roi in ids_and_rois:%0A img = cv2.imread('grayscale_images/'+ig_id+%22.jpg%22,0)%0A face_roi = json.loads(face_roi)%0A if img is not None:%0A cropped_img = img%5Bface_roi%5B1%5D:face_roi%5B1%5D+face_roi%5B3%5D, face_roi%5B0%5D:face_roi%5B0%5D+face_roi%5B2%5D%5D%0A resized_image = cv2.resize(cropped_img, (640, 640)) %0A cropped_faces += resized_image%0A %0Aavg_face = cropped_faces/len(ids_and_rois)%0Aavg_face = avg_face.astype(np.uint8)%0Acv2.imshow('img',avg_face)%0Acv2.waitKey(0)%0Acv2.destroyAllWindows()%0Acv2.imwrite(%22avg_face_from_numpy_large%22+%22.jpg%22, avg_face)
15dca96debdc04d18ef69e457dc0c41e5288d99b
create fields.py so you don't have to specify trix fields in the admin
trix/fields.py
trix/fields.py
Python
0
@@ -0,0 +1,243 @@ +from django.db import models%0A%0Afrom trix.widgets import TrixEditor%0A%0A%0Aclass TrixField(models.TextField):%0A%0A def formfield(self, **kwargs):%0A kwargs.update(%7B'widget': TrixEditor%7D)%0A return super(TrixField, self).formfield(**kwargs)%0A
2572feea64ee5e4556763132d0663fe4412fe369
Add fixtures to test_journal.py and add test for write_entry method.
test_journal.py
test_journal.py
Python
0
@@ -0,0 +1,2154 @@ +# -*- coding: utf-8 -*-%0Afrom contextlib import closing%0Afrom pyramid import testing%0Aimport pytest%0A%0Afrom journal import connect_db%0Afrom journal import DB_SCHEMA%0A%0A%0ATEST_DSN = 'dbname=test_learning_journal user=mark'%0A%0A%0Adef init_db(settings):%0A with closing(connect_db(settings)) as db:%0A db.cursor().execute(DB_SCHEMA)%0A db.commit()%0A%0A%0Adef clear_db(settings):%0A with closing(connect_db(settings)) as db:%0A db.cursor().execute(%22DROP TABLE entries%22)%0A db.commit()%0A%0A%0Adef clear_entries(settings):%0A with closing(connect_db(settings)) as db:%0A db.cursor().execute(%22DELETE FROM entries%22)%0A db.commit()%0A%0A%0Adef run_query(db, query, params=(), get_results=True):%0A cursor = db.cursor()%0A cursor.execute(query, params)%0A db.commit()%0A results = None%0A if get_results:%0A results = cursor.fetchall()%0A return results%0A%0A%0Adef test_write_entry(req_context):%0A from journal import write_entry%0A fields = ('title', 'text')%0A expected = ('Test Title', 'Test Text')%0A req_context.params = dict(zip(fields, expected))%0A%0A # assert that there are no entries when we start%0A rows = run_query(req_context.db, %22SELECT * FROM entries%22)%0A assert len(rows) == 0%0A%0A result = write_entry(req_context)%0A # manually commit so we can see the entry on query%0A req_context.db.commit()%0A%0A rows = run_query(req_context.db, %22SELECT title, text FROM entries%22)%0A assert len(rows) == 1%0A actual = rows%5B0%5D%0A for idx, val in enumerate(expected):%0A assert val == actual%5Bidx%5D%0A%0A%0A@pytest.fixture(scope='session')%0Adef db(request):%0A %22%22%22set up and tear down a database%22%22%22%0A settings = %7B'db': TEST_DSN%7D%0A init_db(settings)%0A%0A def cleanup():%0A clear_db(settings)%0A%0A request.addfinalizer(cleanup)%0A%0A return settings%0A%0A%0A@pytest.yield_fixture(scope='function')%0Adef req_context(db, request):%0A %22%22%22mock a request with a database attached%22%22%22%0A settings = db%0A req = testing.DummyRequest()%0A with closing(connect_db(settings)) as db:%0A req.db = db%0A req.exception = None%0A yield req%0A%0A # after a test has run, we clear out entries for isolation%0A clear_entries(settings)
7ad1c83776c78e39b47792e6a8240686b04d3726
Create main.v.py
contracts/main.v.py
contracts/main.v.py
Python
0.000001
@@ -0,0 +1 @@ +%0A
6cffe1d30c16062e3a0414310aad89e7a04b2df6
add handler-specific tests
tests/test_handler_specific.py
tests/test_handler_specific.py
Python
0.000001
@@ -0,0 +1,298 @@ +from pygelf import GelfTlsHandler%0Aimport pytest%0A%0A%0Adef test_tls_handler_creation():%0A with pytest.raises(ValueError):%0A GelfTlsHandler(host='127.0.0.1', port=12204, validate=True)%0A%0A with pytest.raises(ValueError):%0A GelfTlsHandler(host='127.0.0.1', port=12204, keyfile='/dev/null')%0A
2069dccb5f1cf5dc4c0dc0ec3cca3daa3e4c87b3
Remove solr.thumbnail from test config.
tests/config.py
tests/config.py
import os import django from django.conf import settings, global_settings import oscar def configure(): if not settings.configured: from oscar.defaults import OSCAR_SETTINGS # Helper function to extract absolute path location = lambda x: os.path.join( os.path.dirname(os.path.realpath(__file__)), x) test_settings = { 'DATABASES': { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, }, 'INSTALLED_APPS': [ 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.flatpages', 'django.contrib.staticfiles', 'sorl.thumbnail', 'compressor', 'tests._site.model_tests_app', # contains models we need for testing # Use a custom partner app to test overriding models. I can't # find a way of doing this on a per-test basis, so I'm using a # global change. ] + oscar.get_core_apps([ 'tests._site.apps.partner', 'tests._site.apps.customer']), 'TEMPLATE_CONTEXT_PROCESSORS': ( "django.contrib.auth.context_processors.auth", "django.core.context_processors.request", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.static", "django.contrib.messages.context_processors.messages", 'oscar.apps.search.context_processors.search_form', 'oscar.apps.customer.notifications.context_processors.notifications', 'oscar.apps.promotions.context_processors.promotions', 'oscar.apps.checkout.context_processors.checkout', 'oscar.core.context_processors.metadata', ), 'TEMPLATE_DIRS': ( location('templates'), oscar.OSCAR_MAIN_TEMPLATE_DIR, ), 'TEMPLATE_LOADERS': (('django.template.loaders.cached.Loader', global_settings.TEMPLATE_LOADERS),), 'MIDDLEWARE_CLASSES': global_settings.MIDDLEWARE_CLASSES + ( 'oscar.apps.basket.middleware.BasketMiddleware', ), 'AUTHENTICATION_BACKENDS': ( 'oscar.apps.customer.auth_backends.EmailBackend', 'django.contrib.auth.backends.ModelBackend', ), 'HAYSTACK_CONNECTIONS': { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', } }, 'PASSWORD_HASHERS': ['django.contrib.auth.hashers.MD5PasswordHasher'], 'ROOT_URLCONF': 'tests._site.urls', 'LOGIN_REDIRECT_URL': '/accounts/', 'STATIC_URL': '/static/', 'COMPRESS_ENABLED': False, 'COMPRESS_ROOT': '', # needed to avoid issue #1214 'ADMINS': ('admin@example.com',), 'DEBUG': False, 'SITE_ID': 1, 'USE_TZ': 1, 'APPEND_SLASH': True, 'DDF_DEFAULT_DATA_FIXTURE': 'tests.dynamic_fixtures.OscarDynamicDataFixtureClass', 'SESSION_SERIALIZER': 'django.contrib.sessions.serializers.JSONSerializer', # temporary workaround for issue in sorl-thumbnail in Python 3 # https://github.com/mariocesar/sorl-thumbnail/pull/254 'THUMBNAIL_DEBUG': False, 'OSCAR_INITIAL_ORDER_STATUS': 'A', 'OSCAR_ORDER_STATUS_PIPELINE': {'A': ('B',), 'B': ()}, 'OSCAR_INITIAL_LINE_STATUS': 'a', 'OSCAR_LINE_STATUS_PIPELINE': {'a': ('b', ), 'b': ()}, } if django.VERSION >= (1, 5): test_settings['INSTALLED_APPS'] += ['tests._site.myauth', ] test_settings['AUTH_USER_MODEL'] = 'myauth.User' test_settings.update(OSCAR_SETTINGS) settings.configure(**test_settings)
Python
0
@@ -889,42 +889,8 @@ s',%0A - 'sorl.thumbnail',%0A
4121e3502f10f0ca36f696bf32e2dfe64bb19d0e
Create tibrvlisten.py
examples/api/tibrvlisten.py
examples/api/tibrvlisten.py
Python
0.000001
@@ -0,0 +1,2452 @@ +%0A%0Aimport sys%0Aimport getopt%0Afrom tibrv.events import *%0A%0Adef usage() :%0A print()%0A print(%22tibrvlisten.py %5B-service service%5D %5B-network network%5D%22)%0A print(%22 %5B-daemon daemon%5D %3Csubject%3E %22)%0A print()%0A sys.exit(1)%0A%0A%0Adef get_params(argv):%0A%0A try:%0A opts, args = getopt.getopt(argv, '', %5B'service', 'network', 'daemon'%5D)%0A%0A except getopt.GetoptError:%0A usage()%0A%0A service = None%0A network = None%0A daemon = None%0A%0A for opt, arg in opts:%0A if opt == '-service':%0A service = arg%0A elif opt == '-network':%0A network = arg%0A elif opt == '-daemon':%0A daemon = arg%0A else:%0A usage()%0A%0A if len(args) != 1:%0A usage()%0A%0A return service, network, daemon, args%5B0%5D%0A%0Adef my_callback(event, msg, closure):%0A%0A err, send_subject = tibrvMsg_GetSendSubject(msg)%0A%0A err, reply_subject = tibrvMsg_GetReplySubject(msg)%0A%0A err, theString = tibrvMsg_ConvertToString(msg)%0A%0A err, localTime, gmtTime = tibrvMsg_GetCurrentTimeString()%0A%0A if reply_subject is not None:%0A print(%22%7B%7D (%7B%7D): subject=%7B%7D, reply=%7B%7D, message=%7B%7D%22.format(%0A localTime, gmtTime, send_subject, reply_subject, theString));%0A else:%0A print(%22%7B%7D (%7B%7D): subject=%7B%7D, message=%7B%7D%22.format(%0A localTime, gmtTime, send_subject, theString));%0A%0A%0A# MAIN PROGRAM%0Adef main(argv):%0A%0A progname = argv%5B0%5D%0A%0A service, network, daemon, subj = get_params(argv%5B1:%5D)%0A%0A err = tibrv_Open()%0A if err != TIBRV_OK:%0A print('%7B%7D: Failed to open TIB/RV: %7B%7D'.format('', progname, tibrvStatus_GetText(err)))%0A sys.exit(1)%0A%0A err, tx = tibrvTransport_Create(service, network, daemon)%0A if err != TIBRV_OK:%0A print('%7B%7D: Failed to initialize transport: %7B%7D'.format('', progname, tibrvStatus_GetText(err)))%0A sys.exit(1)%0A%0A tibrvTransport_SetDescription(tx, progname)%0A%0A print(%22tibrvlisten: Listening to subject %7B%7D%22.format(subj))%0A%0A err, listenID = tibrvEvent_CreateListener(TIBRV_DEFAULT_QUEUE, my_callback, tx, subj, None)%0A if err != TIBRV_OK:%0A print('%7B%7D: Error %7B%7D listening to %7B%7D'.format('', progname, tibrvStatus_GetText(err), subj))%0A sys.exit(2)%0A%0A while tibrvQueue_Dispatch(TIBRV_DEFAULT_QUEUE) == TIBRV_OK:%0A pass%0A%0A # In Linux/OSX%0A # CTRL-C will not interrupt the process%0A # CTRL-%5C (SIGQUIT) would work%0A%0A tibrv_Close()%0A%0A sys.exit(0)%0A%0A%0A return%0A%0Aif __name__ == %22__main__%22 :%0A main(sys.argv)%0A%0A%0A%0A
5d8a9223905117e6b01099c318a2294e148f84b4
Add rpmgrill check
coprcheck/checks.py
coprcheck/checks.py
Python
0
@@ -0,0 +1,2291 @@ +%22%22%22Checks to run on fetched builds.%22%22%22%0A%0A%0Afrom contextlib import contextmanager%0Afrom distutils.spawn import find_executable%0Afrom functools import wraps%0Aimport fnmatch%0Aimport os%0Afrom shutil import rmtree%0Afrom subprocess import check_call%0A%0A%0Aclass MissingBinaryError(OSError):%0A %22%22%22The binary required for this check is not present in the $PATH.%22%22%22%0A%0A%0Adef require_bin(*binaries: %5Bstr%5D):%0A %22%22%22Decorator which checks for binaries on a system before calling%0A the decorated function.%0A%0A Arguments:%0A %5Bbinary, ...%5D: Names of binaries to look for.%0A %22%22%22%0A def decorator(func):%0A%0A @wraps(func)%0A def check_binaries(*args, **kwargs):%0A%0A for binary in binaries:%0A exe = find_executable(binary)%0A if exe is None: raise MissingBinaryError(binary)%0A%0A return func(*args, **kwargs)%0A%0A return check_binaries%0A return decorator%0A%0A%0Adef rpm_dirs(root: str):%0A %22%22%22Generate paths to all directories under root that contains any RPM file.%0A%0A Keyword arguments:%0A root: The top of the searched tree%0A%0A Yields:%0A Paths from root (included) to the directory with RPM(s).%0A %22%22%22%0A%0A for root, _, flist in os.walk(root):%0A if len(fnmatch.filter(flist, '*.rpm')) %3E 0:%0A yield root%0A%0A%0A@require_bin('rpmgrill', 'rpmgrill-unpack-rpms')%0Adef rpmgrill(project_root: str) -%3E None:%0A %22%22%22Run rpmgrill on all packages in the tree.%0A%0A * Assumes following directory structure:%0A %3Cproject_root%3E/%3Cdistro%3E/%3Csrpm_name%3E/*.rpm%0A The rpmgrill is run for each %3Cdistro%3E/%3Csrpm_name%3E variant.%0A%0A Keyword arguments:%0A project_root: Path to the stored rpms tree.%0A %22%22%22%0A%0A @contextmanager%0A def unpacked(path):%0A %22%22%22Unpacks and then cleans files required by rpmgrill.%0A%0A Keyword arguments:%0A path: the directory to be unpacked and tested.%0A%0A Returns/yields:%0A path to the unpacked files.%0A %22%22%22%0A%0A cmd = 'rpmgrill-unpack-rpms %7B0%7D'.format(path).split()%0A check_call(cmd)%0A resultdir = os.path.join(path, 'unpacked')%0A%0A yield resultdir%0A%0A #rmtree(resultdir)%0A%0A for directory in rpm_dirs(project_root):%0A with unpacked(directory) as grillroot:%0A cmd = %5B'rpmgrill', grillroot%5D%0A check_call(cmd)%0A
df227e598aeda7646a6ae24384a1d9e7f9179dc2
add vcs parsing test
tests/test_vcs_requirements.py
tests/test_vcs_requirements.py
Python
0
@@ -0,0 +1,249 @@ +from pundle import parse_vcs_requirement%0A%0A%0Adef test_parse_vcs_requirement():%0A assert parse_vcs_requirement('git+https://github.com/pampam/PKG.git@master#egg=PKG') == %5C%0A ('pkg', 'git+https://github.com/pampam/PKG.git@master#egg=PKG', None)%0A
5d7e4615657d947ec4a7500433f7008de223b622
Add test
tests/test_dllist.py
tests/test_dllist.py
Python
0.000005
@@ -0,0 +1,869 @@ +# Copyright (C) 2016, 2017 Allen Li%0A#%0A# Licensed under the Apache License, Version 2.0 (the %22License%22);%0A# you may not use this file except in compliance with the License.%0A# You may obtain a copy of the License at%0A#%0A# http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS,%0A# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A# See the License for the specific language governing permissions and%0A# limitations under the License.%0A%0Aimport subprocess%0Aimport sys%0A%0A%0Adef test_dllist():%0A proc = subprocess.run(%5Bsys.executable, '-m', 'mir.dlsite.cmd.dllist', '--no-info'%5D,%0A input=b'foo RJ12345 bar%5Cnbad%5Cn',%0A stdout=subprocess.PIPE)%0A assert proc.stdout == b'RJ12345%5Cn'%0A
722b11eab90c6d532ea96209f7632e17181c0b3e
Test if points are in footprint
tests/test_inpoly.py
tests/test_inpoly.py
Python
0.000004
@@ -0,0 +1,773 @@ +import unittest%0Aimport pcl%0Aimport numpy as np%0Afrom patty_registration.conversions import loadLas, loadCsvPolygon%0Afrom numpy.testing import assert_array_equal, assert_array_almost_equal%0Afrom matplotlib import path%0A%0Aclass TestInPoly(unittest.TestCase):%0A def testInPoly(self):%0A fileLas = 'data/footprints/162.las'%0A filePoly = 'data/footprints/162.las_footprint.csv'%0A pc = loadLas(fileLas)%0A footprint = loadCsvPolygon(filePoly)%0A pc2 = points_in_poly(pc, footprint)%0A%0Adef point_in_poly(point, polyPath):%0A return polyPath.contains_point(point%5B:2%5D)%0A%0Adef points_in_poly(pc, poly):%0A polyPath = path.Path(poly%5B:,:2%5D)%0A points = np.asarray(pc)%0A return np.array(%5B point for point in points if point_in_poly(point+pc.offset, polyPath) %5D)%0A
01494bfbc15987a2b925ca7990e8704767c9457b
Create secret.py
tests/secret.py
tests/secret.py
Python
0
@@ -0,0 +1,39 @@ +public_key = 'xxx'%0Aprivate_key = 'yyy'%0A
6b132720c1f7596db34a2fdab3f6ca0134aaabc9
create new model to store uploaded images with id
api/migrations/0001_initial.py
api/migrations/0001_initial.py
Python
0
@@ -0,0 +1,501 @@ +# Generated by Django 3.0 on 2020-11-07 13:11%0A%0Afrom django.db import migrations, models%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A initial = True%0A%0A dependencies = %5B%0A %5D%0A%0A operations = %5B%0A migrations.CreateModel(%0A name='UploadedImages',%0A fields=%5B%0A ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),%0A ('image', models.ImageField(upload_to='image/%25Y/')),%0A %5D,%0A ),%0A %5D%0A
ca90d083005e1c29b3b394d556296fd8e734c40a
implement top extrapolation module
PyAnalysisTools/AnalysisTools/TopExtrapolationModule.py
PyAnalysisTools/AnalysisTools/TopExtrapolationModule.py
Python
0
@@ -0,0 +1,1837 @@ +from PyAnalysisTools.base import _logger%0Aimport ROOT%0A%0A%0Aclass TopExtrapolationModule(object):%0A def __init__(self, **kwargs):%0A _logger.debug('Initialising TopExtrapolationModule')%0A self.build_functions(**kwargs)%0A self.type = %22DataModifier%22%0A%0A def build_functions(self, **kwargs):%0A def build_fct(name, params):%0A fcts = %5Bkwargs%5B'functions'%5D%5Bname%5D%5D * 3%0A for i, param in enumerate(params):%0A param = eval(param)%0A fcts%5B0%5D = fcts%5B0%5D.replace('%5B%7B:d%7D%5D'.format(i), str(param%5B0%5D))%0A fcts%5B1%5D = fcts%5B1%5D.replace('%5B%7B:d%7D%5D'.format(i), str(param%5B0%5D - param%5B1%5D))%0A fcts%5B2%5D = fcts%5B2%5D.replace('%5B%7B:d%7D%5D'.format(i), str(param%5B0%5D + param%5B1%5D))%0A return map(lambda f: ROOT.TF1(%22%22, f), fcts)%0A%0A self.functions = %7B%7D%0A for reg_name, cfg in kwargs.iteritems():%0A if reg_name == 'functions':%0A continue%0A self.functions%5Breg_name%5D = build_fct(cfg%5B'func'%5D, cfg%5B'params'%5D), cfg%5B'stitch'%5D%0A%0A def get_extrapolated_bin_content(self, region, xmin, xmax=None, lumi=1.):%0A if xmax is None:%0A xmax = 1e12%0A if xmin %3C self.functions%5Bregion%5D%5B1%5D:%0A return None%0A return lumi * self.functions%5Bregion%5D%5B0%5D%5B0%5D.Integral(xmin, xmax)%0A%0A def execute(self, histograms):%0A top_hist = histograms%5B'ttbar'%5D%0A region = %5Br for r in self.functions.keys() if r in top_hist.GetName()%5D%5B0%5D%0A print region%0A for i in range(top_hist.GetNbinsX() + 1):%0A bin_content = self.get_extrapolated_bin_content(region, top_hist.GetXaxis().GetBinLowEdge(i),%0A top_hist.GetXaxis().GetBinUpEdge(i), 139.)%0A if bin_content is None:%0A continue%0A top_hist.SetBinContent(i, bin_content)%0A
181ca07d3d7bdb3e07b8f9e608ebd8e42235a38c
test module;
mas_vae/models.py
mas_vae/models.py
Python
0
@@ -0,0 +1,2526 @@ +from keras import backend as K%0Afrom keras.models import Model, Sequential%0Afrom keras.layers import Input, Dense, concatenate%0Afrom keras.layers import Flatten, Reshape, BatchNormalization%0Afrom keras.layers import Conv2D, MaxPooling2D, Conv2DTranspose%0A%0Afrom mas_tools.ml import save_model_arch%0A%0A%0Adef deep_conv2d_ae(input_shape):%0A%0A latent_dim = 32%0A kernel_size = (1, 5)%0A kernel_pooling = (1, 2)%0A strides = (1, 1)%0A %0A # Encoder%0A input_tensor = Input(shape=input_shape, name='encoder_input')%0A x = Conv2D(filters=32,%0A kernel_size=kernel_size,%0A padding='same',%0A activation='relu',%0A strides=strides,%0A input_shape=input_shape)(input_tensor)%0A x = Conv2D(filters=64,%0A kernel_size=kernel_size,%0A padding='same',%0A activation='relu',%0A strides=strides)(x)%0A # shape info needed to build decoder model%0A shape = K.int_shape(x)%0A # shape = enc.output_shape%0A # generate latent vector Q(z%7CX)%0A x = Flatten()(x)%0A x = Dense(latent_dim, activation='relu', name='encoder_output')(x)%0A%0A # Decoder%0A latent_inputs = Input(shape=(latent_dim,), name='latent_input')%0A y = Dense(shape%5B1%5D * shape%5B2%5D * shape%5B3%5D, activation='relu')(latent_inputs)%0A y = Reshape((shape%5B1%5D, shape%5B2%5D, shape%5B3%5D))(y)%0A y = Conv2DTranspose(filters=64,%0A kernel_size=kernel_size,%0A padding='same',%0A activation='relu',%0A strides=strides)(y)%0A y = Conv2DTranspose(filters=32,%0A kernel_size=kernel_size,%0A padding='same',%0A activation='relu',%0A strides=strides)(y)%0A y = Conv2DTranspose(filters=1,%0A kernel_size=kernel_size,%0A padding='same',%0A activation='relu',%0A strides=strides,%0A name='decoder_output')(y)%0A%0A # Create models%0A encoder = Model(input_tensor, x, name='encoder')%0A decoder = Model(latent_inputs, y, name='decoder')%0A autoencoder = Model(input_tensor, decoder(encoder(input_tensor)), name='ae')%0A%0A return encoder, decoder, autoencoder%0A%0A%0Aif __name__ == %22__main__%22:%0A path = 'E:/Projects/market-analysis-system/'%0A%0A enc, dec, ae = deep_conv2d_ae((4, 20, 1))%0A save_model_arch(enc, path+'ae_enc')%0A enc.summary()%0A save_model_arch(dec, path+'ae_dec')%0A dec.summary()%0A save_model_arch(ae, path+'ae')%0A ae.summary()%0A
0515cdac701b6fbd4bb9281b6412313ad31072cc
Add file to run flask app
app.py
app.py
Python
0.000001
@@ -0,0 +1,821 @@ +from flask import Flask, request%0Afrom twilio import twiml%0Aimport subprocess%0A%0Afrom cmd import cmds%0A%0Aapp = Flask(__name__)%0A%0Aimport os%0AACCOUNT_SID = %22%22 #os.environ%5B'ACCOUNT_SID'%5D%0AAUTH_TOKEN = %22%22 #os.environ%5B'AUTH_TOKEN'%5D%0AAPP_SID = %22Twilix%22 #os.environ%5B'APP_SID'%5D%0ACALLER_ID = %22+14389855700%22 #os.environ%5B'CALLER_ID'%5D%0A#CALLER_ID = %22+18175985398%22 #os.environ%5B'CALLER_ID'%5D%0A%0A@app.route(%22/%22)%0Adef index():%0A return %22Hello, world, motherfucker!!!%22%0A%0A@app.route('/sms', methods=%5B'POST'%5D)%0Adef sms():%0A response = twiml.Response()%0A user_input = request.form%5B'Body'%5D%0A if '%7C' in user_input:%0A%09pass%0A else:%0A%09args = user_input.lower().spit() %0A output = args%5B0%5D(args%5B1:%5D)%0A response.sms(output)%0A return str(response)%0A%0Aif __name__ == %22__main__%22:%0A #app.run(debug=True)%0A app.debug = True%0A app.run(host='0.0.0.0')%0A
a0ee0998457976aa45b3d3a462f2b2aab1bfb15f
add objects module
crossprocess/objects.py
crossprocess/objects.py
Python
0
@@ -0,0 +1,185 @@ +#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A%0A%0Aclass SimpleObject(object):%0A def __init__(self, name):%0A self.__name = name%0A%0A def get_name(self):%0A return self.__name%0A
8c276c8c2e45ff0fe634669ea65d0df40c96463c
Add python example using metadata
examples/python/metadata.py
examples/python/metadata.py
Python
0.000059
@@ -0,0 +1,877 @@ +from infomap import infomap%0A%0AmyInfomap = infomap.Infomap(%22--two-level --meta-data-rate 0.3%22)%0A%0A# Add weight as an optional third argument%0AmyInfomap.addLink(0, 1)%0AmyInfomap.addLink(0, 2)%0AmyInfomap.addLink(0, 3)%0AmyInfomap.addLink(1, 0)%0AmyInfomap.addLink(1, 2)%0AmyInfomap.addLink(2, 1)%0AmyInfomap.addLink(2, 0)%0AmyInfomap.addLink(3, 0)%0AmyInfomap.addLink(3, 4)%0AmyInfomap.addLink(3, 5)%0AmyInfomap.addLink(4, 3)%0AmyInfomap.addLink(4, 5)%0AmyInfomap.addLink(5, 4)%0AmyInfomap.addLink(5, 3)%0A%0Anetwork = myInfomap.network()%0Anetwork.addMetaData(0, 1)%0Anetwork.addMetaData(1, 1)%0Anetwork.addMetaData(2, 2)%0Anetwork.addMetaData(3, 2)%0Anetwork.addMetaData(4, 3)%0Anetwork.addMetaData(5, 3)%0A%0AmyInfomap.run()%0A%0Aprint(f%22Found %7BmyInfomap.numTopModules()%7D modules with codelength: %7BmyInfomap.codelength()%7D%22)%0A%0Aprint(%22%5Cn#node module%22)%0Afor node,module in myInfomap.getModules().items():%0A%09print(f%22%7Bnode%7D %7Bmodule%7D%22)%0A%09%0A
7115d25c57404a42bc29513eb514073747d876ce
Add platform_map to remap Platform.os and arch based on config
src/rez/utils/platform_mapped.py
src/rez/utils/platform_mapped.py
Python
0
@@ -0,0 +1,1457 @@ +import re%0A%0A%0Adef platform_mapped(func):%0A %22%22%22%0A Decorates functions for lookups within a config.platform_map dictionary.%0A The first level key is mapped to the func.__name__ of the decorated function.%0A Regular expressions are used on the second level key, values.%0A Note that there is no guaranteed order within the dictionary evaluation. Only the first matching%0A regular expression is being used.%0A For example:%0A%0A config.platform_map = %7B%0A %22os%22: %7B%0A r%22Scientific Linux-(.*)%22: r%22Scientific-%5C1%22, # Scientific Linux-x.x -%3E Scientific-x.x%0A r%22Ubuntu-14.%5Cd%22: r%22Ubuntu-14, # Any Ubuntu-14.x -%3E Ubuntu-14%0A %7D,%0A %22arch%22: %7B%0A %22x86_64%22: %2264bit%22, # Maps both x86_64 and amd64 -%3E 64bit%0A %22amd64%22: %2264bit%22,%0A %7D,%0A %7D%0A %22%22%22%0A def inner(*args, **kwargs):%0A%0A # Since platform is being used within config lazy import config to prevent circular dependencies%0A from rez.config import config%0A%0A # Original result%0A result = func(*args, **kwargs)%0A%0A # The function name is used as primary key%0A if func.__name__ in config.platform_map:%0A for key, value in config.platform_map%5Bfunc.__name__%5D.iteritems():%0A result, changes = re.subn(key, value, result)%0A if changes %3E 0:%0A break%0A return result%0A%0A return result%0A return inner%0A%0A
904a37589d8ef0f7b69d9b0f83f41c94fbbfcde6
Update 1.7 migrations
aldryn_categories/migrations/0003_auto_20150128_1359.py
aldryn_categories/migrations/0003_auto_20150128_1359.py
Python
0
@@ -0,0 +1,760 @@ +# -*- coding: utf-8 -*-%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import models, migrations%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('aldryn_categories', '0002_auto_20150109_1415'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterField(%0A model_name='categorytranslation',%0A name='language_code',%0A field=models.CharField(db_index=True, max_length=15, verbose_name='Language', choices=%5B(b'en', b'English'), (b'de', b'German'), (b'fr', b'French')%5D),%0A preserve_default=True,%0A ),%0A migrations.AlterUniqueTogether(%0A name='categorytranslation',%0A unique_together=set(%5B('language_code', 'master'), ('language_code', 'slug')%5D),%0A ),%0A %5D%0A
8a1448ed3bd426d11f6222d63f77604ec132b2da
Add an example for pre signed URL
examples/signed_url_auth.py
examples/signed_url_auth.py
Python
0.000011
@@ -0,0 +1,1785 @@ +# Copyright 2016 Catalyst IT Ltd%0A#%0A# Licensed under the Apache License, Version 2.0 (the %22License%22); you may%0A# not use this file except in compliance with the License. You may obtain%0A# a copy of the License at%0A#%0A# http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS, WITHOUT%0A# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the%0A# License for the specific language governing permissions and limitations%0A# under the License.%0A%0Afrom zaqarclient.queues.v2 import client%0A%0AURL = 'http://localhost:8888'%0A%0A%0Adef create_post_delete(queue_name, messages):%0A %22%22%22Presigned queue example%0A%0A Creates a queue, posts messages to it and finally deletes it with%0A %60%60signed-url%60%60 auth strategy enabled on Zaqar server side.%0A%0A :params queue_name: The name of the queue%0A :type queue_name: %60six.text_type%60%0A :params messages: Messages to post.%0A :type messages: list%0A %22%22%22%0A conf = %7B'auth_opts':%0A %7B'backend': 'signed-url',%0A 'options': %7B'signature': '',%0A 'expires': '',%0A 'methods': %5B'GET', 'PATCH', 'POST', 'PUT'%5D,%0A 'paths': %5B'/v2/queues/beijing/claims'%5D,%0A 'os_project_id': '2887aabf368046a3bb0070f1c0413470'%7D%0A %7D%0A %7D%0A cli = client.Client(URL, conf=conf)%0A queue = cli.queue(queue_name)%0A queue.post(messages)%0A%0A for msg in queue.messages(echo=True):%0A print(msg.body)%0A msg.delete()%0A%0A%0Aif __name__ == '__main__':%0A messages = %5B%7B'body': %7B'id': idx%7D, 'ttl': 360%7D%0A for idx in range(20)%5D%0A create_post_delete('beijing', messages)%0A
59f37975bb06edd38bbcdea6f0ea031f079ba2c3
Add an utility function to load YAML
lib/hawaiibuildbot/common/utils.py
lib/hawaiibuildbot/common/utils.py
Python
0.000003
@@ -0,0 +1,974 @@ +#%0A# This file is part of Hawaii.%0A#%0A# Copyright (C) 2015 Pier Luigi Fiorini %3Cpierluigi.fiorini@gmail.com%3E%0A#%0A# This program is free software: you can redistribute it and/or modify%0A# it under the terms of the GNU General Public License as published by%0A# the Free Software Foundation, either version 2 of the License, or%0A# (at your option) any later version.%0A#%0A# This program is distributed in the hope that it will be useful,%0A# but WITHOUT ANY WARRANTY; without even the implied warranty of%0A# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the%0A# GNU General Public License for more details.%0A#%0A# You should have received a copy of the GNU General Public License%0A# along with this program. If not, see %3Chttp://www.gnu.org/licenses/%3E.%0A#%0A%0Adef loadYaml(fileName):%0A from yaml import load%0A try:%0A from yaml import CLoader as Loader%0A except ImportError:%0A from yaml import Loader%0A stream = open(fileName, %22r%22)%0A return load(stream, Loader=Loader)%0A
8e58bf21cf39892df07d42d650619e2292b8efb5
Create new package (#7796)
var/spack/repos/builtin/packages/perl-statistics-pca/package.py
var/spack/repos/builtin/packages/perl-statistics-pca/package.py
Python
0.000002
@@ -0,0 +1,1843 @@ +##############################################################################%0A# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.%0A# Produced at the Lawrence Livermore National Laboratory.%0A#%0A# This file is part of Spack.%0A# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.%0A# LLNL-CODE-647188%0A#%0A# For details, see https://github.com/spack/spack%0A# Please also see the NOTICE and LICENSE files for our notice and the LGPL.%0A#%0A# This program is free software; you can redistribute it and/or modify%0A# it under the terms of the GNU Lesser General Public License (as%0A# published by the Free Software Foundation) version 2.1, February 1999.%0A#%0A# This program is distributed in the hope that it will be useful, but%0A# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF%0A# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and%0A# conditions of the GNU Lesser General Public License for more details.%0A#%0A# You should have received a copy of the GNU Lesser General Public%0A# License along with this program; if not, write to the Free Software%0A# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA%0A##############################################################################%0Afrom spack import *%0A%0A%0Aclass PerlStatisticsPca(PerlPackage):%0A %22%22%22A simple Perl implementation of Principal Component Analysis.%22%22%22%0A%0A homepage = %22http://search.cpan.org/~dsth/Statistics-PCA/lib/Statistics/PCA.pm%22%0A url = %22http://search.cpan.org/CPAN/authors/id/D/DS/DSTH/Statistics-PCA-0.0.1.tar.gz%22%0A%0A version('0.0.1', '6e0e05fe13f6becea525b973a0c29001')%0A%0A depends_on('perl-module-build', type='build')%0A depends_on('perl-contextual-return', type=('build', 'run'))%0A depends_on('perl-text-simpletable', type=('build', 'run'))%0A depends_on('perl-math-matrixreal', type=('build', 'run'))%0A
f6fc6960bf44c63fd854455efd3d5eff135d5877
Fix failing build due to missing file
SegmentEditorSplitVolume/SegmentEditorSplitVolumeLib/__init__.py
SegmentEditorSplitVolume/SegmentEditorSplitVolumeLib/__init__.py
Python
0
@@ -0,0 +1,182 @@ +from SegmentEditorEffects.AbstractScriptedSegmentEditorEffect import *%0Afrom SegmentEditorEffects.AbstractScriptedSegmentEditorLabelEffect import *%0A%0Afrom SegmentEditorEffect import *%0A
c81ecdf74f3e668559ed4c257e3cdfb1d95f376c
Add files via upload
myFirstPythonProgram.py
myFirstPythonProgram.py
Python
0
@@ -0,0 +1,341 @@ +# Bryan Barrows%0A# CSC 110 - 9830%0A# January 13th, 2017%0A# File: myFirstPythonProgram.py%0A# A simple program illustrating chaotic behavior.%0A%0Adef main():%0A print(%22This program illustrates a chaotic function%22)%0A x = eval(input(%22Enter a number between 0 and 1: %22))%0A for i in range(10):%0A x = 3.9 * x * (1 - x)%0A print(x)%0A%0Amain()%0A
f3eb56111c115e65db6e55fcd1c69d695178b33b
Integrate LLVM at llvm/llvm-project@6144fc2da1b8
third_party/llvm/workspace.bzl
third_party/llvm/workspace.bzl
"""Provides the repository macro to import LLVM.""" load("//third_party:repo.bzl", "tf_http_archive") def repo(name): """Imports LLVM.""" LLVM_COMMIT = "eb03fa1d2c05bad5a5f75a89d47b4b31d84bb90b" LLVM_SHA256 = "53260f7983218c72b07f905694505188695e94e4e68fb9f2959f89073724feac" tf_http_archive( name = name, 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), ], link_files = { "//third_party/llvm:llvm.autogenerated.BUILD": "llvm/BUILD", "//third_party/mlir:BUILD": "mlir/BUILD", "//third_party/mlir:build_defs.bzl": "mlir/build_defs.bzl", "//third_party/mlir:linalggen.bzl": "mlir/linalggen.bzl", "//third_party/mlir:tblgen.bzl": "mlir/tblgen.bzl", "//third_party/mlir:test.BUILD": "mlir/test/BUILD", }, )
Python
0.000004
@@ -160,133 +160,133 @@ = %22 -eb03fa1d2c05bad5a5f75a89d47b4b31d84bb90b%22%0A LLVM_SHA256 = %2253260f7983218c72b07f905694505188695e94e4e68fb9f2959f89073724feac +6144fc2da1b87dc64ff887d73b60f7708f5cb0a4%22%0A LLVM_SHA256 = %22e6fe7c8df75bc1d3fb5f29758431e056406542768dd48333d32675dd4e06f1aa %22%0A%0A
62b2c69482d36a7afcdb732dd70a037d2513ba51
Add script to execute a simple command in a remote server over SSH
bh_sshcmd.py
bh_sshcmd.py
Python
0.000001
@@ -0,0 +1,657 @@ +import paramiko # pip install paramiko%0Aimport os%0A%0A%0Adef ssh_command(ip, user, command):%0A # you can run this script as%0A # SSH_PRIV_KEY=%5Byour private key path%5D python bh_sshcmd.py%0A key = paramiko.RSAKey.from_private_key_file(os.getenv('SSH_PRIV_KEY'))%0A%0A client = paramiko.SSHClient()%0A client.set_missing_host_key_policy(paramiko.AutoAddPolicy())%0A%0A print %22%5B==%3Econnecting%5D%22%0A client.connect(ip, username=user, pkey=key)%0A ssh_session = client.get_transport().open_session()%0A%0A if ssh_session.active:%0A ssh_session.exec_command(command)%0A print(ssh_session.recv(1024))%0A return%0A%0Assh_command('52.35.195.113', 'ubuntu', 'id')%0A
7ea3075b488b9cb89594128f41c22f0a14b7566c
Fix Exception names
tvrenamr/cli/core.py
tvrenamr/cli/core.py
#!/usr/bin/env python from __future__ import absolute_import import functools import logging import sys import click from tvrenamr import errors from tvrenamr.cli.helpers import (build_file_list, get_config, start_dry_run, stop_dry_run) from tvrenamr.logs import start_logging from tvrenamr.main import File, TvRenamr log = logging.getLogger('CLI') @click.command() @click.option('--config', type=click.Path(), help='Select a location for your config file. If the path is invalid the default locations will be used.') # noqa @click.option('-c', '--canonical', help='Set the show\'s canonical name to use when performing the online lookup.') # noqa @click.option('--debug', is_flag=True) @click.option('-d', '--dry-run', is_flag=True, help='Dry run your renaming.') @click.option('-e', '--episode', type=int, help='Set the episode number. Currently this will cause errors when working with more than one file.') # noqa @click.option('--ignore-filelist', type=tuple, default=()) @click.option('--log-file', type=click.Path(exists=True), help='Set the log file location.') @click.option('-l', '--log-level', help='Set the log level. Options: short, minimal, info and debug.') # noqa @click.option('--log-file', type=click.Path(exists=True), help='Set the log file location.') @click.option('-n', '--name', help="Set the episode's name.") @click.option('--no-cache', is_flag=True, help='Force all renames to ignore the cache.') @click.option('-o', '--output-format', help='Set the output format for the episodes being renamed.') @click.option('--organise/--no-organise', default=True, help='Organise renamed files into folders based on their show name and season number. Can be explicitly disabled.') # noqa @click.option('-p', '--partial', is_flag=True, help='Allow partial regex matching of the filename.') @click.option('-q', '--quiet', is_flag=True, help="Don't output logs to the command line") @click.option('-r', '--recursive', is_flag=True, help='Recursively lookup files in a given directory') # noqa @click.option('--rename-dir', type=click.Path(), help='The directory to move renamed files to, if not specified the working directory is used.') # noqa @click.option('--regex', help='The regular expression to use when extracting information from files.') # noqa @click.option('-s', '--season', help='Set the season number.') @click.option('--show', help="Set the show's name (will search for this name).") @click.option('--show-override', help="Override the show's name (only replaces the show's name in the final file)") # noqa @click.option('--specials', help='Set the show\'s specials folder (defaults to "Season 0")') @click.option('-t', '--the', is_flag=True, help="Set the position of 'The' in a show's name to the end of the show name") # noqa @click.argument('paths', nargs=-1, required=False, type=click.Path(exists=True)) def rename(config, canonical, debug, dry_run, episode, # pylint: disable-msg=too-many-arguments ignore_filelist, log_file, log_level, name, # pylint: disable-msg=too-many-arguments no_cache, output_format, organise, partial, # pylint: disable-msg=too-many-arguments quiet, recursive, rename_dir, regex, season, # pylint: disable-msg=too-many-arguments show, show_override, specials, the, paths): # pylint: disable-msg=too-many-arguments if debug: log_level = 10 start_logging(log_file, log_level, quiet) logger = functools.partial(log.log, level=26) if dry_run or debug: start_dry_run(logger) for current_dir, filename in build_file_list(paths, recursive, ignore_filelist): try: tv = TvRenamr(current_dir, debug, dry_run, no_cache) _file = File(**tv.extract_details_from_file( filename, user_regex=regex, partial=partial, )) # TODO: Warn setting season & episode will override *all* episodes _file.user_overrides(show, season, episode) _file.safety_check() config = get_config(config) for episode in _file.episodes: canonical = config.get( 'canonical', _file.show_name, default=episode.file_.show_name, override=canonical ) # TODO: Warn setting name will override *all* episodes episode.title = tv.retrieve_episode_title( episode, canonical=canonical, override=name, ) show = config.get_output(_file.show_name, override=show_override) the = config.get('the', show=_file.show_name, override=the) _file.show_name = tv.format_show_name(show, the=the) _file.set_output_format(config.get( 'format', _file.show_name, default=_file.output_format, override=output_format )) organise = config.get( 'organise', _file.show_name, default=False, override=organise ) rename_dir = config.get( 'renamed', _file.show_name, default=current_dir, override=rename_dir ) specials_folder = config.get( 'specials_folder', _file.show_name, default='Season 0', override=specials, ) path = tv.build_path( _file, rename_dir=rename_dir, organise=organise, specials_folder=specials_folder, ) tv.rename(filename, path) except errors.NoNetworkConnectionException: if dry_run or debug: stop_dry_run(logger) sys.exit(1) except (AttributeError, errors.EmptyEpisodeTitleException, errors.EpisodeNotFoundException, errors.IncorrectCustomRegularExpressionSyntaxException, errors.InvalidXMLException, errors.MissingInformationException, errors.OutputFormatMissingSyntaxException, errors.PathExistsException, errors.ShowNotFoundException, errors.UnexpectedFormatException) as e: continue except Exception as e: if debug: # In debug mode, show the full traceback. raise for msg in e.args: log.critical('Error: %s', msg) sys.exit(1) # if we're not doing a dry run add a blank line for clarity if not (debug and dry_run): log.info('') if dry_run or debug: stop_dry_run(logger)
Python
0.000045
@@ -5860,27 +5860,15 @@ ors. -No Network -Connection Exce @@ -6136,37 +6136,14 @@ rect -CustomRegularExpressionSyntax +RegExp Exce
cb7b286d1aa9fc10669b1b59afe334995a4c1174
add missed migration
taiga/projects/userstories/migrations/0021_auto_20201202_0850.py
taiga/projects/userstories/migrations/0021_auto_20201202_0850.py
Python
0.000003
@@ -0,0 +1,953 @@ +# Generated by Django 2.2.14 on 2020-12-02 08:50%0A%0Afrom django.db import migrations, models%0Aimport taiga.base.utils.time%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('userstories', '0020_userstory_swimlane'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterField(%0A model_name='userstory',%0A name='backlog_order',%0A field=models.BigIntegerField(default=taiga.base.utils.time.timestamp_mics, verbose_name='backlog order'),%0A ),%0A migrations.AlterField(%0A model_name='userstory',%0A name='kanban_order',%0A field=models.BigIntegerField(default=taiga.base.utils.time.timestamp_mics, verbose_name='kanban order'),%0A ),%0A migrations.AlterField(%0A model_name='userstory',%0A name='sprint_order',%0A field=models.BigIntegerField(default=taiga.base.utils.time.timestamp_mics, verbose_name='sprint order'),%0A ),%0A %5D%0A
74d094e1071f4fadffbb5f2351c4e171e528b68e
Update split-array-into-consecutive-subsequences.py
Python/split-array-into-consecutive-subsequences.py
Python/split-array-into-consecutive-subsequences.py
# Time: O(n) # Space: O(1) # You are given an integer array sorted in ascending order (may contain duplicates), # you need to split them into several subsequences, # where each subsequences consist of at least 3 consecutive integers. Return whether you can make such a split. # # Example 1: # Input: [1,2,3,3,4,5] # Output: True # Explanation: # You can split them into two consecutive subsequences : # 1, 2, 3 # 3, 4, 5 # Example 2: # Input: [1,2,3,3,4,4,5,5] # Output: True # Explanation: # You can split them into two consecutive subsequences : # 1, 2, 3, 4, 5 # 3, 4, 5 # Example 3: # Input: [1,2,3,4,4,5] # Output: False # Note: # The length of the input is in range of [1, 10000] class Solution(object): def isPossible(self, nums): """ :type nums: List[int] :rtype: bool """ pre, cur = float("-inf"), 0 cnt1, cnt2, cnt3 = 0, 0, 0 i = 0 while i < len(nums): cnt = 0 cur = nums[i] while i < len(nums) and cur == nums[i]: cnt += 1 i += 1 if cur != pre + 1: if cnt1 != 0 or cnt2 != 0: return False cnt1, cnt2, cnt3 = cnt, 0, 0 else: if cnt < cnt1 + cnt2: return False cnt1, cnt2, cnt3 = max(0, cnt - (cnt1 + cnt2 + cnt3)), \ cnt1, \ cnt2 + min(cnt3, cnt - (cnt1 + cnt2)) pre = cur return cnt1 == 0 and cnt2 == 0
Python
0.000154
@@ -1217,17 +1217,16 @@ , cnt3 = - cnt, 0,
615cb67e0082b6a2d2ab1c91623e9b2a20ddedec
create milestone migration for Havana release
neutron/db/migration/alembic_migrations/versions/havana_release.py
neutron/db/migration/alembic_migrations/versions/havana_release.py
Python
0
@@ -0,0 +1,1183 @@ +# vim: tabstop=4 shiftwidth=4 softtabstop=4%0A#%0A# Copyright 2013 OpenStack Foundation%0A#%0A# Licensed under the Apache License, Version 2.0 (the %22License%22); you may%0A# not use this file except in compliance with the License. You may obtain%0A# a copy of the License at%0A#%0A# http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS, WITHOUT%0A# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the%0A# License for the specific language governing permissions and limitations%0A# under the License.%0A#%0A%0A%22%22%22havana%0A%0ARevision ID: havana%0ARevises: 1341ed32cc1e%0ACreate Date: 2013-10-02 00:00:00.000000%0A%0A%22%22%22%0A%0A# revision identifiers, used by Alembic.%0Arevision = 'havana'%0Adown_revision = '3a520dd165d0'%0A%0A# Change to %5B'*'%5D if this migration applies to all plugins%0A%0Amigration_for_plugins = %5B'*'%5D%0A%0A%0Adef upgrade(active_plugins=None, options=None):%0A %22%22%22A no-op migration for marking the Havana release.%22%22%22%0A pass%0A%0A%0Adef downgrade(active_plugins=None, options=None):%0A %22%22%22A no-op migration for marking the Havana release.%22%22%22%0A pass%0A
e5247e1123ecd2e5ea1d98668ceded22d99c1c42
Create twitter-auth.py
twitter-auth.py
twitter-auth.py
Python
0.000012
@@ -0,0 +1,117 @@ +# paste your apps.twitter.com keys in here%0Aaccess_key = %22%22%0Aaccess_secret = %22%22%0Aconsumer_key = %22%22%0Aconsumer_secret = %22%22%0A
f63747a7e19b82a59d7ff1435725c3f35a4ba61b
Add contex processor to use cart in any template
apps/cart/context_processors.py
apps/cart/context_processors.py
Python
0
@@ -0,0 +1,79 @@ +from .cart import Cart%0A%0A%0Adef cart(request):%0A return %7B'cart': Cart(request)%7D%0A
9f0b46080ff3d8861e5b11527b6490d6e3d918fb
test making sure form edits are atomic
corehq/ex-submodules/couchforms/tests/test_edits.py
corehq/ex-submodules/couchforms/tests/test_edits.py
import os from django.test import TestCase from couchforms.models import XFormDeprecated from couchforms.tests.testutils import post_xform_to_couch class EditFormTest(TestCase): ID = '7H46J37FGH3' def tearDown(self): try: XFormInstance.get_db().delete_doc(self.ID) except: pass deprecated_xforms = XFormDeprecated.view( 'couchforms/edits', include_docs=True, ).all() for form in deprecated_xforms: form.delete() def test_basic_edit(self): first_file = os.path.join(os.path.dirname(__file__), "data", "duplicate.xml") edit_file = os.path.join(os.path.dirname(__file__), "data", "edit.xml") with open(first_file, "rb") as f: xml_data1 = f.read() with open(edit_file, "rb") as f: xml_data2 = f.read() docs = [] doc = post_xform_to_couch(xml_data1) self.assertEqual(self.ID, doc.get_id) self.assertEqual("XFormInstance", doc.doc_type) self.assertEqual("", doc.form['vitals']['height']) self.assertEqual("other", doc.form['assessment']['categories']) doc.domain = 'test-domain' doc.save() doc = post_xform_to_couch(xml_data2, domain='test-domain') self.assertEqual(self.ID, doc.get_id) self.assertEqual("XFormInstance", doc.doc_type) self.assertEqual("100", doc.form['vitals']['height']) self.assertEqual("Edited Baby!", doc.form['assessment']['categories']) docs.append(doc) doc = XFormDeprecated.view('couchforms/edits', include_docs=True).first() self.assertEqual(self.ID, doc.orig_id) self.assertNotEqual(self.ID, doc.get_id) self.assertEqual(XFormDeprecated.__name__, doc.doc_type) self.assertEqual("", doc.form['vitals']['height']) self.assertEqual("other", doc.form['assessment']['categories']) for doc in docs: doc.delete()
Python
0.000432
@@ -12,35 +12,177 @@ rom -django.test import TestCase +couchdbkit import ResourceNotFound, RequestFailed%0Afrom django.test import TestCase%0Afrom mock import MagicMock%0Afrom corehq.apps.receiverwrapper import submit_form_locally %0Afro @@ -223,16 +223,31 @@ precated +, XFormInstance %0Afrom co @@ -460,16 +460,33 @@ except + ResourceNotFound :%0A @@ -703,23 +703,18 @@ def -test_basic_edit +_get_files (sel @@ -1030,24 +1030,142 @@ = f.read()%0A%0A + return xml_data1, xml_data2%0A%0A def test_basic_edit(self):%0A xml_data1, xml_data2 = self._get_files()%0A%0A docs @@ -2241,16 +2241,16 @@ n docs:%0A - @@ -2258,16 +2258,1702 @@ doc.delete()%0A +%0A def test_broken_save(self):%0A %22%22%22%0A Test that if the second form submission terminates unexpectedly%0A and the main form isn't saved, then there are no side effects%0A such as the original having been marked as deprecated.%0A %22%22%22%0A%0A class BorkDB(object):%0A %22%22%22context manager for making a db's bulk_save temporarily fail%22%22%22%0A def __init__(self, db):%0A self.old = %7B%7D%0A self.db = db%0A%0A def __enter__(self):%0A self.old%5B'bulk_save'%5D = self.db.bulk_save%0A self.db.bulk_save = MagicMock(name='bulk_save',%0A side_effect=RequestFailed())%0A%0A def __exit__(self, exc_type, exc_val, exc_tb):%0A self.db.bulk_save = self.old%5B'bulk_save'%5D%0A%0A self.assertEqual(%0A XFormInstance.view('couchforms/edits', key=self.ID).count(), 0)%0A self.assertFalse(XFormInstance.get_db().doc_exist(self.ID))%0A%0A xml_data1, xml_data2 = self._get_files()%0A%0A submit_form_locally(xml_data1, 'test-domain')%0A doc = XFormInstance.get(self.ID)%0A self.assertEqual(self.ID, doc.get_id)%0A self.assertEqual(%22XFormInstance%22, doc.doc_type)%0A self.assertEqual('test-domain', doc.domain)%0A%0A with BorkDB(XFormInstance.get_db()):%0A with self.assertRaises(RequestFailed):%0A submit_form_locally(xml_data2, 'test-domain')%0A%0A # it didn't go through, so make sure there are no edits still%0A self.assertEqual(%0A XFormInstance.view('couchforms/edits', key=self.ID).count(), 0)%0A self.assertTrue(XFormInstance.get_db().doc_exist(self.ID))%0A
7c6077e107f40a3fcc3e1414f26071ceab0e0cf6
Create missing migration in taiga.projects.notifications
taiga/projects/notifications/migrations/0006_auto_20151103_0954.py
taiga/projects/notifications/migrations/0006_auto_20151103_0954.py
Python
0.000001
@@ -0,0 +1,528 @@ +# -*- coding: utf-8 -*-%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations, models%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('notifications', '0005_auto_20151005_1357'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterField(%0A model_name='notifypolicy',%0A name='notify_level',%0A field=models.SmallIntegerField(choices=%5B(%3CNotifyLevel.involved: 1%3E, 'Involved'), (%3CNotifyLevel.all: 2%3E, 'All'), (%3CNotifyLevel.none: 3%3E, 'None')%5D),%0A ),%0A %5D%0A
d9d27733d1885de0723f91558973c038be0386ec
Fix arm/disarm calls. (#17381)
homeassistant/components/alarm_control_panel/spc.py
homeassistant/components/alarm_control_panel/spc.py
""" Support for Vanderbilt (formerly Siemens) SPC alarm systems. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/alarm_control_panel.spc/ """ import logging import homeassistant.components.alarm_control_panel as alarm from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.core import callback from homeassistant.components.spc import (DATA_API, SIGNAL_UPDATE_ALARM) from homeassistant.const import ( STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_HOME, STATE_ALARM_ARMED_NIGHT, STATE_ALARM_DISARMED, STATE_ALARM_TRIGGERED) _LOGGER = logging.getLogger(__name__) def _get_alarm_state(area): """Get the alarm state.""" from pyspcwebgw.const import AreaMode if area.verified_alarm: return STATE_ALARM_TRIGGERED mode_to_state = { AreaMode.UNSET: STATE_ALARM_DISARMED, AreaMode.PART_SET_A: STATE_ALARM_ARMED_HOME, AreaMode.PART_SET_B: STATE_ALARM_ARMED_NIGHT, AreaMode.FULL_SET: STATE_ALARM_ARMED_AWAY, } return mode_to_state.get(area.mode) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the SPC alarm control panel platform.""" if discovery_info is None: return api = hass.data[DATA_API] async_add_entities([SpcAlarm(area=area, api=api) for area in api.areas.values()]) class SpcAlarm(alarm.AlarmControlPanel): """Representation of the SPC alarm panel.""" def __init__(self, area, api): """Initialize the SPC alarm panel.""" self._area = area self._api = api async def async_added_to_hass(self): """Call for adding new entities.""" async_dispatcher_connect(self.hass, SIGNAL_UPDATE_ALARM.format(self._area.id), self._update_callback) @callback def _update_callback(self): """Call update method.""" self.async_schedule_update_ha_state(True) @property def should_poll(self): """No polling needed.""" return False @property def name(self): """Return the name of the device.""" return self._area.name @property def changed_by(self): """Return the user the last change was triggered by.""" return self._area.last_changed_by @property def state(self): """Return the state of the device.""" return _get_alarm_state(self._area) async def async_alarm_disarm(self, code=None): """Send disarm command.""" from pyspcwebgw.const import AreaMode self._api.change_mode(area=self._area, new_mode=AreaMode.UNSET) async def async_alarm_arm_home(self, code=None): """Send arm home command.""" from pyspcwebgw.const import AreaMode self._api.change_mode(area=self._area, new_mode=AreaMode.PART_SET_A) async def async_alarm_arm_night(self, code=None): """Send arm home command.""" from pyspcwebgw.const import AreaMode self._api.change_mode(area=self._area, new_mode=AreaMode.PART_SET_B) async def async_alarm_arm_away(self, code=None): """Send arm away command.""" from pyspcwebgw.const import AreaMode self._api.change_mode(area=self._area, new_mode=AreaMode.FULL_SET)
Python
0.000001
@@ -2692,32 +2692,38 @@ reaMode%0A +await self._api.change @@ -2736,32 +2736,68 @@ area=self._area, +%0A new_mode=AreaMo @@ -2943,32 +2943,38 @@ reaMode%0A +await self._api.change @@ -2987,32 +2987,68 @@ area=self._area, +%0A new_mode=AreaMo @@ -3200,32 +3200,38 @@ reaMode%0A +await self._api.change @@ -3244,32 +3244,68 @@ area=self._area, +%0A new_mode=AreaMo @@ -3456,32 +3456,38 @@ reaMode%0A +await self._api.change @@ -3508,16 +3508,52 @@ f._area, +%0A new_mod
f10209add7513cba71441b410bf3a52a1d1c816c
add new site PyDéfis
tehbot/plugins/challenge/py.py
tehbot/plugins/challenge/py.py
Python
0
@@ -0,0 +1,886 @@ +# -*- coding: utf-8 -*-%0Afrom tehbot.plugins.challenge import *%0Aimport urllib%0Aimport urllib2%0Aimport urlparse%0Aimport lxml.html%0Aimport re%0A%0Aclass Site(BaseSite):%0A def prefix(self):%0A return u%22%5BPyD%C3%A9fis%5D%22%0A%0A def siteurl(self):%0A return %22https://pydefis.callicode.fr%22%0A%0A def userstats(self, user):%0A return self.userstats_api(user)%0A%0A def userstats_api(self, user):%0A url = %22https://pydefis.callicode.fr/wechall/userscore?username=%25s&authkey=%25s%22%0A authkey = self.settings%5B%22pydefis_api_key%22%5D%0A html = urllib2.urlopen(url %25 (Plugin.to_utf8(user), authkey), timeout=5).read()%0A if html == %220%22:%0A return None%0A user, rank, score, scoremax, challs_solved, challs_total, users_total = html.split(%22:%22)%0A return user, str(int(challs_solved)), int(challs_total), str(int(rank)), int(users_total), int(score), int(scoremax), None%0A
90a22bf70efbc6b14c697305919f6fca3aae39a1
Create __init__.py
__init__.py
__init__.py
Python
0.000429
@@ -0,0 +1 @@ +%0A
ad053bd49c0a108ed06df5385a6571b405476bd8
Create web_browser.py
web_browser.py
web_browser.py
Python
0.000417
@@ -0,0 +1,180 @@ +from webbrowser import *%0A%0Aurl=%22https://www.google.co.in%22%0A%0Aopen(url)%0A%0A'''%0AThis script lets you open the given link from terminal directly.%0AIt is made meanwhile learning python.%0A'''%0A
a2c702e226074763f78cc49eea30a020853bc6a7
Use `raise SystemError` instead of calling sys.exit().
libexec/windows_shares_discovery_runner.py
libexec/windows_shares_discovery_runner.py
#!/usr/bin/env python # # Copyright (C) 2009-2012: # Gabes Jean, naparuba@gmail.com # Gerhard Lausser, Gerhard.Lausser@consol.de # Gregory Starck, g.starck@gmail.com # # This file is part of Shinken. # # Shinken is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Shinken is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Shinken. If not, see <http://www.gnu.org/licenses/>. import optparse import sys import os import subprocess VERSION = '1.0' parser = optparse.OptionParser( "%prog [options] -H HOSTADRESS -u DOMAIN\\USER -p PASSWORD", version="%prog " + VERSION) parser.add_option('-H', "--hostname", help="Hostname to scan") parser.add_option('-u', '--user', default='guest', help="Username to scan with. Default to '%default'") parser.add_option('-p', '--password', default='', help="Password of your user. Default to ''") parser.add_option('-d', "--debug", action='store_true', help="Debug mode") opts, args = parser.parse_args() if not opts.hostname: parser.error("Requires one host to scan (option -H)") hostname = opts.hostname # The username may contain a domains like in `DOMAIN\user`. We must # protect the the `\` with another one for the command-line call. user = opts.user.replace('\\', '\\\\') debug = opts.debug password = opts.password cred = '%s%%%s' % (user, password) def p_debug(s): if debug: print "DEBUG:", s cmd = "smbclient --user=%s --grepable -L %s" % (cred, hostname) p_debug("Launching command, %s" % cmd) try: process = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, shell=True) except OSError, exp: print "Error in launching command:", cmd, exp sys.exit(2) p_debug("Try to communicate with the subprocess") (stdoutdata, stderrdata) = process.communicate() if process.returncode != 0: print "Error: the share scanner return an error: '%s'" % (stderrdata + stdoutdata) sys.exit(2) disks = [] printers = [] p_debug("Good return" + stdoutdata) def get_elements(line): if line.count('|') < 2: p_debug("Not a good line" + line) return None elts = line.split('|', 2) return elts for line in stdoutdata.splitlines(): line = line.strip() elts = get_elements(line) # Avoid strange line if not elts: continue typ = elts[0] sharename = elts[1] desc = elts[2] if typ == 'Printer': printers.append(sharename) if typ == 'Disk' and not sharename.endswith('$'): disks.append(sharename) if len(disks) > 0: print "%s::shares_detected=1" print "%s::_shares=%s" % (hostname, ','.join(disks)) if len(printers) > 0: print "%s::printers_detected=1" print "%s::_printers=%s" % (hostname, ','.join(printers))
Python
0
@@ -865,19 +865,8 @@ rse%0A -import sys%0A impo @@ -2214,29 +2214,37 @@ md, exp%0A -sys.e +raise SystemE xit(2)%0A%0Ap_de @@ -2462,13 +2462,21 @@ -sys.e +raise SystemE xit(
3b29a94a7009c0b652e8eca0b175bb97250e1b33
Add an extract_features(image, measurements) function returning a feature vector
feature_extraction/extraction.py
feature_extraction/extraction.py
Python
0.000018
@@ -0,0 +1,365 @@ +import numpy as np%0A%0A%22%22%22%0AGiven an image as a Numpy array and a set of measurement objects%0Aimplementing a compute method returning a feature vector, return a combined%0Afeature vector.%0A%22%22%22%0Adef extract_features(image, measurements):%0A%09# TODO(liam): parallelize multiple measurements on an image by using Celery%0A%09return np.ravel(%5Bm.compute(image) for m in measurements%5D)%0A%0A
1ee6e4f99318a065ee6cceaf2ed470bb3513188e
Add py-hstspreload (#19188)
var/spack/repos/builtin/packages/py-hstspreload/package.py
var/spack/repos/builtin/packages/py-hstspreload/package.py
Python
0
@@ -0,0 +1,673 @@ +# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other%0A# Spack Project Developers. See the top-level COPYRIGHT file for details.%0A#%0A# SPDX-License-Identifier: (Apache-2.0 OR MIT)%0A%0Afrom spack import *%0A%0A%0Aclass PyHstspreload(PythonPackage):%0A %22%22%22Chromium HSTS Preload list as a Python package and updated daily%22%22%22%0A%0A homepage = %22https://github.com/sethmlarson/hstspreload%22%0A url = %22https://pypi.io/packages/source/h/hstspreload/hstspreload-2020.9.23.tar.gz%22%0A%0A version('2020.9.23', sha256='35822733ba67cfb4efc6cd7d1230b509f0bd42c90eeb329faf2fe679f801e40f')%0A%0A depends_on('py-setuptools', type='build')%0A depends_on('py-wheel', type='build')%0A
6533ac770ffd97ece23dcaba154a31297be76b04
add Steam Store helper
reviews/utils.py
reviews/utils.py
Python
0
@@ -0,0 +1,1198 @@ +import requests%0Afrom django.core.cache import cache%0A%0A%0Aclass SteamException(Exception):%0A pass%0A%0A%0Aclass SteamStore(object):%0A l = None%0A cc = None%0A%0A def __init__(self, language='en', country='jp'):%0A self.l = language%0A self.cc = country%0A%0A def appdetails(self, app_id: int) -%3E dict:%0A url = 'http://store.steampowered.com/api/appdetails'%0A cache_key = 'appdetails_%7B:d%7D'.format(app_id)%0A app_id_str = str(app_id)%0A%0A j = cache.get(cache_key)%0A%0A if not j:%0A%0A r = requests.get(url=url, params=%7B'l': self.l, 'cc': self.cc, 'appids': app_id%7D)%0A%0A if r.status_code != 200:%0A raise SteamException('Steam API returned non-200 status')%0A%0A j = r.json()%0A cache.set(cache_key, j, 1209600)%0A%0A if app_id_str not in j or not j%5Bapp_id_str%5D%5B'success'%5D:%0A raise SteamException('Steam API returned unexpected error')%0A%0A return j%5Bapp_id_str%5D%5B'data'%5D%0A%0A @staticmethod%0A def is_support_japanese(data: dict) -%3E bool:%0A k = 'supported_languages'%0A return k in data and 'Japanese' in data%5Bk%5D%0A%0A @staticmethod%0A def name(data: dict) -%3E str:%0A return data%5B'name'%5D%0A
d11491d30a2fb418dd40bf7e97d4d35cc84d6f3f
Move Chuck database query function to another file
pyjokes/chuck.py
pyjokes/chuck.py
Python
0
@@ -0,0 +1,406 @@ +# -*- coding: utf-8 -*-%0A%0Aimport json%0A%0Atry:%0A from urllib2 import urlopen%0Aexcept:%0A from urllib.request import urlopen%0A%0A%0Adef get_chuck_nerd_jokes():%0A url = 'http://api.icndb.com/jokes/random?limitTo=%5Bnerdy%5D'%0A response = urlopen(url).readall().decode('utf-8')%0A data = json.loads(response)%0A d = data%5B'value'%5D%0A return d%5B'joke'%5D%0A%0A%0Aif __name__ == '__main__':%0A print(get_chuck_nerd_jokes())%0A
46db4860911e687bf5d3beef5f0b2f96ea145cd2
FIX lasso_dense_vs_sparse_data.py example needed update.
examples/linear_model/lasso_dense_vs_sparse_data.py
examples/linear_model/lasso_dense_vs_sparse_data.py
""" ============================== Lasso on dense and sparse data ============================== We show that linear_model.Lasso and linear_model.sparse.Lasso provide the same results and that in the case of sparse data linear_model.sparse.Lasso improves the speed. """ print __doc__ from time import time import numpy as np from scipy import sparse from scipy import linalg from sklearn.linear_model.sparse import Lasso as SparseLasso from sklearn.linear_model import Lasso as DenseLasso ############################################################################### # The two Lasso implementations on Dense data print "--- Dense matrices" n_samples, n_features = 200, 10000 np.random.seed(0) y = np.random.randn(n_samples) X = np.random.randn(n_samples, n_features) alpha = 1 sparse_lasso = SparseLasso(alpha=alpha, fit_intercept=False) dense_lasso = DenseLasso(alpha=alpha, fit_intercept=False) t0 = time() sparse_lasso.fit(X, y, max_iter=1000) print "Sparse Lasso done in %fs" % (time() - t0) t0 = time() dense_lasso.fit(X, y, max_iter=1000) print "Dense Lasso done in %fs" % (time() - t0) print "Distance between coefficients : %s" % linalg.norm(sparse_lasso.coef_ - dense_lasso.coef_) ############################################################################### # The two Lasso implementations on Sparse data print "--- Sparse matrices" Xs = X.copy() Xs[Xs < 2.5] = 0.0 Xs = sparse.coo_matrix(Xs) Xs = Xs.tocsc() print "Matrix density : %s %%" % (Xs.nnz / float(X.size) * 100) alpha = 0.1 sparse_lasso = SparseLasso(alpha=alpha, fit_intercept=False) dense_lasso = DenseLasso(alpha=alpha, fit_intercept=False) t0 = time() sparse_lasso.fit(Xs, y, max_iter=1000) print "Sparse Lasso done in %fs" % (time() - t0) t0 = time() dense_lasso.fit(Xs.todense(), y, max_iter=1000) print "Dense Lasso done in %fs" % (time() - t0) print "Distance between coefficients : %s" % linalg.norm(sparse_lasso.coef_ - dense_lasso.coef_)
Python
0
@@ -831,32 +831,47 @@ _intercept=False +, max_iter=1000 )%0Adense_lasso = @@ -905,32 +905,47 @@ _intercept=False +, max_iter=1000 )%0A%0At0 = time()%0As @@ -960,39 +960,24 @@ sso.fit(X, y -, max_iter=1000 )%0Aprint %22Spa @@ -1048,31 +1048,16 @@ fit(X, y -, max_iter=1000 )%0Aprint @@ -1622,16 +1622,31 @@ pt=False +, max_iter=1000 )%0Adense_ @@ -1696,16 +1696,31 @@ pt=False +, max_iter=1000 )%0A%0At0 = @@ -1748,31 +1748,16 @@ it(Xs, y -, max_iter=1000 )%0Aprint @@ -1843,31 +1843,16 @@ nse(), y -, max_iter=1000 )%0Aprint
35e30faabc3fd7ca68b7b28c9fd5b7a4c15b0e21
add charset compilation script
util/charset.py
util/charset.py
Python
0
@@ -0,0 +1,1959 @@ +# charset.py - lazy utility script for compiling character svgs, animation data and details into a single .json%0A#%0A# Usage:%0A# python charset.py %5Bcharset directory%5D%0A#%0A# The charset directory should have the following:%0A# - 'base.json' which contains the data and animation timings for each character in an array format, which an object for each character:%0A# - id%0A# - romaji (pronunciation/name for the character in the Latin alphabet)%0A# - timings (array of timings for each path)%0A# - an 'svg' directory containing an svg file for each character, in the format of %5Bcharacter id%5D.svg%0A#%0A# For an example, check out https://github.com/jaames/kakimasu/tree/master/charsets/hiragana%0A%0Afrom os.path import splitext%0A%0Afrom sys import argv%0A%0Aimport xml.etree.ElementTree as xmlParser%0Aimport json%0A%0A# xml namespace for svgs%0A# ref: https://docs.python.org/3/library/xml.etree.elementtree.html#parsing-xml-with-namespaces%0Ans = %7B%22svg%22: %22http://www.w3.org/2000/svg%22%7D%0A%0AcharSetDir = argv%5B1%5D%0A%0Awith open(charSetDir + %22/base.json%22) as file:%0A charMap = json.load(file)%0A%0Afor char in charMap:%0A tree = xmlParser.parse(charSetDir + %22/svg/%22 + char%5B%22id%22%5D + %22.svg%22)%0A root = tree.getroot()%0A%0A pathGroup = root.find(%22svg:g%22, ns)%5B0%5D%0A%0A # for debugging:%0A # print(char%5B'id'%5D)%0A # for path in pathGroup:%0A # print(path.attrib)%0A%0A # lazyyyy fallback for if there's no defined stroke timings%0A timings = char%5B%22timings%22%5D if %22timings%22 in char else %5B100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100%5D%0A%0A # create an array of svg paths (d) and their stroke timings (t)%0A char%5B%22paths%22%5D = %5B%7B%22d%22: path.attrib%5B'd'%5D, %22t%22: timings%5Bi%5D%7D for i, path in enumerate(pathGroup)%5D%0A%0A # we don't want the timings array in the compiled file%0A if %22timings%22 in char: del char%5B%22timings%22%5D%0A%0Awith open(charSetDir + %22/compiled.json%22, %22w%22) as out:%0A out.write(json.dumps(charMap, sort_keys=True))%0A%0Aprint(%22Finished compiling %22 + charSetDir)%0A
0d9613a1410aad150ccaf4b828971ec6f9e31520
Create lang.py
lang.py
lang.py
Python
0.000024
@@ -0,0 +1 @@ +%0A
2f268173e25bee5d671583bb905829e0ffd4f631
Add management command to clear all matches mostly useful with heroku
match/management/commands/reset-matches.py
match/management/commands/reset-matches.py
Python
0
@@ -0,0 +1,250 @@ +from django.core.management.base import BaseCommand, CommandError%0Afrom match.models import Match%0A%0Aimport sys%0A%0Aclass Command(BaseCommand):%0A help = 'Reset all match data'%0A%0A def handle(self, *args, **options):%0A Match.objects.all().delete()%0A
732eee568f19ed2e63f357b62fa539ff50a1c046
add program to display light readings in terminal in inf loop
light.py
light.py
Python
0
@@ -0,0 +1,1107 @@ +#!/usr/bin/python%0A%22%22%22%0Alight.py%0A%0ARead analog values from the photoresistor%0A%0A=======%0Arun with:%0A sudo ./light.py%0A%0ACopyright 2014 David P. Bradway (dpb6@duke.edu)%0A%0ALicensed under the Apache License, Version 2.0 (the %22License%22);%0Ayou may not use this file except in compliance with the License.%0AYou may obtain a copy of the License at%0A%0Ahttp://www.apache.org/licenses/LICENSE-2.0%0A%0AUnless required by applicable law or agreed to in writing, software%0Adistributed under the License is distributed on an %22AS IS%22 BASIS,%0AWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0ASee the License for the specific language governing permissions and%0Alimitations under the License.%0A%22%22%22%0A%0A__author__ = %22David Bradway%22%0A__email__ = %22dpb6@duke.edu%22%0A__license__ = %22Apache v2.0%22%0A%0A%0Adef main():%0A import Adafruit_BBIO.ADC as ADC%0A import time%0A %0A sensor_pin = 'P9_40'%0A %0A ADC.setup()%0A %0A print('Reading%5Ct%5CtVolts')%0A %0A while True:%0A reading = ADC.read(sensor_pin)%0A volts = reading * 1.800%0A print('%25f%5Ct%25f' %25 (reading, volts))%0A time.sleep(1)%0A%0Aif __name__ == %22__main__%22:%0A main()%0A
591bdcbfb80927d0ffb4922eb684fe7ce17c5456
Add manage.py
web/zoohackathon2016/manage.py
web/zoohackathon2016/manage.py
Python
0.000001
@@ -0,0 +1,814 @@ +#!/usr/bin/env python%0Aimport os%0Aimport sys%0A%0Aif __name__ == %22__main__%22:%0A os.environ.setdefault(%22DJANGO_SETTINGS_MODULE%22, %22zoohackathon2016.settings%22)%0A try:%0A from django.core.management import execute_from_command_line%0A except ImportError:%0A # The above import may fail for some other reason. Ensure that the%0A # issue is really that Django is missing to avoid masking other%0A # exceptions on Python 2.%0A try:%0A import django%0A except ImportError:%0A raise ImportError(%0A %22Couldn't import Django. Are you sure it's installed and %22%0A %22available on your PYTHONPATH environment variable? Did you %22%0A %22forget to activate a virtual environment?%22%0A )%0A raise%0A execute_from_command_line(sys.argv)%0A
cb26da63add95ebf9e7aa84a381293dd80f433cb
add test_db, test is OK
www/test_db.py
www/test_db.py
Python
0.998585
@@ -0,0 +1,537 @@ +#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A%0A__author__ = 'Haibo-Yu'%0A%0Afrom models import User, Blog, Comment%0A%0Afrom transwarp import db%0A%0Adb.create_engine(user='www-data', password='www-data', database='awesome')%0A%0Au = User(name='Test', email='test@example.com', password='1234567890', image='about:blank')%0A%0Au.insert()%0A%0Aprint 'new user id:', u.id%0A%0Au1 = User.find_first('where email=?', 'test@example.com')%0Aprint 'find user%5C's name:', u1.name%0A%0Au1.delete()%0A%0Au2 = User.find_first('where email=?', 'test@example.com')%0Aprint 'find user:', u2%0A%0A
ad5b3a334203394792c90b0d1bfe2dda8efe13b3
add admin interface for tracking logs
common/djangoapps/track/admin.py
common/djangoapps/track/admin.py
Python
0
@@ -0,0 +1,143 @@ +'''%0Adjango admin pages for courseware model%0A'''%0A%0Afrom track.models import *%0Afrom django.contrib import admin%0A%0Aadmin.site.register(TrackingLog)%0A
0196d9498644223959b4efae4fc084552bec8393
Add check_tar test.
check_tar.py
check_tar.py
Python
0
@@ -0,0 +1,3139 @@ +#!/usr/bin/env python3%0Afrom argparse import ArgumentParser%0Aimport logging%0Aimport os%0Aimport tarfile%0Afrom textwrap import dedent%0Aimport re%0Aimport sys%0A%0A%0Aclass TarfileNotFound(Exception):%0A %22%22%22Raised when specified tarfile cannot be found.%22%22%22%0A%0A%0Aclass TestedDirNotFound(Exception):%0A %22%22%22Raised when specified tested text dir cannot be found.%22%22%22%0A%0A%0Adef get_fpc_text(juju_tar):%0A %22%22%22Return the fallback-public-cloud.yaml text from a tarball.%0A%0A Raises an exception if the tarfile contains more or fewer than one%0A falllback-public-cloud.yaml.%0A %22%22%22%0A fpc_members = %5B%0A m for m in juju_tar.getmembers()%0A if os.path.basename(m.name) == 'fallback-public-cloud.yaml'%5D%0A if len(fpc_members) == 1:%0A return juju_tar.extractfile(fpc_members%5B0%5D).read()%0A else:%0A if len(fpc_members) == 0:%0A raise Exception('Tarfile has no fallback-public-cloud.')%0A else:%0A raise Exception(%0A 'Tarfile %7B:d%7D copies of fallback-public-cloud.'.format(%0A len(fpc_members)))%0A%0A%0Adef check_tar(tested_texts_dir, tar_filename):%0A %22%22%22Check the contents of the tarfile.%0A%0A tested_texts_dir is the name of a directory with the texted%0A fallback-public-cloud texts.%0A%0A tar_filename is the filename of the tarfile.%0A %22%22%22%0A base_tar_name = os.path.basename(tar_filename)%0A if re.match(r'juju-core_1%5C..*%5C.tar.gz', base_tar_name) is not None:%0A logging.info(%0A 'Juju 1 does not use fallback-public-cloud.yaml. Skipping.')%0A return 0%0A try:%0A tf = tarfile.open(tar_filename, 'r:*')%0A except FileNotFoundError:%0A raise TarfileNotFound('Tarfile not found: %22%7B%7D%22'.format(tar_filename))%0A with tf:%0A fpc_text = get_fpc_text(tf)%0A try:%0A tested_list = os.listdir(tested_texts_dir)%0A except FileNotFoundError:%0A raise TestedDirNotFound(%0A 'Tested dir not found: %22%7B%7D%22'.format(tested_texts_dir))%0A%0A for tested in tested_list:%0A if tested.startswith('.'):%0A continue%0A with open(os.path.join(tested_texts_dir, tested), 'rb') as tested_file:%0A if tested_file.read() == fpc_text:%0A logging.info('fallback-public-cloud.yaml matched %7B%7D.'.format(%0A tested))%0A return 0%0A else:%0A print(%0A 'fallback-public-cloud.yaml does not match a tested version.%5Cn'%0A 'Please have the QA team test it before landing.',%0A file=sys.stderr)%0A return 1%0A%0A%0Adef main():%0A logging.basicConfig(level=logging.INFO)%0A parser = ArgumentParser(description=dedent(%22%22%22%5C%0A Ensure fallback-public-cloud.yaml has been tested.%0A %22%22%22))%0A parser.add_argument('tested_texts_dir', help=(%0A 'The directory containing previously-tested versions of'%0A ' fallback-public-cloud.'))%0A parser.add_argument('tarfile', help='The tarfile to check.')%0A args = parser.parse_args()%0A try:%0A return check_tar(args.tested_texts_dir, args.tarfile)%0A except (TarfileNotFound, TestedDirNotFound) as e:%0A print(e, file=sys.stderr)%0A return 1%0A%0A%0Aif __name__ == '__main__':%0A sys.exit(main())%0A
a0123aad7414ce78be6b0c984f0895bba9568c99
Solve 50.
050/solution.py
050/solution.py
Python
0.999992
@@ -0,0 +1,1259 @@ +# coding: utf-8%0A%0A%22%22%22 Project Euler problem #50. %22%22%22%0A%0Aimport itertools as it%0A%0A%0Adef problem():%0A u%22%22%22 Solve the problem.%0A%0A The prime 41, can be written as the sum of six consecutive primes:%0A%0A 41 = 2 + 3 + 5 + 7 + 11 + 13%0A%0A This is the longest sum of consecutive primes that adds to a prime below%0A one-hundred.%0A%0A The longest sum of consecutive primes below one-thousand that adds to a%0A prime, contains 21 terms, and is equal to 953.%0A%0A Which prime, below one-million, can be written as the sum of the most%0A consecutive primes?%0A%0A Answer: 997651%0A%0A %22%22%22%0A limit = 10**6%0A primes = list(primes_xrange(limit))%0A sums = %5B0%5D%0A while sums%5B-1%5D %3C limit:%0A sums.append(sums%5B-1%5D + primes%5Blen(sums) - 1%5D)%0A return max(%0A set(a - b for b, a in it.combinations(sums%5B:-1%5D, 2)) & set(primes))%0A%0A%0Adef primes_xrange(a, b=0):%0A %22%22%22 Get prime numbers below passed stop value. %22%22%22%0A stop, start = (a, b) if not b else (b, a)%0A primes = %5BTrue%5D * stop%0A primes%5B0%5D, primes%5B1%5D = %5BFalse, False%5D%0A for idx, value in enumerate(primes):%0A if value is True:%0A primes%5Bidx*2::idx%5D = %5BFalse%5D * ((stop - 1)/idx - 1)%0A if idx %3E= start:%0A yield idx%0A%0A%0Aif __name__ == '__main__':%0A print problem()%0A
4e7310e8d7485e132c62c85599e2694d228e0747
Add an example
examples/chat.py
examples/chat.py
Python
0
@@ -0,0 +1,825 @@ +from zeroservices import BaseService%0Afrom zeroservices import ZeroMQMedium%0A%0Afrom time import time%0A%0A%0Aclass ChatService(BaseService):%0A%0A def __init__(self, username):%0A self.username = username%0A super(ChatService, self).__init__(ZeroMQMedium(self, port_random=True))%0A%0A def service_info(self):%0A return %7B'name': self.username%7D%0A%0A def on_event(self, message_type, message):%0A print %22ON EVENT%22, message_type, message%0A%0A def on_new_node(self, node_info):%0A print %22A NEW CHALLENGER !%22, node_info%0A%0A def coucou(self):%0A self.medium.publish('Hello', %7B'message': 'World'%7D)%0A%0A def main(self):%0A self.medium.ioloop.add_timeout(time() + 2, self.coucou)%0A super(ChatService, self).main()%0A%0Aif __name__ == '__main__':%0A import sys%0A s = ChatService(sys.argv%5B1%5D)%0A s.main()%0A