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
google/loaner
loaner/web_app/backend/lib/bootstrap.py
Python
apache-2.0
13,356
0.007263
# Copyright 2018 Google 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 or a...
un_function_as_task(all_functions_list, function_name, kwargs=None): """Runs a specific function and its kwargs as an AppEngine task.
Args: all_functions_list: string list, A list with all function names that are registered as bootstrap functions on the Loaner app. function_name: string, A specific function that should be ran as a task. kwargs: dict, Optional kwargs to be passed to the function that will run. Returns: T...
symroe/remakery
manage.py
Python
mit
251
0
#!/usr/bin/env python impo
rt os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "remakery.settings") from django.core.management import execute_from_command_line execut
e_from_command_line(sys.argv)
simontakite/sysadmin
pythonscripts/pythonnetworkingcoookbook/chapter5/5_7_cgi_server.py
Python
gpl-2.0
877
0.009122
#!/usr/bin/env python # Python Network Programming Cookbook -- Chapter - 5 # This program requires Python 2.7 or any later version import os import cgi import argparse import BaseHTTPServer import CGIHTTPServ
er import cgitb cgitb.enable() ## enable CGI error reporting def web_server(port): server = BaseHTTPServer.HTTPServer handler = CGIHTTPServer.CGIHTTPRequestHandler #RequestsHandler server_address = ("", port
) handler.cgi_directories = ["/cgi-bin", ] httpd = server(server_address, handler) print "Starting web server with CGI support on port: %s ..." %port httpd.serve_forever() if __name__ == '__main__': parser = argparse.ArgumentParser(description='CGI Server Example') parser.add_argument('--port',...
rdo-management/heat
heat/tests/test_engine_api_utils.py
Python
apache-2.0
40,809
0
# # 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 # ...
self.stack = parser.Stack(utils.dummy_context(), 'test_stack', tmpl, stack_id=str(uuid.uuid4()))
def _dummy_event(self, event_id): resource = self.stack['generic1'] return event.Event(utils.dummy_context(), self.stack, 'CREATE', 'COMPLETE', 'state changed', 'z3455xyc-9f88-404d-a85b-5315293e67de', resource.properties...
snowch/movie-recommender-demo
web_app/app/main/forms.py
Python
apache-2.0
232
0.008621
from fla
sk.ext.wtf import Form from wtforms import StringField, SubmitField from wtforms.validators import Required class SearchForm(Form): search_string = StringField('Enter search string') submit = SubmitField('Submit')
StevenCHowell/zazmol
src/python/test_sasmol/test_system/test_intg_system_Atom_setResid.py
Python
gpl-3.0
1,510
0.027152
''' SASMOL: Copyright (C) 2011 Joseph E. Curtis, Ph.D. This program is free
software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public Licens...
2syume/telegram-majyobot
bot/cloud/__init__.py
Python
mit
318
0.003145
from google.oau
th2 import service_account from ..config import config cred_file = config.get("GoogleCloud", "CredentialPath") credentials = service_account.Credentials.from_service_account_file(cred_file) scoped_credentials = credentials.with_scopes([ 'https://www.googleapis.com/auth/devstorage.read_write' ]
)
shubhendusaurabh/referiend
homepage/admin.py
Python
mit
94
0
from django.c
ontrib import admin from homepage.
models import Rotw admin.site.register(Rotw)
michaelsmit/openparliament
parliament/urls.py
Python
agpl-3.0
2,327
0.006876
from django.conf.urls.defaults import * from django.conf import settings from django.contrib import admin admin.autodiscover() from parliament.core.sitemap import sitemaps from parliament.core.views import SiteNewsFeed urlpatterns = patterns('', (r'^search/', include('parliament.search.urls')), (r'^debates/',...
(r'', include(
'parliament.legacy_urls')), ) if settings.DEBUG: urlpatterns += patterns('', (r'^admin/', include(admin.site.urls)), (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) if getattr(settings, 'ADMIN_URL', False): urlpatterns += p...
nickgaya/python2
tests/integration/conftest.py
Python
mit
1,499
0
import contextlib import pytest from python2.client import Py2Error, Py2Object, Python2 def pytest_addoption(parser): parser.addoption("--python2", default="python2", help="Python 2 executable for client to use") @pytest.fixture def py2command(): return pytest.config.getoption("--pyth...
else: # For now, this function just support lists/tuples raise TypeError("Unsupported spec type: {}".format( type(spec).__name__)) @contextl
ib.contextmanager def py2_raises(self, p2e): with pytest.raises(Py2Error) as einfo: yield einfo assert self.py2.isinstance(einfo.value.exception, p2e) @pytest.fixture def helpers(py2): return Helpers(py2)
Hao-Liu/avocado
avocado/core/restclient/cli/app.py
Python
gpl-2.0
4,537
0
# 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 the hope that it will be useful, # bu...
n from ... import settings from ... import output from ... import exit_codes __all__ = ['App'] class App(object): """
Base class for CLI application """ def __init__(self): """ Initializes a new app instance. This class is intended both to be used by the stock client application and also to be reused by custom applications. If you want, say, to limit the amount of command line acti...
Agnishom/ascii-art-007
facebook.py
Python
mit
20,087
0.000747
#!/usr/bin/env python # # Copyright 2010 Facebook # # 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 la...
req.add_header('Content-Type', content_type) try: data = urllib2.urlopen(req).read() #For Python 3 use this: #except urllib2.HTTPEr
ror as e: except urllib2.HTTPError, e: data = e.read() # Facebook sends OAuth errors as 400, and urllib2 # throws an exception, we want a GraphAPIError try: response = _parse_json(data) # Raise an error if we got one, but don't not i...
Thielak/program-y
src/test/parser/template/graph/test_topic.py
Python
mit
663
0.012066
import unittest from programy.parser.template.nodes import * from test.parser.template.graph.test_graph_client import TemplateGraphTestClient class TemplateGraphTopicTests(
TemplateGraphTestClient):
def test_topicstar_index_as_attrib_full(self): template = ET.fromstring(""" <template> <topicstar index="1"></topicstar> </template> """) ast = self.parser.parse_template_expression(template) self.assertIsNotNone(ast) self.assertEqual(ast.children[0].to_string(), "TOP...
RallySoftware/eclipselink.runtime
jpa/eclipselink.jpars.test/resource/weblogic/wls_reset.py
Python
epl-1.0
904
0.00885
############################################################################ # Generic script applicable on any Operating Environments (Unix, Windows) # ScriptName : wls_reset.py # Properties : weblogic.properties # Author : Kevin Yuan #######################################################################...
======================================================================
=== connect('@WL_USR@','@WL_PWD@','t3://@WL_HOST@:@WL_PORT@') #=========================================================================== # Remove Data Sources using wlst on-line commonds #=========================================================================== edit() startEdit() delete('@DS_NAME@','JDBCSystemRe...
GeotrekCE/Geotrek-admin
geotrek/core/migrations/0026_auto_20211022_1104.py
Python
bsd-2-clause
426
0.002347
# Generated by Django 3.1.13 on 2021-10-22 11:04 from django.db import migrations, models import uuid class Mi
gration(migrations.Migration): dependencies = [ ('core', '0025_auto_20211022_1104'), ] operations = [ mi
grations.AlterField( model_name='path', name='uuid', field=models.UUIDField(default=uuid.uuid4, editable=False, unique=True), ), ]
alexandrul-ci/robotframework
src/robot/model/totalstatistics.py
Python
apache-2.0
2,319
0.000431
# Copyright 2008-2015 Nokia Networks # Copyright 2016- Robot Framework Foundation # # 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 ...
tests, 1
passed, 1 failed 2 tests total, 1 passed, 1 failed """ ctotal, cend, cpass, cfail = self._get_counts(self.critical) atotal, aend, apass, afail = self._get_counts(self.all) return ('%d critical test%s, %d passed, %d failed\n' '%d test%s total, %d passed, %d fai...
agniveshadhikari/edx-agea
agea/storage/__init__.py
Python
mit
22
0
from
storage
import *
technologiescollege/Blockly-rduino-communication
scripts/Lib/site-packages/serial/serialposix.py
Python
gpl-3.0
29,639
0.001147
#!/usr/bin/env python # # backend for serial IO for POSIX compatible systems, like Linux, OSX # # This file is part of pySerial. https://github.com/pyserial/pyserial # (C) 2001-2016 Chris Liechti <cliechti@gmx.net> # # SPDX-License-Identifier: BSD-3-Clause # # parts based on code from Grant B. Edwards <grante@visi....
t sys import termi
os import time import serial from serial.serialutil import SerialBase, SerialException, to_bytes, portNotOpenError, writeTimeoutError class PlatformSpecificBase(object): BAUDRATE_CONSTANTS = {} def _set_special_baudrate(self, baudrate): raise NotImplementedError('non-standard baudrates are not suppo...
machinalis/refo
setup.py
Python
bsd-3-clause
2,459
0.000407
#!/usr/bin/env python import sys def setup_python3(): # Taken from "distribute" setup.py from distutils.filelist import FileList from distutils import dir_util, file_util, util, log from os.path import join, exists tmp_src = join("build", "src") # Not covered by "setup.py clean --all", so exp...
config = dict( name="REfO", version="0.12", description="Regula
r expressions for objects", long_description=open('README.txt').read(), author="Rafael Carrascosa", author_email="rafacarrascosa@gmail.com", url="https://github.com/machinalis/refo", keywords=["regular expressions", "regexp", "re", "objects", "classes"], classifiers=[ "Programming Langua...
jkitchin/scopus
pybliometrics/scopus/serial_title.py
Python
mit
7,337
0.000273
from collections import namedtuple from pybliometrics.scopus.superclasses import Retrieval from pybliometrics.scopus.utils import check_parameter_value, get_link class SerialTitle(Retrieval): @property def aggregation_type(self): """The type of the source.""" return self._entry['prism:aggrega...
get('openaccess') @property def openaccessstartdate(self): """Starting availability date.""" return self._entry.get('openaccessStartDate') @property def openaccesstype(self): """Open Archive status (full or partial).""" return self._entry.get('openaccessType') @pro...
self._entry.get('openaccessArticle') @property def openarchivearticle(self): """Open Archive status (boolean).""" return self._entry.get('openArchiveArticle') @property def openaccesssponsorname(self): """The name of the Open Access sponsor.""" return self._entry.get('...
antipoachingmap/django-app
antipoaching/migrations/0004_event_timestamp.py
Python
mit
684
0.001462
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-05-29 13:41 f
rom __future__ import unicode_literals import datetime from django.db import migrations from django.utils.timezone import utc import django_unixdatetimefield.fields class Migration(migrations.Migration): dependencies = [ ('antipoaching', '0003_event_description'), ] operations = [ migra...
ld( model_name='event', name='timestamp', field=django_unixdatetimefield.fields.UnixDateTimeField(auto_now_add=True, default=datetime.datetime(2016, 5, 29, 13, 41, 51, 882425, tzinfo=utc)), preserve_default=False, ), ]
solvery/lang-features
python/use_lib/re.4.py
Python
gpl-2.0
204
0.009804
import re p = re.compile(r'(\w+) (\w+)(?P<sign>.*)', re.DOTALL)
print re.DOTALL print "p.pattern:", p.pattern print "p.flags:", p.flags print "p.groups:", p.groups print "p.groupindex
:", p.groupindex
Suor/django-cacheops
cacheops/transaction.py
Python
bsd-3-clause
4,124
0.00097
import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in...
f push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionSta
tes(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) ...
songfj/calibre
src/calibre/devices/usbms/driver.py
Python
gpl-3.0
23,329
0.003686
# -*- coding: utf-8 -*- __license__ = 'GPL v3' __copyright__ = '2009, John Schember <john at nachtimwald.com>' __docformat__ = 'restructuredtext en' ''' Generic USB Mass storage device driver. This is not a complete stand alone driver. It is intended to be subclassed with the relevant parts implemented for a partic...
(self._main_prefix, 'main') except (IOError, OSError) as e: raise IOError(_('Failed to access files in the main memory of'
' your device. You should contact the device' ' manufacturer for support. Common fixes are:' ' try a different USB cable/USB port on your computer.' ' If you device has a "Reset to factory defaults" type' ...
gkotton/vmware-nsx
vmware-nsx/neutron/plugins/vmware/dbexts/networkgw_db.py
Python
apache-2.0
24,912
0.00004
# Copyright 2013 VMware, 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 a...
efault
s(self, mapping_info): if not mapping_info.get('segmentation_type'): mapping_info['segmentation_type'] = 'flat' if not mapping_info.get('segmentation_id'): mapping_info['segmentation_id'] = 0 def _validate_network_mapping_info(self, network_mapping_info): self._set_m...
gtaylor/btmux_battlesnake
battlesnake/plugins/contrib/inventories/inbound_commands.py
Python
bsd-3-clause
16,609
0.001264
from twisted.internet.defer import inlineCallbacks from battlesnake.core.inbound_command_handling.base import BaseCommand, \ CommandError from battlesnake.core.inbound_command_handling.btargparse import \ BTMuxArgumentParser from battlesnake.core.inbound_command_handling.command_table import \ InboundComma...
er_blueprint_inventory, get_player_blueprint_inventory, \ reward_random_blueprint from battlesnake.plugins.contrib.in
ventories.cbill_api import \ mod_player_cbill_balance, get_player_cbill_balance from battlesnake.plugins.contrib.inventories.items_api import modify_player_item_inventory, \ get_player_item_inventory from battlesnake.plugins.contrib.inventories.defines import ITEM_TYPES, \ ITEM_TYPE_WEAPON, ITEM_TYPE_MELEE...
markfinger/assembla
assembla/settings.py
Python
mit
81
0.012346
API_VERSIO
N = 'v1' API_ROOT_PAT
H = 'https://api.assembla.com' MAX_PER_PAGE = 100
akaszynski/vtkInterface
pyvista/core/__init__.py
Python
mit
570
0.001754
"""Core routines.""" from .dataset import DataSet, DataObject from .composite import MultiBlock from .datasetattributes import DataSetAttributes fr
om .filters import (CompositeFilters, DataSetFilters, PolyDataFilters, UnstructuredGridFilters, UniformGridFilters) from .grid import Grid, RectilinearGrid, UniformGrid from .objects import Table, Texture from .pointset import PointGrid, PolyData, StructuredGrid, UnstructuredGrid, ExplicitStructur...
import pyvista_ndarray from .common_data import * from .imaging import *
VirusTotal/content
Packs/Vertica/Integrations/Vertica/Vertica.py
Python
mit
4,860
0.001646
import demistomock as demisto from CommonServerPython import * from datetime import datetime # fix for: https://github.com/vertica/vertica-python/issues/296 # (we need this for running in non-root where getpass will fail as uid doesn't map to a user name) import getpass class FixGetPass(): def __init__(self): ...
man_readable = 'No results found' # Get arguments from user query = demisto.args().get('q
uery') limit = int(demisto.args().get('limit', 50)) # Query and get raw response (list of ordered dicts) rows = query_request(query, cursor) # Parse response into context & content entries if rows: if limit: rows = rows[:limit] for i, row in enumerate(rows): ...
qtumproject/qtum
test/functional/p2p_feefilter.py
Python
mit
4,085
0.002693
#!/usr/bin/env python3 # Copyright (c) 2016-2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test processing of feefilter messages.""" from decimal import Decimal import time from test_framework...
d, so that we # we can sync the test on receipt (if node1's txs were relayed, they'd # be received by the time this node0 tx is received). This is # unfortunately reliant on the current relay behavior where we batch up # to 35 entries in an inv, which means that when this next transactio...
well. node0.settxfee(Decimal("0.02000000")) txids = [node0.sendtoaddress(node0.getnewaddress(), 1)] assert allInvsMatch(txids, self.nodes[0].p2p) self.nodes[0].p2p.clear_invs() # Remove fee filter and check that txs are received again self.nodes[0].p2p.send_and_ping(msg_...
eugenekolo/kololib
testing/big-bad-naughty-strings/naughtystrings/__init__.py
Python
mit
982
0.003055
import os FILEPATH = os.path.join( os.path.abspath(os.path.dirname(os.path.dirname(__file__))), 'blns.txt') """Path to the file""" def naughty_strings(filepath=FILEP
ATH): """Get the list of naughty_strings. By default this will get the strings from the blns.txt file Code is a simple port of what is already in the /scripts directory :param filepath: Optional filep
ath the the blns.txt file :returns: The list of naughty strings """ strings = [] with open(filepath, 'r') as f: # put all lines in the file into a Python list strings = f.readlines() # above line leaves trailing newline characters; strip them out strings = [x.s...
Jorge-Rodriguez/ansible
lib/ansible/modules/cloud/google/gcp_compute_instance_group_facts.py
Python
gpl-3.0
6,993
0.003003
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2017 Google # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ---------------------------------------------------------------------------- # # *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** # ...
format. returned: success type: str description: description: - An optional description of this resource. Provide this property when you create the resource. returned: success type: str id: description: - A unique identifier for this instance group. ...
rs long, and comply with RFC1035. returned: success type: str namedPorts: description: - Assigns a name to a port number. - 'For example: {name: "http", port: 80}.' - This allows the system to reference ports by the assigned name instead of a port number. Named ports can ...
genos/online_problems
rosalind/iev.py
Python
mit
333
0
#!/u
sr/bin/env python # coding: utf-8 from itertools import starmap from operator import mul PROBS = [1.0, 1.0, 1.0, .75, .5, 0] def iev(xs): return 2 * sum(starmap(mul, zip(PROBS, xs))) if __name__ == "__main__": with open("data/rosalind_iev.txt") as f: xs = map(int, f.read().split()) print(...
xs))
edx/edx-platform
openedx/core/djangoapps/content/block_structure/migrations/0001_config.py
Python
agpl-3.0
1,174
0.005111
from django.db import migrations, models import django.db.models.deletion from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='BlockS
tructureConfiguration', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('change_date', models.DateTimeField(auto_now_add=True, verbose_name='Change date')), ('enabled', models.BooleanField(default=Fa...
('cache_timeout_in_seconds', models.IntegerField(default=86400, null=True, blank=True)), ('changed_by', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, editable=False, to=settings.AUTH_USER_MODEL, null=True, verbose_name='Changed by')), ], options={ ...
xbmc/atv2
xbmc/lib/libPython/Python/Lib/test/test_unicodedata.py
Python
gpl-2.0
8,080
0.002104
""" Test script for the unicodedata module. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. """#" import unittest, test.test_support import sha encoding = 'utf-8' ### Run tests class UnicodeMethodsTest(unittest.TestCase): # update this, if the d...
al(self.db.bidirectional(u'\uFFFE'), '') self.assertEqual(self.db.bidirectional(u' '), 'WS') self.assertEqual(
self.db.bidirectional(u'A'), 'L') self.assertRaises(TypeError, self.db.bidirectional) self.assertRaises(TypeError, self.db.bidirectional, u'xx') def test_decomposition(self): self.assertEqual(self.db.decomposition(u'\uFFFE'),'') self.assertEqual(self.db.decomposition(u'\u00bc'), '<...
fnaum/rez
src/rez/utils/schema.py
Python
lgpl-3.0
2,777
0.00036
""" Utilities for working with dict-based schemas. """ from rez.vendor.six import six from rez.vendor.schema.schema import Schema, Optional, Use, And basestring = six.string_types[0] # an alias which just so happens to be the same number of characters as # 'Optional' so that our schema are easier to read Required =...
ich is in the form (eg): schema = Schema({Required("foo"): int, Optional("bah"): basestring}) """ def _get_leaf(value): if isinstance(value, Schema): return _get_leaf(value._schema) return value keys = set() dict_ = schema._schema ...
key_ = _get_leaf(key) if isinstance(key_, basestring): keys.add(key_) return keys def dict_to_schema(schema_dict, required, allow_custom_keys=True, modifier=None): """Convert a dict of Schemas into a Schema. Args: required (bool): Whether to make schema keys optional or requi...
yunity/foodsaving-backend
karrot/conversations/migrations/0020_remove_conversation_group.py
Python
agpl-3.0
353
0
# Generated by Django 2.1 on 2018-08-28 16:35 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('conversat
ions', '0019_conversationmessage_latest_message'), ] oper
ations = [ migrations.RemoveField( model_name='conversation', name='group', ), ]
brennanmorell/Mariner
WhaleTracker.py
Python
mit
5,712
0.007003
import gdax, time import pandas as pd from bintrees import RBTree from bson.decimal128 import Decimal128 from decimal import Decimal from WhaleOrder import WhaleOrder from Logging import Logging class WhaleTracker(): current_milli_time = lambda self: int(time.time() * 1000) def __init__(self, ticker): ...
whales_frame = pd.DataFrame(whales) return whales_frame def get_top_bid_whale(self): if not self._bid_whales.is_empty():
top_bid = self._bid_whales.max_key() return self.get_bid_whale(top_bid) else: return None def get_bid_whale(self, price): return self._bid_whales.get(price) def remove_bid_whale(self, price): self._bid_whales.remove(price) def set_bid_whale(self, price,...
andrei-alpha/robotics
old/obstacle_without_sensors.py
Python
mit
477
0.02935
import random import os from utils import
* def speak(text): os.system('espeak -a 200 "' + text + ' &"') speed = 100 dirmv = 1 while True: er = move(10, dirmv * speed, True) # if it hits an obstacle if er is -1: speak('Ops an obstacle!') dirmv *= -1 move(4, dirmv * speed, False) #rotate between -50 and 50 degrees deg = in...
tlake/learning-journal
tests/conftest.py
Python
mit
4,853
0.000412
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os import pytest from sqlalchemy import create_engine from pyramid import testing from cryptacular.bcrypt import BCRYPTPasswordManager import journal
DB_USR = os.environ.get("USER", ) TEST_DATABASE_URL = os.environ.get( 'DATABASE_URL', 'postgresql://' + DB_US
R + '@localhost:5432/travis_ci_test' ) os.environ['DATABASE_URL'] = TEST_DATABASE_URL os.environ['TESTING'] = 'True' """ This decorator registers the connection function as a fixture with pytest. The scope argument passed to the decorator determines how often a fixture is run: session scope: only ...
tdtrask/ansible
lib/ansible/plugins/action/enos.py
Python
gpl-3.0
3,638
0.002199
# # (c) 2017 Red Hat Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is d...
onstants as C from ansible.plugins.action.normal import ActionModule as _ActionModule from ansible.module_utils.network.enos.enos import enos_provider_spec from ansible.module_utils.network.common.utils import load_provider from ansible.module_utils.connection import Connection from ansible.module_utils._text import to...
mport Display display = Display() class ActionModule(_ActionModule): def run(self, tmp=None, task_vars=None): socket_path = None if self._play_context.connection == 'local': provider = load_provider(enos_provider_spec, self._task.args) pc = copy.deepcopy(self._play_co...
jabesq/home-assistant
tests/components/smartthings/test_init.py
Python
apache-2.0
17,803
0
"""Tests for the SmartThings component init module.""" from uuid import uuid4 from aiohttp import ClientConnectionError, ClientResponseError from asynctest import Mock, patch from pysmartthings import InstalledAppStatus, OAuthToken import pytest from homeassistant.components import cloud, smartthings from homeassista...
L] = "https://test.cloud" hass.config.api.base_url = 'http://0.0.0.0' smartthings_mock.app.return_value = app smartthings_mock.installed_app.return_value = installed_app smartthings_mock.devices.return_value = [device] smartthings_mock.scenes.return_value = [scene] mock_token
= Mock() mock_token.access_token.return_value = str(uuid4()) mock_token.refresh_token.return_value = str(uuid4()) smartthings_mock.generate_tokens.return_value = mock_token subscriptions = [subscription_factory(capability) for capability in device.capabilities] smartthings_mock...
BoPeng/simuPOP
docs/genoStru.py
Python
gpl-2.0
1,769
0.002261
#!/usr/bin/env python # # $File: genoStru.py $ # # This file is part of simuPOP, a forward-time population genetics # simulation environment. Please visit http://simupop.sourceforge.net # for details. # # Copyright (C) 2004 - 2010 Bo Peng (bpeng@mdanderson.org) # # This program is free software: you can redistribute i...
ral Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even th
e implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # This script is an example in the simuPOP ...
us-ignite/us_ignite
us_ignite/hubs/tests/forms_tests.py
Python
bsd-3-clause
2,096
0
from nose.tools import eq_ from django.test import TestCase from us_ignite.hubs import forms class TestHubRequestForm(TestCase): def test_form_fields_are_not_sensitive(self): form = forms.HubRequestForm() eq_(sorted(form.fields.keys()),
sorted(['name', 'website', 'summary', 'description'])) def test_empty_form_fails(self): form = forms.HubRequestForm({}) eq_(form.is_valid(), False) def test_valid_data_is_successful(self): data = { 'name': 'Gig
abit community', 'description': 'Community description.', } form = forms.HubRequestForm(data) eq_(form.is_valid(), True) class TestHubForm(TestCase): def test_form_fields_are_not_sensitive(self): form = forms.HubForm() eq_(sorted(form.fields.keys()), ...
rmachedo/MEater
py/SentimentAnalyzerP.py
Python
gpl-3.0
5,719
0.011736
#!/usr/bin/python # -*- coding: utf-8 -*- from edu.umd.rhsmith.diads.tools.sentiment import ISentimentAnalyzer import pickle import re import os import sys import time import traceback import nltk from nltk.corpus import stopwords class SentimentAnalyzerP(ISentimentAnalyzer, object): ''' Sentiment Analyzer Utility ...
ii", "ignore") except UnicodeDecodeError: print "Unicode error on status; skipping." sys.stdout.flush() # featurify the text, using only the features in the master list statfeat = {} #try: # with time_limit(10): statfeat = self.featurify(text, self.masterf
eats) #except TimeoutException: # print "Featurify timed out for status_id %i" % row['id'] if len(statfeat) > 0: result = self.classifier.prob_classify(statfeat) probs = dict([(x, result.prob(x)) for x in result.samples()]) # calculate a score in [-1, +1] score = prob...
qingpingguo/git-repo
editor.py
Python
apache-2.0
2,620
0.014122
# # Copyright (C) 2008 The Android Open Source Project # # 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 la...
ing this command.""" sys.exit(1) return 'vi' @classmethod def EditString(cls, data): """Opens an editor to edit the given content. Args: data : the text to edit Returns: new value of edited text; None if editing did not succeed """ editor = cls._GetEd...
r == ':': return data fd, path = tempfile.mkstemp() try: os.write(fd, data) os.close(fd) fd = None if re.compile("^.*[$ \t'].*$").match(editor): args = [editor + ' "$@"', 'sh'] shell = True else: args = [editor] shell = False args.appen...
bnzk/djangocms-misc
setup.py
Python
mit
1,190
0
# coding: utf-8 from setuptools import setup, find_packages import os # not so bad: http://joebergantine.com/blog/2015/jul/17/releasing-package-pypi/ version = __import__('djangocms_misc').__version__ def read(fname): # read the contents of a text file return open(os.path.join(os.path.dirname(__file__), fna...
:: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :
: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', ], )
coingraham/codefights
python/fileNaming/fileNaming.py
Python
mit
1,136
0.001761
""" You are given an array of desired filenames in the order of their creation. Since two files cannot have equal names
, the one which comes later will have an addition to its name in a form of (k), where k is the smallest positive integer such that the obtained name is not used yet. Return an array of names that will be given to the files. Example For names = ["doc", "doc", "image", "doc(1)", "doc"], the output should be fileNaming...
["doc", "doc(1)", "image", "doc(1)(1)", "doc(2)"]. Input/Output [execution time limit] 4 seconds (py) [input] array.string names Guaranteed constraints: 5 <= names.length <= 15, 1 <= names[i].length <= 15. [output] array.string """ def fileNaming(names): new_names = [] for name in names: if nam...
EnTeQuAk/dmlt
dmlt/tests/datastructure/test_token_stack.py
Python
bsd-3-clause
1,756
0.001708
#-*- coding: utf-8 -*- from nose.tools import * from dmlt.exc import StackEmpty
from dmlt.datastructure import Stack, Token, _unde
fined TEST_TOKENS = ['bold', 'italic', 'uff', 'papapapa', 'foo', 'python', 'spaghetti', 'car', 'mom'] def test_current(): stack = Stack() assert_true(stack.current is _undefined) stack.push('foo') assert_equal(stack.current, 'foo') stack.pop() assert_true(stack.current is _undefined) ...
MathieuDuponchelle/gobject-introspection
tests/scanner/annotationparser/test_parser.py
Python
gpl-2.0
21,886
0.002559
# -*- Mode: Python -*- # GObject-Introspection - a framework for introspecting GObject libraries # Copyright (C) 2012 Dieter Verfaillie <dieterv@optionexplicit.be> # # 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 S...
s' % (indent)) expected_serialized = expected_serialized.text + '\n' or None commentblockwriter = GtkDocCommentBlockWriter(indent=indent) serialized = commentblockwriter.write(parsed_docblock) msg = 'Seriali
zed comment block does not match expected output:\n\n' msg += self._diff_messages(expected_serialized.split('\n'), serialized.split('\n')) self.assertTrue(expected_serialized == serialized, msg) return do_test def parsed2tree(self, docblock): parsed = '' if docbloc...
seadsystem/ShR2
ESP8266/keys/hex_array.py
Python
mit
804
0.033582
#!/usr/bin/env python2 # ============================================================ # File: hex-array.py [input files] # Description: inputs a file, and formats it in a hex array # Create
d by Henry Crute # 3/5/2015 # ============================================================ #12 hex digits on a line import sys def read_file(filename): i = 0 with open(filename) as f: while True: c = f.read(1) if not c: print "\nEnd of file ", filename, " ", i, " lines" break elif c != ' ' and...
\n" % ord(c)) else: sys.stdout.write("0x%x, " % ord(c)) def main(): i = 0 for arg in sys.argv: if (i == 0): i += 1 continue read_file(arg) i += 1 return if __name__ == "__main__": main()
sloria/aiohttp_utils
tests/test_runner.py
Python
mit
1,003
0
import pytest from aiohttp import web from aiohttp_utils.runner import Runner class TestRunner: def test_bind(self): app = web.Application() runner = Runner(app, host='1.2.3.4', port=5678, app_uri='http://1.2.3.4:5678') assert runner.bind == '1.2.3.4:5678' def...
ed_for_reload(self): app = web.Application() with pytest.raises(RuntimeError): Runner(app, reload=True) # no api_uri def test_reload_takes_value_of_app_debug_by_default(self): app = web.Application(debug=True) assert Runner(app, app_uri='foo').reload is True app...
app = web.Application(debug=True) assert Runner(app, reload=False).reload is False app = web.Application(debug=False) assert Runner(app, reload=True, app_uri='foo').reload is True
Juraci/tempest
tempest/api/compute/servers/test_servers.py
Python
apache-2.0
5,584
0
# Copyright 2012 OpenStack Foundation # 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 requ...
'id']) self.assertEqual(key_name, server['key_name']) def _update_server_name(self, server_id, status): # The server name should be changed to the the provided value new_name = data_utils.rand_name('server') # Update the server with a new name self.client.update_serve
r(server_id, name=new_name) waiters.wait_for_server_status(self.client, server_id, status) # Verify the name of the server has changed server = self.client.show_server(server_id) self.assertEqual(new_name, server['name']) return server @tes...
Ehtaga/account-financial-reporting
account_financial_report_webkit/account_move_line.py
Python
agpl-3.0
3,309
0
# -*- encoding: utf-8 -*- ############################################################################## # # Author: Nicolas Bessi. # Copyright Camptocamp SA 2011 # # 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 #...
oncile.line_partial_ids: moves.append(move_line.id) for move_line in reconcile.line_id: m
oves.append(move_line.id) return list(set(moves)) def _get_last_rec_date(self, cursor, uid, ids, name, args, context=None): if not isinstance(ids, list): ids = [ids] res = {} for line in self.browse(cursor, uid, ids, context): res[line.id] = {'last_rec_date':...
concentricsky/python-systemd
systemd/unit.py
Python
lgpl-2.1
6,112
0.005399
# # Copyright (c) 2010 Mandriva # # This file is part of python-systemd. # # python-systemd is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation; either version 2.1 of # the License, or (at your option) any l...
erface.dbus_interface) attr_property = Property() for key, value in properties.items(): setattr(attr_property, key, value) setattr(self, 'properties', attr_property) def kill(self, who, mode, signal): """Kill unit. @param who: Must be one of main, contr...
@param signal: Must be one of the well know signal number such as SIGTERM(15), SIGINT(2), SIGSTOP(19) or SIGKILL(9). @raise SystemdError: Raised when who, mode or signal are invalid. @rtype: systemd.job.Job """ try: self.__interface.KillUnit(who...
arnif/CouchPotatoServer
couchpotato/core/providers/nzb/nzbmatrix/__init__.py
Python
gpl-3.0
1,064
0.003759
from .main import NZBMatrix def start(): return NZBMatrix() config = [{ 'name': 'nzbmatrix', 'groups': [ { 'tab': 'searcher', 'subtab': 'nzb_providers', 'name': 'nzbmatrix', 'label': 'NZBMatrix', 'descripti
on': 'See <a href="https://nzbmatrix.com/">NZBMatrix</a>', 'wizard': True, 'options': [ { 'name': 'enabled', 'type': 'enabler', }, { 'name': 'username',
}, { 'name': 'api_key', 'default': '', 'label': 'Api Key', }, { 'name': 'english_only', 'default': 1, 'type': 'bool', 'l...
CingHu/neutron-ustack
neutron/services/loadbalancer/constants.py
Python
apache-2.0
4,424
0.005651
# Copyright 2013 Mirantis, 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 b...
don-logan): change these to LB_ALGORITHM LB_METHOD_ROUND_ROBIN = 'ROUND_ROBIN' LB_METHOD_LEAST_CONNECTIONS = 'LEAST_CONNECTIONS' LB_METHOD_SOURCE_IP = 'SOURCE_IP' SUPPORTED_LB_ALGORITHMS = (LB_METHOD_LEAST_CONNECTIONS, LB_ME
THOD_ROUND_ROBIN, LB_METHOD_SOURCE_IP) PROTOCOL_TCP = 'TCP' PROTOCOL_HTTP = 'HTTP' PROTOCOL_HTTPS = 'HTTPS' PROTOCOL_TERMINATED_HTTPS = 'TERMINATED_HTTPS' #POOL_SUPPORTED_PROTOCOLS = (PROTOCOL_TCP, PROTOCOL_HTTPS, PROTOCOL_HTTP, PROTOCOL_TERMINATED_HTTPS) POOL_SUPPORTED_PROTOCOLS = (PROTOCOL...
freelan-developers/teapot
teapot/extra/rfc6266.py
Python
mit
15,052
0.000199
# vim: set fileencoding=utf-8 sw=4 ts=4 et : """Implements RFC 6266, the Content-Disposition HTTP header. parse_headers handles the receiver side. It has shortcuts for some http libraries: parse_httplib2_response and parse_requests_response. It returns a ContentDisposition object with attributes like is_inline, f...
self): return 'ContentDisposition(%r, %r, %r)' % ( self.disposition, self.assocs, self.location) def ensure_charset(text, encoding): if isinstance(text, bytes): return text.decode(encoding) else: assert fits_inside_codec(text, encoding) return text def parse_heade...
sition is None: return ContentDisposition(location=location) # Both alternatives seem valid. if False: # Require content_disposition to be ascii bytes (0-127), # or characters in the ascii range content_disposition = ensure_charset(content_disposition, 'ascii') else: ...
giltis/scikit-xray
skxray/core/constants/xrs.py
Python
bsd-3-clause
10,527
0.000285
# -*- coding: utf-8 -*- # ###################################################################### # Copyright (c) 2014, Brookhaven Science Associates, Brookhaven # # National Laboratory. All rights reserved. # # # # @...
# are met: # # # # * Redistributions of source code must retain the above copyright # # notice, this list of conditions and the following disclaimer. # # ...
r in # # the documentation and/or other materials provided with the # # distribution. # # # # * Neither the name of the Brookhaven Science Associates, Brookhaven # # National Labo...
birkenfeld/elpy
elpy/ropebackend.py
Python
gpl-3.0
10,694
0.000374
"""Elpy backend using the Rope library. This backend uses the Rope library: http://rope.sourceforge.net/ """ import os import time import traceback import rope.contrib.codeassist import rope.base.project import rope.base.libutils import rope.base.exceptions import rope.contrib.findit from elpy import rpc import e...
calltip = calltip.replace("(self, ", "(") # "elpy.tests.support.source_and_offset(source)" # => # "support.sour
ce_and_offset(source)" try: openpos = calltip.index("(") period2 = calltip.rindex(".", 0, openpos) period1 = calltip.rindex(".", 0, period2) calltip = calltip[period1 + 1:] except ValueError: pass return calltip def rpc_get_docstri...
tedlaz/pyted
tedutil_old/mis.py
Python
gpl-3.0
3,105
0.00198
# -*- coding: utf-8 -*- import ted_util as tu from ted_util import dec import ted_sqlite as ts fil = 'tdf.sql3' sqlc = "create table mis(id INTEGER PRIMARY KEY, xr, per, typ, erg, js, jse);" sqli = "insert into mis values (null, ?, ?, ?, ?, ?, ?);" sqls =
'''select xr, per, typ, erg, p0(js, 'forol') as sk, p0(jse
, 'mert') as kl from mis''' # ts.script_on_new_db(fil, sqlc) par = {'mer': 2, 'mad': 0, 'apousia': 0, 'ony': 0, 'mky': 0, 'oky': 0, 'oyp': 0, 'astheneia': [ {'apo': '2014-02-10', 'eos': '2014-02-12', 'm...
quentinhardy/odat
Constants.py
Python
lgpl-3.0
1,740
0.020208
# -*- coding: utf-8 -* import string DESCRIPTION = ""\ """ _ __ _ ___ / \| \ / \|_ _| ( o ) o ) o || | \_/|__/|_n_||_| ------------------------------------------- _ __ _ ___ / \ | \ / \ |_ _| ( o ) o ) ...
оль%", "%wachtwoord%", "%hasło%", "%senha%", ] EXPLOITABLE_SYSTEM_PRIVILEGES = [ '
CREATE ANY PROCEDURE', 'ANALYZE ANY', 'CREATE ANY TRIGGER', 'CREATE ANY INDEX', ]
macchina-io/macchina.io
platform/JS/V8/v8/tools/v8heapconst.py
Python
apache-2.0
12,703
0
# Copyright 2017 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can # be found in the LICENSE file. # This file is automatically generated by mkgrokdump and should not # be modified manually. # List of known V8 instance types. INSTANCE_TYPES = { 0: "IN...
145: "FIXED_FLOAT64_ARRAY_TYPE", 146: "FIXED_UINT8_CLAMPED_ARRAY_TYPE", 147: "FIXED_DOUBLE_ARRAY_TYPE"
, 148: "FILLER_TYPE", 149: "ACCESSOR_INFO_TYPE", 150: "ACCESSOR_PAIR_TYPE", 151: "ACCESS_CHECK_INFO_TYPE", 152: "INTERCEPTOR_INFO_TYPE", 153: "FUNCTION_TEMPLATE_INFO_TYPE", 154: "OBJECT_TEMPLATE_INFO_TYPE", 155: "ALLOCATION_SITE_TYPE", 156: "ALLOCATION_MEMENTO_TYPE", 157: "SCRIPT_TYPE", 158: "ALIA...
tnemis/staging-server
baseapp/views/disadvantaged_group_views.py
Python
mit
1,981
0.002524
from django.views.generic import ListView, DetailView, CreateView, \ DeleteView, UpdateView from baseapp.models import Disadvantaged_group from django.contrib import auth, messages class Disadvantaged_groupView(object): model = Disadvantaged_group def get_template_names(sel...
[0] app = self.model._meta.app_label mdl = 'disadvantaged_group' self.template_name = tpl.replace(app, '{0}/{1}'.format(app, mdl)) retu
rn [self.template_name] class Disadvantaged_groupBaseListView(Disadvantaged_groupView): paginate_by = 10 class Disadvantaged_groupCreateView(Disadvantaged_groupView, CreateView): def get_success_url(self): from django.core.urlresolvers import reverse messages.add_message( se...
mir-dataset-loaders/mirdata
tests/datasets/test_mtg_jamendo_autotagging_moodtheme.py
Python
bsd-3-clause
3,299
0.001516
import numpy as np import pytest from mirdata.datasets import mtg_jamendo_autotagging_moodtheme from tests.test_utils import run_track_tests def test_track(): default_trackid = "track_0000948" data_home = "tests/resources/mir_datasets/mtg_jamendo_autotagging_moodtheme" dataset = mtg_jamendo_autotagging_m...
ng_moodtheme" dataset = mtg_jamendo_autotagging_moodtheme.Dataset(data_home) track = dataset.track(default_trackid) assert track.track_id == d
efault_trackid assert track.artist_id == "artist_000087" assert track.album_id == "album_000149" assert track.duration == 212.7 assert track.tags == "mood/theme---background" def test_to_jams(): default_trackid = "track_0000948" data_home = "tests/resources/mir_datasets/mtg_jamendo_autotagging...
zatarra/rubberduino
rubberduino/__init__.py
Python
mit
36
0
from rubberduino
import
RubberDuino
jas32096/mps-youtube
mps_youtube/content.py
Python
gpl-3.0
8,740
0.000572
import math import copy import random import pafy from . import g, c, config from .util import getxy, fmt_time, uea_pad, yt_datetime, F try: import qrcode import io HAS_QRCODE = True except ImportError: HAS_QRCODE = False # In the future, this could support more advanced features class Content: ...
g'][:x['size']] for x in columns]) hrow = c.ul + fmt % titles + c.w out = "\n" + hrow + "\n" for n, x in enumerate(g.model[:max_results]): col = (c.r if n % 2 == 0 else c.p) if not song else c.b details = {'title': x.title, "length": fmt_time(x.length)} details = copy.copy(g.meta[x....
lumns[1]['size'], otitle) cat = details.get('category') or '-' details['category'] = pafy.get_categoryname(cat) details['ytid'] = x.ytid line = '' for z in columns: fieldsize, field, direction = z['size'], z['name'], "<" if z['sign'] == "-" else ">" line ...
Jumpscale/go-raml
docs/tutorial/python/requests_client/goramldir/__init__.py
Python
bsd-2-clause
639
0
# DO NOT EDIT THIS FILE. This file will be overwritten when re-running go-raml. from .User import User from .users_service import UsersService
from .oauth2_client_itsyouonline import Oauth2ClientItsyouonline from .http_client import HTTPClient class Client: def __init__(self, base_uri="http://localhost:5000"): http_client = HTTPClient(base_uri) self.security_schemes = Security(http_client) s
elf.users = UsersService(http_client) self.close = http_client.close class Security: def __init__(self, http_client): self.oauth2_client_itsyouonline = Oauth2ClientItsyouonline(http_client)
samfoo/vt102
vt102/graphics.py
Python
lgpl-3.0
1,195
0.005021
dsg = dict( zip( [ord(c) for c in "\x60\x61\x66\x67\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x7b\x7e
"], u"\u25c6\u2592\u25cb\u00b1\u2518\u2510\u250c\u2514\u253c\u2500\u2500\u2500\u2500\u2500\u251c\u2524\u2534\u252c\u2502\u03c0\xb7" ) ) text = { 0: "reset", 24: "under
line-off", 25: "blink-off", 27: "reverse-off", 1: "bold" , 2: "dim" , 4: "underline", 5: "blink", 7: "reverse", } colors = { "foreground": { 39: "default", # This is technically "default with underscore", but I don't understand # the utility of mixing the text st...
Conflagrationator/AAE251
Atmosphere.py
Python
mit
4,278
0.013324
from scipy import * from Reference import * ############################
#################################################### # DATA ###########################
##################################################### # EARTH FACTS R = 287.058 # ideal gas constant for earth air, in J/kg*K r = 6356766 # radius of the earth, in m g = 9.80665 # gravitational acceleration at sea level, in m/s^2 # ATMOSPHERE FACTS baseHeights = [0, 11000, 25000, 47000, 53000, 79000, 90000, 105000]...
piskvorky/pattern
examples/01-web/05-flickr.py
Python
bsd-3-clause
1,357
0.006632
import os, sys; sys.path.insert(0, os.path.join("..", "..")) from pattern.web import Flickr, extension from pattern.web import RELEVANCY, LATEST, INTERESTING # Image sort order. from pa
ttern.web import SMALL, MEDIUM, LARGE # Image size. # This example downloads an image from Flickr (http://flickr.com). # Acquiring the image data takes three Flickr queries: # - the first query with Flickr.search() retrieves a list of results, # - th
e second query is executed behind the scenes in the FlickResult.url property, # - the third query downloads the actual image data using this URL. # It is a good idea to cache results from Flickr locally, # which is what the cached=True parameter does. # You should obtain your own license key at: # http://www.flickr.co...
giannitedesco/funky
funky/resourceview.py
Python
gpl-3.0
4,577
0.008521
import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, GObject from enum import Enum class Prices(Enum): other = ( 8, 8, 8, 7, 7, 7, 6, 6, 6, 5, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 1, 1, 1, ) ...
ount(count) def update_count(self, count): self.c.set_range(count, count) self.c.set_value(count) self.p.set_range(0, count) def __int__(self): return self.p.get_value_as_int() class ButtonRow(Gtk.ListBoxRow): def __init__(self, buy_cb): def cb_shim(*_): ...
entation.HORIZONTAL, spacing = 5) self.name = Gtk.Label(xalign = 0) self.name.set_markup('<b>Purchase</b>') self.d = Gtk.Label()#xalign = 0) self.update_stock(0, 0, 0, 0) self.update_totals(0, 0, 0, 0) b = Gtk.Button.new_with_label('buy') b....
4Catalyzer/flask-jsonapiview
example/settings.py
Python
mit
88
0
SQLALCHEMY_DATABASE_URI = "s
qlite:///example.db" SQ
LALCHEMY_TRACK_MODIFICATIONS = False
SylvainA/os-event-catcher
openstack/common/report/models/threading.py
Python
apache-2.0
3,320
0
# Copyright 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
. seealso:: Class :class:`StackTraceModel` :param stack: the python stack state for the green t
hread """ # gr in greenpool.coroutines_running --> gr.gr_frame def __init__(self, stack): super(GreenThreadModel, self).__init__( {'stack_trace': StackTraceModel(stack)}, text_view=text_views.GreenThreadView())
Maplenormandy/list-62x
python/twocamera/Q.py
Python
mit
1,704
0.051056
# Binary search tree that holds status of sweep line. Only leaves hold values. # Operations for finding left and right neighbors of a query point p and finding which segments contain p. # Author: Sam Lichtenberg # Email: splichte@princeton.edu # Date: 09/02/2013 from helper import * ev = 0.00000001 class Q: def __i...
.left.print_tree() print self.key print self.value
if self.right: self.right.print_tree()
allink/allink-apps
locations/__init__.py
Python
bsd-3-clause
118
0
# -*- codi
ng: utf-8 -*- default_app_config = 'allink_apps.locations.apps.AllinkLocationsConfig' _
_version__ = '0.0.1'
ITU-DB-MANAGEMENT-HM/itunder-backend-rest
models/base_model.py
Python
apache-2.0
9,264
0.001403
""" Models initializer. """ from functools import wraps from flask_sqlalchemy import SQLAlchemy from server import app from utils import time_to_json from errors import DataBaseException DB = SQLAlchemy(app) def db_factory_func(func): """ Database connection decorator. Creates a database connection and ...
,", selected_cols) else: raise DataBaseException("Invalid column selection.") sql_statement = "SELECT {} FROM {} ".format( selected_cols, self.table_name) if query: sql_statemen
t += " WHERE {} ".format(query) if limit > 0: sql_statement += " LIMIT {} ".format(limit) if offset: sql_statement += " OFFSET {} ".format(offset) if sort_by: sql_statement += " ORDER BY {} ".format(sort_by) try: ...
jairglez/intel-iot-refkit
meta-refkit-core/lib/ostree/ostreeupdate.py
Python
mit
12,419
0.003543
import bb import oe.path import glob import hashlib import os.path import shutil import string import subprocess class OSTreeUpdate(string.Formatter): """ Create an OSTree-enabled version of an image rootfs, using an intermediate per-image OSTree bare-user repository. Optionally export the content of ...
# root symlinks for the following: # # /home -> /var/home (further linked -> /sysroot/home) # /opt -> /var/opt # /srv -> /var/srv # /root -> /var/roothome # /usr/local -> /var/local # /mnt -> /var/mnt # /tmp -> /sysroot/t...
can be a persistent second data partition. # We just use one partition, so instead we have: # # /boot = mount point for persistent /boot directory in the root partition # /var = mount point for persistent /ostree/deploy/refkit/var # /home = mount point for persistent...
etherkit/OpenBeacon2
client/win/venv/Lib/site-packages/PyInstaller/hooks/hook-nanite.py
Python
gpl-3.0
558
0.003584
#------
----------------------------------------------------------------------- # Copyright (c) 2017-2019, PyInstaller Development Team. # # Distributed under the terms of the GNU General Public License with exception # for distributing bootloader. # # The full license is in the file COPYING.txt, distributed with this software...
ttps://pypi.python.org/pypi/nanite from PyInstaller.utils.hooks import collect_data_files datas = collect_data_files('nanite')
dayatz/taiga-back
taiga/events/middleware.py
Python
agpl-3.0
2,029
0
# -*- coding: utf-8 -*- # Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz> # Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com> # Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com> # Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net> # This program is free software: you can r...
import threading _local = threading.local() _local.session_id = None def get_current_session_id() -> str: """ Get current session id for current request. This function should be used only
whithin request context. Out of request context it always return None """ global _local if not hasattr(_local, "session_id"): raise RuntimeError("No session identifier is found, " "are you sure that session id middleware " "is active?") ...
dimtruck/magnum
magnum/tests/unit/common/x509/test_sign.py
Python
apache-2.0
7,885
0
# Copyright 2015 NEC Corporation. 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 l...
elf.assertHasIssuerName(cert, issuer_name) def test_generate_
ca_certificate_has_publickey(self): keypairs = self._generate_ca_certificate(self.issuer_name) self.assertHasPublicKey(keypairs) def test_generate_ca_certificate_set_subject_name(self): cert, _ = self._generate_ca_certificate(self.issuer_name) self.assertHasSubjectName(cert, self....
loopback1/scripts
compare_files/compare_ip_file_dumps_1.py
Python
unlicense
698
0.011461
import re def get_ip_from_file(file_1): with open(file_1) as f: x = [y.strip() for y in f] ip_list = [re.findall('[0-9]{1,3}\.[0
-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}', t) for t in x] return ip_list def parse(file_1): filter_1 = get_ip_from_file(file_1) filter_finish = {x for i in filter_1 for x in
i} return sorted(filter_finish) old = parse("C:\python27\ip.csv") new = parse("C:\python27\ip2.csv") report = [x for x in new if x in old] print "IPs in file2 that EXIST in file1:\n\n" for i in report: print i print "\n\nfile1 unique IPs: " + str(len(old)) print "file2 unique IPs: " + str(len(new)) p...
kizzen/Baller-Shot-Caller
web_site/baller_shot_caller/apps.py
Python
mit
109
0
from
django.apps import AppConfig class BallerShotCallerConfig(AppConfig): name = 'baller_shot_caller'
MSK61/django-yabe
yabe/views.py
Python
gpl-3.0
1,382
0.000724
# -*- coding: utf-8 -*- """displays the root page""" ############################################################ # # Cop
yright 2010, 2014 Mohammed El-Afifi # This file is part of yabe. # # yabe is free software: you can redistribute it and
/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # yabe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of ...
GbalsaC/bitnamiP
venv/lib/python2.7/site-packages/pylint/test/functional/exception_is_binary_op.py
Python
agpl-3.0
416
0
"""Warn about binary operations used as exceptions.""" try: pass except Exception or BaseException: # [binary-op-exception] print("caught1") except Exception and BaseException: # [binary-op-exception]
print("caught2") except Exception or Bas
eException: # [binary-op-exception] print("caught3") except (Exception or BaseException) as exc: # [binary-op-exception] print("caught4")
stefsmeets/lines
setup.py
Python
gpl-2.0
911
0.002195
#!/usr/bin/env python from setuptools import setup, find_packages from os import path # www.pythonhosted.org/setuptools/setuptools.html setup( name="lines", version="1.4.0", description="Program for plotting powder diffraction patterns
and background subtraction", author="Stef Smeets", author_email="s.smeets@esciencecenter.nl", license="GPL", url="https://github.com/stefsmeets/lines", classifiers=[ 'Programming Language :: Python :: 2.7', ], packages=["lines", "zeolite_database"], install_requires=[ ...
, "zeolite_database": ["*.cif"], }, entry_points={ 'console_scripts': [ 'lines = lines.lines:main', 'cif2xy = lines.cif2xy:main', ] } )
chapware/aircrack
scripts/airgraph-ng/airgraph-ng.py
Python
gpl-2.0
15,099
0.039539
#!/usr/bin/python __author__ = 'Bryan Chapman' __email__ = 'bryanwchapman@gmail.com' __website__= 'http://trac.aircrack-ng.org/browser/trunk/scripts/airgraph-ng/' __date__ = '07/16/10' __version__ = '0.2.5.1' __file__ = 'airgraph-ng' __data__ = 'This is the main airgraph-ng file' """ Welcome to airgraph written by Bry...
turns a list of 2 dictionaries (Clients and APs) """ try: #some very basic error handeling to make sur
e they are loading up the correct file try: apStart = cleanedDump.index('BSSID, First time seen, Last time seen, Channel, Speed, Privacy, Power, # beacons, # data, LAN IP, ESSID') except Exception: apStart = cleanedDump.index('BSSID, First time seen, Last time seen, channel, Speed, Privacy, Cipher, Authentica...
rezoo/illustration2vec
i2v/base.py
Python
mit
5,296
0.000378
from abc import ABCMeta, abstractmethod import numpy as np class Illustration2VecBase(object): __metaclass__ = ABCMeta def __init__(self, net, tags=None, threshold=None): self.net = net if tags is not None: self.tags = np.array(tags) self.index = {t: i for i, t in enu...
acter_arg[i]], character_prob[i, character_arg[i]].tolist())), 'copyright': list(zip( self.ta
gs[1024 + copyright_arg[i]], copyright_prob[i, copyright_arg[i]].tolist())), 'rating': list(zip( self.tags[1536 + rating_arg[i]], rating_prob[i, rating_arg[i]].tolist())), }) return result def __extract_plausible_tags(s...
uw-it-aca/bridge-sis-provisioner
sis_provisioner/tests/__init__.py
Python
apache-2.0
267
0
# Copyright 2022 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 from uw_gws
.utilities import fdao_gws_override from uw_pws.util import fdao_pws_override from uw_h
rp.util import fdao_hrp_override from uw_bridge.util import fdao_bridge_override
AndriiL/python_training
fixture/session.py
Python
apache-2.0
2,629
0.000761
class SessionHelper: def __init__(self, app): self.app = app def login(self, username, password): wd = self.app.wd self.app.open_home_page() wd.get("http://localhost/addressbook/group.php") wd.find_element_by_name("pass").click() wd.find_element_by_name("user")...
t_by_name("pass").click() wd.find_element_by_name("user").click() wd.find_element_by_name("user").click() wd.find_element_by_name("user").clear() wd.find_element_by_name("user").send_keys(username) wd.find_element_by_name("user").click() wd.find_element_by_name("pass").cl...
ent_by_xpath("//form[@id='LoginForm']/input[3]").click() def logout(self, ): wd = self.app.wd wd.find_element_by_link_text("Logout").click()
taikoa/wevolver-server
wevolve/tasks/admin.py
Python
agpl-3.0
371
0
from django.contrib import admin from wevolve.tasks.models import Task, TaskSkill, TaskUser class TaskAdmin(admin.ModelAdmin): pass
class TaskSkillAdmin(admin.ModelAdmin): pass class TaskUserAdmin(admin.ModelAdmin): pass admin.site.register(Task, TaskAdmin) admin.site.register(T
askSkill, TaskSkillAdmin) admin.site.register(TaskUser, TaskUserAdmin)
mariano/snakefire
snakefire/pxss.py
Python
mit
15,957
0.006392
#!/usr/bin/env python # Copyright 2009 Yu-Jie Lin # Copyright 2003 David McClosky # # This code is licensed under the GPLv3 # # This Python code does not require any Python binding library, such as # python-xlib or PyXSS. It directly accesses libXss via ctypes. # # It was written with intention of using PyXSS' IdleTrac...
aults fr
om server */ # /* there is more to this structure, but it is private to Xlib */ ] class XScreenSaverInfo(Structure): _fields_ = [ # X.h:101:typedef XID Window; # X.h:71:typedef unsigned long XID; ('window', c_ulong), # Window window; /* screen saver ...
carlosp420/VoSeq
blast_local_full/tests/test_views.py
Python
bsd-3-clause
538
0.003717
from django.test import TestCase, Client from django.core.management import call_command from django.conf import settings class TestViews(TestCase): def setUp(self): self.client = Client() args = [] opts = {'dumpfile': settings.MEDIA
_ROOT + 'test_db_dump.xml', 'verbosity': 0} cmd = 'migrate_db' call_command(cmd, *args, **opts) def test_index(self): r
esponse = self.client.get('/blast_local_full/CP100-10/COI/', follow=True) self.assertEqual(200, response.status_code)
alexis-roche/nipy
nipy/algorithms/graph/tests/test_forest.py
Python
bsd-3-clause
3,578
0.009782
from __future__ import print_function from __future__ import absolute_import import numpy as np from ..forest import Forest def simple_forest(): """ generate a simple forest """ parents = np.array([2, 2, 4, 4, 4]) F = Forest(5, parents) return F def test_forest(): """ test creation of forest...
forest object """ F = Forest(5) assert F.E == 0 assert (F.cc() == np.arange(5)).all() def test_children(): """ test that we obtain children """ sf = simple_forest() ch = sf.get_children() assert len(ch) == 5 assert ch[0] == [] assert ch[1] == [] assert ch[2] == [0, 1] ...
== [0] assert sf.get_descendants(1) == [1] assert sf.get_descendants(2) == [0, 1, 2] assert sf.get_descendants(4) == [0, 1, 2, 3, 4] def test_root(): """ test the isroot() method """ root = simple_forest().isroot() assert root[4] == True assert root.sum() == 1 def test_merge_simpl...
TechInvestLab/dot15926
editor_qt/iso15926/common/testing.py
Python
lgpl-3.0
4,639
0.001725
""" .15925 Editor Copyright 2014 TechInvestLab.ru dot15926@gmail.com .15925 Editor is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version....
Widget(self.report) layout.addWidget(box) self.exec_() def SelectAll(self): self.tests_list.SetCheck
ed([x for x in xrange(self.tests_list.Count)]) def UnselectAll(self): self.tests_list.SetChecked([]) def OnPrepare(self): if Choice(tm.main.tests_prepare_warning): for k in self.tests_list.CheckedStrings: self.report.AppendText(tm.main.tests_preparing.format(k)) ...
andrewyang96/FlappyPipes
lib/graphics/spritesheet.py
Python
mit
4,255
0.028672
# This class handles sprite sheets # This was taken from www.scriptefun.com/transcript-2-using # sprite-sheets-and-drawing-the-background # I've added some code to fail if the file wasn't found.. # Note: When calling images_at the rect is the format: # (x, y, x + offset, y + offset) import pygame, sys class Sprites...
'fb3':Rect(209,49,17,12), # flappy bird 3 'logo':Rect(159,71,106,22), # flappy pipes logo 'gameover':Rect(159,103,94,19), # game over logo 'getready':Rect(159,132,87,22), # get ready logo 'bronze':Rect(263,103,22,22), # bronze medal 'gold':Rect...
'platinum':Rect(159,167,22,22), # platinum medal 'silver':Rect(191,167,22,22), # silver medal 'instructions':Rect(223,167,49,49), # instructions 'player':Rect(159,226,42,26), # pipe player 'scorebg':Rect(282,5,113,58), # scoreboard 'terrain':...
rezoo/chainer
chainer/function_hooks/cuda_profile.py
Python
mit
780
0
from chainer.backends import cuda from chainer import function_hook class CUDAProfileHook(function_hook.FunctionHook): name
= 'CUDAProfileHook' def __init__(self): cuda.check_cuda_available() if not cuda.cupy.cuda.nvtx_enabled: raise RuntimeError('nvtx is required for CUDAProfileHook') def forward_preprocess(self, function, in_data): cuda.cupy.cuda.nvtx.RangePush(function.label + '.forward') ...
data, out_grad): cuda.cupy.cuda.nvtx.RangePush(function.label + '.backward') def backward_postprocess(self, function, in_data, out_grad): cuda.cupy.cuda.nvtx.RangePop()
alexbredo/honeypot-ssh
ssh.py
Python
bsd-2-clause
6,489
0.030821
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2014 Alexander Bredo # All rights reserved. # # Redistribution and use in source and binary forms, with or # without modification, are permitted provided that the # following conditions are met: # # 1. Redistributions of source code must retain the abov...
licKey = Key.fromString(data=publicBlob) class SSHDemoProtocol(recvline.HistoricRecvLine): def __init__(self, user): self.user = user self.pseudosys = Path(config.filesystem) def connectionMade(self): welcomeMessage = '''Lin
ux www01-master 2.6.32-5-amd64 #1 SMP Fri May 10 08:43:19 UTC 2013 x86_64 GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent permitted by applicable law. Last login: Tue Sep 10 13:40:21 2013 from support.microsoft.com''' recvline.HistoricRecvLine.connectionMade(self) self.terminal.write(welcomeMessage) s...
upsuper/servo
components/script/dom/bindings/codegen/parser/tests/test_cereactions.py
Python
mpl-2.0
3,527
0.003686
def WebIDLTest(parser, harness): threw = False try: parser.parse(""" interface Foo { [CEReactions(DOMString a)] void foo(boolean arg2); }; """) results = parser.finish() except: threw = True harness.ok(threw, "Should have thrown for...
for [CEReactions] used on regular operations. %s" % e) threw = True parser =
parser.reset() threw = False try: parser.parse(""" interface Foo { [CEReactions] readonly attribute boolean A; }; """) results = parser.finish() except: threw = True harness.ok(threw, "Should have thrown for [CEReactions] used on a ...
modalexii/RPi-Environd
config.py
Python
mpl-2.0
2,371
0.007592
# # This is the configuration file for the RPi environd # ### Presentation - General # All datetime stamps use typical strftime codes: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior # The date/time stamp of the last (most current) reading. present_lastread_stamp = "%I:%M %p on %A, %b %d" ...
15) = 96 points. present_recent_point_count = 720 # How much to reduce the specified number of data points. # This is how many points will be drawn. The value of # present_recent_point_count is divided in to this many chunk
s, and then time # stamp and value of each chunk is averaged. present_recent_reduce_to = 16 ### Presentation - All Time Graph # < tbd... not implemented yet > ### Files # The static html file that is output. Must be writable by the user running # environd. Presumably this is in the www directory of a web server....