repo_name stringlengths 5 100 | path stringlengths 4 231 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k | score float64 0 0.34 | prefix stringlengths 0 8.16k | middle stringlengths 3 512 | suffix stringlengths 0 8.17k |
|---|---|---|---|---|---|---|---|---|
RevansChen/online-judge | Codewars/8kyu/8kyu-interpreters-hq9-plus/Python/solution2.py | Python | mit | 552 | 0.014493 | # Python - 3.6.0
gets = lambda i: 's' if i != 1 else ''
getn = lambda i: f'{i if i > 0 else "no more" if i == 0 else 99} | bottle{gets(i)}'
getm = lambda i: 'Go to the store and buy some more' if i <= 0 else 'Take one down and pass it around'
g | etl1 = lambda i: f'{getn(i)} of beer on the wall, {getn(i)} of beer.'.capitalize()
getl2 = lambda i: f'{getm(i)}, {getn(i - 1)} of beer on the wall.'.capitalize()
HQ9 = {
'H': 'Hello World!',
'Q': 'Q',
'9': '\n'.join(
'\n'.join([getl1(i), getl2(i)]) for i in range(99, -1, -1)
)
}.get
|
Darkdadaah/pywikibot-core | tests/wikibase_edit_tests.py | Python | mit | 14,484 | 0.000276 | # -*- coding: utf-8 -*-
"""
Tests for editing Wikibase items.
Tests which should fail should instead be in the TestWikibaseSaveTest
class in edit_failiure_tests.py
"""
#
# (C) Pywikibot team, 2014-2017
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals
impor... | get_repo()
item = self._clean_item(testsite, 'P271')
# set new claim
claim = pywikibot.page.Claim(testsite, 'P271', datatype='monolingualtext')
target = pywikibot.WbMonolingua | lText(text='Test this!', language='en')
claim.setTarget(target)
item.addClaim(claim)
# confirm new claim
item.get(force=True)
claim = item.claims['P271'][0]
self.assertEqual(claim.getTarget(), target)
def test_Coordinate_edit(self):
"""Attempt adding a Coord... |
ItsCalebJones/SpaceLaunchNow-Server | api/migrations/00010_astronauts_populate_slug.py | Python | apache-2.0 | 732 | 0.001366 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2018-11-28 22:08
from __future__ import unicode_literals
from django.db import migrations, models
from django.template.defaultfilters import truncatechars, slugify
def gen_slug(apps, schema_editor):
Astronauts = apps.get_model('api', 'Astronauts')
for ... | item.id)) |
item.save()
class Migration(migrations.Migration):
dependencies = [
('api', '0009_astronauts_slug'),
]
operations = [
# omit reverse_code=... if you don't want the migration to be reversible.
migrations.RunPython(gen_slug, reverse_code=migrations.RunPython.noop),
]
|
googleapis/python-datacatalog | samples/generated_samples/datacatalog_v1_generated_data_catalog_update_tag_sync.py | Python | apache-2.0 | 1,524 | 0.000656 | # -*- coding: utf-8 -*-
# Copyright 2022 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable | law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Generated code. DO NOT EDIT!
#
#... | as been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-datacatalog
# [START datacatalog_v1_generated_DataCatalog_UpdateTag_sync]
fr... |
aziz/SublimeFileBrowser | common.py | Python | mit | 21,576 | 0.00325 | # coding: utf-8
'''Common stuff, used in other modules'''
from __future__ import print_function
import re, os, fnmatch, sys, itertools
import sublime
from sublime import Region
from os.path import isdir, join, basename
try: # unavailable dependencies shall not break basic functionality
import package_events
exc... | ghorror.com/blog/2007/12/sorting-for-humans-natural-sort-order.html
"""
convert = lambda text: int(text) if text.isdigit() else text.lower()
alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
names.sort(key=alphanum_key)
def print(*args, **kwargs):
""" Redefine print() func... | unicode literals among Python versions used in ST2.
Redefining/tweaking built-in things is relatively safe; of course, when
ST2 will become irrelevant, this def might be removed undoubtedly.
"""
if not (ST3 or NT):
args = (s.encode('utf-8') if isinstance(s, unicode) else str(s) for ... |
eunchong/build | third_party/buildbot_8_4p1/buildbot/test/unit/test_db_buildrequests.py | Python | bsd-3-clause | 30,318 | 0.009433 | # This file is part of Buildbot. Buildbot 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, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | results=75, priority=7,
claimed_ | by_name=self.MASTER_NAME,
claimed_by_incarnation=self.MASTER_INCARN,
claimed_at=self.CLAIMED_AT_EPOCH,
submitted_at=self.SUBMITTED_AT_EPOCH,
complete_at=self.COMPLETE_AT_EPOCH),
])
d.addCallback(lambda _ :
self.db.buildreque... |
Alkemic/webpage | module/static_page/cms/views.py | Python | mit | 5,262 | 0 | # -*- coding: utf-8 -*-
"""CMS view for static pages"""
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from boski.mixins impor... | ': 'update',
'delete': 'delete',
'index': 'index',
}
return locals()
@login_required
@with_template('crud/update.html')
def update(request, pk):
entry = Entry.objects.get(pk=pk)
form = EntryForm(request.POST or None, instance=entry)
if form.is_valid():
entry = form.save(... | if request.POST.get('next', None) == 'edit':
return HttpResponseRedirect(reverse(
'cms:static_page:update', args=[pk]
))
return HttpResponseRedirect(reverse('cms:static_page:index'))
name = _('Edit entry "%s"') % entry
request.breadcrumbs = (
{'name'... |
AccuraGit/PodcastPlatform | build/lib/audiofield/models.py | Python | mit | 2,333 | 0.001715 | #
# django-audiofield License
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not | distributed with this file,
# You ca | n obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (C) 2011-2014 Star2Billing S.L.
#
# The Initial Developer of the Original Code is
# Arezqui Belaid <info@star2billing.com>
#
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from audiofield.... |
DedMemez/ODS-August-2017 | tutorial/TutorialTVScenes.py | Python | apache-2.0 | 4,254 | 0.007287 | # Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.tutorial.TutorialTVScenes
from panda3d.core import Camera
from direct.task.Task import Task
from otp.avatar import Emote
from toontown.television.TVScenes import *
from toontown.television.TVEffects import *
from toontown.suit.Suit import Suit
f... | arentTo(self)
self.taskStarted = False
self.npcs = []
for id, posHpr in self.ToonPos.iteritems():
npc = NPCToons.createLocalNPC(id)
npc.reparentTo(self.geom)
npc.setPosHpr(*posHpr)
npc.nametag3d.removeNode()
npc.nametag.destroy(... |
self.geom = None
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
npc.delete()
self.npcs = []
self.taskStarted = False
ThreeDScene.delete(self)
return
def startTask(self):
if self.taskStarted:
... |
fxfitz/ansible | lib/ansible/modules/network/nxos/nxos_linkagg.py | Python | gpl-3.0 | 12,502 | 0.0024 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Ansible by Red Hat, inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | : 'no'
aggregate:
description: List of link aggregation definitions.
state:
description:
- State of the link aggregation group.
default: present
choices: ['present','absent']
purge:
description:
- Purge links not defined in the | I(aggregate) parameter.
type: bool
default: 'no'
"""
EXAMPLES = """
- name: create link aggregation group
nxos_linkagg:
group: 99
state: present
- name: delete link aggregation group
nxos_linkagg:
group: 99
state: absent
- name: set link aggregation group to members
nxos_linkagg:
g... |
appuio/ansible-role-openshift-zabbix-monitoring | vendor/openshift-tools/openshift_tools/ircbot/trello/trello.py | Python | apache-2.0 | 16,279 | 0.001106 | #!/usr/bin/env python
''' Interact with Trello API as a CLI or Sopel IRC bot module '''
import argparse
from datetime import date
from email.mime.text import MIMEText
import json
import os
import re
import smtplib
import sys
# sopel is only for IRC bot installation. Not required for CLI
try:
import sopel.module ... | ser(
description='Create, comment, move Trello cards, also reporting.')
subparsers = parser.add_subparsers(help='sub-command help')
parser_get = subparsers.add_parser('get',
help="""Get board information:
... | card details""")
parser_get.add_argument(
'card',
nargs='?',
metavar='CARD_URL',
help='Card short URL to get details for')
parser_get.add_argument(
'--list', '-l',
metavar='TRELLO_LIST',
default=DEFA... |
JackKelly/neuralnilm_prototype | scripts/e159.py | Python | mit | 5,375 | 0.004465 | from __future__ import print_function, division
import matplotlib
matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab!
from neuralnilm import Net, RealApplianceSource, BLSTMLayer, DimshuffleLayer
from lasagne.nonlinearities import sigmoid, rectify
from lasagne.objectives import crossentropy, mse... | }
]
)
return net
def init_experiment(experiment):
full_exp_name = NAME + experiment
func_call = 'exp_{:s}(full_exp_name)'.format(experiment)
print("***********************************")
print("Preparing", full_exp_name, "...")
net = eval(func_call)
return net
def main(... | _experiment(experiment)
run_experiment(net, path, epochs=None)
except KeyboardInterrupt:
break
except TrainingError as exception:
print("EXCEPTION:", exception)
except Exception as exception:
print("EXCEPTION:", exception)
import ipdb; ... |
tux-00/ansible | lib/ansible/module_utils/aos.py | Python | gpl-3.0 | 5,550 | 0.003964 | #
# Copyright (c) 2017 Apstra Inc, <community@apstra.com>
#
# This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the m... | os import *
"""
import json
from ansible.module_utils.pycompat24 import get_exception
from distutils.version import LooseVersion
try:
import yaml
HAS_YAML = True
except ImportError:
HAS_YAML = False
try:
from apstra.aosom.session import Session
HAS_AOS_PYEZ = True
except ImportError:
HAS_AO... | e minimum version requirement is met
"""
if not HAS_AOS_PYEZ:
module.fail_json(msg='aos-pyez is not installed. Please see details '
'here: https://github.com/Apstra/aos-pyez')
elif min:
import apstra.aosom
AOS_PYEZ_VERSION = apstra.aosom.__version__
... |
mdaif/olympia | apps/accounts/tests/test_serializers.py | Python | bsd-3-clause | 412 | 0 | from a | ccounts | .serializers import UserProfileSerializer
from amo.tests import BaseTestCase
from users.models import UserProfile
class TestAccountSerializer(BaseTestCase):
def setUp(self):
self.user = UserProfile.objects.create(email='a@m.o')
def test_picture_url(self):
serial = UserProfileSerializer(inst... |
h4/fuit-webdev | examples/lesson2/3.1/2.2.4.py | Python | mit | 180 | 0.031447 | # -*- enc | oding: utf-8 -*-
"""
Групповое присваивание
"""
v = ('a', 'b', 'e')
(x, y, z) = v
print x
print y
print | z
|
locationtech/geowave | python/src/main/python/pygw/statistics/statistic_type.py | Python | apache-2.0 | 933 | 0.004287 | #
# Copyright (c) 2013-2020 Contributors to the Eclipse Foundation
#
# See the NOTICE file distributed with this work for additional information regarding copyright
# ownership. All rights reserved. This program and the accompanying materials are made available
# under the terms of the Apache License, Version 2.0 whic... | """
Base statistic type.
"""
def __init__(self, java_ref):
super().__init__(java_ref)
def get_string(self):
return self._ja | va_ref.getString()
class IndexStatisticType(StatisticType):
pass
class DataTypeStatisticType(StatisticType):
pass
class FieldStatisticType(StatisticType):
pass
|
fizwit/filesystem-reporting-tools | reassemble.py | Python | gpl-2.0 | 1,682 | 0.014269 | #!/usr/bin/env python3
#
import sys
import csv
from pprint import pprint
"""2018.10.28 John Dey
consume CSV output from pwalk and reassemble directory data.
File system data from pwalk is flattened and out of order.
Rewalk the tree data and create two new fields for each directory.
Create a tree sum of file count and ... | root = int(row[0])
dd[int(row[0])]['sumcnt'] += 1
dd[int(row[0])]['sumsiz'] += int(row[7])
print("Total directories: %d" % len(dd.keys()))
"""reassemble the tree"""
for inode in dd.keys():
parent = dd[inode]['parent']
while parent != 0:
dd[parent]['sumcnt'... | d[inode]['dirsiz']
parent = dd[parent]['parent']
pprint(dd[root])
|
jvicu2001/alexis-bot | modules/fullwidth.py | Python | mit | 993 | 0.005035 | from bot import Command, categories
class Fullwidth(Command):
__version__ = '1.0.0'
__author__ = 'makzk'
__description__ = 'Translate a set of allowed characters (below) to the fullwidth format.'
supported = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&()+,-./:;<=>?@[\\]^`{|}'... | t)
self.name = 'fullwidth'
self.aliases = ['full']
self.help = '$[fullwidth-help]'
self.category = categories.UTILITY
async def handle(self, cmd):
# Fetch the text to convert
text = [cmd.no_tags(), cmd.lng('fullwidth-default')][cmd.text == ''].replace(' ', ' ')
... | ullwidth.supported else i for i in list(text)]
# Send the result and remove the author's message
await cmd.answer(''.join(converted), delete_trigger=True, as_embed=True)
|
aaronpcz/py-electret-serial-with-bucket-normalisation | serial-electret-data-listener.py | Python | mit | 4,819 | 0.001868 | import serial
import time
import threading
from socketIO_client import SocketIO, LoggingNamespace, BaseNamespace
from threading import Thread
from tendo import singleton
import configparser
import sys
me = singleton.SingleInstance()
config = configparser.ConfigParser()
config.read('./config.cfg')
password = config.g... | = "/eos/chan/402"
osc_chan_403 = "/eos/chan/403"
osc_chan_default = "/eos/chan/402"
def get_score_for_scene(scene_id):
return {
"play": {
"themes": [
],
"scenes": [
scene_id
]
}
}
def get_osc_command(target, value):
return ... | def __init__(self):
self.socketio = SocketIO(media_hub_url, 80, LoggingNamespace)
self.socketio.emit('auth', {'password': password}, self.on_auth_r)
self.socketio.wait_for_callbacks(seconds=10)
self.receive_events_thread = Thread(target=self._receive_events_thread)
self.recei... |
DailyActie/Surrogate-Model | 01-codes/numpy-master/numpy/distutils/setup.py | Python | mit | 610 | 0 | #!/usr/bin/env python
from __future__ import div | ision, print_function
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('distutils', parent_package, top_path)
config.add_subpackage('command')
config.add_subpackage('fcompiler')
config.add_data_dir('tests')
config.a... | config.add_data_files('mingw/gfortran_vs2003_hack.c')
config.make_config_py()
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(configuration=configuration)
|
RecNes/service.subtitles.planetdp_by_recnes | service.py | Python | gpl-3.0 | 4,634 | 0.004532 | # -*- coding: utf-8 -*-
import os
import urllib
import urllib2
try: import simplejson as json
except ImportError: import json
import sys
reload(sys) # Reload does the trick!
sys.setdefaultencoding('UTF8')
class PlanetDP(object):
"""
PlanetDP.org subtitle search and fetch class
"""
def __init__(s... | return False
return False
def authenticate(self | ):
"""
Authentication module
"""
_url = self.build_url(self.auth_uri, secure=True)
values = {'authname': _authname, 'pass': _pass}
result = self.send_request(_url, values, jsonresp=True)
self.token = result['token']
def search_movie(self, _movie_name=""):
... |
hwine/build-relengapi | relengapi/blueprints/slaveloan/rest.py | Python | mpl-2.0 | 3,346 | 0.001494 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from __future__ import absolute_import
from datetime import datetime
import wsme.types
class Machine(wsme.types.Base... | (in UTC) of the start of action.(see
#: :ref:`Datetime-Format` for format information)
timestamp_start = datetime
#: Datetime string (in UTC) when action was completed. (see
#: :ref:`Datetime-Format` for for | mat information)
timestamp_complete = datetime
#: Who performed the completion (admin ldap)
complete_by = unicode
#: What action needs performing
msg = unicode
class UpdateManualAction(wsme.types.Base):
"Represents payload used to update a manual action"
#: Mark the action as complete
... |
cphyc/ScriptManager | mysite/scripts/urls.py | Python | unlicense | 407 | 0 | from django.conf.urls import url
from scripts import views
urlpatterns = [ |
url(r'^$', views.index, name='index'),
# ex: /polls/5/
url(r'^(?P<script_id>[0-9]+)/$', views.detail, name='detail'),
# ex: /polls/5/results/
url(r'^(?P<script_id>[0-9]+)/results/$', views.results, name='results'),
# ex: /polls/5/vote/
url(r'^(?P<script_id>[0-9]+)/vote/$', views.vote, name=... | e'),
]
|
nathanshartmann/portuguese_word_embeddings | sentence_similarity/utils/commons.py | Python | gpl-3.0 | 2,224 | 0.001349 | # -*- coding: utf-8 -*-
"""
Common structures and functions used by other scripts.
"""
from xml.etree import cElementTree as ET
str_to_entailment = {'none': 0,
'entailment': 1,
'paraphrase': 2}
entailment_to_str = {v: k for k, v in str_to_entailment.items()}
class Pair(obj... | root.iter('pair'):
t = xml_pair.find('t').text
h = xml_pair.find('h').text
attribs = dict(xml_pair.items())
id_ = int(attribs['id'])
if 'entailment' in attribs:
ent_string = attribs['entailment'].lower()
try:
ent_value = str_to_entailment... | _string))
else:
ent_value = None
if 'similarity' in attribs:
similarity = float(attribs['similarity'])
else:
similarity = None
if need_labels and similarity is None and ent_value is None:
msg = 'Missing both entailment and similarity val... |
mattjmorrison/Pylint | checkers/typecheck.py | Python | gpl-2.0 | 15,613 | 0.001986 | # Copyright (c) 2006-2010 LOGILAB S.A. (Paris, FRANCE).
# http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, o... | nt.checkers import BaseChecker
from pylint.checkers.utils import safe_infer, is_super, check_messages
MSGS = {
'E1101': ('%s %r has no %r member',
'Used when a variable is accessed for an unexistent member.'),
| 'E1102': ('%s is not callable',
'Used when an object being called has been inferred to a non \
callable object'),
'E1103': ('%s %r has no %r member (but some types could not be inferred)',
'Used when a variable is accessed for an unexistent member, but \
a... |
grade-it/grader | redkyn-grader/grader/commands/init.py | Python | mit | 1,386 | 0.002165 | ''' TODO: Init package docs
'''
import logging
import uuid
from grader.models import Grader
from grader.utils.config import is_grader_dir
logger = logging.getLogger(__name__)
help = 'Initialize grader by creating grader.yml'
def setup_parser(parser):
parser.add_argument('--course-id', default=str(uuid.uuid4()... | rce:
logger.critical(
"grader already configured in {}. Abort!".format(args.path)
)
raise SystemExit(1)
if args.canvas_host:
canvas_token = input("Canvas access token (from {}/profile/settings): ".format(args.canvas_host))
else:
canvas_to | ken = None
# Create the new grader
g = Grader.new(args.path, args.name, args.course_id, args.canvas_host, canvas_token)
logger.info("Wrote {}".format(g.config.file_path))
|
FunTimeCoding/jenkins-job-manager | script/python/flake8.py | Python | mit | 357 | 0 | #!/usr/bin/env python3
from python_utility.command_process import CommandProcess
def main():
process = CommandProcess(
arguments=[
'flake8',
'--ex | clude', '.git,.idea,.tox',
| '--verbose',
'--max-complexity', '5'
],
)
process.print_output()
if __name__ == '__main__':
main()
|
dscorbett/pygments | pygments/lexers/other.py | Python | bsd-2-clause | 1,744 | 0 | """
pygments.lexers.other
~~~~~~~~~~~~~~~~~~~~~
Just export lexer classes previously contained in this module.
:copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.lexers.sql import SqlLexer, MySqlLexer, SqliteConsoleLexer
fr... | ngine3Lexer
from pygments.lexers.modeling import ModelicaLexer
from pygments.lexers.scripting import AppleScriptLexer, MOOCodeLexer, \
HybrisLexer
from pygments.lexers.graphics import PostScriptLexer, GnuplotLexer, \
AsymptoteLexer, PovrayLexer
from pygments.lexers.business import ABAPLexer, OpenEdgeLexer, \
... | ments.lexers.dsls import ProtoBufLexer, BroLexer, PuppetLexer, \
MscgenLexer, VGLLexer
from pygments.lexers.basic import CbmBasicV2Lexer
from pygments.lexers.pawn import SourcePawnLexer, PawnLexer
from pygments.lexers.ecl import ECLLexer
from pygments.lexers.urbi import UrbiscriptLexer
from pygments.lexers.smalltal... |
michalpravda/Anki_helpers | scripts/import_maker_de2.py | Python | mit | 11,395 | 0.005265 | # coding=windows-1250
import re
import os
import sys
import logging
import shutil
from argparse import ArgumentParser
import urllib
import zipfile
from datetime import datetime
import htmlentitydefs
from os.path import expanduser
import unicodedata
DIR_HTML = 'html'
DIR_SOUNDS = 'sounds'
DIR_DONE = 'done'
'''
Takes... | "9": "nueve",
"10": " | diez",
"11": "once",
"12": "doce",
"13": "trece",
"14": "catorce",
"15": "quince",
"16": "dieciséis",
"17": "diecisiete",
"18": "dieciocho",
"19": "diecinueve",
"20": "veinte",
"21": "veintiuno",
"22": "veintidós",
"... |
qingqing01/Paddle | python/paddle/trainer/__init__.py | Python | apache-2.0 | 599 | 0 | # Copyright (c) 2016 Baidu, Inc. All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | re
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing pe | rmissions and
# limitations under the License.
|
HeatherJW/Code | book_review/book_reviews.py | Python | unlicense | 8,418 | 0.003564 | import webbrowser
import os
import re
from books import Book, Movie
# Styles and scripting for the page
main_page_head = '''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Book reviews</title>
<!-- Bootstrap 3 -->
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/boot... | le {
margin-bottom: 20px;
padding-top: 20px;
}
#trailer .modal-dialog {
margin-top: 200px;
width: 640px;
height: 480px;
}
.hanging-close {
positi | on: absolute;
top: -12px;
right: -12px;
z-index: 9001;
}
#trailer-video {
width: 100%;
height: 100%;
}
.movie-tile {
margin-bottom: 20px;
padding-top: 20px;
}
.movie-tile:hover {
... |
webtweakers/django-tinymce4-widget | setup.py | Python | mit | 1,881 | 0 | #!/usr/bin/env python
from setuptools import setup
import metadata
app_name = metadata.name
version = metadata.version
def read(filename):
with open(filename) as fp:
return fp.read()
long_description = read('README.rst')
setup(
name='django-%s' % app_name,
version=version,
packages=['tinym... | : Text Processing',
'Topic :: Text Processing :: Markup',
| 'Topic :: Text Processing :: Markup :: HTML',
],
platforms=['any'],
url='https://github.com/browniebroke/django-tinymce4-widget',
zip_safe=False
)
|
CLVsol/clvsol_odoo_addons | clv_report/models/report.py | Python | agpl-3.0 | 1,353 | 0 | # -*- coding: utf-8 -*-
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class Report(models.Model):
_description = 'Report'
_name = 'clv.report'
_inherit = 'clv.abstract.report'
_order =... | _id = fields.Integer(
string='Record ID',
help="ID of the target record in the database"
)
reference = fields.Char(
string='Reference ',
compute='_co | mpute_reference',
readonly=True,
store=True
)
reference_name = fields.Char(
string='Reference Name',
compute='_compute_reference',
readonly=True,
store=True
)
active = fields.Boolean(string='Active', default=1)
@api.depends('model', 'res_id')
def... |
citrix-openstack-build/pecan | pecan/tests/test_hooks.py | Python | bsd-3-clause | 34,390 | 0 | from webtest import TestApp
from six import b as b_
from six import u as u_
from six.moves import cStringIO as StringIO
from webob import Response
from pecan import make_app, expose, redirect, abort
from pecan.hooks import (
PecanHook, TransactionHook, HookController, RequestViewerHook
)
from pecan.configuration ... | run_hook[2] == 'inside'
assert run_hook[3] == 'after' |
def test_basic_multi_hook(self):
run_hook = []
class RootController(object):
@expose()
def index(self):
run_hook.append('inside')
return 'Hello, World!'
class SimpleHook(PecanHook):
def __init__(self, id):
... |
ProjectSWGCore/NGECore2 | scripts/loot/lootItems/re_junk/ear_jewel.py | Python | lgpl-3.0 | 135 | 0.02963 |
d | ef itemTe | mplate():
return ['/object/tangible/loot/npc_loot/shared_jewelry_ear_s02.iff']
def customItemName():
return 'Ear jewel' |
Hanse00/LecToCal | lectocal/__init__.py | Python | apache-2.0 | 60 | 0 | _ | _all__ = [" | gauth", "gcalendar", "lectio", "lesson", "run"]
|
carvalhomb/sg-userprofile | userprofile/userprofile_app/__init__.py | Python | apache-2.0 | 1,654 | 0.013301 | '''
Main module for starting the dashboard application service. Imports required
modules from Flask (including DB and auth modules),
and sets up logging.
'''
import os
import sys
from flask import Flask
import config
from .extensions import db
def create_app(testing=False):
# We are using the "Application Fac... | flask.pocoo.org/docs/patterns/appfactories/
app = Flask(__name__)
# Our application uses blueprints. Import and register the blueprint:
from .views import userprofile
app.register_blueprint(userprofile)
# Configure app
app.config.from_object('config')
if testing:
app... | ATABASE_URI_TEST
app.config['LOG_FILENAME'] = config.LOG_FILENAME_TEST
# Init database
db.init_app(app)
# Logging when in production:
import logging
from logging.handlers import RotatingFileHandler
#from logging import StreamHandler
file_handler = RotatingFil... |
eliksir/mailmojo-python-sdk | test/test_contact.py | Python | apache-2.0 | 815 | 0 | # coding: utf-8
"""
MailMojo API
v1 of the MailMojo API # noqa: E501
OpenAPI spec version: 1.1.0
Contact: hjelp@mailmojo.no
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import | unittest
import mailmojo_sdk
from mailmojo_sdk.models.contact import Contact # noqa: E501
from mailmojo_sdk.rest import ApiException
class TestContact(unittest.TestCase):
"""Contact unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def te | stContact(self):
"""Test Contact"""
# FIXME: construct object with mandatory attributes with example values
# model = mailmojo_sdk.models.contact.Contact() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
|
claudep/translate | translate/lang/el.py | Python | gpl-2.0 | 2,156 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2007-2009,2011 Zuza Software Foundation
#
# This file is part of translate.
#
# translate 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 vers... |
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
"""This module represents the Greek language.
.. seealso:: http://en.wikipedia.org/wiki/Greek_language
"""
from __future__ import unicode_literals
import re
from translate.lan... | as question mark and the middot instead
sentenceend = ".!;…"
sentencere = re.compile(r"""
(?s) # make . also match newlines
.*? # anything, but match non-greedy
[%s] # the puntuation for sentence ending
\s+ # the spacing after the puntuation
... |
pblottiere/QGIS | python/plugins/processing/gui/RectangleMapTool.py | Python | gpl-2.0 | 3,872 | 0.000258 | # -*- coding: utf-8 -*-
"""
***************************************************************************
RectangleMapTool.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
**********************... | alse
if self.rectangle() is not None:
self.rectangleCreate | d.emit()
def canvasMoveEvent(self, e):
if not self.isEmittingPoint:
return
self.endPoint = self.toMapCoordinates(e.pos())
self.showRect(self.startPoint, self.endPoint)
def showRect(self, startPoint, endPoint):
self.rubberBand.reset(QgsWkbTypes.PolygonGeometry)
... |
mozilla/caseconductor-ui | tests/core/test_conf.py | Python | gpl-3.0 | 2,735 | 0.003291 | # Case Conductor is a Test Case Management system.
# Copyright (C) 2011 uTest Inc.
#
# This file is part of Case Conductor.
#
# Case Conductor 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... | self.assertEqual(settings.failed, ["SOME_SETTING"])
def test_no_default(self):
from django.core.exceptions import ImproperlyConfigured
conf = self.cls()
settings = FakeSettings()
with patch("ccui.core.conf.settings", settings):
with self.assertRaises(ImproperlyC... | ()
settings = FakeSettings(SOME_SETTING="a val")
with patch("ccui.core.conf.settings", settings):
val = conf.SOME_SETTING
self.assertEqual(val, "a val")
self.assertEqual(settings.accessed, ["SOME_SETTING"])
def test_default_is_fallback(self):
conf = self.cls(S... |
davidhalter/depl | depl/helpers.py | Python | mit | 308 | 0 | from StringIO | import StringIO
from fabric.api import get, put
def read_file(remote_path):
"""Wrapper around fabric's ``get``"""
sio = StringIO()
get(remote_path, sio)
return sio.getvalue()
def write_file(text, remote_path, use_sudo=False):
put(Str | ingIO(text), remote_path, use_sudo)
|
emgirardin/compassion-modules | message_center_compassion/tests/base_test_onramp.py | Python | agpl-3.0 | 3,074 | 0 | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Yannick Vaucher, Emanuel Cino
#
# The licence is in the file __openerp__.py
#
#... | "application/x-www-form-urlencoded",
"Content-Length": 46,
"Expect": "100-continue",
"Connection": "Keep-Alive",
}
conn = httplib.HTTPSConnection('api2.compassion.com')
conn.request("POST", "/c | ore/connect/token", params_post, header_post)
response = conn.getresponse()
data_token = simplejson.loads(response.read())
conn.close()
self.headers = {
'Content-type': 'application/json',
'Authorization': '{token_type} {access_token}'.format(
**d... |
NeuroDataDesign/seelviz | jon/algorithms/analysis2.py | Python | apache-2.0 | 30,374 | 0.004247 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import matplotlib
from matplotlib import pyplot as plt
import numpy as np
from numpy import linalg as LA
import cv2
import math
import os
import plotly
from plotly.graph_objs import *
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot
from plotly import... | raise ValueError("Number of points given should be at most equal to total points: %d" % total_points)
fraction = num_points / float(total_points)
if fraction < 1.0:
# np.random.random returns random floats in the half-open interval [0.0, 1.0)
filt = np.random.random(size=l) < fraction
... | print('z.size before downsample: %d' % z.size)
print('v.size before downsample: %d' % v.size)
x = x[filt]
y = y[filt]
z = z[filt]
v = v[filt]
# print('x.size after downsample: %d' % x.size)
# print('y.size after downsample: %d' % y.size)
... |
Dfred/concept-robot | experiments/play-human/human_player.py | Python | gpl-3.0 | 3,524 | 0.018729 | #!/usr/bin/python
#
# You should have received a copy of the GNU General Public License
# along with comm module. If not, see <http://www.gnu.org/licenses/>.
#
#
# Playing custom datafiles (.lpd) to remote submodules.
# The .lpd entries shall be sorted according to their 1st field (time).
#
import sys
import time
im... | tion(conf.conn_gaze, "Gaze")
if gaze.connected == True:
face = moduleConnection(conf.conn_face, "Face")
if face.connected == True:
interpretLDPFile(if | ilename, jump_first)
sys.exit(0)
|
datacratic/Diamond-old | src/diamond/handler/sentry.py | Python | mit | 10,698 | 0 | # coding=utf-8
"""
Diamond handler that check if values are too high or too low, if so send an
alert to a Sentry server
This handler requires the Python module Raven:
http://raven.readthedocs.org/en/latest/index.html
To work this handler need a similar configuration:
[[SentryHandler]]
# Create a new project in Sen... | Handler
@param handler: configured Sentry graphite handler
@rtype None
"""
match = self.regexp.match(metric.path)
if match:
minimum = Minimum(metric.value, self.min)
maximum = Maximum(metric.value, self.max)
if minimum.i | s_error or maximum.is_error:
self.counter_errors += 1
message = "%s Warning on %s: %.1f" % (self.name,
handler.hostname,
metric.value)
culprit = "%s %s" % (handler.... |
zaneswafford/songaday_searcher | songs/migrations/0013_auto_20170309_0356.py | Python | bsd-3-clause | 956 | 0 | # -*- coding: utf-8 -*-
# Generated | by Django 1.10.5 on 2017-03-09 03:56
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('songs', '0012_song_download_url'),
]
operations = [
migrations.RemoveField(
... | ),
migrations.RemoveField(
model_name='songupdatetoken',
name='last_started',
),
migrations.AddField(
model_name='songupdatetoken',
name='finished',
field=models.DateTimeField(blank=True, null=True),
),
migrations.A... |
tommo/gii | lib/gii/SceneEditor/SceneEditor.py | Python | mit | 2,647 | 0.047979 | import os
import logging
from gii.core import app, signals, EditorCommandStack, RemoteCommand
from gii.core.selection import SelectionManager, getSelectionManager
from gii.qt.controls.Window import MainWindow
from gii.qt.controls.Menu import MenuManager
from gii.qt import TopEditorModule, SubEditorModule
f... | -----------------------##
from gii.moai.MOAIRuntime import MOAILuaDelegate
##----------------------------------------------------------------##
class SceneEditorModule( SubEditorModule ):
def getParentModuleId( self ):
re | turn 'scene_editor'
def getSceneEditor( self ):
return self.getParentModule()
def getSceneToolManager( self ):
return self.getModule( 'scene_tool_manager' )
def changeSceneTool( self, toolId ):
self.getSceneToolManager().changeTool( toolId )
def getAssetSelection( self ):
return getSelectionManager( 'as... |
sllt/snowy | handler/notification.py | Python | bsd-3-clause | 1,557 | 0.008349 | #!/usr/bin/env python
# coding=utf-8
#
# Copyright 2013 snowy.in
import uuid
import hashlib
import Image
import StringIO
import time
import json
import re
import urllib2
import tornado.web
import lib.jsonp
import pprint
from base import *
from lib.variables import *
from form.topic import *
from lib.variables import ... | e_variables["user_info"]["counter"] = {
"topics": self.topic_model.get_user_all_topics_count(user_info["uid"]),
"replies": self.reply_model.get_user_all_replies_count(user_info["uid"]),
"favorites": self.favorite_model.get_user_favorite_count(user_info["uid"]),
}
tem... | bles["notifications"] = self.notification_model.get_user_all_notifications(user_info["uid"], current_page = page)
template_variables["active_page"] = "topic"
template_variables["gen_random"] = gen_random
# mark user unread notifications as read
self.notification_model.mark_user_unread_n... |
nkoech/trialscompendium | trialscompendium/search/api/urls.py | Python | mit | 252 | 0 | from django.conf.urls import url
from .views import (
| global_search_views,
)
# Global search URLs |
urlpatterns = [
url(
r'^$',
global_search_views['GlobalSearchListAPIView'].as_view(),
name='global_search_list'
),
]
|
nozuono/calibre-webserver | src/calibre/ebooks/oeb/polish/tests/main.py | Python | gpl-3.0 | 572 | 0.008741 | #!/usr/bin/env python
# vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' |
try:
import init_calibre # noqa
except ImportError:
pass
import os, unittest
def find_tests():
return unittest.defaultTestLoader.discover(os.path.dirname(os.path.abspath(__file__)), pattern='*.py')
if __name__ == '_ | _main__':
from calibre.db.tests.main import run_tests
run_tests(find_tests=find_tests)
|
faizan-barmawer/openstack_ironic | ironic/common/exception.py | Python | apache-2.0 | 12,909 | 0 | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# 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 ... | _("An unknown exception occ | urred.")
code = 500
headers = {}
safe = False
def __init__(self, message=None, **kwargs):
self.kwargs = kwargs
if 'code' not in self.kwargs:
try:
self.kwargs['code'] = self.code
except AttributeError:
pass
if not message:... |
nbro/ands | ands/algorithms/sorting/comparison/selection_sort.py | Python | mit | 1,231 | 0.000814 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# Meta-info
Author: Nelson Brochado
Created: 09/09/2015
Updated: 07/03/2018
# Description
Selection sorting is conceptually probably the simplest sorting algorithm.
This algorit | hm first finds the smallest element in the list and exchanges it
with the element in the first position, then find the second smallest element
and exchange it with the element in the second position, and continues in this
way until the entire list is sorted.
# References
- http://www.studytonight.com/data-structures/... | ["selection_sort"]
def selection_sort(ls: list) -> None:
"""Selection-sort in-place sorting algorithm.
Time complexity
+-------+----------+----------+
| Best | Average | Worst |
+-------+----------+----------+
| O(n²) | O(n²) | O(n²) |
+-------+----------+----------+
Spac... |
dlancer/django-crispy-contact-form | contact_form/translation.py | Python | bsd-3-clause | 308 | 0 | from modeltranslation.tran | slator import translator, TranslationOptions
from contact_form.models import Subject
class SubjectTranslationOptions(TranslationOptions):
fields = ('title', 'des | cription')
fallback_languages = {'default': ('en',)}
translator.register(Subject, SubjectTranslationOptions)
|
drongo-framework/drongo | tests/test_response.py | Python | mit | 978 | 0 | from drongo.response import Response
import unittest
class TestResponse(unittest.TestCase):
def test_response(self):
resp = Response()
def start_response(status, headers):
pass # TODO: Add more checks here
resp.set_cookie('hello', 'world', domain='localhost', secure=True)
... | es), b'hello world!')
def test_generated_response(self):
resp = Response()
def start_re | sponse(status, headers):
pass
def content():
yield b'hello world!'
resp.set_content(content(), 12)
res = resp.bake(start_response)
self.assertEqual(b''.join(list(res)), b'hello world!')
def test_redirect(self):
resp = Response()
resp.set_red... |
moddabiri/simple_talking_robot | controllers/head/speech_control.py | Python | mit | 9,262 | 0.006156 | __author__ = "Mohammad Dabiri"
__copyright__ = "Free to use, copy and modify"
__credits__ = ["Mohammad Dabiri"]
__license__ = "MIT Licence"
__version__ = "0.0.1"
__maintainer__ = "Mohammad Dabiri"
__email__ = "moddabiri@yahoo.com"
import tts
import stt
import time
from random import Random
from pythonds.graphs import... | hrase = phrase.replace(exp, action_point)
elif isinstance(action_point, list):
phrase = None
processed = processed + action_point
else:
raise ValueError("The variable was mapped to an unac... | tion point. Possible implementation bug. Only string and list of strings are acceptable.")
if phrase:
processed.append(phrase)
if len(processed) > 0:
tts.say(processed, env_state.human_name, is_online=env_state.internet)
return 'NULL... |
JetStarBlues/Nand-2-Tetris | Components/_4__flipFlops_performance.py | Python | mit | 734 | 0.061308 | '''----------------------------- Imports -----------------------------'''
# Built ins
from random import random
# Hack computer
from ._x__components import *
'''--------------------------- Flip flops ---------------------------'''
class DFlipFlop():
def __init__( self ):
# Assign random start values. Truer t... | clear_, set_, d ):
if clear_:
self.clear()
return
elif set_:
self.set()
return
else:
self.q = d
self._q = not_( self | .q )
def read( self ):
return self.q
def clear( self ):
self.q = 0
self._q = 1
def set( self ):
self.q = 1
self._q = 0
|
andete/madparts | gui/defaultsettings.py | Python | gpl-3.0 | 1,561 | 0.006406 | # (c) 2013-2015 Joost Yervante Damad <joost@damad.be>
# License: GPL
# default values for settings
color_schemes = {}
color_schemes['default'] = {
'background': (0.0, 0.0, 0.0, 1.0),
'grid': (0.5, 0.5, 0.5, 1.0),
'axes': (1.0, 0.0, 0.0, 1.0),
'name': (1.0, 1.0, 1.0, 1.0),
'value': (1.0, 1.0, 1.0, 1.0),... | 5),
'user1': (0.3, 0.6, 0.0, 0.7),
'user2': (0.3, 0.0, 0.6, 0.7)
}
def _inverse(color_scheme):
re = {}
for (k,(r,g,b,a)) in color_scheme.items():
re[k] = (1.0-r, 1.0-g, 1.0-b, a)
return re
color_schemes['inverse'] = _inverse(color_schemes['default'])
default_settings = {
'gl/dx': '200',
'gl/dy': ... | isplaydocu': 'True',
'gui/displayrestrict': 'False',
'gui/displaystop': 'False',
'gui/displaykeepout': 'False',
'gui/autocompile': 'True',
}
|
fbradyirl/home-assistant | tests/components/ps4/test_media_player.py | Python | apache-2.0 | 17,932 | 0.001004 | """Tests for the PS4 media player platform."""
from unittest.mock import MagicMock, patch
from pyps4_homeassistant.credential import get_ddp_message
from homeassistant.components import ps4
from homeassistant.components.media_player.const import (
ATTR_INPUT_SOURCE,
ATTR_INPUT_SOURCE_LIST,
ATTR_MEDIA_CONT... | E_ART_URL = "https://somecoverurl"
MOCK_GAMES_DATA = {
ATTR_LOCKED: False,
ATTR_MEDIA_CONTENT_TYPE: MEDIA_TYPE_GAME,
ATTR_MEDIA_IMAGE_URL: MOCK_TITLE_ART_URL,
ATTR_MEDIA_TITLE: MOCK_TITLE_NAME,
}
MOCK_GAMES_DATA_LOCKED = {
ATTR_LOCKED: True,
ATTR_MEDIA_CONTENT_TYPE: MEDIA_TYPE_GAME,
ATTR_M... | E: MOCK_TITLE_NAME,
}
MOCK_STATUS_PLAYING = {
"host-type": MOCK_HOST_TYPE,
"host-ip": MOCK_HOST,
"host-request-port": MOCK_TCP_PORT,
"host-id": MOCK_HOST_ID,
"host-name": MOCK_HOST_NAME,
"running-app-titleid": MOCK_TITLE_ID,
"running-app-name": MOCK_TITLE_NAME,
"status": MOCK_STATUS_ON,... |
enthought/etsproxy | enthought/block_canvas/app/segy_reader/utils.py | Python | bsd-3-clause | 102 | 0 | # proxy module
from __future__ import absolute_import
from blockcan | vas.app.segy_reader.utils import * | |
all-of-us/raw-data-repository | rdr_service/lib_fhir/fhirclient_1_0_6/models/devicecomponent_tests.py | Python | bsd-3-clause | 4,893 | 0.007153 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 1.0.2.7202 on 2016-06-23.
# 2016, SMART Health IT.
import io
import json
import os
import unittest
from . import devicecomponent
from .fhirdate import FHIRDate
class DeviceComponentTests(unittest.TestCase):
def instantiate_from(self, filen... | .ietf.org/html/bcp47")
self.assertEqual(inst.lastSystemChange.date, FHIRDate("2014-10-07T14:45:00Z").date)
self.assertEqual(inst.lastSystemChange.as_json(), "2014-10-07T14:45:00Z")
self.assertEqual(inst.operationalStatus[0].coding[0].code, "0")
self.assertEqual(inst.operationalStatus[0].... | al(inst.text.status, "generated")
self.assertEqual(inst.type.coding[0].code, "2000")
self.assertEqual(inst.type.coding[0].display, "MDC_DEV_ANALY_SAT_O2_MDS")
self.assertEqual(inst.type.coding[0].system, "urn:iso:std:iso:11073:10101")
|
django/djangoproject.com | djangoproject/test_registration.py | Python | bsd-3-clause | 1,304 | 0.003834 | from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.core import mail
from django.test import TestCase
from registration.models import RegistrationProfile
class TestRegistration(TestCase):
def test_activation_email(self):
site = Site.objects.get()
us... | n-key')
profile.send_activation_email(site)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox.pop()
self.assertEqual(message.subject, 'Activate your djangoproject.com account')
self.assertEqual(
message.body,
"\nSomeone, hopefully you, signed up ... | link below "
"or copy and paste it into your web browser's address bar:\n\n"
"https://www.djangoproject.com/accounts/activate/activation-key/\n\n"
"If you didn't request this, you don't need to do anything; you "
"won't receive any more email from us, and the account will... |
werdeil/pibooth | pibooth/controls/light.py | Python | mit | 2,328 | 0 | # -*- coding: utf-8 -*-
import threading
from pibooth.controls import GPIO
class BlinkingThread(threading.Thr | ead):
"""Thread which manage blinking LEDs synchronously.
"""
def __init__(self):
threading.Thread.__init__(self)
self.d | aemon = True
self._leds = []
self._tick = 0.3
self._lock = threading.Lock()
self._stop_event = threading.Event()
self.start()
def register(self, led):
"""Add a new LED to manage.
"""
with self._lock:
if led not in self._leds:
... |
Sage-Bionetworks/DREAM_Alzheimers_Challenge_Scoring | test.py | Python | apache-2.0 | 6,996 | 0.007004 | import glob
import os
import synapseclient
import uuid
from synapseclient import Project, File, Folder, Evaluation
from challenge import *
import challenge
from collections import OrderedDict
syn = synapseclient.Synapse()
syn.login()
CLEANUP = True
## module scope variable to hold project
project = None
evaluation =... | valuation.id,
q3_evaluation_id=q3_evaluation.id))
wiki = syn.store(wiki)
finally:
if CLEANUP:
if evaluation:
syn.delete(evaluation)
if project:
| syn.delete(project)
else:
print "don't clean up"
|
charris/numpy | tools/swig/test/testFarray.py | Python | bsd-3-clause | 5,103 | 0.002548 | #!/usr/bin/env python3
# System imports
from distutils.util import get_platform
import os
impor | t sys
import unittest
# Import NumPy
import numpy as np
major, minor = [ int(d) for d | in np.__version__.split(".")[:2] ]
if major == 0: BadListError = TypeError
else: BadListError = ValueError
# Add the distutils-generated build directory to the python search path and then
# import the extension module
libDir = "lib.{}-{}.{}".format(get_platform(), *sys.version_info[:2])
sys.path.insert(0, os... |
SKA-ScienceDataProcessor/FastImaging-Python | src/fastimgproto/bindings/__init__.py | Python | apache-2.0 | 200 | 0.005 | " | ""
Define the Python wrapper-functions which provide an interface to the C++
implementations.
"""
from .present import CPP_BINDINGS_PRESENT
from .imager import cpp_image_visibilities, Cpp | KernelFuncs |
Ecpy/ecpy_pulses | exopy_pulses/pulses/sequences/template_sequence.py | Python | bsd-3-clause | 7,795 | 0 | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2015-2018 by ExopyPulses Authors, see AUTHORS for more details.
#
# Distributed under the terms of the BSD license.
#
# The full license is in the file LICENCE, distributed with this software.
# ---------... | quence())
return seq
@classmethod
def build_from_config(cls, config, dependencies):
""" Create a new instance using the provided infos for initialisation.
Overridden here to allow context creation.
Parameters
----------
config : dict(str)
| Dictionary holding the new values to give to the members in string
format, or dictionnary like for instance with prefs.
dependencies : dict
Dictionary holding the necessary classes needed when rebuilding.
Returns
-------
sequence : TemplateSequence
... |
2bithacker/ansible-modules | inventory/digitalocean.py | Python | bsd-3-clause | 2,629 | 0.00038 | #!/usr/bin/env python2.7
import urllib2
import json
import ConfigParser
import argparse
import os
import collections
class DigitalOceanInventory(object):
def __init__(self):
self.conf = ConfigParser.SafeConfigParser()
self.args = None
self.api_token = None
def read_config(self):
... | conf
def parse_args(self):
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--list', action='store_true',
help='List all droplets')
group.add_argument('--host', help='Get information on sing... | ()
if self.args.token:
self.api_token = self.args.token
def do_request(self, path):
req = urllib2.Request(url='https://api.digitalocean.com%s' % (path))
req.add_header('Content-type', 'application/json')
req.add_header('Authorization', 'Bearer ' + self.api_token)
... |
jrleeman/MetPy | metpy/io/_nexrad_msgs/parse_spec.py | Python | bsd-3-clause | 6,685 | 0.001496 | #!/usr/bin/env python
# Copyright (c) 2015 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Parse specification extracted from NEXRAD ICD PDFs and generate Python code."""
from __future__ import print_function
import warnings
def register_proces... | units)
info.append({'name': var_name, 'desc': full_desc, 'fmt': fmt})
if (ignored_item(info[-1]) and var_name != 'SPARE'
and 'SPARE' not in full_desc):
warnings.warn('{} has type {}. Setting as SPARE'.format(var_name, typ))
exce... | info
types = [('Real*4', ('f', 4)), ('Integer*4', ('L', 4)), ('SInteger*4', ('l', 4)),
('Integer*2', ('H', 2)),
('', lambda s: ('{size}x', s)), ('N/A', lambda s: ('{size}x', s)),
(lambda t: t.startswith('String'), lambda s: ('{size}s', s))]
def fix_type(typ, size, additional=None):
""... |
andrevmatos/Librix-ThinClient | src/ui/common/__init__.py | Python | gpl-2.0 | 828 | 0.006039 | #!/usr/bin/env python3
#
#
#
# This file is part of librix-thinclient.
#
# librix-thinclient is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later ver... |
'ProfileSumm | ary',
'LeftMenuItem',
'Ui_tabItemWidget',
'Ui_profileSummary',
]
|
samupl/simpleERP | apps/contacts/app_config.py | Python | mit | 189 | 0.005291 | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
cl | ass ContactsAppConfig(AppConfig):
name = ' | apps.contacts'
verbose_name = _('Contacts')
|
CroissanceCommune/autonomie | autonomie/alembic/versions/1_7_active_tag_2b29f533fdfc.py | Python | gpl-3.0 | 830 | 0.010843 | """1.7 : Add ac | tive tags to expense types and tva
Revision ID: 2b29f533fdfc
Revises: 4ce6b915de98
Create Date: 2013-09-03 16:05:22.824684
"""
# revision identifiers, used by Alembic.
revision = '2b29f533fdfc'
down_revision = '4ce6b915de98'
from alembic import op
import sqlalchemy as sa
def u | pgrade():
try:
col = sa.Column('active',
sa.Boolean(),
default=True,
server_default=sa.sql.expression.true())
op.add_column("expense_type", col)
except:
print "The column already exists"
col = sa.Column('active',
sa.Boolean(... |
cattleprod/samsung-kernel-gt-i9100 | external/webkit/WebKitTools/Scripts/webkitpy/patchcollection.py | Python | gpl-2.0 | 2,853 | 0.002103 | #!/usr/bin/env python
# Copyright (c) 2009, Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this lis... | id] = status
return status
def next(self):
patch_ids = self._delegate.fetch_potential_patch_ids()
| for patch_id in patch_ids:
status = self._cached_status(patch_id)
if not status or not self._delegate.is_terminal_status(status):
return patch_id
|
boldfield/s3-encryption | s3_encryption/client.py | Python | bsd-3-clause | 2,351 | 0.001276 | import boto3
from s3_encryption import crypto
from s3_encryption.handler import EncryptionHandler, DecryptionHandler
from s3_encryption.exceptions import ArgumentError
from s3_encryption.key_provider import DefaultKeyProvider
class S3EncryptionClient(object):
def __init__(self, encryption_key=None, **kwargs):
... | t)
return context['raw_body | ']
def extract_key_provider(self, **kwargs):
if 'encryption_key' not in kwargs:
msg = 's3_encryption currently only supports '\
'encryption with client provided keys.'
raise ArgumentError(msg)
return DefaultKeyProvider(kwargs['encryption_key'], **kwargs)
... |
dNG-git/pas_http_table | src/dNG/data/xhtml/table/abstract_row.py | Python | mpl-2.0 | 1,804 | 0.002772 | # -*- coding: utf-8 -*-
"""
direct PAS
Python Application Services
----- | ---------------------------------------------------------------- | -------
(C) direct Netware Group - All rights reserved
https://www.direct-netware.de/redirect?pas;http;table
This Source Code Form is subject to the terms of the Mozilla Public License,
v. 2.0. If a copy of the MPL was not distributed with this file, You can
obtain one at http://mozilla.org/MPL/2.0/.
-----------------... |
nikpap/inspire-next | inspirehep/modules/forms/validators/simple_fields.py | Python | gpl-2.0 | 5,657 | 0.000177 | # -*- coding: utf-8 -*-
#
# This file is part of INSPIRE.
# Copyright (C) 2014, 2015 CERN.
#
# INSPIRE is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any... | imilar to '141 | 3304540', '1-4133-0454-0', '978-1413304541' or \
'978-1-4133-0454-1'."
if field.data and not is_isbn(field.data):
raise StopValidation(message)
def does_exist_in_inspirehep(query, collection=None):
"""Check if there exist an item in the db which satisfies query.
:param query: htt... |
zofuthan/edx-platform | lms/djangoapps/licenses/tests.py | Python | agpl-3.0 | 9,416 | 0.002443 | """Tests for License package"""
import logging
import json
from uuid import uuid4
from random import shuffle
from tempfile import NamedTemporaryFile
import factory
from factory.django import DjangoModelFactory
from django.test import TestCase
from django.test.client import Client
from django.core.management import ca... | UserLicenseFactory(software=self.software)
response = self.client.post(reverse('user_software_license'),
{'so | ftware': SOFTWARE_1, 'generate': 'true'},
HTTP_X_REQUESTED_WITH='XMLHttpRequest',
HTTP_REFERER='/courses/{0}/some_page'.format(COURSE_1))
self.assertEqual(200, response.status_code)
json_returned = json.loads(response.content)
... |
ddrmanxbxfr/servo | python/servo/bootstrap_commands.py | Python | mpl-2.0 | 14,058 | 0.002916 | # Copyright 2013 The Servo Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution.
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
#... | install_dir = path.join(self.context.sharedir, "rust", version)
if not self.config["build"]["llvm-assertions"]:
install_dir += "-alt"
if not force an | d path.exists(path.join(rust_dir, "rustc", "bin", "rustc" + BIN_SUFFIX)):
print("Rust compiler already downloaded.", end=" ")
print("Use |bootstrap-rust --force| to download again.")
else:
if path.isdir(rust_dir):
shutil.rmtree(rust_dir)
os.makedir... |
cxxgtxy/tensorflow | tensorflow/python/keras/layers/preprocessing/hashing.py | Python | apache-2.0 | 11,280 | 0.004255 | # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | by default,
| which provides a consistent hashed output across different platforms and is
stable across invocations, regardless of device and context, by mixing the
input bits thoroughly.
If you want to obfuscate the hashed output, you can also pass a random `salt`
argument in the constructor. In that case, the layer will u... |
bd808/striker | striker/goals/migrations/0001_squashed.py | Python | gpl-3.0 | 1,193 | 0.003353 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
from django.utils import timezone
class Migration(migrations.Migration):
replaces = [('goals', '0001_initial'), ('goals', '0002_auto_20160531_1721')]
dependencies = [
... | toField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('goal', models.SmallIntegerField()),
('completedDate', models.DateTimeField(default=time | zone.now, editable=False, blank=True)),
('user', models.ForeignKey(related_name='milestones', to=settings.AUTH_USER_MODEL)),
],
),
migrations.AlterUniqueTogether(
name='milestone',
unique_together=set([('user', 'goal')]),
),
migrations.... |
stewartsmith/bzr | bzrlib/url_policy_open.py | Python | gpl-2.0 | 10,733 | 0.00028 | # Copyright (C) 2011 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in ... | mport Branch
from bzrlib.controldir import (
ControlDir,
)
class BadUrl(errors.BzrError):
_fmt = "Tried to access a branch from bad URL %(url)s."
class BranchReferenceForbidden(errors.BzrError):
_fmt = ("Trying to mirror a branch reference and the branch type "
"does not allow referenc... | le.
A URL may point to a branch reference or it may point to a stacked branch.
In either case, it's possible for there to be a cycle in these references,
and this exception is raised when we detect such a cycle.
"""
_fmt = "Encountered a branch cycle"""
class BranchOpenPolicy(object):
"""Pol... |
Captain-Coder/tribler | Tribler/community/popularity/repository.py | Python | lgpl-3.0 | 8,030 | 0.003861 | from __future__ import absolute_import
import logging
import time
from collections import deque
import six
from Tribler.community.popularity.payload import SearchResponseItemPayload, ChannelItemPayload
try:
long # pylint: disable=long-builtin
except NameError:
long = int # pylint: disable=redefined-... | self.queue = None
def add_content(self, content_type, content):
if self.queue is not None:
self.queue.append((content_type, content))
def count_content(self):
return len(self.queue) if self.queue else 0
def pop_content(self):
return self.queue.pop() if self.queue el... | self.torrent_db.getRecentlyCheckedTorrents(limit)
def update_torrent_health(self, torrent_health_payload, peer_trust=0):
def update_torrent(db_handler, health_payload):
db_handler.updateTorrent(infohash, notify=False, num_seeders=health_payload.num_seeders,
... |
Mikescher/Project-Euler_Befunge | compiled/Python2/Euler_Problem-075.py | Python | mit | 4,387 | 0.05881 | #!/usr/bin/env python2
# transpiled with BefunCompile v1.3.0 (c) 2017
import sys
import zlib, base64
_g = ("Ah+LCAAAAAAABACT7+ZgAAEWhre3/LNvG0iwP1i/yPTlUbXVqdvzlJoi+a3Lj8v6RJl1JZacmaK7/Otuf07ZXEnrN/zZZ+cdV4iexrfrz59Tftsevr0tcO7wz0oLK678"
+ "PLvaHVX/Lff8K6otFRbb/W/369X9D7+oMAiXlZWJlbEzGIQaM4yCUTAKRsEoGPzgnzcjw4w9ejJ3... | r(3,0),gr(2,0)),(td(gr(3,0),gr(2,0)))+3,0)
return 1
def _1():
return (2)if(sp()! | =0)else(3)
def _2():
sa(sr());
sa(0)
v0=sp()
v1=sp()
sa(v0)
sa(v1)
sa(tm(sr(),gr(2,0)))
v0=sp()
v1=sp()
sa(v0)
sa(v1)
sa(td(sp(),gr(2,0)))
sa(sp()+3)
v0=sp()
v1=sp()
gw(v1,v0,sp())
sa(sr()-1)
v0=sp()
v1=sp()
sa(v0)
sa(v1)
return 1... |
googleads/google-ads-python | google/ads/googleads/v10/resources/types/recommendation.py | Python | apache-2.0 | 31,171 | 0.001636 | # -*- coding: utf-8 -*-
# Copyright 2020 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | resources.typ | es.Recommendation.OptimizeAdRotationRecommendation):
Output only. The Optimize Ad Rotation
recommendation.
This field is a member of `oneof`_ ``recommendation``.
callout_extension_recommendation (google.ads.googleads.v10.resources.types.Recommendation.CalloutExtensionRecomme... |
groboclown/py-book-selfpub | src/selfpub/text.py | Python | apache-2.0 | 10,783 | 0.000927 | """
Generic interchange document structures.
"""
STYLE_TYPE_INT = 'int'
STYLE | _TYPE_FLOAT = 'float'
STYLE_TYPE_CDATA = 'cdata'
STYLE_TYPE_BOOLEAN = 'bo | olean'
STYLE_TYPES = (
STYLE_TYPE_INT,
STYLE_TYPE_FLOAT,
STYLE_TYPE_CDATA,
STYLE_TYPE_BOOLEAN
)
class Style(object):
def __init__(self, types):
object.__init__(self)
self.name = None
self.source = None
self.__settings = {}
self.__types = types
for ke... |
guanhuamai/DPM | PythonSource/DecisionMakerLib/ApollingSelect.py | Python | mit | 9,439 | 0.003602 | import sys
sys.path.append("..")
import math
import heapq
import numpy as np
import copy
from scipy import optimize
global nodes, edges, M, BaseMatrix
global left_edges, selected_edges, last_score, Hessian, record_inv_matrix, record_current_matrix
global crowdgauss_estimation_edges
global num_workers
normal_pdf = la... | trix.append(inv_curr_matrix)
if len(record_current_matrix) >= 100:
record_current_matrix = record_current_matrix[len(record_current_matrix) - 100:]
else:
inv_curr_matrix = record_inv_matrix[-1]
factor1 = np.trace(np.dot(inv_curr_matrix, past_matrix))
factor2_1 = np.transpose(... | ent_matrix[-1]
except IndexError:
pass
factor2_3 = curr_s - past_s
factor2_4 = np.dot(factor2_1, factor2_2)
factor2 = np.dot(factor2_4, factor2_3)
x1 = math.fabs(np.linalg.det(past_matrix))
x2 = math.fabs(np.linalg.det(curr_matrix) + min_value)
factor3 = math.log10(x1 / x... |
bougui505/SOM | test/generatedatasets.py | Python | gpl-2.0 | 685 | 0.00438 | #!/usr/bin/env python
# -*- coding: UTF8 -*-
"""
author: Guillaume Bouvier
email: guillaume.bouvier@ens-cachan.org
creation date: 2014 04 03
license: GNU GPL
Please feel free to use and m | odify this, but keep the above information.
Thanks!
"""
import numpy
# generate datasets
def dataset_fixed_cov():
'''Generate 2 Gaussians samples with the same covariance matrix'''
n, dim = 2000, 2
| numpy.random.seed(0)
C = numpy.array([[0., -0.23], [0.83, .23]])
X = numpy.r_[numpy.dot(numpy.random.randn(n, dim), C),
numpy.dot(numpy.random.randn(n, dim), C) + numpy.array([5, 5])]
y = numpy.hstack((numpy.zeros(n), numpy.ones(n)))
return X, y
|
incuna/django-avatar | setup.py | Python | bsd-3-clause | 5,542 | 0.002887 | from setuptools import setup, find_packages
version = '2.0a2-incuna'
LONG_DESCRIPTION = """
Using django-avatar
===================
Basics
------
To integrate ``django-avatar`` with your site, there are relatively few things
that are required. A minimal integration can work like this:
1. List this application i... | ed, the user will be redirected | to the specified
URL after form submission. Otherwise the user will be redirected to the URL
specified in the ``next`` parameter in ``request.POST``. If ``request.POST``
has no ``next`` parameter, ``request.GET`` will be searched. If ``request.GET``
has no ``next`` parameter, the ``HTTP_REFERER`` header will be ins... |
VirtualWatershed/vw-py | vwpy/test/test_netcdf.py | Python | bsd-2-clause | 16,089 | 0.000249 | """Tests of NetCDF functionality including enforcement of CF standards,
metadata gleaning, CF-Station data conversion, and maybe more, like opendap.
"""
import os
import unittest
from netCDF4 import Dataset
from numpy import ravel, shape, sum
from ..netcdf import utm2latlon, ncgen_from_template
# include tests f... | irectory structure"
nc = g | enerate_standard_nc(self.full_nc_base_dir, self.full_nc_out)
nc = Dataset(self.full_nc_out, mode='r')
new_ipw_basedir = os.path.join(self.full_nc_base_dir, 'ipw_from_nc')
nc_to_standard_ipw(nc, new_ipw_basedir)
new_ipw_dirlist = os.listdir(new_ipw_basedir)
assert len(new_ipw... |
alvations/pywsd | test_wsd.py | Python | mit | 4,733 | 0.006972 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Python Word Sense Disambiguation (pyWSD): WSD function tests
#
# Copyright (C) 2014-2015 alvations
# URL:
# For license information, see LICENSE.md
bank_sents = ['I went to the bank to deposit my money',
'The river bank was full of dead fishes']
plant_sents = ['The w... | STING baseline ===========\n")
from pywsd.baseline import random_sense, first_sense
from pywsd.baseline import max_lemma_count as most_frequent_sense
print("#TESTING random_sense() ...")
print("Context:", bank_sents[0])
answer = random_sense('bank')
print("Sense:", answer)
definition = answer.defini | tion()
print("Definition:", definition)
print()
print("#TESTING first_sense() ...")
print("Context:", bank_sents[0])
answer = first_sense('bank')
print("Sense:", answer)
definition = answer.definition()
print("Definition:", definition)
print()
print("#TESTING most_frequent_sense() ...")
print("Context:", bank_sents[0... |
ricksladkey/generateDS | tests/out2_sup.py | Python | mit | 153,816 | 0.003556 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated by generateDS.py.
#
import sys
import getopt
import re as re_
import base64
import datetime as datetime_
etree_ = None
Verbose_import_ = False
(
XMLParser_import_none, XMLParser_import_lxml,
XMLParser_import_elementtree
) = range(3)
XMLParser_impor... | _name=''):
return '%s' % input_data
def gds_validate_float_list(self, input_data, node, input_name=''):
values = input_data.split()
for value in values:
try:
float(value)
exc | ept (TypeError, ValueError):
raise_parse_error(node, 'Requires sequence of floats')
return input_data
def gds_format_double(self, input_data, input_name=''):
return '%e' % input_data
def gds_validate_double(self, input_data, node, input_name=''):
r... |
seanfisk/cpg-islands | cpg_islands/qt/views.py | Python | gpl-3.0 | 21,504 | 0.000186 | # -*- coding: utf-8 -*-
# The encoding declaration is necessary to tell Python that we are
# using Unicode in this file. See
# <http://www.python.org/dev/peps/pep-0263/>.
""":mod:`cpg_islands.views.qt` --- Views based on Q toolkit
"""
from xml.sax import saxutils
from PySide import QtGui, QtCore
from cpg_islands im... | o_validator.setBottom(0)
self.min_obs_exp_cpg_ratio_input.setValidator(
self.min_obs_exp_ratio_validator)
self.form_layout.addRow(u'&Observed/Expected CpG Ratio | ≥',
self.min_obs_exp_cpg_ratio_input)
self.algorithms_combo_box = QtGui.QComboBox(self)
self.form_layout.addRow('&Algorithm', self.algorithms_combo_box)
self.top_layout.addLayout(self.form_layout)
self.seq_input_label = QtGui.QLabel('S&equence')
... |
willrp/willbuyer | backend/tests/functional/api/cart/test_order.py | Python | mit | 1,226 | 0 | import requests
from backend.util.response.error import ErrorSchema
def test_order(domain_url, auth_session, es_create, willorders_ws_db_session):
prod_list = es_create("products", 2)
item_id = prod_list[0].meta["id"]
item_id2 = prod_list[1].meta["id"]
auth_session.post(
domain_url + "/api/c... | kie = r | esponse.cookies.get("session")
response = auth_session.put(
domain_url + "/api/cart/order"
)
data = response.json()
ErrorSchema().load(data)
assert response.status_code == 400
assert cookie == response.cookies.get("session")
def test_order_unauthorized(domain_url):
response = req... |
lnielsen/zenodo | zenodo/modules/fixtures/cli.py | Python | gpl-2.0 | 4,703 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2015, 2016 CERN.
#
# Zenodo 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 2 of the
# License, or (at your option) any l... | ists=False, dir_okay=False))
def matchlicenses_cli(legacy_source, od_source, destination):
"""Match legacy Zenodo licenses with OpenDefinition.org licenses."""
matchlicenses(legacy_source, od_source, destination)
@fixtures.command('loadcommunities')
@click.ar | gument('owner_email')
@with_appcontext
def loadcommunities_cli(owner_email):
"""Load Zenodo communities."""
try:
loadcommunities(owner_email)
except NoResultFound:
click.echo("Error: Provided owner email does not exist.")
|
scottstephens/boo | lib/antlr-2.7.5/examples/python/lexRewrite/rewrite.py | Python | bsd-3-clause | 355 | 0.047887 | ### main - create and run lexer from stdin
if __name__ == '__main__' :
import sys
import antlr
import rewrite_l
### create lexer - shall read from stdin
L = rewrite_l.Lexer()
try:
L. | mSTART(1);
token = | L.getTokenObject()
except antlr.TokenStreamException, e:
print "error: exception caught while lexing: "
### end of main
|
huyphan/pyyawhois | test/record/parser/test_response_whois_nic_bj_status_registered.py | Python | mit | 3,633 | 0.003578 |
# This file is autogenerated. Do not edit it manually.
# If you want change the content of this file, edit
#
# spec/fixtures/responses/whois.nic.bj/status_registered
#
# and regenerate the tests with the following script
#
# $ scripts/generate_tests.py
#
from nose.tools import *
from dateutil.parser import parse ... | q_(self.record.registrant_contacts[0].organization, None)
eq_(self.record.registrant_contacts[0].address, None)
eq_(self.record.registrant_contacts[0].city, None)
eq_(self.record.registrant_contacts[0].zip, None)
eq_(self.record.registrant_contacts[0].state, None)
eq_(self.record... | eq_(self.record.registrant_contacts[0].email, None)
def test_technical_contacts(self):
assert_raises(yawhois.exceptions.AttributeNotSupported, self.record.technical_contacts)
def test_updated_on(self):
eq_(self.record.updated_on.__class__.__name__, 'datetime')
eq_(self.record.updated_o... |
pmghalvorsen/gramps_branch | gramps/gen/filters/rules/person/_havealtfamilies.py | Python | gpl-2.0 | 2,182 | 0.007333 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2002-2006 Donald N. Allingham
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at you... | m; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
#-------------------------------------------------------------------------
#
# Standard Python modules
#
#-------------------------------------------------------------------------
from ....const impo... | ---------------------------------------------------
#
# GRAMPS modules
#
#-------------------------------------------------------------------------
from .. import Rule
from ....lib.childreftype import ChildRefType
#-------------------------------------------------------------------------
# "People who were adopted"
#-... |
eroicaleo/ThePythonStandardLibraryByExample | ch06TheFileSystem/linecache_test.py | Python | mit | 1,655 | 0.001813 | #!/usr/bin/env python3
import os
import linecache
import tempfile
lorem = '''Lorem ipsum dolor sit amet, consectetuer
adipiscing elit. Vivamus eget elit. In posuere mi non
risus. Mauris id quam posuere lectus sollicitudin
varius. Praesent at mi. Nunc eu velit. Sed augue massa,
fermentum id, nonummy a, nonummy sit ame... | '
def makefile():
fd, temp_file_name = tempfile.mkstemp()
os.close(fd)
fd = open(temp_file_name, 'wt')
try:
fd.write(lorem)
finally:
fd.close()
return temp_file_name
def cleanup(filename):
os.unlink(filename)
filename = makefile()
print('SOURCE:')
print | ('%r' % (lorem.split('\n')[4]))
print()
print('CACHE:')
print('%r' % linecache.getline(filename, 5))
print()
print('BLANK: %r' % linecache.getline(filename, 8))
print()
not_there = linecache.getline(filename, 500)
print('NOT THERE: %r includes %d characters' % (not_there, len(not_there)))
module_line = linecache.getl... |
EsriOceans/btm | legacy/10.0/scripts_ags10/structure_classification.py | Python | mpl-2.0 | 5,717 | 0.008046 | # structure_classification.py
# Description: The Benthic Terrain Modeler (BTM) functions as a toolbox within ArcMap, and relies
# on a methodology to analyze benthic terrain from input multibeam bathymetry in ESRI's
# GRID (raster) format. The BTM toolbox contains a set of tools that allow ... | Raster) < float(FineCreDiv)), 5, # Broad depression with an open bottom
Con((Raster(BroadBPIRaster) > f | loat(BroadDepDiv)) & (Raster(FineBPIRaster) > float(FineDepDiv)) & (Raster(FineBPIRaster) < float(FineCreDiv)) & (Raster(SlopeRaster) <= float(GentleSlopeDiv)) & (Raster(BathyRaster) < float(DepthDiv)), 6, # Broad flat
Con((Raster(BroadBPIRaster) > float(BroadDepDiv)) & (Raster(... |
allaboutbit/Cludcoin-project | contrib/bitrpc/bitrpc.py | Python | mit | 7,838 | 0.038147 | from jsonrpc import ServiceProxy
import sys
import string
# ===== BEGIN USER SETTINGS =====
# if you do not set these you will be prompted for a password for every command
rpcuser = ""
rpcpass = ""
# ====== END USER SETTINGS ======
if rpcpass == "":
access = ServiceProxy("http://127.0.0.1:6960")
else:
access = Ser... | -\n"
elif cmd == "getaddressesbyaccount":
try:
acct = raw_input("Enter an account name: ")
pr | int access.getaddressesbyaccount(acct)
except:
print "\n---An error occurred---\n"
elif cmd == "getbalance":
try:
acct = raw_input("Enter an account (optional): ")
mc = raw_input("Minimum confirmations (optional): ")
try:
print access.getbalance(acct, mc)
except:
print access.getbalance()
except:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.