commit stringlengths 40 40 | old_file stringlengths 4 236 | new_file stringlengths 4 236 | old_contents stringlengths 1 3.26k | new_contents stringlengths 16 4.43k | subject stringlengths 16 624 | message stringlengths 17 3.29k | lang stringclasses 5
values | license stringclasses 13
values | repos stringlengths 5 91.5k |
|---|---|---|---|---|---|---|---|---|---|
ccafc2164b0b4a1734a1d4c47bf237eea293eae4 | nodeconductor/logging/admin.py | nodeconductor/logging/admin.py | from django.contrib import admin
from nodeconductor.logging import models
class AlertAdmin(admin.ModelAdmin):
list_display = ('uuid', 'alert_type', 'closed', 'scope', 'severity')
ordering = ('alert_type',)
base_model = models.Alert
admin.site.register(models.Alert, AlertAdmin)
| from django.contrib import admin
from nodeconductor.logging import models
class AlertAdmin(admin.ModelAdmin):
list_display = ('uuid', 'alert_type', 'created', 'closed', 'scope', 'severity')
list_filter = ('alert_type', 'created', 'closed', 'severity')
ordering = ('alert_type',)
base_model = models.Al... | Add list filtering for alerts | Add list filtering for alerts
| Python | mit | opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor |
cc4764da88f1629554ec3760f08ad6b299aae821 | examples/basics/scene/sphere.py | examples/basics/scene/sphere.py | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2015, Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
# -------------------------------------------------------------------------... | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2015, Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
# -------------------------------------------------------------------------... | Update example to demo various tessellations | Update example to demo various tessellations
| Python | bsd-3-clause | inclement/vispy,drufat/vispy,ghisvail/vispy,michaelaye/vispy,ghisvail/vispy,srinathv/vispy,RebeccaWPerry/vispy,julienr/vispy,inclement/vispy,bollu/vispy,inclement/vispy,dchilds7/Deysha-Star-Formation,Eric89GXL/vispy,michaelaye/vispy,kkuunnddaannkk/vispy,michaelaye/vispy,dchilds7/Deysha-Star-Formation,jdreaver/vispy,dru... |
ccf6626d86dd00b3f9848e19b3cb1139dba17e56 | tests/integration-test/test_junctions_create.py | tests/integration-test/test_junctions_create.py | #!/usr/bin/env python
from integrationtest import IntegrationTest, main
import unittest
class TestCreate(IntegrationTest, unittest.TestCase):
def test_junctions_create(self):
bam1 = self.inputFiles("test_hcc1395.bam")[0]
output_file = self.tempFile("create.out")
print "BAM1 is ", bam1
... | #!/usr/bin/env python
from integrationtest import IntegrationTest, main
import unittest
class TestCreate(IntegrationTest, unittest.TestCase):
def test_junctions_create(self):
bam1 = self.inputFiles("test_hcc1395.bam")[0]
output_file = self.tempFile("create.out")
print "BAM1 is ", bam1
... | Move positional argument to the end. | Move positional argument to the end.
This doesn't seem to work on a Mac when option comes after the positional
argument, not sure why this is, something to do with options parsing.
| Python | mit | tabbott/regtools,griffithlab/regtools,tabbott/regtools,tabbott/regtools,griffithlab/regtools,gatoravi/regtools,griffithlab/regtools,griffithlab/regtools,griffithlab/regtools,gatoravi/regtools,gatoravi/regtools,gatoravi/regtools,gatoravi/regtools,griffithlab/regtools,tabbott/regtools,tabbott/regtools |
8d0b472f6e84ac1167f8d8cedfb063f74f7fc3b0 | diamondash/widgets/text/text.py | diamondash/widgets/text/text.py | from pkg_resources import resource_string
from twisted.web.template import renderer, XMLString
from diamondash.widgets.widget.widget import Widget
class TextWidget(Widget):
"""A widget that simply displays static text."""
loader = XMLString(resource_string(__name__, 'template.xml'))
TYPE_NAME = 'text'... | from pkg_resources import resource_string
from twisted.web.template import renderer, XMLString
from diamondash.widgets.widget.widget import Widget, WidgetConfig
class TextWidgetConfig(WidgetConfig):
TYPE_NAME = 'text'
MIN_COLUMN_SPAN = 2
class TextWidget(Widget):
"""A widget that simply displays stati... | Refactor TextWidgetConfig out of TextWidget | Refactor TextWidgetConfig out of TextWidget
| Python | bsd-3-clause | praekelt/diamondash,praekelt/diamondash,praekelt/diamondash |
9de3f433a1c323831becbbe0d799475da96a92ae | virtualfish/__main__.py | virtualfish/__main__.py | from __future__ import print_function
import os
import sys
import inspect
if __name__ == "__main__":
base_path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
commands = ['. {}'.format(os.path.join(base_path, 'virtual.fish'))]
for plugin in sys.argv[1:]:
path = os.path... | from __future__ import print_function
import os
import sys
import inspect
if __name__ == "__main__":
base_path = os.path.dirname(os.path.abspath(__file__))
commands = ['. {}'.format(os.path.join(base_path, 'virtual.fish'))]
for plugin in sys.argv[1:]:
path = os.path.join(base_path, plugin + '.fis... | Use __file__ to find find the module | Use __file__ to find find the module
`inspect.getfile(inspect.currentframe())` seems to return a relative path that
ends up with the virtualfish functions not being loaded.
| Python | mit | scorphus/virtualfish,adambrenecki/virtualfish,adambrenecki/virtualfish,scorphus/virtualfish |
1e88a3de5ed96847baf17eb1beb2599f5c79fb6b | djangobb_forum/search_indexes.py | djangobb_forum/search_indexes.py | from haystack.indexes import *
from haystack import site
from celery_haystack.indexes import CelerySearchIndex
import djangobb_forum.models as models
class PostIndex(CelerySearchIndex):
text = CharField(document=True, use_template=True)
author = CharField(model_attr='user')
created = DateTimeField(model_... | from haystack.indexes import *
from haystack import site
from gargoyle import gargoyle
try:
if gargoyle.is_active('solr_indexing_enabled'):
from celery_haystack.indexes import CelerySearchIndex as SearchIndex
except:
# Allow migrations to run
from celery_haystack.indexes import CelerySearchIndex as... | Disable indexing through celery when it's disabled. | Disable indexing through celery when it's disabled.
| Python | bsd-3-clause | tjvr/s2forums,LLK/s2forums,LLK/s2forums,LLK/s2forums,tjvr/s2forums,tjvr/s2forums |
2ca115789b96287ba0c8a32c514d1fe2beedb750 | girc/capabilities.py | girc/capabilities.py | #!/usr/bin/env python3
# Written by Daniel Oaks <daniel@danieloaks.net>
# Released under the ISC license
from .utils import CaseInsensitiveDict, CaseInsensitiveList
class Capabilities:
"""Ingests sets of client capabilities and provides access to them."""
def __init__(self, wanted=[]):
self.available ... | #!/usr/bin/env python3
# Written by Daniel Oaks <daniel@danieloaks.net>
# Released under the ISC license
from .utils import CaseInsensitiveDict, CaseInsensitiveList
class Capabilities:
"""Ingests sets of client capabilities and provides access to them."""
def __init__(self, wanted=[]):
self.available ... | Mark CAPA= as None instead of True | [caps] Mark CAPA= as None instead of True
| Python | isc | DanielOaks/girc,DanielOaks/girc |
cc143597dd7673fb13d8257c4dd7bdafa31c2dd4 | examples/distributed_workers.py | examples/distributed_workers.py | import sc2
from sc2 import run_game, maps, Race, Difficulty
from sc2.player import Bot, Computer
from sc2.constants import *
class TerranBot(sc2.BotAI):
async def on_step(self, iteration):
await self.distribute_workers()
await self.build_supply()
await self.build_workers()
await se... | import sc2
from sc2 import run_game, maps, Race, Difficulty
from sc2.player import Bot, Computer
from sc2.constants import *
class TerranBot(sc2.BotAI):
async def on_step(self, iteration):
await self.distribute_workers()
await self.build_supply()
await self.build_workers()
await se... | Fix command center selection in example | Fix command center selection in example
| Python | mit | Dentosal/python-sc2 |
fd9f69cbc5512ea91837ff4512d4c9549b2f9eeb | plugin/DebianUtils/__init__.py | plugin/DebianUtils/__init__.py | # -*- coding: utf-8 -*-
#
# Debian Changes Bot
# Copyright (C) 2008 Chris Lamb <chris@chris-lamb.co.uk>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the... | # -*- coding: utf-8 -*-
#
# Debian Changes Bot
# Copyright (C) 2008 Chris Lamb <chris@chris-lamb.co.uk>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the... | Add reload routines to DebianUtils plugin | Add reload routines to DebianUtils plugin
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@chris-lamb.co.uk>
| Python | agpl-3.0 | lamby/debian-devel-changes-bot,lamby/debian-devel-changes-bot,lamby/debian-devel-changes-bot,xtaran/debian-devel-changes-bot,sebastinas/debian-devel-changes-bot,xtaran/debian-devel-changes-bot |
8f30a7d3794891373a1f707bdf6afa083717dfc0 | ggplot/scales/scale_identity.py | ggplot/scales/scale_identity.py | from __future__ import absolute_import, division, print_function
from ..utils import identity, alias
from .scale import scale_discrete, scale_continuous
class scale_color_identity(scale_discrete):
aesthetics = ['color']
palette = staticmethod(identity)
class scale_fill_identity(scale_color_identity):
a... | from __future__ import absolute_import, division, print_function
from ..utils import identity, alias
from .scale import scale_discrete, scale_continuous
class MapTrainMixin(object):
"""
Override map and train methods
"""
def map(self, x):
return x
def train(self, x):
# do nothing... | Fix identity scales, override map & train methods | Fix identity scales, override map & train methods
| Python | mit | has2k1/plotnine,has2k1/plotnine |
f04ec6d18ac1dd9932c517ef19d0d7a9d7bae003 | app/__init__.py | app/__init__.py | import os
from flask import Flask, jsonify, g
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def create_app(config_name):
"""Create an application instance.
This is called by a runner script, such as /run.py.
"""
from .auth import password_auth
app = Flask(__name__)
# apply ... | import os
from flask import Flask, jsonify, g
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def create_app(config_name):
"""Create an application instance.
This is called by a runner script, such as /run.py.
"""
from .auth import password_auth
app = Flask(__name__)
# apply ... | Allow app to be imported | Allow app to be imported
Flask httpdomain needs to import the Flask app. It turns out the the
way to get the path to the configuration file assumed the app was always
being run/imported from the base of the ltd-keeper repo, which isn't
always true, especially for Sphinx doc builds.
This correctly derives a path from ... | Python | mit | lsst-sqre/ltd-keeper,lsst-sqre/ltd-keeper |
5c1fc4b6ebbd2ee54318c5bc9877868858ea03ee | auth0/v2/authentication/base.py | auth0/v2/authentication/base.py | import json
import requests
from ..exceptions import Auth0Error
class AuthenticationBase(object):
def post(self, url, data={}, headers={}):
response = requests.post(url=url, data=json.dumps(data),
headers=headers)
return self._process_response(response)
def _... | import json
import requests
from ..exceptions import Auth0Error
class AuthenticationBase(object):
def post(self, url, data={}, headers={}):
response = requests.post(url=url, data=json.dumps(data),
headers=headers)
return self._process_response(response)
def g... | Add .get() method to AuthenticationBase | Add .get() method to AuthenticationBase
| Python | mit | auth0/auth0-python,auth0/auth0-python |
d2e88ec95f3a4b2ac01b47154d675996cbed23d3 | split_dataset.py | split_dataset.py | import os
import numpy as np
data_dir = "data/dataset/"
jpg_filenames = list(filter(lambda x: x[-3:] == "jpg", os.listdir(data_dir)))
# Randomly select the test dataset
test_percentage = 0.1
n_test = int(round(len(jpg_filenames) * test_percentage))
if n_test == 0: n_test = 1
# Randomly select the images for testing... | import os
import numpy as np
data_dir = "data/dataset/"
jpg_filenames = list(filter(lambda x: x[-3:] == "jpg", os.listdir(data_dir)))
# Randomly select the test dataset
test_percentage = 0.1
n_test = int(round(len(jpg_filenames) * test_percentage))
if n_test == 0: n_test = 1
# Randomly select the images for testing... | Add verbose print on split dataset script | Add verbose print on split dataset script
| Python | mit | SetaSouto/license-plate-detection |
edab226942fbab75aa66e16d5814b1c38c0e8507 | 2048/policy.py | 2048/policy.py | import tensorflow as tf
class EpsilonGreedyPolicy:
def __init__(self, env, dqn, epsilon_max, epsilon_min, epsilon_decay):
self.env = env
self.dqn = dqn
self.epsilon_max = epsilon_max
self.epsilon_min = epsilon_min
self.epsilon_decay = epsilon_decay
def take_action(self... | import tensorflow as tf
class EpsilonGreedyPolicy:
def __init__(self, env, dqn, epsilon_max, epsilon_min, epsilon_decay):
self.env = env
self.dqn = dqn
self.epsilon_max = epsilon_max
self.epsilon_min = epsilon_min
self.epsilon_decay = epsilon_decay
def take_action(self... | Fix error in state shape in EGP | [2048] Fix error in state shape in EGP
| Python | mit | akshaykurmi/reinforcement-learning |
ee623ec4511c4aa7d93384b8a935144cd52621ae | test.py | test.py | import subprocess
import unittest
class CompareErrorMessages(unittest.TestCase):
def test_missing_file_return_code_the_same_as_ls(self):
args = ['./lss.sh', 'foo']
ret = subprocess.call(args)
args2 = ['ls', 'foo']
ret2 = subprocess.call(args2)
self.assertEqual(ret == 0, ret2... | import os
import subprocess
import unittest
class CompareErrorMessages(unittest.TestCase):
def test_missing_file_return_code_the_same_as_ls(self):
DEVNULL = open(os.devnull, 'wb')
args = ['./lss.sh', 'foo']
ret = subprocess.call(args, stderr=DEVNULL)
args2 = ['ls', 'foo']
re... | Discard output when checking return code. | Discard output when checking return code.
| Python | bsd-3-clause | jwg4/les,jwg4/les |
7c09e2df765b466b65570116fe8d0cc5f42d30dd | indra/sources/phosphoELM/api.py | indra/sources/phosphoELM/api.py | import csv
ppelm_s3_key = ''
def process_from_dump(fname=None, delimiter='\t'):
if fname is None:
# ToDo Get from S3
return []
else:
with open(fname, 'r') as f:
csv_reader = csv.reader(f.readlines(), delimiter=delimiter)
ppelm_json = _get_json_from_entry_rows(c... | import csv
from .processor import PhosphoELMPRocessor
s3_bucket = 'bigmech'
ppelm_s3_key = ''
def process_from_dump(fname=None, delimiter='\t'):
if fname is None:
# ToDo Get from S3
return []
else:
with open(fname, 'r') as f:
csv_reader = csv.reader(f.readlines(), delimit... | Return processor w processed statements | Return processor w processed statements
| Python | bsd-2-clause | johnbachman/belpy,bgyori/indra,bgyori/indra,sorgerlab/indra,sorgerlab/belpy,bgyori/indra,sorgerlab/indra,sorgerlab/indra,johnbachman/indra,sorgerlab/belpy,johnbachman/belpy,johnbachman/indra,sorgerlab/belpy,johnbachman/indra,johnbachman/belpy |
0858d7ded502ee7d1a31d8df767bf1b52648e32e | issues_hel/tests/test_import.py | issues_hel/tests/test_import.py | import json
import os
import pytest
from issues.models import Issue
from issues.sync.down import update_local_issue
@pytest.mark.django_db
def test_import_taskful_georeport():
with open(os.path.join(os.path.dirname(__file__), "taskful_request.json"), "r") as infp:
data = json.load(infp)
issue, creat... | import json
import os
import pytest
from issues.sync.down import update_local_issue
@pytest.mark.django_db
def test_import_taskful_georeport():
with open(os.path.join(os.path.dirname(__file__), "taskful_request.json"), "r", encoding="utf8") as infp:
data = json.load(infp)
issue, created = update_loc... | Fix failing import test (how did this ever work?) | Fix failing import test (how did this ever work?)
| Python | mit | 6aika/issue-reporting,6aika/issue-reporting,6aika/issue-reporting |
604e7d15c3072682ba3327c1ef6333d6bb0c768b | astropy/io/misc/asdf/__init__.py | astropy/io/misc/asdf/__init__.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-
"""
The **asdf** subpackage contains code that is used to serialize astropy types
so that they can be represented and stored using the Advanced Scientific Data
Format (ASDF). This subpackage defines classes, referred to as **tags**,... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-
"""
The **asdf** subpackage contains code that is used to serialize astropy types
so that they can be represented and stored using the Advanced Scientific Data
Format (ASDF). This subpackage defines classes, referred to as **tags**,... | Update ASDF-related docs to reflect presence of schemas [docs only] | Update ASDF-related docs to reflect presence of schemas [docs only]
| Python | bsd-3-clause | lpsinger/astropy,StuartLittlefair/astropy,pllim/astropy,StuartLittlefair/astropy,larrybradley/astropy,saimn/astropy,mhvk/astropy,astropy/astropy,mhvk/astropy,lpsinger/astropy,StuartLittlefair/astropy,bsipocz/astropy,stargaser/astropy,dhomeier/astropy,astropy/astropy,pllim/astropy,StuartLittlefair/astropy,aleksandr-baka... |
4b63093abbc388bc26151422991ce39553cf137f | neuroimaging/utils/tests/test_odict.py | neuroimaging/utils/tests/test_odict.py | """Test file for the ordered dictionary module, odict.py."""
from neuroimaging.externals.scipy.testing import *
from neuroimaging.utils.odict import odict
class TestOdict(TestCase):
def setUp(self):
print 'setUp'
self.thedict = odict((('one', 1.0), ('two', 2.0), ('three', 3.0)))
def test_cop... | """Test file for the ordered dictionary module, odict.py."""
from neuroimaging.externals.scipy.testing import *
from neuroimaging.utils.odict import odict
class TestOdict(TestCase):
def setUp(self):
print 'setUp'
self.thedict = odict((('one', 1.0), ('two', 2.0), ('three', 3.0)))
def test_cop... | Fix nose call so tests run in __main__. | BUG: Fix nose call so tests run in __main__. | Python | bsd-3-clause | alexis-roche/nipy,alexis-roche/nipy,arokem/nipy,nipy/nipy-labs,nipy/nireg,alexis-roche/nireg,alexis-roche/register,nipy/nipy-labs,arokem/nipy,alexis-roche/register,nipy/nireg,bthirion/nipy,bthirion/nipy,alexis-roche/nireg,arokem/nipy,bthirion/nipy,alexis-roche/register,arokem/nipy,alexis-roche/niseg,alexis-roche/nipy,a... |
8b92bc6c4a782dbb83aadb1bbfc5951dc53f53e1 | netbox/dcim/migrations/0145_site_remove_deprecated_fields.py | netbox/dcim/migrations/0145_site_remove_deprecated_fields.py | from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('dcim', '0144_fix_cable_abs_length'),
]
operations = [
migrations.RemoveField(
model_name='site',
name='asn',
),
migrations.RemoveField(
model_nam... | from django.db import migrations
from django.db.utils import DataError
def check_legacy_data(apps, schema_editor):
"""
Abort the migration if any legacy site fields still contain data.
"""
Site = apps.get_model('dcim', 'Site')
if site_count := Site.objects.exclude(asn__isnull=True).count():
... | Add migration safeguard to prevent accidental destruction of data | Add migration safeguard to prevent accidental destruction of data
| Python | apache-2.0 | digitalocean/netbox,digitalocean/netbox,digitalocean/netbox,digitalocean/netbox |
90eb1118c69a1b9e9785145c59a98d7c48613650 | nlppln/commands/ls_chunk.py | nlppln/commands/ls_chunk.py | #!/usr/bin/env python
import click
import os
import json
from nlppln.utils import cwl_file
@click.command()
@click.argument('in_dir', type=click.Path(exists=True))
@click.argument('chunks', type=click.File(encoding='utf-8'))
@click.option('--name', '-n')
def ls_chunk(in_dir, chunks, name):
div = json.load(chunks... | #!/usr/bin/env python
import click
import os
import json
from nlppln.utils import cwl_file
@click.command()
@click.argument('in_dir', type=click.Path(exists=True))
@click.argument('chunks', type=click.File(encoding='utf-8'))
@click.argument('name')
def ls_chunk(in_dir, chunks, name):
div = json.load(chunks)
... | Make name an argument instead of an option | Make name an argument instead of an option
It is required to specify a chunk name.
| Python | apache-2.0 | WhatWorksWhenForWhom/nlppln,WhatWorksWhenForWhom/nlppln,WhatWorksWhenForWhom/nlppln |
b50aee7a23c44b98b3cd6fee607cc5978a57c927 | contrail_provisioning/config/templates/contrail_sudoers.py | contrail_provisioning/config/templates/contrail_sudoers.py | import string
template = string.Template("""
Defaults:contrail !requiretty
Cmnd_Alias CONFIGRESTART = /usr/sbin/service supervisor-config restart
contrail ALL = (root) NOPASSWD:CONFIGRESTART
""")
| import string
template = string.Template("""
Defaults:contrail !requiretty
Cmnd_Alias CONFIGRESTART = /usr/sbin/service supervisor-config restart
Cmnd_Alias IFMAPRESTART = /usr/sbin/service ifmap restart
contrail ALL = (root) NOPASSWD:CONFIGRESTART,IFMAPRESTART
""")
| Allow contrail user to restart ifmap without password closes-jira-bug: JCB-218958 | Allow contrail user to restart ifmap without password
closes-jira-bug: JCB-218958
Change-Id: Id95001cf5ab455650b5b900b9b5f7bb33ccef8e3
| Python | apache-2.0 | Juniper/contrail-provisioning,Juniper/contrail-provisioning |
249c6bbd74174b3b053fed13a58b24c8d485163a | src/ggrc/models/custom_attribute_value.py | src/ggrc/models/custom_attribute_value.py | # Copyright (C) 2014 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: laran@reciprocitylabs.com
# Maintained By: laran@reciprocitylabs.com
from ggrc import db
from .mixins import (
deferred, Base
)
class Cust... | # Copyright (C) 2014 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: laran@reciprocitylabs.com
# Maintained By: laran@reciprocitylabs.com
from ggrc import db
from ggrc.models.mixins import Base
from ggrc.models.mixin... | Fix code style for custom attribute value | Fix code style for custom attribute value
| Python | apache-2.0 | plamut/ggrc-core,selahssea/ggrc-core,hasanalom/ggrc-core,AleksNeStu/ggrc-core,jmakov/ggrc-core,andrei-karalionak/ggrc-core,AleksNeStu/ggrc-core,andrei-karalionak/ggrc-core,j0gurt/ggrc-core,jmakov/ggrc-core,NejcZupec/ggrc-core,selahssea/ggrc-core,plamut/ggrc-core,josthkko/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core... |
e2ce9ad697cd686e91b546f6f3aa7b24b5e9266f | masters/master.tryserver.chromium.angle/master_site_config.py | masters/master.tryserver.chromium.angle/master_site_config.py | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class TryServerANGLE(Master.Master4a):
project_name = 'ANGLE Try Server'
master_port... | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class TryServerANGLE(Master.Master4a):
project_name = 'ANGLE Try Server'
master_port... | Add buildbucket service account to Angle master. | Add buildbucket service account to Angle master.
BUG=577560
TBR=nodir@chromium.org
Review URL: https://codereview.chromium.org/1624703003
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@298368 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | eunchong/build,eunchong/build,eunchong/build,eunchong/build |
eab3d891d7b0460223990642251bec4bb377543d | website/addons/github/tests/factories.py | website/addons/github/tests/factories.py | # -*- coding: utf-8 -*-
from factory import Sequence, SubFactory
from tests.factories import ExternalAccountFactory, ModularOdmFactory, ProjectFactory, UserFactory
from website.addons.github.model import GitHubNodeSettings, GitHubUserSettings
class GitHubAccountFactory(ExternalAccountFactory):
provider = 'githu... | # -*- coding: utf-8 -*-
from factory import Sequence, SubFactory
from tests.factories import ExternalAccountFactory, ModularOdmFactory, ProjectFactory, UserFactory
from website.addons.github.model import GitHubNodeSettings, GitHubUserSettings
class GitHubAccountFactory(ExternalAccountFactory):
provider = 'githu... | Include display_name in factory for tests | Include display_name in factory for tests
| Python | apache-2.0 | leb2dg/osf.io,doublebits/osf.io,DanielSBrown/osf.io,kwierman/osf.io,abought/osf.io,mluo613/osf.io,jnayak1/osf.io,cslzchen/osf.io,aaxelb/osf.io,pattisdr/osf.io,mluke93/osf.io,laurenrevere/osf.io,alexschiller/osf.io,kwierman/osf.io,wearpants/osf.io,acshi/osf.io,Nesiehr/osf.io,zachjanicki/osf.io,monikagrabowska/osf.io,mon... |
9ff005d1c3ffc82e8469f1ecf7dda2d9ebf8bb46 | Museau/urls.py | Museau/urls.py | from django.conf.urls.defaults import patterns, include, url
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Museau
url(r'^$', 'music.views.home', name='home'),
# Ajax requests
url(r'^... | from django.conf.urls.defaults import patterns, include, url
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Museau
url(r'^$', 'music.views.home', name='home'),
# django-registration
u... | Remove ajax urlconf since we don't use it anymore | Remove ajax urlconf since we don't use it anymore
| Python | mit | folz/Museau,folz/Museau |
306336d4445149cd2f0d6fa3a58b7244eafe3cd0 | conveyor/store.py | conveyor/store.py | class BaseStore(object):
def set(self, key, value):
raise NotImplementedError
def get(self, key):
raise NotImplementedError
class InMemoryStore(BaseStore):
def __init__(self, *args, **kwargs):
super(InMemoryStore, self).__init__(*args, **kwargs)
self._data = {}
def... | class BaseStore(object):
def set(self, key, value):
raise NotImplementedError
def get(self, key):
raise NotImplementedError
class InMemoryStore(BaseStore):
def __init__(self, *args, **kwargs):
super(InMemoryStore, self).__init__(*args, **kwargs)
self._data = {}
def... | Add a RedisStore to conveyor | Add a RedisStore to conveyor
| Python | bsd-2-clause | crateio/carrier |
2bdf58c9a707c0a08c7c48d46c5b9b13db14965f | github/data_types/repository.py | github/data_types/repository.py | from data_types.user import User
class Repository:
"""
GitHub Repository
https://developer.github.com/v3/repos/
Attributes:
id: GitHub internal id
name: Repository short name like "codex"
full_name: Repository short full_name like "codex-team/codex"
description: Optio... | from data_types.user import User
class Repository:
"""
GitHub Repository
https://developer.github.com/v3/repos/
Attributes:
id: GitHub internal id
name: Repository short name like "codex"
full_name: Repository short full_name like "codex-team/codex"
description: Optio... | Add a new field "stargazers_count" | Add a new field "stargazers_count" | Python | mit | codex-bot/github |
19dd85a13ef0108bd2860a658881a255f6e31613 | debsources/app/patches/views.py | debsources/app/patches/views.py | # Copyright (C) 2015 The Debsources developers <info@sources.debian.net>.
# See the AUTHORS file at the top-level directory of this distribution and at
# https://anonscm.debian.org/gitweb/?p=qa/debsources.git;a=blob;f=AUTHORS;hb=HEAD
#
# This file is part of Debsources. Debsources is free software: you can
# redistrib... | # Copyright (C) 2015 The Debsources developers <info@sources.debian.net>.
# See the AUTHORS file at the top-level directory of this distribution and at
# https://anonscm.debian.org/gitweb/?p=qa/debsources.git;a=blob;f=AUTHORS;hb=HEAD
#
# This file is part of Debsources. Debsources is free software: you can
# redistrib... | Add version handling in SummaryView for the patches BP | Add version handling in SummaryView for the patches BP
| Python | agpl-3.0 | devoxel/debsources,vivekanand1101/debsources,vivekanand1101/debsources,zacchiro/debsources,Debian/debsources,devoxel/debsources,zacchiro/debsources,matthieucan/debsources,Debian/debsources,oorestisime/debsources,vivekanand1101/debsources,devoxel/debsources,matthieucan/debsources,devoxel/debsources,matthieucan/debsource... |
84ff58c997c163f9e3566245beb9af308a77b880 | spyder_terminal/server/rest/term_rest.py | spyder_terminal/server/rest/term_rest.py | # -*- coding: iso-8859-15 -*-
"""Main HTTP routes request handlers."""
import tornado.web
import tornado.escape
from os import getcwd
class MainHandler(tornado.web.RequestHandler):
"""Handles creation of new terminals."""
@tornado.gen.coroutine
def post(self):
"""POST verb: Create a new termina... | # -*- coding: iso-8859-15 -*-
"""Main HTTP routes request handlers."""
import tornado.web
import tornado.escape
from os import getcwd
class MainHandler(tornado.web.RequestHandler):
"""Handles creation of new terminals."""
@tornado.gen.coroutine
def post(self):
"""POST verb: Create a new termina... | Change default terminal size arguments - Add server debug log message | Change default terminal size arguments - Add server debug log message
| Python | mit | spyder-ide/spyder-terminal,spyder-ide/spyder-terminal,spyder-ide/spyder-terminal,spyder-ide/spyder-terminal,andfoy/spyder-terminal,andfoy/spyder-terminal,andfoy/spyder-terminal |
0e69efcd3a6992d0a34d7ecb80a76c3fbc52975c | pikka_bird_collector/sender.py | pikka_bird_collector/sender.py | import datetime
import logging
import json
import urllib.parse
import requests
class Sender():
SERVER_SERVICES = {
'collections': '/collections'}
REQUEST_HEADERS = {
'Content-Type': 'application/json'}
def __init__(self, server_uri, logger=None):
self.server_uri = se... | import datetime
import logging
import json
import urllib.parse
import requests
class Sender():
SERVER_SERVICES = {
'collections': '/collections'}
REQUEST_HEADERS = {
'Content-Type': 'application/json'}
def __init__(self, server_uri, logger=None):
self.server_uri = se... | Extend Sender.send() to return boolean status. | Extend Sender.send() to return boolean status.
| Python | mit | tiredpixel/pikka-bird-collector-py |
89cb0d1558e02a72048047709d9960a1f7ee265e | src/waldur_mastermind/marketplace_checklist/import_export_resources.py | src/waldur_mastermind/marketplace_checklist/import_export_resources.py | import tablib
from import_export import fields, resources, widgets
from . import models
CategoryResource = resources.modelresource_factory(models.Category)
QuestionResource = resources.modelresource_factory(models.Question)
class ChecklistResource(resources.ModelResource):
questions = fields.Field(column_name='... | import tablib
from import_export import fields, resources, widgets
from . import models
CategoryResource = resources.modelresource_factory(models.Category)
QuestionResource = resources.modelresource_factory(models.Question)
class ChecklistResource(resources.ModelResource):
questions = fields.Field(column_name='... | Remove statement without side effect. | Remove statement without side effect.
| Python | mit | opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind |
5d463f5823baad3ea485a54719a5799d14f10a27 | lda/__init__.py | lda/__init__.py | from __future__ import absolute_import, unicode_literals # noqa
import logging
import pbr.version
from lda.lda import LDA # noqa
__version__ = pbr.version.VersionInfo('lda').version_string()
logging.getLogger('lda').addHandler(logging.NullHandler())
| from __future__ import absolute_import, unicode_literals # noqa
import logging
import pbr.version
from lda.lda import LDA # noqa
import lda.datasets # noqa
__version__ = pbr.version.VersionInfo('lda').version_string()
logging.getLogger('lda').addHandler(logging.NullHandler())
| Make lda.datasets available after import lda | Make lda.datasets available after import lda
| Python | mpl-2.0 | hothHowler/lda,ww880412/lda,ww880412/lda,ariddell/lda,tdhopper/lda-1,tdhopper/lda-1,ariddell/lda-debian,ww880412/lda,tdhopper/lda-1,ariddell/lda,hothHowler/lda,ariddell/lda-debian,ariddell/lda,hothHowler/lda,ariddell/lda-debian |
fd1783df3648cdb80b32ae41ffd1d9e1ccb23196 | tests/ex25_tests.py | tests/ex25_tests.py | from nose.tools import *
from exercises import ex25
def test_make_ing_form_ie():
'''
Test for ie match
'''
present_verb = ex25.make_ing_form('tie')
assert_equal(third_person_form, 'tying')
def test_make_ing_form_e():
'''
Test for e match
'''
present_verb = ex25.make_ing_form('g... | from nose.tools import *
from exercises import ex25
def test_make_ing_form_ie():
'''
Test for ie match
'''
present_verb = ex25.make_ing_form('tie')
assert_equal(present_verb, 'tying')
def test_make_ing_form_e():
'''
Test for e match
'''
present_verb = ex25.make_ing_form('grate'... | Fix a copy paste fail | Fix a copy paste fail
| Python | mit | gravyboat/python-exercises |
7c1cce47e2a3cd8743e5e7d7795e9f5014d5f6ec | tests/test_utils.py | tests/test_utils.py | from tinydb.utils import LRUCache
def test_lru_cache():
cache = LRUCache(capacity=3)
cache["a"] = 1
cache["b"] = 2
cache["c"] = 3
_ = cache["a"] # move to front in lru queue
cache["d"] = 4 # move oldest item out of lru queue
assert cache.lru == ["c", "a", "d"]
def test_lru_cache_set_m... | from tinydb.utils import LRUCache
def test_lru_cache():
cache = LRUCache(capacity=3)
cache["a"] = 1
cache["b"] = 2
cache["c"] = 3
_ = cache["a"] # move to front in lru queue
cache["d"] = 4 # move oldest item out of lru queue
assert cache.lru == ["c", "a", "d"]
def test_lru_cache_set_m... | Improve test coverage once again... | Improve test coverage once again...
| Python | mit | cagnosolutions/tinydb,raquel-ucl/tinydb,ivankravets/tinydb,Callwoola/tinydb,msiemens/tinydb |
4e20731050c4b9f5a27693427e73ade62af0012e | web/impact/impact/v1/helpers/matching_criterion_helper.py | web/impact/impact/v1/helpers/matching_criterion_helper.py | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from django.db.models import Q
from impact.v1.helpers.criterion_helper import CriterionHelper
class MatchingCriterionHelper(CriterionHelper):
def __init__(self, subject):
super().__init__(subject)
self._app_ids_to_targets = {}
self._t... | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from django.db.models import Q
from impact.v1.helpers.criterion_helper import CriterionHelper
class MatchingCriterionHelper(CriterionHelper):
def __init__(self, subject):
super().__init__(subject)
self._app_ids_to_targets = {}
self._t... | Address CodeClimate cognitive complexity concern | [AC-5625] Address CodeClimate cognitive complexity concern
| Python | mit | masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api |
378ef98e78894024aaed18d55543c755c7095df4 | src/InventoryManagement/Item/models.py | src/InventoryManagement/Item/models.py | from django.db import models
# Create your models here.
| from django.db import models
# Create your models here.
# Model of an Item
class Item(models.Model):
item_name = models.CharField(max_lenght=100)
objects = ItemManager()
class ItemManager(models.Manager):
def create_item(self, item_name):
item = self.create(item_name=item_name)
| Add name field and object manager | Add name field and object manager
| Python | apache-2.0 | Hekaton/InventoryManagement |
fccf3df85eb79ea7f270e454f5bb9eda162985f9 | test_api_project/test_api_project/autocomplete_light_registry.py | test_api_project/test_api_project/autocomplete_light_registry.py | import autocomplete_light
from cities_light.contrib.autocomplete_light_restframework import RemoteCountryChannel, RemoteCityChannel
from cities_light.models import City, Country
class RemoteCountryChannel(RemoteCountryChannel):
source_url = 'http://localhost:8000/cities_light/country/'
class RemoteCityChannel(Re... | import autocomplete_light
from cities_light.contrib.autocomplete_light_restframework import RemoteCountryChannel, RemoteCityChannel
from cities_light.models import City, Country
autocomplete_light.register(Country, RemoteCountryChannel,
source_url = 'http://localhost:8000/cities_light/country/')
autocomplete_ligh... | Update example to match current register signature, avoids subclassing | Update example to match current register signature, avoids subclassing
| Python | mit | jonashaag/django-autocomplete-light,Visgean/django-autocomplete-light,dsanders11/django-autocomplete-light,Eraldo/django-autocomplete-light,jonashaag/django-autocomplete-light,dsanders11/django-autocomplete-light,luzfcb/django-autocomplete-light,spookylukey/django-autocomplete-light,Eraldo/django-autocomplete-light,blu... |
26b1845419cd7ea55cf1f40f26812eb9c124299f | kolibri/core/content/signals.py | kolibri/core/content/signals.py | from django.db.models import F
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from .models import ChannelMetadata
from .models import ContentNode
from kolibri.core.notifications.models import LearnerProgressNotification
@receiver(pre_delete, sender=ContentNode)
def cascade_delet... | from django.db.models import F
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from .models import ChannelMetadata
from .models import ContentNode
from kolibri.core.notifications.models import LearnerProgressNotification
from kolibri.core.lessons.models import Lesson
@receiver(pr... | Add Channel deletion side-effect that updates affected lessons | Add Channel deletion side-effect that updates affected lessons
| Python | mit | learningequality/kolibri,lyw07/kolibri,mrpau/kolibri,learningequality/kolibri,indirectlylit/kolibri,lyw07/kolibri,mrpau/kolibri,mrpau/kolibri,indirectlylit/kolibri,indirectlylit/kolibri,learningequality/kolibri,indirectlylit/kolibri,lyw07/kolibri,learningequality/kolibri,lyw07/kolibri,mrpau/kolibri |
2a4c13d46cb7168482985af4ab7eeaf251042a09 | camera_filters.py | camera_filters.py | """ Apply different filters here """
import cv2 # import OpenCV 3 module
camera = cv2.VideoCapture(0) # get default camera
mode = 2 # default mode, apply Canny edge detection
while True:
ok, frame = camera.read() # read frame
if ok: # frame is read correctly
if mode == 2:
frame = cv2.... | """ Apply different filters here """
import cv2 # import OpenCV 3 module
camera = cv2.VideoCapture(0) # get default camera
mode = 2 # default mode, apply Canny edge detection
while True:
ok, frame = camera.read() # read frame
if ok: # frame is read correctly
if mode == 2:
frame = cv2.... | Apply Canny edge detection to grayscale. No big difference with colored Canny edge detection. | Apply Canny edge detection to grayscale. No big difference with colored Canny edge detection.
| Python | mit | foobar167/junkyard,foobar167/junkyard,foobar167/junkyard,foobar167/junkyard,foobar167/junkyard,foobar167/junkyard |
695043ff82e80fdc3b0186dea268dd0eff79d642 | webapp/tests/test_util.py | webapp/tests/test_util.py | from django.test import TestCase
from graphite import util
from graphite.wsgi import application # NOQA makes sure we have a working WSGI app
class UtilTest(TestCase):
def test_is_local_interface(self):
addresses = ['127.0.0.1', '127.0.0.1:8080', '8.8.8.8']
results = [ util.is_local_interface(a)... | from django.test import TestCase
from graphite import util
from graphite.wsgi import application # NOQA makes sure we have a working WSGI app
class UtilTest(TestCase):
def test_is_local_interface(self):
addresses = ['127.0.0.1', '127.0.0.1:8080', '8.8.8.8']
results = [ util.is_local_interface(a)... | Add coverage to util.py for IPv6 and make_index | Add coverage to util.py for IPv6 and make_index
| Python | apache-2.0 | brutasse/graphite-web,DanCech/graphite-web,obfuscurity/graphite-web,deniszh/graphite-web,drax68/graphite-web,cbowman0/graphite-web,mcoolive/graphite-web,drax68/graphite-web,atnak/graphite-web,krux/graphite-web,johnseekins/graphite-web,brutasse/graphite-web,krux/graphite-web,drax68/graphite-web,bmhatfield/graphite-web,c... |
c63391026fadc6f23ca7802e6ec706365ae4e117 | daemon/daemon.py | daemon/daemon.py | #!/usr/bin/env python
import json
from objects.album import Album
from spotify_crawler import SpotifyCrawler
if __name__ == "__main__":
crawler = SpotifyCrawler()
artist = crawler.searchArtist("Ed Sheeran")
if artist:
albums = crawler.getAlbumsByArtist(artist.getArtistId())
for album... | #!/usr/bin/env python
import json
from objects.album import Album
from spotify_crawler import SpotifyCrawler
if __name__ == "__main__":
crawler = SpotifyCrawler()
artist_name = "Ed Sheeran"
artist = crawler.searchArtist(artist_name)
if artist:
albums = crawler.getAlbumsByArtist(artist.get... | Add the error handle if artist doesn't exist.. | Add the error handle if artist doesn't exist..
| Python | apache-2.0 | rockers7414/xmusic,rockers7414/xmusic-crawler |
f735cd9f9cfdcfba54005151fee3deb7741282c3 | show.py | show.py | import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
def sweep(x, sweep_time, fs):
t = np.arange(0, sweep_time, 1 / fs)
p = 20 * np.log10(abs(sp.fft(x)))
f = np.linspace(0, fs / 2, len(p))
plt.figure(1)
plt.subplot(211)
plt.plot(t, x)
plt.grid()
plt.subplot(212)
p... | import numpy as np
import matplotlib.pyplot as plt
def sweep(x, sweep_time, fs):
plt.subplots_adjust(hspace=0.4)
t = np.arange(0, sweep_time, 1 / fs)
p = 20 * np.log10(abs(np.fft.rfft(x)))
f = np.linspace(0, fs / 2, len(p))
plt.figure(1)
plt.subplot(211)
plt.plot(t, x)
plt.grid()
... | Add axis label and change import | Add axis label and change import
| Python | mit | franzpl/sweep,spatialaudio/sweep |
8930337ef2402a9e5a6dfe3a336fc24b0ffbf87f | reviewboard/accounts/urls.py | reviewboard/accounts/urls.py | from __future__ import unicode_literals
from django.conf.urls import patterns, url
urlpatterns = patterns(
"reviewboard.accounts.views",
url(r'^register/$', 'account_register',
{'next_url': 'dashboard'}, name="register"),
url(r'^preferences/$', 'user_preferences', name="user-preferences"),
)
ur... | from __future__ import unicode_literals
from django.conf.urls import patterns, url
urlpatterns = patterns(
"reviewboard.accounts.views",
url(r'^register/$', 'account_register',
{'next_url': 'dashboard'}, name="register"),
url(r'^preferences/$', 'user_preferences', name="user-preferences"),
)
ur... | Fix internal server error at url /account/recover | Fix internal server error at url /account/recover
Fixed a 500 error at /account/recover when trying to reset password on the
login page.
Testing Done:
Verified that the server no longer returns a 500 error when loading the form.
Reviewed at https://reviews.reviewboard.org/r/5431/
| Python | mit | beol/reviewboard,davidt/reviewboard,beol/reviewboard,1tush/reviewboard,custode/reviewboard,reviewboard/reviewboard,KnowNo/reviewboard,KnowNo/reviewboard,1tush/reviewboard,beol/reviewboard,1tush/reviewboard,beol/reviewboard,brennie/reviewboard,sgallagher/reviewboard,reviewboard/reviewboard,bkochendorfer/reviewboard,cust... |
50199aa8e270ff68f8d1026f88519609e2c97229 | djgunicorn/config.py | djgunicorn/config.py | """Gunicorn configuration file used by gunserver's Gunicorn subprocess.
This module is not designed to be imported directly, but provided as
Gunicorn's configuration file.
"""
import os
import sys
import django
import gunicorn
# General configs.
bind = os.environ['DJANGO_ADDRPORT']
logger_class = 'djgunicorn.loggi... | """Gunicorn configuration file used by gunserver's Gunicorn subprocess.
This module is not designed to be imported directly, but provided as
Gunicorn's configuration file.
"""
import os
import sys
import django
import gunicorn
# General configs.
bind = os.environ['DJANGO_ADDRPORT']
logger_class = 'djgunicorn.loggi... | Use worker_int to avoid \n being printed too late | Use worker_int to avoid \n being printed too late
| Python | bsd-3-clause | uranusjr/django-gunicorn |
01c7a5657078bff2670ec2913ad0b884598dbcbb | cde/types.py | cde/types.py | """Types to make coding cde easier"""
import os
from pysyte.types import paths
from pysyte.types.lists import UniquelyTrues
class PossiblePaths(UniquelyTrues):
"""A unique list of possible paths"""
def predicate(self, item):
"""Exclude items which don't exist"""
return bool(item) and os.pat... | """Types to make coding cde easier"""
import os
from typing import List
from pysyte.types import paths
from pysyte.types.lists import UniquelyTrues
class PossiblePaths(UniquelyTrues):
"""A unique list of possible paths"""
def convert(self, item: str) -> paths.StringPath:
return paths.path(item)
... | Add Roots class to filter paths of children | Add Roots class to filter paths of children
Takes out python dirs like .../cde/cde
| Python | mit | jalanb/kd,jalanb/kd |
3d7ba9709b33982e6e65b24ee6f7d97cfa6ef22f | db/buyout.py | db/buyout.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from .common import Base, session_scope
from sqlalchemy import and_
class Buyout(Base):
__tablename__ = 'buyouts'
__autoload__ = True
STANDARD_ATTRS = [
'buyout_team_id', 'buyout_date', 'length', 'value',
'start_season', 'end_season'
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from .common import Base, session_scope
class Buyout(Base):
__tablename__ = 'buyouts'
__autoload__ = True
STANDARD_ATTRS = [
'buyout_team_id', 'buyout_date', 'length', 'value',
'start_season', 'end_season'
]
def __init__(self, pl... | Add find, update and comparison methods | Add find, update and comparison methods
| Python | mit | leaffan/pynhldb |
3feccc140c0371becccb3f80bef00d30b4bc15bf | corehq/sql_accessors/migrations/0056_add_hashlib_functions.py | corehq/sql_accessors/migrations/0056_add_hashlib_functions.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-12-04 08:36
from __future__ import absolute_import, unicode_literals
from django.db import migrations
from django.conf import settings
from corehq.sql_db.operations import HqRunSQL, noop_migration
class Migration(migrations.Migration):
dependencies = ... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-12-04 08:36
from __future__ import absolute_import, unicode_literals
from django.db import migrations
from django.conf import settings
from corehq.sql_db.operations import HqRunSQL, noop_migration
class Migration(migrations.Migration):
dependencies = ... | Add comment about moving hashlib extention creation to test harness | Add comment about moving hashlib extention creation to test harness
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq |
3ca4a7334a3a759762d309bcff94ddde62d5a48b | accounts/management/__init__.py | accounts/management/__init__.py | from django.db.models.signals import post_syncdb
from accounts import models, names
def ensure_core_accounts_exists(sender, **kwargs):
# We only create core accounts the first time syncdb is run
if models.Account.objects.all().count() > 0:
return
# Create asset accounts
assets = models.Accou... | from accounts import models, names
def ensure_core_accounts_exists(sender, **kwargs):
# We only create core accounts the first time syncdb is run
if models.Account.objects.all().count() > 0:
return
# Create asset accounts
assets = models.AccountType.add_root(name='Assets')
assets.accounts... | Remove syncdb signal - will move to migration shortly | Remove syncdb signal - will move to migration shortly
| Python | bsd-3-clause | Jannes123/django-oscar-accounts,machtfit/django-oscar-accounts,michaelkuty/django-oscar-accounts,Mariana-Tek/django-oscar-accounts,amsys/django-account-balances,michaelkuty/django-oscar-accounts,Jannes123/django-oscar-accounts,carver/django-account-balances,Mariana-Tek/django-oscar-accounts,amsys/django-account-balance... |
a84c02b4369bf698c82be22b6231fe412ad67c63 | Cauldron/ext/click/__init__.py | Cauldron/ext/click/__init__.py | # -*- coding: utf-8 -*-
try:
import click
except ImportError:
raise ImportError("Cauldron.ext.click requires the click package.")
from ...api import use
__all__ = ['backend', 'service']
def select_backend(ctx, param, value):
"""Callback to set the Cauldron backend."""
if not value or ctx.resilient_p... | # -*- coding: utf-8 -*-
try:
import click
except ImportError:
raise ImportError("Cauldron.ext.click requires the click package.")
from ...api import use
__all__ = ['backend', 'service']
def select_backend(ctx, param, value):
"""Callback to set the Cauldron backend."""
if not value or ctx.resilient_p... | Fix a bug in Cauldron click extension | Fix a bug in Cauldron click extension
| Python | bsd-3-clause | alexrudy/Cauldron |
5547e59360126baa20e1684a22e7f88fdacb530a | s2v2.py | s2v2.py | from s2v1 import *
def number_of_records(data_sample):
return len(data_sample)
number_of_ties = number_of_records(data_from_csv) - 1 # minus header row
# print(number_of_ties, "ties in our data sample")
def number_of_records2(data_sample):
return data_sample.size
number_of_ties_my_csv = number_of_records2(my_csv... | from s2v1 import *
def number_of_records(data_sample):
return len(data_sample)
def number_of_records_ignore_header(data_sample, header=True):
if header:
return len(data_sample) - 1
else:
return len(data_sample)
number_of_ties = number_of_records(data_from_csv) - 1 # minus header row
# print(number_of_ties,... | Create new function for number of records and do a header check | Create new function for number of records and do a header check
| Python | mit | alexmilesyounger/ds_basics |
2b88f8f458781bd88f559f1a5a966fd5050414a0 | tests/merchandise/music/test_models.py | tests/merchandise/music/test_models.py | import pytest
from components.merchandise.music.models import Album, Single
from components.merchandise.music.factories import (AlbumFactory,
BaseFactory, SingleFactory)
@pytest.mark.django_db
class TestAlbums(object):
def test_album_factory(self):
album = AlbumFactory()
assert isinstance(alb... | import pytest
from components.merchandise.music.models import Album, Single
from components.merchandise.music.factories import (AlbumFactory,
BaseFactory, SingleFactory)
@pytest.mark.django_db
def test_album_factory():
factory = AlbumFactory()
assert isinstance(factory, Album)
assert 'album' in facto... | Remove the class surrounding the music tests. Staying strictly functional. | Remove the class surrounding the music tests. Staying strictly functional.
| Python | apache-2.0 | hello-base/web,hello-base/web,hello-base/web,hello-base/web |
b45193582f96853e0cb17a962a7e83aada529a10 | DataLogger/SQLiteLogger.py | DataLogger/SQLiteLogger.py | import sqlite3
import time
class SQLiteLogger:
def __init__(self, filename="test.db"):
self.filename = filename
self.connection = None
def __enter__(self):
try:
with open(self.filename):
self.connection = sqlite3.connect(self.filename)
except IOErro... | import sqlite3
import time
class SQLiteLogger:
def __init__(self, filename="test.db"):
self.filename = filename
self.connection = None
def __enter__(self):
try:
with open(self.filename):
self.connection = sqlite3.connect(self.filename)
except IOErro... | Allow log time to be passed into logger | Allow log time to be passed into logger
| Python | mit | thelonious/g2x,gizmo-cda/g2x,thelonious/g2x,gizmo-cda/g2x,gizmo-cda/g2x,gizmo-cda/g2x |
c5049b9bf465aee93d4c87b9cd62608d338ede7f | robokassa/migrations/0003_load_source_type.py | robokassa/migrations/0003_load_source_type.py | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
pass
def backwards(self, orm):
pass
models = {
u'robokassa.successnotification': {
... | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
depends_on = (
('payment', '0003_auto__chg_field_sourcetype_code__add_unique_sourcetype_code'),
)
def forwards(self, orm):
orm['p... | Add the code that correctly adds the new payment source. | Add the code that correctly adds the new payment source.
| Python | mit | a-iv/django-oscar-robokassa |
51c37e74da9fe2bfc068fd29a52422c84b13900d | froide/frontpage/models.py | froide/frontpage/models.py | from django.db import models
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager
from foirequest.models import FoiRequest
class FeaturedRequestManager(CurrentSiteManage... | from django.db import models
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager
from foirequest.models import FoiRequest
class FeaturedRequestManager(CurrentSiteManage... | Add meta class to FeaturedRequest model | Add meta class to FeaturedRequest model | Python | mit | ryankanno/froide,fin/froide,okfse/froide,catcosmo/froide,catcosmo/froide,okfse/froide,CodeforHawaii/froide,CodeforHawaii/froide,LilithWittmann/froide,LilithWittmann/froide,fin/froide,catcosmo/froide,ryankanno/froide,stefanw/froide,stefanw/froide,CodeforHawaii/froide,fin/froide,ryankanno/froide,ryankanno/froide,LilithWi... |
fa7bd3247302407da423c38690b07b0917fadb80 | core/urls.py | core/urls.py | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
| from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
# Use GeoJSON api
from djgeojson.views import GeoJSONLayerView
from .models import BookLocation
# GeoJSON book locations hook. Returns object with all BookLocation elements.
urlpatterns += [
url(r'^ap... | Add a GeoJSON book locations hook | Add a GeoJSON book locations hook
Located at URL/api/bookLocs.geojson.
Returns all book locations. | Python | mit | edushifts/book-voyage,edushifts/book-voyage,edushifts/book-voyage,edushifts/book-voyage |
461ea32b927e35975c04b6b01679f4898ea490b6 | shellReporter.py | shellReporter.py | #!/usr/bin/env python
class ShellReporter:
def send_status(self, timestamp, context, metric_value):
self._send(timestamp, context + '.STATUS', metric_value)
def send_duration(self, timestamp, context, metric_value):
self._send(timestamp, context + '.DURATION', metric_value)
def _send(self... | #!/usr/bin/env python
class ShellReporter:
def send_status(self, timestamp, context, metric_value):
self._send(timestamp, context + '.STATUS', metric_value + ' (%s)' % 'SUCCESS' if metric_value else 'FAILURE')
def send_duration(self, timestamp, context, metric_value):
self._send(timestamp, con... | Add SUCCESS/FAILURE when reporting duration to shell | Add SUCCESS/FAILURE when reporting duration to shell
| Python | mit | luigiberrettini/build-deploy-stats |
4e7b8e0b03951faa0a43ce8b216b31c5bc4543a4 | create_db.py | create_db.py | import os
import sys
import psycopg2
import sqlalchemy as sa
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
def main():
database = 'postgres'
user = 'postgres'
url = sa.engine.url.URL('postgresql', host=os.environ['PGHOST'],
database=database, username=user)
d... | import os
import sys
import psycopg2
import sqlalchemy as sa
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
def main():
database = 'postgres'
user = 'postgres'
url = sa.engine.url.URL(
'postgresql', host=os.environ['PGHOST'], database=database,
username=user, password=os.envi... | Add password envar for db creation. | Add password envar for db creation.
| Python | mit | portfoliome/pgawedge |
6f5e987b5a102b0c4b0bfcd88c17faab00655142 | ctypeslib/test/test_toolchain.py | ctypeslib/test/test_toolchain.py | import unittest
import sys
from ctypeslib import h2xml, xml2py
class ToolchainTest(unittest.TestCase):
if sys.platform == "win32":
def test(self):
h2xml.main(["h2xml", "-q",
"-D WIN32_LEAN_AND_MEAN",
"-D _UNICODE", "-D UNICODE",
... | import unittest
import sys
from ctypeslib import h2xml, xml2py
class ToolchainTest(unittest.TestCase):
if sys.platform == "win32":
def test_windows(self):
h2xml.main(["h2xml", "-q",
"-D WIN32_LEAN_AND_MEAN",
"-D _UNICODE", "-D UNICODE",
... | Add a test for stdio.h. | Add a test for stdio.h.
git-svn-id: ac2c3632cb6543e7ab5fafd132c7fe15057a1882@60472 6015fed2-1504-0410-9fe1-9d1591cc4771
| Python | mit | trolldbois/ctypeslib,luzfcb/ctypeslib,trolldbois/ctypeslib,luzfcb/ctypeslib,luzfcb/ctypeslib,trolldbois/ctypeslib |
73a9ba740d446e19c0428ffc29bf5bb5b033d7fe | PynamoDB/persistence_engine.py | PynamoDB/persistence_engine.py | """
persistence_engine.py
~~~~~~~~~~~~
Implements put, get, delete methods for PersistenceStage. Using an actual persistence engine (i.e. MySQL, BDB), one would implement the three methods themselves.
"""
class PersistenceEngine(object):
""" Basic persistence engine implemented as a regular Pytho... | """
persistence_engine.py
~~~~~~~~~~~~
Implements put, get, delete methods for PersistenceStage. Using an actual persistence engine (i.e. MySQL, BDB), one would implement the three methods themselves.
"""
class PersistenceEngine(object):
""" Basic persistence engine implemented as a regular Pytho... | Remove use of timestamped value. | Remove use of timestamped value.
Thought it was dumb/inelegant to have a Value() object floating around
with value and timestamp . Instead, now all messages are sent around
as json dicts.
The request enters the system as json, flows through to an endpoint
where it becomes a reply message, then flows back to the clie... | Python | mit | samuelwu90/PynamoDB |
dcd2972bee896ea3c7885b1d6a8a6e132329d66b | apps/persona/urls.py | apps/persona/urls.py | from django.conf.urls.defaults import *
from mozorg.util import page
import views
urlpatterns = patterns('',
page('', 'persona/persona.html'),
page('about', 'persona/about.html'),
page('privacy-policy', 'persona/privacy-policy.html'),
page('terms-of-service', 'persona/terms-of-service.html'),
page(... | from django.conf.urls.defaults import *
from mozorg.util import page
urlpatterns = patterns('',
page('', 'persona/persona.html'),
page('about', 'persona/about.html'),
page('privacy-policy', 'persona/privacy-policy.html'),
page('terms-of-service', 'persona/terms-of-service.html'),
page('developer-fa... | Remove unnecessary 'import views' line | Remove unnecessary 'import views' line
| Python | mpl-2.0 | jacshfr/mozilla-bedrock,marcoscaceres/bedrock,mmmavis/bedrock,sgarrity/bedrock,ericawright/bedrock,hoosteeno/bedrock,pascalchevrel/bedrock,schalkneethling/bedrock,alexgibson/bedrock,yglazko/bedrock,gauthierm/bedrock,sylvestre/bedrock,TheJJ100100/bedrock,dudepare/bedrock,davehunt/bedrock,bensternthal/bedrock,bensterntha... |
414c8fa0a5576645831d58c8fa1285c9aef3610d | conditional/blueprints/intro_evals.py | conditional/blueprints/intro_evals.py | from flask import Blueprint
from flask import render_template
from flask import request
intro_evals_bp = Blueprint('intro_evals_bp', __name__)
@intro_evals_bp.route('/intro_evals/')
def display_intro_evals():
# get user data
user_name = request.headers.get('x-webauth-user')
members = [
{... | from flask import Blueprint
from flask import render_template
from flask import request
intro_evals_bp = Blueprint('intro_evals_bp', __name__)
@intro_evals_bp.route('/intro_evals/')
def display_intro_evals():
# get user data
user_name = request.headers.get('x-webauth-user')
members = [
{... | Edit intro evals data route | Edit intro evals data route
| Python | mit | RamZallan/conditional,ComputerScienceHouse/conditional,RamZallan/conditional,RamZallan/conditional,ComputerScienceHouse/conditional,ComputerScienceHouse/conditional |
1be4fcb077d63155e6c0beed9e4138fa377fa067 | ColorHistograms-python/color_histogram.py | ColorHistograms-python/color_histogram.py | from color_histogram_cuda import histogram
print histogram('../data/spotted_ball_3500.png', 16) | import sys
from color_histogram_cuda import histogram
print histogram(sys.argv[1], 16)
| Read file name from command line in python wrapper | Read file name from command line in python wrapper
| Python | bsd-3-clause | kwadraterry/GPGPU-LUT,kwadraterry/GPGPU-LUT,kwadraterry/GPGPU-LUT,kwadraterry/GPGPU-LUT,kwadraterry/GPGPU-LUT |
a1c570001e4214d1e2e2c4d34e2ee74721ecb2d5 | xpserver_api/serializers.py | xpserver_api/serializers.py | from django.contrib.auth.models import User
from rest_framework import serializers, viewsets
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'email')
def create(self, validated_data):
user = User.objects.create(**validated_data)
... | from django.contrib.auth.models import User
from rest_framework import serializers, viewsets
from xpserver_api.services import generate_activation_code, EmailSender
from xpserver_web.models import Profile
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields... | Add user profile when reg via api | Add user profile when reg via api
When user is registered via api it will create profile, activation link
and send it to given email just like a web registration flow.
| Python | mit | xp2017-hackergarden/server,xp2017-hackergarden/server,xp2017-hackergarden/server,xp2017-hackergarden/server |
a786079d5603eada9186180542096cc334d465f3 | tests/fixtures/postgres.py | tests/fixtures/postgres.py | import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.models import Base
@pytest.fixture(scope="function")
async def engine():
engine = create_async_en... | import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.models import Base
@pytest.fixture(scope="function")
async def engine():
engine = create_async_en... | Update Postgres test connection string | Update Postgres test connection string
| Python | mit | igboyes/virtool,virtool/virtool,igboyes/virtool,virtool/virtool |
2d9e6d9ca46cdd58f5b811082f3fc40d62f3ead8 | dev/__init__.py | dev/__init__.py | # coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
package_name = "certbuilder"
other_packages = []
package_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
build_root = os.path.abspath(os.path.join(package_root, '..'))
md_source_map =... | # coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
package_name = "certbuilder"
other_packages = []
task_keyword_args = []
requires_oscrypto = True
has_tests_package = False
package_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
bui... | Add missing dev config values | Add missing dev config values
| Python | mit | wbond/certbuilder |
1223726c081000ef42a580881c9f8d2002d91c0b | src/hireme/tasks/__init__.py | src/hireme/tasks/__init__.py | # -*- coding: utf-8 -*-
from flask import render_template
from flask import request
def render_task(func):
def rendered():
params = dict(title=func.__module__.split('.')[-1] or '')
if request.method == 'POST':
input_data = request.form.get('input')
params['input_data'] = i... | # -*- coding: utf-8 -*-
from flask import render_template
from flask import request
def render_task(func):
"""Decorator for task solving functions. Provides raw form data from the
request and expects a string formatted return value."""
def rendered():
params = dict(title=func.__module__.split('.... | Add docstring, fix template param name | Add docstring, fix template param name
| Python | bsd-2-clause | cutoffthetop/hireme |
1e76a9c7ee030875929a65d9f30194166dcd62ef | docs/reencode.py | docs/reencode.py | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | Add a comment about line endings in Stardoc files. | Add a comment about line endings in Stardoc files.
| Python | apache-2.0 | phst/rules_elisp,phst/rules_elisp,phst/rules_elisp,phst/rules_elisp,phst/rules_elisp |
ab0ba3232c1a7a4b028abe6d371b3935ea0ab110 | eve_api/tasks.py | eve_api/tasks.py | from celery.decorators import task
from eve_api.api_puller.accounts import import_eve_account
from eve_api.app_defines import *
from sso.tasks import update_user_access
@task()
def import_apikey(api_userid, api_key, user=None, force_cache=False):
log = import_apikey.get_logger()
l.info("Importing %s/%s" % (ap... | from celery.decorators import task
from eve_api.api_puller.accounts import import_eve_account
from eve_api.app_defines import *
from sso.tasks import update_user_access
@task()
def import_apikey(api_userid, api_key, user=None, force_cache=False):
acc = import_eve_account(api_key, api_userid, force_cache=force_cach... | Fix error in the apikey import task | Fix error in the apikey import task
| Python | bsd-3-clause | nikdoof/test-auth |
fcde79c7743b621be31acc4bd4e5826b121d573d | nalaf/download_corpora.py | nalaf/download_corpora.py | """
Downloads the necessary NLTK corpora for nalaf.
Usage: ::
$ python -m nalaf.download_corpora
"""
if __name__ == '__main__':
import nltk
CORPORA = ['punkt']
for corpus in CORPORA:
nltk.download(corpus) | """
Downloads the necessary NLTK corpora for nalaf.
Usage: ::
$ python -m nalaf.download_corpora
"""
if __name__ == '__main__':
from nltk import download
CORPORA = ['punkt']
for corpus in CORPORA:
download(corpus)
| Fix a build for travis-CI | Fix a build for travis-CI
| Python | apache-2.0 | Rostlab/nalaf |
84f17b192c97212c7fdd963208f41085c85f08a5 | examples/constant_liar.py | examples/constant_liar.py | """
Example for parallel optimization with skopt.
The points to evaluate in parallel are selected according to the "constant lie" approach.
"""
import numpy as np
from multiprocessing.pool import ThreadPool
from skopt.space import Real
from skopt.learning import GaussianProcessRegressor
from skopt import Optimizer
#... | """
Example for parallel optimization with skopt.
The points to evaluate in parallel are selected according to the "constant lie" approach.
"""
import numpy as np
from sklearn.externals.joblib import Parallel, delayed
from skopt.space import Real
from skopt.learning import GaussianProcessRegressor
from skopt import O... | Drop ThreadPool, use joblib instead | Drop ThreadPool, use joblib instead
| Python | bsd-3-clause | scikit-optimize/scikit-optimize,betatim/BlackBox,betatim/BlackBox,scikit-optimize/scikit-optimize |
4071adfe51a94376045fa31538f1ab94615ba962 | escalator.py | escalator.py | """Creates the escalator class"""
class Escalator:
"""
Each escalator is an instance of the escalator class.
Methods:
__init__: creates a new escalator
rate: calculates the rate people leave the escalator
"""
def __init__(self):
self.stand_time = None
self.stand_space = No... | """Creates the escalator class"""
class Escalator:
"""
Each escalator is an instance of the escalator class.
Methods:
__init__: creates a new escalator
rate: calculates the rate people leave the escalator
"""
def __init__(self):
self.stand_time = eval(input("Enter a standing escal... | Add input statements and edit parentheses in rate | Add input statements and edit parentheses in rate
Attempted to add some input functions into the elevator constructor.
Ref #25 #23 | Python | mit | ForestPride/rail-problem |
65b418b8eaa8f57fdd3c8207168451da20b452bf | src/python/rgplot/RgChart.py | src/python/rgplot/RgChart.py | import matplotlib.pyplot as plt
#class RgChart(object):
#__metaclass__ = ABCMeta
class RgChart(object):
def with_grids(self):
self._ax.xaxis.grid(True)
self._ax.yaxis.grid(True)
return self
def save_as(self, filename):
self._create_plot()
self._fig.savefig(fil... | import matplotlib.pyplot as plt
#class RgChart(object):
#__metaclass__ = ABCMeta
class RgChart(object):
TITLE_Y_OFFSET = 1.08
def with_grids(self):
self._ax.xaxis.grid(True)
self._ax.yaxis.grid(True)
return self
def save_as(self, filename):
self._create_plot()
... | Add y log option and title offset | Add y log option and title offset
| Python | mit | vjuranek/rg-offline-plotting,vjuranek/rg-offline-plotting |
164891392f9a68abb0fa29a74787ef127849d0c0 | benchexec/tools/avr.py | benchexec/tools/avr.py | # This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.t... | # This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.t... | Determine AVR's results more precisely | Determine AVR's results more precisely
| Python | apache-2.0 | sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec |
e493d5403de51d8ee448e532d60204041aa88c19 | jedihttp/handlers.py | jedihttp/handlers.py | import bottle
from bottle import response, request
import json
import jedi
import logging
app = bottle.Bottle( __name__ )
logger = logging.getLogger( __name__ )
@app.post( '/healthy' )
def healthy():
return _Json({})
@app.post( '/ready' )
def ready():
return _Json({})
@app.post( '/completions' )
def complet... | import bottle
from bottle import response, request
import json
import jedi
import logging
app = bottle.Bottle( __name__ )
logger = logging.getLogger( __name__ )
@app.post( '/healthy' )
def healthy():
return _Json({'healthy': True})
@app.post( '/ready' )
def ready():
return _Json({'ready': True})
@app.post( ... | Send descriptive responses for /ready and /healthy | Send descriptive responses for /ready and /healthy
| Python | apache-2.0 | vheon/JediHTTP,micbou/JediHTTP,micbou/JediHTTP,vheon/JediHTTP |
647bfbff75f7356a974fdf3bc98612c12c47a151 | angkot/geo/webapi/views.py | angkot/geo/webapi/views.py | from django.views.decorators.cache import cache_page
from ..models import Province, City
from angkot.common.decorators import wapi
def _province_to_dict(province):
data = dict(pid=province.id,
name=province.name,
code=province.code)
return (province.id, data)
def _city_to_dic... | from django.views.decorators.cache import cache_page
from ..models import Province, City
from angkot.common.decorators import wapi
def _province_to_dict(province):
return dict(pid=province.id,
name=province.name,
code=province.code)
def _city_to_dict(city):
data = dict(cid=ci... | Simplify the province list API | Simplify the province list API
It only contains province data as a list without the separate ordering
information. The order of the province data in the list is the order of
provinces.
| Python | agpl-3.0 | shirone/angkot,angkot/angkot,shirone/angkot,angkot/angkot,angkot/angkot,shirone/angkot,shirone/angkot,angkot/angkot |
60f05c64d60d7db6f05a53548dd0434437bd0719 | accelerator/migrations/0074_update_url_to_community.py | accelerator/migrations/0074_update_url_to_community.py | # Generated by Django 2.2.10 on 2021-11-05 12:29
from django.db import migrations
def update_url_to_community(apps, schema_editor):
people_url = "/people"
mentor_url = "/directory"
community_url = "/community"
SiteRedirectPage = apps.get_model('accelerator', 'SiteRedirectPage')
for siteredirectpage in Site... | # Generated by Django 2.2.10 on 2021-11-05 12:29
from django.db import migrations
from django.db.models.query_utils import Q
def update_url_to_community(apps, schema_editor):
people_url = "/people"
mentor_url = "/directory"
community_url = "/community"
SiteRedirectPage = apps.get_model('accelerator', 'SiteRe... | Fix filter for people and mentor urls | [AC-9046] Fix filter for people and mentor urls
| Python | mit | masschallenge/django-accelerator,masschallenge/django-accelerator |
6c2685fd6701600950d01b8f3ac3de08c0583ec9 | indico/core/extpoint/location.py | indico/core/extpoint/location.py | # -*- coding: utf-8 -*-
##
##
## This file is part of Indico.
## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN).
##
## Indico is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundat... | # This file is part of Indico.
# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... | Update header missed by the script | Update header missed by the script
Really, who puts spaces in front of the comments of a file header?!
| Python | mit | DirkHoffmann/indico,mic4ael/indico,DirkHoffmann/indico,ThiefMaster/indico,OmeGak/indico,indico/indico,mvidalgarcia/indico,indico/indico,DirkHoffmann/indico,mic4ael/indico,OmeGak/indico,pferreir/indico,pferreir/indico,mvidalgarcia/indico,indico/indico,indico/indico,ThiefMaster/indico,mvidalgarcia/indico,mic4ael/indico,p... |
4d95e5cb938c43cacd14085bf752485334ab6f1a | prf/tests/test_mongodb.py | prf/tests/test_mongodb.py | from prf.tests.prf_testcase import PrfTestCase
from prf.mongodb import get_document_cls
class TestMongoDB(PrfTestCase):
def setUp(self):
super(TestMongoDB, self).setUp()
self.drop_databases()
self.unload_documents()
def test_get_document_cls(self):
cls = self.create_collection... | import mock
from prf.tests.prf_testcase import PrfTestCase
from prf.mongodb import get_document_cls, connect_dataset_aliases
class TestMongoDB(PrfTestCase):
def setUp(self):
super(TestMongoDB, self).setUp()
self.drop_databases()
self.unload_documents()
def test_get_document_cls(self):... | Make sure no crashes happen when no namespaces are set | Make sure no crashes happen when no namespaces are set
| Python | mit | vahana/prf |
8143d0735bce0b542b369d84bf9be02d3e6582b6 | test_queue.py | test_queue.py | from queue import Queue
import pytest
def test_enqueue_first_item():
queue = Queue()
queue.enqueue("Bacon")
assert queue.last_item.data == "Bacon"
def test_enqueue_multi_last_item():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Steak")
queue.enqueue("Beer")
assert queue.firs... | from queue import Queue
import pytest
def test_enqueue_first_item():
queue = Queue()
queue.enqueue("Bacon")
assert queue.last_item.data == "Bacon"
def test_enqueue_multi_last_item():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Steak")
queue.enqueue("Beer")
assert queue.firs... | Add test for dequeue from empty list | Add test for dequeue from empty list
| Python | mit | jwarren116/data-structures |
60ac75f10f7e74aea5636651de05b7bedd4f2be2 | tests/main.py | tests/main.py | import json
import unittest
import requests
import validators
class DomainsTests(unittest.TestCase):
def test_json_is_valid(self):
with open("../world_universities_and_domains.json") as json_file:
valid_json = json.load(json_file)
for university in valid_json:
self.assertIn(... | import json
import unittest
import requests
import validators
class DomainsTests(unittest.TestCase):
def test_json_is_valid(self):
with open("../world_universities_and_domains.json") as json_file:
valid_json = json.load(json_file)
for university in valid_json:
self.assertIn(... | Remove URL test due to bad validator | Remove URL test due to bad validator
| Python | mit | Hipo/university-domains-list |
6a379b806dd1992ad3dd2b728878ed35e8d0ea3c | cdf/utils.py | cdf/utils.py | def get_major_dot_minor_version(version):
"""
Convert full VERSION Django tuple to
a dotted string containing MAJOR.MINOR.
For example, (1, 9, 3, 'final', 0) will result in '1.9'
"""
return '.'.join(version.split('.')[:2])
| def get_major_dot_minor_version(version):
"""
Convert full VERSION Django tuple to
a dotted string containing MAJOR.MINOR.
For example, (1, 9, 3, 'final', 0) will result in '1.9'
"""
return '.'.join([str(v) for v in version[:2]])
| Fix getting major.minor django version | Fix getting major.minor django version
| Python | mit | ana-balica/classy-django-forms,ana-balica/classy-django-forms,ana-balica/classy-django-forms |
8be84789d561c916b6d37e61537c4d957061a380 | diceserver.py | diceserver.py | #!/usr/bin/env python
import random
from twisted.protocols import amp
port = 1234
_rand = random.Random()
class RollDice(amp.Command):
arguments = [('sides', amp.Integer())]
response = [('result', amp.Integer())]
class Dice(amp.AMP):
def roll(self, sides=6):
"""Return a random integer from 1... | #!/usr/bin/env python
import random
from twisted.protocols import amp
from twisted.internet import reactor
from twisted.internet.protocol import Factory
from twisted.python import usage
port = 1234
_rand = random.Random()
class Options(usage.Options):
optParameters = [
["port", "p", port, "server port"... | Add command-line option to set port. | Add command-line option to set port.
| Python | mit | dripton/ampchat |
7ec36c81c6437bf83c498661c07802500e3acaa6 | gore/urls.py | gore/urls.py | import os
from django.conf.urls import include, url
from lepo.router import Router
from lepo.validate import validate_router
import gore.handlers.events
import gore.handlers.projects
import gore.handlers.store
router = Router.from_file(os.path.join(os.path.dirname(__file__), 'swagger.yaml'))
router.add_handlers(gore... | import os
from django.conf.urls import include, url
from lepo.decorators import csrf_exempt
from lepo.router import Router
from lepo.validate import validate_router
import gore.handlers.events
import gore.handlers.projects
import gore.handlers.store
router = Router.from_file(os.path.join(os.path.dirname(__file__), ... | Use Lepo 0.1.0's CSRF decorator | Gore: Use Lepo 0.1.0's CSRF decorator
| Python | mit | akx/gentry,akx/gentry,akx/gentry,akx/gentry |
50510c800e7510b0f918553f0c479a10b3a72deb | projections/simpleexpr.py | projections/simpleexpr.py |
import numpy as np
import numpy.ma as ma
import projections.r2py.reval as reval
import projections.r2py.rparser as rparser
class SimpleExpr():
def __init__(self, name, expr):
self.name = name
self.tree = reval.make_inputs(rparser.parse(expr))
lokals = {}
exec(reval.to_py(self.tree, name), lokals)
... |
import numpy as np
import numpy.ma as ma
import projections.r2py.reval as reval
import projections.r2py.rparser as rparser
class SimpleExpr():
def __init__(self, name, expr):
self.name = name
self.tree = reval.make_inputs(rparser.parse(expr))
lokals = {}
exec(reval.to_py(self.tree, name), lokals)
... | Revert "Improve determination of array shape for constant expressions" | Revert "Improve determination of array shape for constant expressions"
This reverts commit c8c9c42f14c742c6fcb180b7a3cc1bab1655ac46.
| Python | apache-2.0 | ricardog/raster-project,ricardog/raster-project,ricardog/raster-project,ricardog/raster-project,ricardog/raster-project |
cf170e9eb489680366d1608db8fd69d781ae65f5 | thinc/loss.py | thinc/loss.py | import numpy
def categorical_crossentropy(scores, labels):
target = numpy.zeros(scores.shape, dtype='float32')
loss = 0.
for i in range(len(labels)):
target[i, int(labels[i])] = 1.
loss += (1.0-scores[i, int(labels[i])])**2
return scores - target, loss
| import numpy
try:
from cupy import get_array_module
except ImportError:
def get_array_module(*a, **k):
return numpy
def categorical_crossentropy(scores, labels):
xp = get_array_module(scores)
target = xp.zeros(scores.shape, dtype='float32')
loss = 0.
for i in range(len(labels)):
... | Use one-hot representation in categorical cross-entropy | Use one-hot representation in categorical cross-entropy
| Python | mit | explosion/thinc,explosion/thinc,spacy-io/thinc,spacy-io/thinc,explosion/thinc,explosion/thinc,spacy-io/thinc |
81112afb181e88a87b3399b8f7a1f0462ab382cc | kparcel/constants.py | kparcel/constants.py | PARSER_REQUEST_HEADER_USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0'
PARSER_RESULT_PARCEL = 'parcel'
PARSER_RESULT_TRACKS = 'tracks'
| PARSER_REQUEST_HEADER_USER_AGENT = 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)'
PARSER_RESULT_PARCEL = 'parcel'
PARSER_RESULT_TRACKS = 'tracks'
| Fix the default user-agent correctly | Constants: Fix the default user-agent correctly
| Python | bsd-2-clause | iBluemind/armatis |
b73dbb1a352f06092d8d0a869363eb8ddc0922e5 | i3pystatus/updates/dnf.py | i3pystatus/updates/dnf.py | from i3pystatus.core.command import run_through_shell
from i3pystatus.updates import Backend
from re import split, sub
class Dnf(Backend):
"""
Gets updates for RPM-based distributions with `dnf check-update`.
The notification body consists of the status line followed by the package
name and version f... | from i3pystatus.core.command import run_through_shell
from i3pystatus.updates import Backend
from re import split, sub
class Dnf(Backend):
"""
Gets updates for RPM-based distributions with `dnf check-update`.
The notification body consists of the status line followed by the package
name and version f... | Return early if the check threw an error. | Return early if the check threw an error.
| Python | mit | Arvedui/i3pystatus,yang-ling/i3pystatus,m45t3r/i3pystatus,Arvedui/i3pystatus,yang-ling/i3pystatus,m45t3r/i3pystatus,teto/i3pystatus,drwahl/i3pystatus,fmarchenko/i3pystatus,facetoe/i3pystatus,schroeji/i3pystatus,ncoop/i3pystatus,drwahl/i3pystatus,richese/i3pystatus,richese/i3pystatus,schroeji/i3pystatus,teto/i3pystatus,... |
8571f61a20f9ef536040c3101e24c48640a72f6a | iss/admin.py | iss/admin.py | from django.contrib import admin
from .models import Organization
class OrganizationAdmin(admin.ModelAdmin):
list_display = ('account_num', 'org_name', 'city', 'state', 'country_iso')
search_fields = ('org_name', 'account_num')
admin.site.register(Organization, OrganizationAdmin)
| from django.contrib import admin
from .models import Organization
class OrganizationAdmin(admin.ModelAdmin):
list_display = ('membersuite_id', 'account_num', 'org_name', 'city',
'state', 'country_iso')
search_fields = ('org_name', 'membersuite_id', 'account_num')
admin.site.register(Organization, Organ... | Add membersuite ID to display and search | Add membersuite ID to display and search
| Python | mit | AASHE/iss |
79ed8bdb4f328a0d9949e75f4aa5a4f60ab9305d | libqtile/widget/currentlayout.py | libqtile/widget/currentlayout.py | import base
from .. import manager, bar, hook
class CurrentLayout(base._TextBox):
defaults = manager.Defaults(
("font", "Arial", "Text font"),
("fontsize", None, "Font pixel size. Calculated if None."),
("padding", None, "Padding left and right. Calculated if None."),
("background"... | import base
from .. import manager, bar, hook
class CurrentLayout(base._TextBox):
defaults = manager.Defaults(
("font", "Arial", "Text font"),
("fontsize", None, "Font pixel size. Calculated if None."),
("padding", None, "Padding left and right. Calculated if None."),
("background"... | Add click support on layout widget | Add click support on layout widget
| Python | mit | w1ndy/qtile,kseistrup/qtile,soulchainer/qtile,jdowner/qtile,tych0/qtile,cortesi/qtile,kiniou/qtile,aniruddhkanojia/qtile,apinsard/qtile,de-vri-es/qtile,xplv/qtile,apinsard/qtile,jdowner/qtile,encukou/qtile,frostidaho/qtile,tych0/qtile,encukou/qtile,rxcomm/qtile,StephenBarnes/qtile,andrewyoung1991/qtile,rxcomm/qtile,ram... |
893e52b16ea7998db1418dab8a10467a1f891289 | forms.py | forms.py | from flask_wtf import Form
from flask_wtf.csrf import CsrfProtect
from wtforms import StringField, IntegerField, SelectField, BooleanField
csrf = CsrfProtect()
class Submission(Form):
submission = StringField('Submission URL')
comments = BooleanField('Include comments')
comments_style = SelectField('Comm... | from flask_wtf import FlaskForm
from flask_wtf.csrf import CsrfProtect
from wtforms import StringField, IntegerField, SelectField, BooleanField
csrf = CsrfProtect()
class Submission(FlaskForm):
submission = StringField('Submission URL')
comments = BooleanField('Include comments')
comments_style = SelectF... | Migrate from Form to FlaskForm | Migrate from Form to FlaskForm
| Python | mit | JamieMagee/reddit2kindle,JamieMagee/reddit2kindle |
18e3c3f716863b1cc259800592a07a89844d4bf8 | appvalidator/testcases/scripting.py | appvalidator/testcases/scripting.py | import javascript.traverser as traverser
from javascript.spidermonkey import get_tree
from appvalidator.constants import SPIDERMONKEY_INSTALLATION
from ..contextgenerator import ContextGenerator
def test_js_file(err, filename, data, line=0, context=None):
"Tests a JS file by parsing and analyzing its tokens"
... | import javascript.traverser as traverser
from javascript.spidermonkey import get_tree
from appvalidator.constants import SPIDERMONKEY_INSTALLATION
from ..contextgenerator import ContextGenerator
def test_js_file(err, filename, data, line=0, context=None):
"Tests a JS file by parsing and analyzing its tokens"
... | Add information about JS test status to metadata | Add information about JS test status to metadata | Python | bsd-3-clause | mozilla/app-validator,stasm/app-validator,diox/app-validator,eviljeff/app-validator,eviljeff/app-validator,diox/app-validator,mstriemer/app-validator,diox/app-validator,eviljeff/app-validator,mstriemer/app-validator,mozilla/app-validator,diox/app-validator,mozilla/app-validator,stasm/app-validator,stasm/app-validator,e... |
0c55c9cbcf9af918abeaff0f7ea612373f1cfbbe | test_trigrams.py | test_trigrams.py | # -*- coding: utf-8 -*-
"""Trigram tests."""
import pytest
text = "az"
text_with_punct = "a.,/-z"
def test_read_file():
"""Assert the file imported and was split into lines."""
from trigrams import read_file
assert len(read_file()) > 0
@pytest.mark.parametrize('text, text_res', text_with_punct, text)
... | # -*- coding: utf-8 -*-
"""Trigram tests."""
import pytest
text = "a z"
text_with_punct = "a.,/-z"
def test_read_file():
"""Assert the file imported and was split into lines."""
from trigrams import read_file
assert len(read_file()) > 0
def test_strip_punct():
"""Assert no punctuation exists in... | Remove paramatrize, edit test so it passes | Remove paramatrize, edit test so it passes
| Python | mit | bgarnaat/401_trigrams |
e53ecef685569dfad2c62cd38c53190a9b2012d0 | metpy/gridding/__init__.py | metpy/gridding/__init__.py | # Copyright (c) 2008-2015 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
from .gridding_functions import * # noqa: F403
from .points import * # noqa: F403
from .triangles import * # noqa: F403
from .polygons import * # noqa: F403
from .interpola... | # Copyright (c) 2008-2015 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
from .gridding_functions import * # noqa: F403
from .interpolation import * # noqa: F403
__all__ = gridding_functions.__all__[:] # pylint: disable=undefined-variable
__all_... | Remove some imported modules from gridding | MNT: Remove some imported modules from gridding
We never intended these to be part of the supported API. The fact that
these were available from metpy.gridding was revealed by the new
autosummary docs.
| Python | bsd-3-clause | ShawnMurd/MetPy,dopplershift/MetPy,ahaberlie/MetPy,jrleeman/MetPy,ahaberlie/MetPy,dopplershift/MetPy,Unidata/MetPy,jrleeman/MetPy,Unidata/MetPy |
62d22972e3440092d479727b6120789d4724c15e | examples/redirects.py | examples/redirects.py | """This example demonstrates how to perform different kinds of redirects using hug"""
import hug
@hug.get()
def sum_two_numbers(number_1: int, number_2: int):
"""I'll be redirecting to this using a variety of approaches below"""
return number_1 + number_2
@hug.post()
def internal_redirection_automatic(numbe... | """This example demonstrates how to perform different kinds of redirects using hug"""
import hug
@hug.get()
def sum_two_numbers(number_1: int, number_2: int):
"""I'll be redirecting to this using a variety of approaches below"""
return number_1 + number_2
@hug.post()
def internal_redirection_automatic(numbe... | Fix grammer within doc string example | Fix grammer within doc string example
| Python | mit | timothycrosley/hug,timothycrosley/hug,timothycrosley/hug |
373297c6d7059344be67b44c7197998954db89b1 | inboxen/app/handlers/in.py | inboxen/app/handlers/in.py | import logging
from lamson.routing import route, route_like, stateless
from config.settings import queue
from lamson import view
@route("(address)@(host)", address=".+")
@stateless
@nolocking
def START(message, address=None, host=None):
queue.push(message)
| import logging
from lamson.routing import route, stateless, nolocking
from config.settings import accepted_queue
from lamson import view
@route("(address)@(host)", address=".+")
@stateless
@nolocking
def START(message, address=None, host=None):
accepted_queue.push(message)
| Make the IN service actually deliver mail to the accepted queue | Make the IN service actually deliver mail to the accepted queue
| Python | agpl-3.0 | Inboxen/Inboxen,Inboxen/router,Inboxen/Inboxen,Inboxen/Inboxen,Inboxen/Inboxen |
6028b113ed37489d51a68dc5f1ae6ec4c9a14540 | jsk_apc2016_common/node_scripts/visualize_pick_json.py | jsk_apc2016_common/node_scripts/visualize_pick_json.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import cv_bridge
import rospy
from sensor_msgs.msg import Image
import jsk_apc2016_common
def publish_cb(event):
imgmsg.header.stamp = rospy.Time.now()
pub.publish(imgmsg)
if __name__ == '__main__':
rospy.init_node('visualize_pick_json')
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import matplotlib.pyplot as plt
import cv_bridge
import rospy
from sensor_msgs.msg import Image
import jsk_apc2016_common
def visualize_cb(event):
if pub.get_num_connections() > 0:
imgmsg.header.stamp = rospy.Time.now()
pub.publish(... | Add mode to display json with --display | Add mode to display json with --display
| Python | bsd-3-clause | pazeshun/jsk_apc,pazeshun/jsk_apc,pazeshun/jsk_apc,pazeshun/jsk_apc,pazeshun/jsk_apc |
3d4a71f6bb84fe4e5c7f51b109a55a7560ebb673 | test/test_absolute_import.py | test/test_absolute_import.py | import jedi
from jedi.parsing import Parser
from . import base
def test_explicit_absolute_imports():
"""
Detect modules with ``from __future__ import absolute_import``.
"""
parser = Parser("from __future__ import absolute_import", "test.py")
assert parser.scope.explicit_absolute_import
def test_... | import jedi
from jedi.parsing import Parser
from . import base
def test_explicit_absolute_imports():
"""
Detect modules with ``from __future__ import absolute_import``.
"""
parser = Parser("from __future__ import absolute_import", "test.py")
assert parser.module.explicit_absolute_import
def test... | Use Parser.module instead of Parser.scope | Use Parser.module instead of Parser.scope
| Python | mit | jonashaag/jedi,WoLpH/jedi,tjwei/jedi,mfussenegger/jedi,dwillmer/jedi,tjwei/jedi,mfussenegger/jedi,WoLpH/jedi,jonashaag/jedi,flurischt/jedi,flurischt/jedi,dwillmer/jedi |
9968e526c00ee221940b30f435ecb866a4a1a608 | tests/core/test_validator.py | tests/core/test_validator.py | import pytest
import asyncio
from rasa.core.validator import Validator
from tests.core.conftest import DEFAULT_DOMAIN_PATH, DEFAULT_STORIES_FILE, DEFAULT_NLU_DATA
from rasa.core.domain import Domain
from rasa.nlu.training_data import load_data, TrainingData
from rasa.core.training.dsl import StoryFileReader
@pytest.fi... | import pytest
import asyncio
from rasa.core.validator import Validator
from tests.core.conftest import (
DEFAULT_DOMAIN_PATH,
DEFAULT_STORIES_FILE,
DEFAULT_NLU_DATA,
)
from rasa.core.domain import Domain
from rasa.nlu.training_data import load_data, TrainingData
from rasa.core.training.dsl import StoryFileR... | Refactor validator tests with black | Refactor validator tests with black
Signed-off-by: Gabriela Barrozo Guedes <ef39217ba926e49eaea73efc4d3c11e5daab460c@gmail.com>
| Python | apache-2.0 | RasaHQ/rasa_nlu,RasaHQ/rasa_nlu,RasaHQ/rasa_nlu |
37833caae3147f9c2f70b83f5b04becaa402a66e | httpDissec.py | httpDissec.py | # sudo apt-get install python-scapy
from scapy.all import *
# sudo pip install scapy_http
from scapy.layers import http
from scapy.layers.http import HTTPResponse
import sys
packets = rdpcap("task07_f1.pcap")
requests = {}
answers = {}
def has_http_header(packet):
return packet.haslayer(HTTPResponse)
for pkt in... | # sudo apt-get install python-scapy
from scapy.all import *
# sudo pip install scapy_http
from scapy.layers import http
from scapy.layers.http import HTTPResponse
import sys
packets = rdpcap("task07_f1.pcap")
requests = []
answers = []
def has_http_header(packet):
return packet.haslayer(HTTPResponse)
for pkt in... | Change from dic to list | Change from dic to list
| Python | mit | alexst07/http_dissector |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.