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 |
|---|---|---|---|---|---|---|---|---|
Kimanicodes/wananchi | app/loans/views.py | Python | mit | 4,187 | 0.000955 | from flask import render_template, flash, redirect, request, url_for, abort
from flask_login import login_user, logout_user, login_required, current_user
from . import loans
from forms import LoanApplicationForm, ApproveLoan, RepayLoan
from ..models import db
from ..models import Loan, User
from datetime import date
... | ())
if loan.loan_amt > loan.user.max_credit_amt:
flash('You can only borrow to a maximum of %s' %
loan.user.max_credit_amt)
return redirect(url_for('loans.request_loan'))
loans.is_requested = True
loan.user.has_requested_loan = Tr... | .Your Loan Application has been submitted.View it below.')
return redirect(url_for('loans.view'))
return render_template('loans/request_loan.html',
form=form, title="New Loan")
@loans.route('/view_history')
@login_required
def view():
if not current_user.is_borro... |
cpennington/edx-platform | lms/djangoapps/discussion/django_comment_client/permissions.py | Python | agpl-3.0 | 10,094 | 0.004557 | # pylint: disable=missing-docstring
"""
Module for checking permissions with the comment_client backend
"""
import logging
import six
from edx_django_utils.cache import DEFAULT_REQUEST_CACHE
from opaque_keys.edx.keys import CourseKey
from lms.djangoapps.teams.models import CourseTeam
from openedx.core.djangoapps.dj... | iscussion_settings(course_id).division_scheme
if (division_scheme is CourseDiscussionSetting | s.NONE
or user_group_id is None
or content_user_group is None
or user_group_id != content_user_group):
return False
return has_permission(user, per, course_id=course_id)
elif isinstance(per, list) and operato... |
tokyo-jesus/tamactiluya | tamactiluya/auth.py | Python | mit | 413 | 0.002421 | # -*- coding: utf-8 -*-
from | flask_login import LoginManager
from tamactiluya.models import User
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'user.login'
@login_manager.user_loader
def user_loader(uname) -> User or None:
"""
:param uname:
:return:
"""
try:
... | cept User.NotFound:
return None |
abilian/abilian-sbe | src/abilian/sbe/apps/documents/webdav/__init__.py | Python | lgpl-2.1 | 121 | 0 | """WebDAV interface to the docum | ent reposit | ory."""
from __future__ import annotations
from .views import webdav # noqa
|
Valchris/tdoa | client/libraries/swamp/chat_example/chat_example/chat/routers.py | Python | mit | 771 | 0 | from swampdragon import route_handler
from swampdragon.route_handler import BaseRouter
class ChatRouter(BaseRouter):
route_name = 'chat-route'
valid_verbs = ['chat', 'subscribe']
def get_subscription_channels(self, **kwargs):
return ['chatroom']
def chat(self, *args, **kwargs):
error... | self.send({'status': 'ok'})
self.publish(self.get_subscription_channels(), | kwargs)
route_handler.register(ChatRouter)
|
sergeyglazyrindev/amigrations | amigrations/adapters/exceptions.py | Python | mit | 36 | 0 | class URIE | rror(Exceptio | n):
pass
|
PMEAL/OpenPNM | openpnm/core/__init__.py | Python | mit | 1,947 | 0 | r"""
Main classes of OpenPNM
=======================
This module contains the main classes from which all other major objects
(Network, Geometry, Physics, Phase, and Algorithm) derive.
The Base class
--------------
The ``Base`` class is a ``dict`` that has added methods for indexing the pores
and throats, applying l... | this is the
Phase that was specified during instantiation.
The associations between an object and it's boss are tracked using labels in
the boss. So a Geometry object named ``geom1`` will put labels 'pore.geom1'
and 'throat.geom1' into the Network dictionary, with ``True`` values indicating
where ``geom1`` applies.
... | -------
`Mixins <https://en.wikipedia.org/wiki/Mixin>`_ are a useful feature of Python
that allow a few methods to be added to a class that needs them. In OpenPNM,
the ability to store and run 'pore-scale' models is not needed by some objects
(Network, Algorithms), but is essential to Geometry, Physics, and Phase
obje... |
polaris-gslb/polaris-core | polaris_common/topology.py | Python | bsd-3-clause | 2,452 | 0.001631 | # -*- coding: utf-8 -*-
import ipaddress
__all__ = [
'config_to_map',
'get_region'
]
def config_to_map(topology_config):
"""
args:
topology_config: dict
{
'region1': [
'10.1.1.0/24',
'10.1.10.0/24',
'172.1... | if len(matches) == 1:
return topology_map[matches[0]]
# if more than 1 match is found, sort the matches
# by prefixlen, return the longest prefixlen entry
elif len(matches) > 1:
matches.sort(key=lambda net: net.prefixlen)
return topology_map[matches[-1]]
# no matches found
... | rn None
|
VaSe7u/Supernutrient_0_5 | hash_check.py | Python | mit | 195 | 0 | from flask_bcrypt import generate_password_hash
# Change the number of rounds (second argument) until it takes betwe | en
# 0.25 and 0.5 seconds to run.
generate_password_h | ash('password1', 8)
|
the-blue-alliance/the-blue-alliance | src/backend/common/consts/award_type.py | Python | mit | 5,567 | 0 | import enum
from typing import Dict, Set
from backend.common.consts.event_type import EventType
@enum.unique
class AwardType(enum.IntEnum):
"""
An award type defines a logical type of award that an award falls into.
These types are the same across both years and competitions within a year.
In other w... | ALIZATION = 54
REALIZATION_HONORABLE_MENTION = 55
DESIGN_YOUR_FUTURE = 56
DESIGN_YOUR_FUTURE_HONORABLE_M | ENTION = 57
SPECIAL_RECOGNITION_CHARACTER_ANIMATION = 58
HIGH_SCORE = 59
TEACHER_PIONEER = 60
BEST_CRAFTSMANSHIP = 61
BEST_DEFENSIVE_MATCH = 62
PLAY_OF_THE_DAY = 63
PROGRAMMING = 64
PROFESSIONALISM = 65
GOLDEN_CORNDOG = 66
MOST_IMPROVED_TEAM = 67
WILDCARD = 68
CHAIRMANS_F... |
crypotex/taas | taas/reservation/handlers.py | Python | gpl-2.0 | 320 | 0.009375 | from taas.reservation.mode | ls import Payment
def delete_payment_before_last_reservation_delete(sender, instance=None, **kwargs):
payment = instance.payment
if payment is None:
return
elif payment.reservation_set.count() == 1 and payment.type == Payment.STAGED:
instance.payment.delete()
| |
karim-omran/openerp-addons | scientific_institutions/wizard/__init__.py | Python | agpl-3.0 | 23 | 0 | import sci_inst | _byname | |
Karel-van-de-Plassche/bokeh | bokeh/application/handlers/code.py | Python | bsd-3-clause | 6,686 | 0.004487 | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2017, Anaconda, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#---------------------------------------------------... | ----------------------------------------------------------------
# Boilerplate
#-----------------------------------------------------------------------------
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
log = logging.getLogger(__name__)
#---------------------------... | andard library imports
import os
import sys
# External imports
# Bokeh imports
from ...io.doc import set_curdoc, curdoc
from .code_runner import CodeRunner
from .handler import Handler
#-----------------------------------------------------------------------------
# Globals and constants
#----------------------------... |
soneoed/naowalkoptimiser | server/MCLLocalisation.py | Python | gpl-3.0 | 26,832 | 0.011777 | """ An SIR Particle Filter based localisation system for tracking a robot with ambiguous bearing
Jason Kulk
"""
from NAO import NAO
import numpy, time
class Localisation:
X = 0
Y = 1
THETA = 2
XDOT = 3
YDOT = 4
THETADOT = 5
STATE_LENGTH = 6
VEL_PAST_LENGTH = 13
def __init__... | asurement
self.previousmeasurementsigma = | self.measurementsigma
self.PreviousStates = numpy.copy(self.States)
def predict(self):
""" Updates each of the particles based on system and control model """
self.modelSystem()
self.modelControl()
def updateWeights(self):
""" """
if not self.st... |
rlee287/pyautoupdate | test/pytest_makevers.py | Python | lgpl-2.1 | 1,008 | 0.001984 | import os
import shutil
import pytest
from ..pyautoupdate.launcher import Launcher
@pytest.fixture(scope='function')
def fixture_update_dir(request):
"""Fixture that creates and tears down version.txt and log files"""
def create_update_dir(version="0.0.1"):
def teardown():
if os.path.isfil... | ir
@pytest.fixture(scope='function')
def create_update_dir(request):
"""Fixture that tears down downloads directory"""
| def teardown():
shutil.rmtree(Launcher.updatedir)
os.remove(Launcher.version_check_log)
request.addfinalizer(teardown)
return create_update_dir
|
wei2912/bce-simulation | utils/coin_var.py | Python | mit | 4,752 | 0.004419 | """
Simulation of a variation of Buffon's Coin Experiment.
The program checks if the coin will balance in addition
to touching one of the lines of the grid.
"""
import random
import math
DEFAULT_TRIALS = 100000
def __convex__hull(points):
"""Computes the convex hull of a set of 2D points.
Input: an iterab... | m. O(n log n) complexity.
Taken from https://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain
"""
# Sort the points lexicographically (tuples are compared lexicographically).
# Remove duplicates to detect the case we have just one unique point.
points = sorted(se... | ct of OA and OB vectors, i.e. z-component of their 3D cross product.
# Returns a positive value, if OAB makes a counter-clockwise turn,
# negative for clockwise turn, and zero if the points are collinear.
def cross(o, a, b):
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
... |
antoinecarme/sklearn_explain | tests/skl_datasets_reg/RandomReg_500/skl_dataset_RandomReg_500_SVR_poly_8_code_gen.py | Python | bsd-3-clause | 149 | 0.006711 | from sklearn_explain.tests.skl_d | atasets_reg import skl_datasets_test as sklte | st
skltest.test_reg_dataset_and_model("RandomReg_500" , "SVR_poly_8")
|
antivirtel/Flexget | flexget/plugins/metainfo/uoccin_lookup.py | Python | mit | 3,924 | 0.004077 | from __future__ import unicode_literals, division, absolute_import
import os
from flexget import plugin
from flexget.event import event
from flexget.utils import json
def load_uoccin_data(path):
udata = {}
ufile = os.path.join(path, 'uoccin.json')
if os.path.exists(ufile):
try:
with o... | .get(str(episode))
entry['uoccin_collected'] = isinstance(edata, list)
entry['uoccin_subtitles'] = edata if entry['uoccin_collected'] else []
entry['uoccin_watched'] = episode in ser.get('watched', | {}).get(season, [])
elif 'imdb_id' in entry:
try:
mov = movies.get(entry['imdb_id'])
except plugin.PluginError as e:
self.log.trace('entry %s imdb failed (%s)' % (entry['imdb_id'], e.value))
continue
... |
qvazzler/Flexget | tests/test_rtorrent.py | Python | mit | 13,663 | 0.001244 | from __future__ import unicode_literals, division, absolute_import
from builtins import * # pylint: disable=unused-import, redefined-builtin
from future.moves.xmlrpc import client as xmlrpc_client
import os
import mock
from flexget.plugins.plugin_rtorrent import RTorrent
torrent_file = os.path.join(os.path.dirname... | roxy.d.start.return_value = 0
client = RTorrent('http://localhost/RPC2')
resp = client.start(torrent_info_hash)
assert resp == 0
assert mocked_proxy.d.start.called_with((torrent_info_hash,))
def test_stop(self, mocked_proxy):
mocked_proxy = mocked_proxy()
mocked_pr... | urn_value = 0
client = RTorrent('http://localhost/RPC2')
resp = client.stop(torrent_info_hash)
assert resp == 0
assert mocked_proxy.d.stop.called_with((torrent_info_hash,))
assert mocked_proxy.d.close.called_with((torrent_info_hash,))
@mock.patch('flexget.plugins.plugin_rtorr... |
KrzysztofStachanczyk/Sensors-WWW-website | www/env/lib/python2.7/site-packages/django/db/migrations/operations/models.py | Python | gpl-3.0 | 29,026 | 0.002136 | from __future__ import unicode_literals
from django.db import models
from django.db.migrations.operations.base import Operation
from django.db.migrations.state import ModelState
from django.db.models.options import normalize_together
from django.utils import six
from django.utils.functional import cached_property
fro... | eturn [
CreateModel(
self.name,
fields=[
| (n, v)
for n, v in self.fields
if n.lower() != operation.name_lower
],
options=self.options,
bases=self.bases,
managers=self.managers,
... |
markreidvfx/pyaaf2 | tests/test_auid.py | Python | mit | 1,210 | 0.002479 | from __future__ import (
unicode_literals,
absolute_import,
print_function,
division,
)
from aaf2.auid import AUID
from uuid import UUID
import uuid
import unittest
class MobIDTests(unittest.Te | stCase):
def test_basic(self):
s = "0d010101-0101-2100-060e-2b3402060101"
v = AUID(s)
u = UUID(s)
assert str(v) == s |
assert str(v.uuid) == s
assert v.uuid == u
def test_be(self):
s = "0d010101-0101-2100-060e-2b3402060101"
v = AUID(s)
u = UUID(s)
assert v.uuid.bytes == v.bytes_be
def test_int(self):
s = "0d010101-0101-2100-060e-2b3402060101"
v = AUID(s)
... |
biswajitsahu/kuma | vendor/packages/translate/storage/test_mo.py | Python | mpl-2.0 | 4,424 | 0.00859 | #!/usr/bin/env python
import os
import subprocess
import sys
from cStringIO import StringIO
from translate.storage import factory, mo, test_base
# get directory of this test
dir = os.path.dirname(os.path.abspath(__file__))
# get top-level directory (moral equivalent of ../..)
dir = os.path.dirname(os.path.dirname(d... | er-Encoding: 8-bit\n"
msgid "plant"
msgstr ""
msgid ""
"_: Noun\n"
"convert"
msgstr "bekeerling"
msgctxt "verb"
msgid ""
"convert"
msgstr "omskakel"
''',
r'''
msgid ""
msgstr ""
"PO-Revision-Date: 2006-02-0 | 9 23:33+0200\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8-bit\n"
msgid "plant"
msgstr ""
msgid ""
"_: Noun\n"
"convert"
msgstr "bekeerling"
msgctxt "verb"
msgid ""
"convert"
msgstr "omskakel"
msgid "tree"
msgid_plural "trees"
msgstr[0] ""
''']
class TestMOFile... |
JonnyJD/rtslib-fb | rtslib/node.py | Python | agpl-3.0 | 8,950 | 0.001453 | '''
Implements the base CFSNode class and a few inherited variants.
This file is part of RTSLib Community Edition.
Copyright (c) 2011 by RisingTide Systems LLC
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Soft... |
'''
import os
| import stat
from utils import fread, fwrite, RTSLibError, RTSLibNotInCFS
class CFSNode(object):
# Where do we store the fabric modules spec files ?
spec_dir = "/var/lib/target/fabric"
# Where is the configfs base LIO directory ?
configfs_dir = '/sys/kernel/config/target'
# TODO: Make the ALUA pat... |
ashang/calibre | src/calibre/ebooks/mobi/debug/mobi6.py | Python | gpl-3.0 | 32,481 | 0.006373 | #!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import struct... | ct.unpack(b'>I', raw[180:184])
if self.tagx_offset != self.header_length:
raise ValueError('TAGX offset and header length disagree')
self.unknown3 = raw[184:self.header_length]
tagx = raw[self.header_length:]
if not tagx.startswith(b' | TAGX'):
raise ValueError('Invalid TAGX section')
self.tagx_header_length, = struct.unpack('>I', tagx[4:8])
self.tagx_control_byte_count, = struct.unpack('>I', tagx[8:12])
self.tagx_entries = [TagX(*x) for x in parse_tagx_section(tagx)[1]]
if self.tagx_entries and not self.tag... |
darky83/E.F.A.-2.x.x.x | build/Sphinx/sphinxapi.py | Python | gpl-3.0 | 34,597 | 0.05434 | #
# $Id$
#
# Python version of Sphinx searchd client (Python API)
#
# Copyright (c) 2006, Mike Osadnik
# Copyright (c) 2006-2013, Andrew Aksyonoff
# Copyright (c) 2008-2013, Sphinx Technologies Inc
# All rights reserved
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the... | BY_YEAR = 3
SPH_GROUPBY_ATTR = 4
SPH_GROUPBY_ATTRPAIR = 5
class SphinxClient:
def __init__ (self):
"""
Create a new client object, and fill defaults.
"""
self._host = 'localhost' # searchd host (default is "localhost")
self._port = 9312 # searchd port (default is 9312)
self._path = None... | sult-set start (default is 0)
self._limit = 20 # how much records to return from result-set starting at offset (default is 20)
self._mode = SPH_MATCH_ALL # query matching mode (default is SPH_MATCH_ALL)
self._weights = [] # per-field weights (default is 1 for all fields)
self._sort = SPH_... |
syllog1sm/TextBlob | text/nltk/tag/simplify.py | Python | mit | 3,411 | 0.004398 | # Natural Lang | uage Toolkit: POS Tag Simplification
#
# Copyright (C) 2001-2013 NLTK Project
# Author: Steven Bird <stevenbird1@gmail.com>
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.TXT
# Brown Corpus
# http://khnt.hit.uib.no/icame/manuals/brown/INDEX.HTM
| brown_mapping1 = {
'j': 'ADJ', 'p': 'PRO', 'm': 'MOD', 'q': 'DET',
'w': 'WH', 'r': 'ADV', 'i': 'P',
'u': 'UH', 'e': 'EX', 'o': 'NUM', 'b': 'V',
'h': 'V', 'f': 'FW', 'a': 'DET', 't': 'TO',
'cc': 'CNJ', 'cs': 'CNJ', 'cd': 'NUM',
'do': 'V', 'dt': 'DET',
'nn': 'N', 'nr': 'N', 'np': 'NP', 'nc': '... |
ejordangottlieb/pyswmap | examples/basic_example.py | Python | mit | 4,881 | 0.002868 | #!/usr/bin/env python
import sys
sys.path.append('..')
from pyswmap import MapCalc
# A quick example showing current module capabilities:
# We create a new instance of class MapCalc and supply the BMR
# with the following values:
# 1. The IPv6 rule prefix: rulev6 (a string)
# 2. The IPv4 rule prefix: rulev4 ... | his will result in the both calculated and validated class variables:
#
# m.rulev4: The IPv4 rule prefix used by a particular
# mapping rule.
#
# m.rulev6: | The IPv6 rule prefix used by a particular
# mapping rule.
#
# m.rulev4mask: The number of bits in the IPv4 rule subnet
# mask.
#
# m.rulev6mask: The number of bits in the IPv6 rule subnet
# ... |
MihaZelnik/Django-Unchained | src/project/apps/web/models.py | Python | mit | 1,716 | 0.000583 | from django_gravatar.helpers import get_gravatar_url, has_gravatar
from django.contrib.auth.models import User
from django.db import models
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='profile')
def __unicode__(self):
return self.user.username
class Meta:
... |
return self. | _get_twitter_avatar('400x400')
else:
return self._get_gravatar(100)
@property
def avatar_small(self):
if self.provider == 'twitter':
return self._get_twitter_avatar('normal')
else:
return self._get_gravatar(30)
@property
def bio(self):
... |
exactassembly/cerise | app/project/models.py | Python | gpl-2.0 | 646 | 0.006192 | from ..app import db
class Step(db.Embedde | dDocument):
action = db.StringField(max_length=255)
workdir = db.StringField(max_length=255)
class SubPro | ject(db.EmbeddedDocument):
id = db.ObjectIdField(required=True, default=lambda: ObjectId())
name = db.StringField(max_length=255)
url = db.StringField(max_length=255)
steps = db.EmbeddedDocumentListField(Step, max_length=25)
class Project(db.EmbeddedDocument):
name = db.StringField(max_length=255)
... |
cloudbase/neutron-virtualbox | neutron/tests/unit/openvswitch/test_ovs_tunnel.py | Python | apache-2.0 | 28,244 | 0 | # Copyright 2012 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 ... | [br_name])
self.mock_int_bridge = self.ovs_bridges[self.INT_BRIDGE]
self.mock_int_bridge.add_port.return_value = self.MAP_TUN_INT_OFPORT
self.mock_int_bridge.add_patch_port.side_effect = (
lambda tap, peer: self.ovs_int_ofports[tap])
self.m | ock_map_tun_bridge = self.ovs_bridges[self.MAP_TUN_BRIDGE]
self.mock_map_tun_bridge.br_name = self.MAP_TUN_BRIDGE
self.mock_map_tun_bridge.add_port.return_value = (
self.MAP_TUN_PHY_OFPORT)
self.mock_map_tun_bridge.add_patch_port.return_value = (
self.MAP_TUN_PHY_OFPORT)
... |
FrodeSolheim/fs-uae-launcher | launcher/apps/dosbox_fs.py | Python | gpl-2.0 | 276 | 0 | import sys
from fsgamesys.plugins.pluginmanager import PluginManager
"""
DOSBox-FS launcher script used for testing.
"""
def app_main():
executable | = PluginManager.instance().find_executable("dosbox-fs")
proc | ess = executable.popen(sys.argv[1:])
process.wait()
|
a10networks/acos-client | acos_client/version.py | Python | apache-2.0 | 641 | 0 | # Copyright 2014, Doug Wiegley, A10 Networks.
#
# 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"... | overning permissions and limitations
# under the License.
VERSION = '2.9.0'
|
oscarbranson/apt-tools | apt_importers.py | Python | gpl-2.0 | 4,972 | 0.007039 | import pandas as pd
import struct
def read_pos(f):
""" Loads an APT .pos file as a pandas dataframe.
Columns:
x: Reconstructed x position
y: Reconstructed y position
z: Reconstructed z position
Da: mass/charge ratio of ion"""
# read in the data
n = len(file(f).read())/4... |
rrngs[['lower','upper','vol']] = rrngs[['lower','upper','vol']].astype(float)
rrngs[['comp','c | olour']] = rrngs[['comp','colour']].astype(str)
return ions,rrngs
def label_ions(pos,rrngs):
"""labels ions in a .pos or .epos dataframe (anything with a 'Da' column)
with composition and colour, based on an imported .rrng file."""
pos['comp'] = ''
pos['colour'] = '#FFFFFF'
for n,r in rrngs... |
perfidia/screensketch | src/screensketch/screenspec/reader/__init__.py | Python | mit | 54 | 0 | from text import TextRead | er
from xml import XML | Reader
|
MaxTyutyunnikov/lino | lino/utils/requests.py | Python | gpl-3.0 | 1,997 | 0.027541 | ## Copyright 2009 Luc Saffre
## This file is part of the Lino project.
## Lino 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.
## L... | )
for k,v in kw.items():
if v is None: # value None means "remove t | his key"
if get.has_key(k):
del get[k]
else:
get[k] = v
path = request.path
if len(args):
path += "/" + "/".join(args)
path = os.path.normpath(path)
path = path.replace("\\","/")
s = get.urlencode()
if len(s):
path += "?" + s
#p... |
agry/NGECore2 | scripts/mobiles/yavin4/geonosian_bunker/enhanced_kliknik.py | Python | lgpl-3.0 | 1,688 | 0.026659 | import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from java.util import Vector
def addTemplate(core):
mobileTemplate = MobileTemplate... | osian_kliknik_force_strong') |
mobileTemplate.setLevel(89)
mobileTemplate.setDifficulty(Difficulty.ELITE)
mobileTemplate.setMinSpawnDistance(4)
mobileTemplate.setMaxSpawnDistance(8)
mobileTemplate.setDeathblow(True)
mobileTemplate.setScale(1)
mobileTemplate.setMeatType("Carnivore Meat")
mobileTemplate.setMeatAmount(45)
mobileTe... |
amadeusproject/amadeuslms | analytics/tests/test_general_dashboard.py | Python | gpl-2.0 | 4,202 | 0.031392 | """
Copyright 2016, 2017 UFPE - Universidade Federal de Pernambuco
Este arquivo é parte do programa Amadeus Sistema de Gestão de Aprendizagem, ou simplesmente Amadeus LMS
O Amadeus LMS é um software livre; você pode redistribui-lo e/ou modifica-lo dentro dos termos da Licença Pública Geral GNU como publicada pela ... |
expected_data = [{'name': 'felipe', 'count': 2}, {'name':'b2', 'c | ount': 1}]
data = self.c.get('/analytics/most_used_tags/')
self.assertEqual(data.status_code, 200 )
self.assertJSONEqual(str(data.content, encoding='UTF-8'), expected_data)
@override_settings(STATICFILES_STORAGE = None) # added decorator
def test_most_accessed_subjects(self):
"""
test if we collect the cor... |
splee/bigdoorkit | tests/test_resource.py | Python | mit | 3,184 | 0.003769 | import os
from nose.too | ls import assert_equal
from nose import SkipTest
from unittest import TestCase
from tests import TEST_APP_KEY, TEST_APP_SECRET
from bigdoorkit.client import Client
from bigdoorkit.resources.leve | l import NamedLevelCollection, NamedLevel
from bigdoorkit.resources.award import NamedAwardCollection, NamedAward
from bigdoorkit.resources.good import NamedGoodCollection, NamedGood
class TestNamedLevelCollection(TestCase):
def setUp(self):
self.client = Client(TEST_APP_SECRET, TEST_APP_KEY)
def tes... |
sebrandon1/neutron | neutron/tests/unit/common/test_utils.py | Python | apache-2.0 | 30,791 | 0.00013 | # Copyright (c) 2012 OpenStack 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
#
# Unless required by applicable... | t eventlet
import mock
import netaddr
from neutron_lib import constants
from neutron_lib import exceptions as exc
from oslo_log import log as logging
import six
import testscenarios
import testtools
from neutron.common import exceptions as n_exc
from neutron.common import utils
from neutron.plugins.common import const... | ort helpers
from neutron.tests.unit import tests
load_tests = testscenarios.load_tests_apply_scenarios
class TestParseMappings(base.BaseTestCase):
def parse(self, mapping_list, unique_values=True, unique_keys=True):
return utils.parse_mappings(mapping_list, unique_values, unique_keys)
def test_parse... |
unnikrishnankgs/va | venv/lib/python3.5/site-packages/tensorflow/contrib/distributions/python/ops/geometric.py | Python | bsd-2-clause | 7,545 | 0.003446 | # Copyright 2017 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... | t absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow... | from tensorflow.python.ops import nn
from tensorflow.python.ops import random_ops
from tensorflow.python.ops.distributions import distribution
from tensorflow.python.ops.distributions import util as distribution_util
class Geometric(distribution.Distribution):
"""Geometric distribution.
The Geometric distributio... |
sposs/DIRAC | TransformationSystem/Agent/MCExtensionAgent.py | Python | gpl-3.0 | 4,963 | 0.032642 | """ Agent to extend the number of tasks given the Transformation definition
"""
from DIRAC import S_OK, gLogger
from DIRAC.Core.Base.AgentModule import AgentModule
from DIRAC.ConfigurationSystem.Client.Helpers.Operations ... | dName, baseAgentName, properties )
self.transClient = TransformationClient()
agentTSTypes = self.am_getOption( 'TransformationTypes', [] )
if agentTSTypes:
self.transformationTypes = sorted( agentTSTypes )
else:
self.transformationTypes = sorted( Operations().getValue( | 'Transformations/ExtendableTransfTypes',
['MCSimulation', 'Simulation'] ) )
self.maxIterationTasks = self.am_getOption( 'TasksPerIteration', 50 )
self.maxFailRate = self.am_getOption( 'MaxFailureRate', 30 )
self.maxWaitingJobs = self.am_getO... |
hlmnrmr/superdesk-core | superdesk/text_utils.py | Python | agpl-3.0 | 4,433 | 0.001805 |
# -*- coding: utf-8; -*-
#
# This file is p | art of Superdesk.
#
# Copyright 2013, 2017 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import re
from lxml import etree # noqa
from superdesk... | ords,
# compound words (e.g. "two-done") or abbreviation (e.g. D.C.)
# If you modify please keep in sync with superdesk-client/core/scripts/apps/authoring/authoring/directives/WordCount.js
WORD_PATTERN = re.compile(r'https?:[^ ]*|([0-9]+[,. ]?)+|([\w]\.)+|[\w][\w-]*')
def get_text_word_count(text):
"""Get word co... |
yzl0083/orange | Orange/OrangeWidgets/Visualize/__init__.py | Python | gpl-3.0 | 266 | 0 | """
=========
Visualize
=========
Widgets for data visualization.
"""
# Category description for the widget registry
NAME = "Visualize"
DESCRIPTION = "Widgets for data visualization. | "
| BACKGROUND = "#FFB7B1"
ICON = "icons/Category-Visualize.svg"
PRIORITY = 2
|
googleapis/python-tasks | samples/generated_samples/cloudtasks_v2beta2_generated_cloud_tasks_cancel_lease_sync.py | Python | apache-2.0 | 1,442 | 0.000693 | # -*- 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... | e_sync]
from google.cloud import tasks_v2beta2
def sample_cancel | _lease():
# Create a client
client = tasks_v2beta2.CloudTasksClient()
# Initialize request argument(s)
request = tasks_v2beta2.CancelLeaseRequest(
name="name_value",
)
# Make the request
response = client.cancel_lease(request=request)
# Handle the response
print(response)
... |
michaelbrooks/uw-message-coding | message_coding/apps/coding/migrations/0007_auto_20150619_2106.py | Python | mit | 744 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
| ('coding', '0006_auto_20150619_2103'),
]
operations = [
migrations.AlterField(
model_name='code',
name='name',
field=models.CharField(default=b'', max_length=150),
),
migrations.AlterField(
model_name='codegroup',
name='nam... | ,
migrations.AlterField(
model_name='scheme',
name='name',
field=models.CharField(default=b'', max_length=150),
),
]
|
DavidAwad/HeroquestBot | app/__init__.py | Python | gpl-2.0 | 184 | 0.01087 | from flask import Flask
from flask import request |
from flask import render_template
from | flask import redirect
from flask import url_for
app = Flask(__name__)
from app import views
|
devananda/ironic | ironic/common/network.py | Python | apache-2.0 | 1,491 | 0 | # Copyright 2014 Rackspace, 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 ag... | rtgroups'] = portgroup_vifs
for port in task.ports:
vif = port.extra.get('vif_port_id')
if vif:
port_vifs[port.uuid] = vif
vifs['p | orts'] = port_vifs
return vifs
|
OpenPLi/enigma2 | lib/python/Components/ImportChannels.py | Python | gpl-2.0 | 6,369 | 0.021667 | import threading
import urllib2
import os
import shutil
import tempfile
from json import loads
from enigma import eDVBDB, eEPGCache
from Screens.MessageBox import MessageBox
from config import config, ConfigText
from Tools import Notifications
from base64 import encodestring
from urllib import quote
from time import sl... | Done(False, _("Error when writing epg.dat on server"))
return
print "[Import Channels] Get EPG Location"
try:
epgdatfile = self.getFallbackSettingsValue(settings, "config.misc.epgcache_filename") or "/hdd/epg.dat"
try:
files = [file for file in loa | ds(self.getUrl("%s/file?dir=%s" % (self.url, os.path.dirname(epgdatfile))).read())["files"] if os.path.basename(file).startswith(os.path.basename(epgdatfile))]
except:
files = [file for file in loads(self.getUrl("%s/file?dir=/" % self.url).read())["files"] if os.path.basename(file).startswith("epg.dat")]
e... |
sysadminmatmoz/odoo-clearcorp | product_invoice_report/__openerp__.py | Python | agpl-3.0 | 1,883 | 0.002124 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Addons modules by CLEARCORP S.A.
# Copyright (C) 2009-TODAY CLEARCORP S.A. (<http://clearcorp.co.cr>).
#
# This program is free software: you can redistribute... | les Management',
'website': "http://clearcorp.co.cr",
'complexity': 'normal',
'images' : [],
'depends': [
'account',
'sale',
'report',
'report_xls_template'
],
'data': [
'views/report_product_invoice_pdf.xml... | roduct_invoice_report_report.xml',
'wizard/wizard.xml',
],
'test' : [],
'demo': [],
'installable': True,
'auto_install': False,
'application': False,
'license': 'AGPL-3',
}
|
davidastephens/pyportfolio | pyportfolio/__init__.py | Python | bsd-3-clause | 131 | 0.007634 | __version__ = version = '0.0.1'
from pypor | tfolio.models import Equity, Option, Future, Account, Trade | , Commodity, Index, Currency
|
nevins-b/lemur | lemur/tests/test_notifications.py | Python | apache-2.0 | 3,324 | 0.003309 | import pytest
from lemur.notifications.views import * # noqa
from .vectors import VALID_ADMIN_HEADER_TOKEN, VALID_USER_HEADER_TOKEN
def test_notification_input_schema(client, notification_plugin, notification):
from lemur.notifications.schemas import NotificationInputSchema
input_data = {
'label'... | nsList), data={}, headers=token).status_code == status
@pytest.mark.parametrize("token,status", [
(VALID_USER_HEADER_TOKEN, 200),
(VALID_ADMIN_HEADER_TOKEN, 200),
('', 401)
])
def test_notification_list_get(client, notification_plugin, notification, token, status):
assert client.get(api.url_for(Notifi... | (VALID_USER_HEADER_TOKEN, 405),
(VALID_ADMIN_HEADER_TOKEN, 405),
('', 405)
])
def test_notification_list_delete(client, token, status):
assert client.delete(api.url_for(NotificationsList), headers=token).status_code == status
@pytest.mark.parametrize("token,status", [
(VALID_USER_HEADER_TOKEN, 405)... |
refnil/CS_Game_Practice | test.py | Python | apache-2.0 | 121 | 0.033058 | def bl | oup(n):
for i in xrange(0,n):
print "%s pikachu lol %d soup | soup" % (" "*(i%10), i)
bloup(666)
|
Donkyhotay/MoonPy | zope/i18n/locales/__init__.py | Python | gpl-3.0 | 22,122 | 0.000271 | ##############################################################################
#
# Copyright (c) 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SO... | d, since all format
information is always provided together. Note that this information by
itself is often not useful, since other calendar data is required to use
the specified pattern for formatting and parsing.
"""
implements(ILocaleFormat)
| def __init__(self, type=None):
"""Initialize the object."""
self.type = type
self.displayName = u''
self.pattern = u''
class LocaleFormatLength(AttributeInheritance):
"""Specifies one of the format lengths of a specific quantity, like
numbers, dates, times and datetimes."""
... |
ahonkela/pol2rna | python/filter_transcript_counts.py | Python | bsd-3-clause | 244 | 0.008197 | # python filter_transcript_co | unts.py < transcript_counts.txt > active_transcripts.txt
import sys
print "Gene\tTranscript\tExpression"
for l in sys.stdin:
t = l.strip().split('\t')
if float(t[2]) > 1.1:
| print '\t'.join(t[0:3])
|
dokipen/trac | trac/web/session.py | Python | bsd-3-clause | 11,069 | 0.000723 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2004-2009 Edgewall Software
# Copyright (C) 2004 Daniel Lundin <daniel@edgewall.com>
# Copyright (C) 2004-2006 Christopher Lenz <cmlenz@gmx.de>
# Copyright (C) 2006 Jonas Borgström <jonas@edgewall.com>
# Copyright (C) 2008 Matt Good <matt@matt-good.net>
# All rights reserved.
#... | sid)
db = sel | f.env.get_db_cnx()
cursor = db.cursor()
self.sid = sid
self.authenticated = authenticated
cursor.execute("SELECT last_visit FROM session "
"WHERE sid=%s AND authenticated=%s",
(sid, int(authenticated)))
row = cursor.fetchone()
... |
valsson/MD-MC-Codes-2016 | MuellerBrown-MD/MD-MuellerBrown.py | Python | mit | 1,665 | 0.013213 | from MuellerBrown import getPotentialAndForces
from PlotUtils import PlotUtils
import numpy as np
import matplotlib.pyplot as plt
import MuellerBrown as mbpot
m=1.0
def getKineticEnergy(velocity):
return 0.5*m*(velocity[0]**2+velocity[1]**2)
dt = 0.01
num_steps = 1000
#initial_position = np.array( [ 0.0 , ... | itial_velocity = np.array( [ 1.0 , -1.0 ] )
position = np.zeros([num_steps+1,2])
velocity = np.zeros([num_steps+1,2])
potential_energy = np.zeros(num_steps+1)
kinetic_energy = np.zeros(num_steps+1)
total_energy = np.zeros(num_steps+1)
times = np.arange(num_steps+1)*dt
time = 0.0
position[0,:] = initial_position
ve... | or i in range(0,num_steps):
# get position at t+dt
position[i+1] = position[i] + velocity[i]*dt+0.5*(force/m)*dt**2
# get velocity at t+dt
(new_pot, new_force) = getPotentialAndForces(position[i+1])
velocity[i+1] = velocity[i] + (0.5/m)*(new_force+force)*dt
# add stuff
kinetic_energy[i+1] = ... |
low-sky/simscript | postproc/pipeline.py | Python | gpl-2.0 | 893 | 0.00224 | import commands
import sys
import postproc_yt as pp
import os
import shutil
targetdir = sys.argv[1]
timestep = float(sys.argv[2])
face = float(sys.argv[3])
level = float(sys.argv[4])
ppdir = os.getenv('PPDIR')
outdir = os.getenv('PPOUTDIR')
D = pp.FileSetup(targetdir, face=face, level=level,
timeste... | mp = D['GasTemp'])
os.chdir(D['TempDir'])
command = ppdir + 'radmc3d image npix ' + \
str(int(D['GridSize']) | ) + \
' iline 1 widthkms 10 linenlam 500 loadlambda fluxcons inclline linelist nostar writepop doppcatch sizepc 10 norefine'
print(command)
result = commands.getoutput(command)
print(result)
save_name = os.path.join(outdir, D['FileName'][17:-5] + '_radmc.fits')
pp.MakeFits(fitsfile=save_name, dpc=260.0, toK=True)... |
anthonyt/mingus-counterpoint | googlecode_upload.py | Python | gpl-3.0 | 9,994 | 0.008505 | #!/usr/bin/env python
#
# !!!!!!!!! WARNING !!!!!!!!!!!!!!!
# This Script was bastardized To Read Password From /home/bspaans/.googlecode
#
#
#
# Copyright 2006, 2007 Google Inc. All Rights Reserved.
# Author: danderson@google.com (David Anderson)
#
# Script for uploading files to a Google Code project.
#
# This is int... | es the mime-type, no need to set it.
'Content-Type: application/octet-stream',
'',
file_content,
])
# Finalize the form body
body.extend(['--' + B | OUNDARY + '--', ''])
return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body)
def upload_find_auth(file_path, project_name, summary, labels=None,
config_dir=None, user_name=None, tries=1):
"""Find credentials and upload a file to a Google Code project's file server.
file_path... |
GGiecold/ECLAIR | src/ECLAIR/Build_instance/ECLAIR_core.py | Python | mit | 58,120 | 0.01139 | #!/usr/bin/env python
# ECLAIR/src/ECLAIR/Build_instance/ECLAIR_core.py
# Author: Gregory Giecold for the GC Yuan Lab
# Affiliation: Harvard University
# Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu
"""ECLAIR is a package for the robust and scalable
inference of cell lineages from gene ex... | port PCA
from sklearn.metrics.pairwise import pairwise_distances
from sklearn.metrics import pairwise_distances_argmin_min
from sklearn.preprocessing import StandardScaler
import subprocess
from sys import exit
import tables
import time
__all__ = ['tree_path_integrals', 'ECLAIR_processing']
Data_info =... | _samples "
"skip_rows cell_IDs_column extra_excluded_columns "
"time_info_column")
AP_parameters = namedtuple('AP_parameters', "clustering_method max_iter "
"convergence_iter")
DBSCAN_parameters = namedtuple('DBSCAN_parameters', "clustering_m... |
kenwilcox/PlayingWithIronPython | PythonLibs.py | Python | mit | 307 | 0.016287 | im | port clr
import xmlutil
clr.AddReference('System.Xml')
from System.Xml import *
d = XmlDocument()
d.Load('C:\Program Files (x86)\IronPython 2.7\Tutorial\load.xml')
n = d.SelectNodes('//Puzzle/SavedGames/Game/@caption')
for e in n:
print e.Value
for e in xmlutil.Walk(d):
prin | t e.Name, e.Value
|
tbleiker/StreamBug | tests/cmd_interface_02_server_clients.py | Python | agpl-3.0 | 3,447 | 0 | #!/usr/bin/env python
# coding: utf-8
#
# StreamBuddy - a video and data streaming serviweng zieleinfahrtce.
# Copyright (c) 2015, Tobias Bleiker & Dumeni Manatschal
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# ... | ITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
#
# Source on github:
# https://github.com/tbleiker/StreamBug
#
import mu... | r
# set up logging
mplogger.setup(debug=True)
log = mplogger.getLogger()
def server_thread(zeromq_context, address, port_pull, port_pub):
server = cmd_interface.Server(zeromq_context, address, port_pull, port_pub)
server.start()
server.join()
def f1_thread(name, role, zeromq_context, address, port_pub,... |
afrachioni/umbrella | tools/plot_hist.py | Python | gpl-3.0 | 556 | 0.034173 | #!/usr/bin/env python
import numpy
import re, os
import matplotlib.pyplot as plt
import pylab
a = 0.8
plt.rc('axes', color_cycle=[[0,0,a], [0,a,0], [a,0,0]])
files = os.listdir('logs')
lookup = sorted([[int(re.search('\d | +', elem).group(0)), elem]
for elem in files], key=lambda x:x[0])
for n, f in lookup:
if not f.endswith('.hist'): continue;
if n % 10 > 0: continue;
x = numpy.loadtxt('logs/' + f, ndmin=2)
if not x.size: conti | nue;
#plt.plot(x[:,2], numpy.log10(x[:,1]))
plt.plot(x[:,2], x[:,1])
pylab.savefig('plot.png')
|
koddsson/coredata-python-client | docs/conf.py | Python | mit | 8,383 | 0.006084 | # -*- coding: utf-8 -*-
""" Sphinx configuration file. """
#
# Coredata API client documentation build configuration file, created by
# sphinx-quickstart on Mon Oct 6 19:20:17 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration value... | .css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If no | t '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document ... |
openvswitch/ovn-scale-test | rally_ovs/plugins/ovs/ovnclients.py | Python | apache-2.0 | 5,955 | 0.002015 | # Copyright 2018 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 agreed to in writing, ... | RandomNameGeneratorMixin
from rally_ovs.plugins.ovs import ovsclients
from rally_ovs.plugins.ovs import utils
LOG = logging.getLogger(__name__)
class OvnClientMixin(ovsclients.ClientsMixin, RandomNameGeneratorMixin):
def _get_ovn_controller(self, install_method="sandbox"):
ovn_nbctl = self.controller_... | ontext['controller']['host_container'])
ovn_nbctl.set_daemon_socket(self.context.get("daemon_socket", None))
return ovn_nbctl
def _start_daemon(self):
ovn_nbctl = self._get_ovn_controller(self.install_method)
return ovn_nbctl.start_daemon()
def _stop_daemon(self):
ovn_n... |
cfelton/gizflo | gizflo/toolchain/_toolflow.py | Python | gpl-3.0 | 3,668 | 0.004362 | # Copyright (c) 2014 Christopher Felton
#
# This program 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.
#
# 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 Lesser General Public License for more details.
#
# You should ... | s/>.
from __future__ import division
from __future__ import print_function
import os
class _toolflow(object):
def __init__(self, brd, top=None, name=None, path='.'):
"""
Provided a myhdl top-level module and board definition
This is the base-class for the various FPGA toolchain... |
pieterdp/serapeum.backup | serapeum/backup/__init__.py | Python | gpl-3.0 | 4,529 | 0.006845 | from serapeum.backup.modules.config.arguments import Arguments
from serapeum.backup.modules.config import Config
from serapeum.backup.modules.log import logger
config = Config(Arguments().config_file)
from serapeum.backup.modules.ds.stack import Stack
from serapeum.backup.modules.files import Files
from serapeum.bac... | ath'],
backup_remote_host=app_config.config['MYSQL']['remote_loc'],
backup_remote_user=app_config.config['MYSQL']['remote_user'],
backup_ssh=app_config.config['MYSQL']['remote_ssh']))
| elif app_config.config['MYSQL'].get('remote_list'):
for remote in Remotes(app_config.config['MYSQL'].get('remote_list')).remotes:
if app_config.config['BACKUP']['remote_role'] == 'source':
destination_path = '{0}/{1}'.format(app_config.config['MYSQL']['backup_path'... |
shiminasai/plataforma_fadcanic | biblioteca/views.py | Python | mit | 1,157 | 0.020743 | from django.shortcuts import render
from .models import Temas, Biblioteca
from django.shortcuts import get_object_or_404
from django.db.models import Q
# Create your views here.
def index(request,template='biblioteca/index.html',slug=None):
temas = Temas.objects.all()
ultimas_guias = Biblioteca.objects.filter(tipo_d... | ia(request, template='biblioteca/lis | ta_guias.html'):
buscar_palabra = request.GET.get('q')
resultado = Biblioteca.objects.filter(tipo_documento=1).filter(Q(titulo__icontains=buscar_palabra) | Q(descripcion__icontains=buscar_palabra))
return render(request, template, locals())
def buscar_tema(request, template='biblioteca/lista_guias.html', id=None... |
tmatth/CloudSound | feldmanesque.py | Python | gpl-3.0 | 6,736 | 0.021229 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2011 Charles Li <chuck@mixed-metaphors.com>
# Copyright (c) 2011 Tristan Matthews <le.businessman@gmail.com>
# This file is part of CloudSound.
# CloudSound is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Pub... | "],feelslike=forecast["feelslike"])
# wind_melody = WindMelody(wspd=forecast["wspd"],wdir=forecast["wdir"],pop=forecast["pop"])
| sounds.append(temp_melody._exc)
sounds.append(temp_melody._exc2)
# sounds.append(wind_melody._exc)
mix = Mix(sounds,2).out()
mixverb = Freeverb(mix,size=0.9,damp=0.95).out()
# reset_sounds(sounds, ambient_sounds)
# update_mixdown(sounds, ambient_sounds)
# update sound data every once in a whi... |
bigmlcom/python | bigml/tests/test_44_compare_predictions.py | Python | apache-2.0 | 22,664 | 0.001456 | # -*- coding: utf-8 -*-
#
# Copyright 2015-2022 BigML
#
# 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 example in examples:
example = dict(zip(headers, example))
| show_method(self, sys._getframe().f_code.co_name, example)
|
bensk/CS9 | _site/Code Examples/March21DoNow.py | Python | mit | 361 | 0.01385 | import random
random.randint(0, 3)
random.randint(0, 3)
print(random.randint(0, 3))
print(random.randint(0, | 3))
print(random.randint(0, 3))
# What does randint do?
# What do the values 0 and 3 do? Try changing those numbers, rerun the program, and write down what changed.
# What is the difference between random.randi | nt(0,3) and print(random.randint(0,3))?
|
vulcansteel/autorest | AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/auto_rest_http_infrastructure_test_service/operations/http_server_failure.py | Python | mit | 6,474 | 0.000618 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | ct response alongside the
deserialized response
:rtype: Error or (Error, requests.response) or
concurrent.futures.Future
"""
# Construct URL
url = '/http/failure/server/505'
# Construct parameters
query_para | meters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if boolean_value is not None:
body_content =... |
quenette/COMPASS-I | t/scripts/test_pycparser.py | Python | apache-2.0 | 289 | 0.031142 | import pycparser
def main_eg():
parser = p | ycparser.CParser()
buf = '''
int main( int argc, char** argv ) {
j = p && r || q;
return j;
}
'''
t = parser.parse( buf, 'x.c' )
return t
if __name__ == "__main__":
t = main_eg()
t.s | how()
|
tehasdf/AdventOfCode2016 | p6.py | Python | mit | 175 | 0.017143 | import sys
from collections | impor | t Counter
rows = zip(*[l.strip() for l in sys.stdin])
print ''.join(Counter(l).most_common()[-1][0] for l in rows) # 0 zamiast -1 dla part1
|
kevin-coder/tensorflow-fork | tensorflow/python/saved_model/simple_save.py | Python | apache-2.0 | 4,171 | 0.001199 | # Copyright 2017 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... | e(session,
export_dir,
inputs={"x": x, "y": y},
outputs={"z": z})
Although in many cases it's not necessary to understand all | of the many ways
to configure a SavedModel, this method has a few practical implications:
- It will be treated as a graph for inference / serving (i.e. uses the tag
`tag_constants.SERVING`)
- The SavedModel will load in TensorFlow Serving and supports the
[Predict
API](https://github.com... |
pseudo-cluster/pseudo-cluster | scripts/run_pseudo_tasks_slurm.py | Python | lgpl-2.1 | 7,019 | 0.011711 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import argparse
import datetime
import time
import gettext
from pseudo_cluster.task import Task_record
from pseudo_cluster.tasks_list import Tasks_list
from pseudo_cluster.extended_task import Extended_task_record
from pseudo_cluster.actions_list impor... | actions_list.register_action(extended_tasks[task.job_id],"canc | el")
actions_list.do_actions(args.compress_times)
print begin_time
print end_time
print "last_task=%d, num_tasks=%d" % (last_task,num_tasks)
delay_value = datetime.datetime.utcnow()- begin_actions_time
if delay_value < datetime.timedelta(minutes=... |
teodoc/home-assistant | homeassistant/components/sensor/efergy.py | Python | mit | 4,293 | 0 | """
homeassistant.components.sensor.efergy
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Monitors home energy use as measured by an efergy
engage hub using its | (unofficial, undocumented) API.
Configuration:
To use the efergy sensor you will need to add something
like the following to your config/co | nfiguration.yaml
sensor:
platform: efergy
app_token: APP_TOKEN
utc_offset: UTC_OFFSET
monitored_variables:
- type: instant_readings
- type: budget
- type: cost
period: day
currency: $
Variables:
api_key
*Required
To get a new App Token, log in to your efergy account, go
to the Setting... |
hodgesds/streamparse | streamparse/cli/quickstart.py | Python | apache-2.0 | 643 | 0 | """
Create new streamparse project template.
"""
from __future__ import absolute_import
from streamparse.bootstrap import quickstart
def subparser_hook(subparsers):
""" Hook to add subparser for this command. """
subparser = subparsers.add_parser('quickstart',
descripti... | .project_na | me)
|
JCHappytime/MyQuantopian | strategies/strategy.py | Python | gpl-2.0 | 3,094 | 0.004848 | #!/usr/bin/env python
LICENSE="""
Copyright (C) 2011 Michael Ihde
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 progra... | l] = {}
self.indicators[symbol][name] = indicator
if self.h5file != None:
try:
| symgroup = self.h5file.getNode(self.indicator_h5group._v_pathname, symbol, classname="Group")
except tables.NoSuchNodeError:
symgroup = self.h5file.createGroup(self.indicator_h5group._v_pathname, symbol)
if self.h5file and self.indicator_h5group:
indicator.setu... |
penglee87/flaskweb | config.py | Python | mit | 1,488 | 0.004704 | import os
import pymysql
pymysql.install_as_MySQLdb()
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
MAIL_SERVER = 'smtp.163.com'
MAIL_PORT = 25
MAIL_USE_TLS = True
MAIL... | _FOLLOWERS_PER_PAGE = 50
FLASKY_COMMENTS_PER_PAGE = 30
DEBUG = True
@staticmethod
def init_app(app):
pass
class DevelopmentConfig(Config):
SQLALCHEMY_DATABASE_URI = os.environ.get('DEV_DATABASE_URL') or 'mysql:// | flasky:flasky@127.0.0.1/flasky'
#'sqlite:///' + os.path.join(basedir, 'data-dev.sqlite')
#'mysql+pymysql://flask:flask@127.0.0.1/flask'
#'mysql://flasky:flasky@127.0.0.1/flasky'
class TestingConfig(Config):
TESTING = True
SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL') or... |
pbecotte/devblog | backend/blog/utils.py | Python | mit | 2,165 | 0.000462 | from flask import request, abort, jsonify, render_template
from flask.ext.sqlalchemy import BaseQuery
import math
class PaginatedQuery(object):
def __init__(self, query_or_model, paginate_by, page_var='page',
check_bounds=False):
self.paginate_by = paginate_by
self.page_var = page... | r_model, BaseQuery):
self.query = query_or_model
else:
self.model = query_or_model
self.query = self.model.all()
def get_page(self):
curr_page = request.args.get(self.page_var)
if curr_page and curr_page.isdigit():
return max(1, int(curr_page)... | il(float(self.query.count()) / self.paginate_by))
def get_object_list(self):
if self.get_page_count() == 0:
return []
if self.check_bounds and self.get_page() > self.get_page_count():
abort(404)
return self.query.paginate(self.get_page(), self.paginate_by).items
d... |
glennyonemitsu/MarkupHiveServer | src/model/admin.py | Python | mit | 506 | 0 | import base64
import hashlib |
import json
import os
import bcrypt
from sqlalchemy.orm.exc import NoResultFound
from server_global import db
class Admin(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(100), nullable=False, unique=True)
password = db.Column(db.String(60), nullable=False)
d... | urn match
|
tsnoam/Flexget | flexget/api/authentication.py | Python | mit | 3,365 | 0.00208 | import base64
from flask import request, jsonify, session as flask_session
from flask.ext.login import login_user, LoginManager, current_user, current_app
from flexget.api import api, APIResource, app
from flexget.webserver import User
from flexget.utils.database import with_session
login_manager = LoginManager()
lo... | .request_loader
@with_session
def load_user_from_request(request, session=None):
auth_value = request.headers.get('Authorization')
if not auth_value:
return
# Login using api key
if auth_value.startswith('Token'):
try:
token = auth_value.replace('Token ', '', 1)
... | token).first()
except (TypeError, ValueError):
pass
# Login using basic auth
if auth_value.startswith('Basic'):
try:
credentials = base64.b64decode(auth_value.replace('Basic ', '', 1))
username, password = credentials.split(':')
return session.qu... |
InakiZabala/odoomrp-wip | product_packaging_through_attributes/__openerp__.py | Python | agpl-3.0 | 1,619 | 0 | # -*- encoding: utf-8 -*-
##############################################################################
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the... | ://www.odoomrp.com",
"contributors": [
"Oihane Crucelaegui <oihanecrucelaegi@avanzosc.es>",
"Pedro M. Baeza <pedro.baeza@serviciosbaeza.com>",
"Ana Juaristi <ajuaristio@gmail.com>"
],
"category": "Custom Module",
| "summary": "",
"data": [
"views/product_view.xml",
"views/res_partner_view.xml",
],
"installable": True,
"auto_install": False,
}
|
jacekdalkowski/bike-timer | web-database/db_migrations/migrate.py | Python | apache-2.0 | 2,224 | 0.022932 |
# migrate.py [up|seed|down] [local|docker]
# e.g. migrate.py up docker
import sys
import os
import re
from subprocess import call, check_output
from operator import itemgetter, attrgetter, methodcaller
CASSANDRA_PATH_LOCAL = '/Users/jacekdalkowski/Dev/_cassandra/apache-cassandra-3.0.0/bin/'
ARTIFACTS_PATH_LOCAL = '/... | H_LOCAL
artifacts_path = ARTIFACTS_PATH_LOCAL
elif env == 'docker':
cassandra_path = CASSANDRA_PATH_DOCKER
artifacts_path = ARTIFACTS_PATH_DOCKER
files = []
for file in os.listdir(current_dir):
if file.endswith(file_sufix):
files += [file]
prefix_and_files = map(lambda f: { 'id': filename_prefix_to_int... | les = filter(lambda pf: pf['id'], prefix_and_files)
sorted_int_prefix_and_files = sorted(prefix_and_files, key=lambda d: d['id'], reverse=reverse)
print sorted_int_prefix_and_files
for file in sorted_int_prefix_and_files:
cqlsh_path = cassandra_path + 'cqlsh'
source_arg = 'SOURCE \'' + artifacts_path + '/' + fil... |
mitsuhiko/sentry | src/sentry/api/endpoints/group_environment_details.py | Python | bsd-3-clause | 2,927 | 0.000342 | from __future__ import absolute_import
from rest_framework.response import Response
from sentry.api.base import StatsMixin
from sentry.api.bases.group import GroupEndpoint
from sentry.api.exceptions import ResourceDoesNotExist
from sentry.api.serializers import serialize
from sentry.api.serializers.models.environment... | se(c | ontext)
|
andreymal/mini_fiction | mini_fiction/dumpload.py | Python | gpl-3.0 | 18,621 | 0.001913 | import os
import sys
from datetime import datetime
from io import BytesIO
from pathlib import Path
from typing import List
from zipfile import ZIP_DEFLATED, ZipFile, ZipInfo
from mini_fiction import ponydump
from mini_fiction.logic.image import SavedImage
# Вообще всё будет работать и без этих exclude, но выкидывание... | тся только один системный пользователь
'include': (
'bio', 'date_joined', 'first_name', 'image_bundle',
'id', 'is_active', 'is_staff', 'is_superuser', 'last_name', 'last_visit', 'username',
'activated_at', 'last_login', 'text_source_behaviour',
),
'exclude': (... | st_viewed_notification_id', 'nsfw', 'premoderation_mode', 'last_password_change',
'silent_email', 'silent_tracker', 'comments_per_page', 'header_mode', 'extra',
'ban_reason', 'published_stories_count', 'all_story_comments_count', 'timezone',
'session_token',
),
'overr... |
thomasvdv/flightbit | forecast/keys_iterator.py | Python | gpl-2.0 | 1,140 | 0.001754 | import traceback
import sys
from gribapi import *
INPUT = 'rap_130_20120822_2200_001.grb2'
VERBOSE = 1 # verbose error reporting
def example():
f = open(INPUT)
while 1:
gid = grib_new_from_file(f)
if gid is None: break
iterid = grib_keys_iterator_new(gid, 'ls')
# Differen... | _iterator_get_name(iterid)
keyval = grib_get_string(iterid, keyname)
print "%s = %s" % (keyname, keyval)
grib_keys_iterator_delete(iterid)
grib_release(gid)
f.close()
def main():
try:
example()
except GribInternalError, er | r:
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
print >> sys.stderr, err.msg
return 1
if __name__ == "__main__":
sys.exit(main()) |
janusnic/shoop | shoop/front/utils/product_sorting.py | Python | agpl-3.0 | 1,352 | 0 | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from django.utils.translation import ugettext_lazy as _
PRODUCT_SORT_CHOI... | r().strip()
def _get_product_name_lowered(produ | ct):
return product.name.lower()
def _get_product_price_getter_for_request(request):
def _get_product_price(product):
return product.get_price(request)
return _get_product_price
|
ejona86/grpc | src/python/grpcio_tests/tests_aio/unit/_constants.py | Python | apache-2.0 | 816 | 0 | # Copyright 2020 The gRPC Authors
#
# Licensed under the Apa | che License, Version 2.0 (the "License");
# you may not use thi | s 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... |
jasonrbriggs/stomp.py | tests/test_override_threading.py | Python | apache-2.0 | 1,654 | 0 | import logging
from concurrent.futures import ThreadPoolExecutor
import stomp
from stomp.listener import TestListener
from .testutils import *
executor = ThreadPoolExecutor()
def create_thread(fc):
f = executor.submit(fc)
print("Created future | %s on executor %s" % (f, executor))
return f
class ReconnectListener(TestListener):
def __in | it__(self, conn):
TestListener.__init__(self, "123", True)
self.conn = conn
def on_receiver_loop_ended(self, *args):
if self.conn:
c = self.conn
self.conn = None
c.connect(get_default_user(), get_default_password(), wait=True)
c.disconnect()
... |
MrAlexDeluxe/Zeeguu-Web | zeeguu_web/app.py | Python | mit | 1,825 | 0.006027 | # -*- coding: utf8 -*-
import os
import os.path
import flask
import flask_assets
im | port flask_sqlalchemy
from .cross_domain_app import CrossDomainApp
from zeeguu.util.configuration import load_config | uration_or_abort
import sys
if sys.version_info[0] < 3:
raise "Must be using Python 3"
# *** Starting the App *** #
app = CrossDomainApp(__name__)
load_configuration_or_abort(app, 'ZEEGUU_WEB_CONFIG',
['HOST', 'PORT', 'DEBUG', 'SECRET_KEY', 'MAX_SESSION',
... |
odoo-colombia/l10n-colombia | account_tax_group_type/__manifest__.py | Python | agpl-3.0 | 636 | 0.001577 | # -*- coding: utf-8 -*-
# Copyright 2019 Joan Marín <Github@JoanMarin>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Tax Group Types",
"category": "Financial", |
"version": "10.0.1.0.0",
"author": "EXA Auto Parts Github@exaap, "
"Joan Marín Github@JoanMarin",
"website": "https://github.com/odooloco/l10n-colombia",
"license": "AGPL-3",
"summary": "Types for Tax Groups",
"depends": [
"account_tax_group_menu",
],
"data": [
... | p_views.xml",
],
"installable": True,
}
|
openstack/neutron-lib | neutron_lib/api/definitions/network_segment_range.py | Python | apache-2.0 | 5,876 | 0 | # Copyright (c) 2018 Intel Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | ert_to': converters.convert_to_int,
'validate': {'type:range': NETWORK_SEGMENT_RANGE_LIMIT},
'is_visible': True},
'used': {'allow_post': False,
'allow_put': False,
'is_visible': True},
'available': {'allow_post': False,
... | 'is_visible': True}
}
}
# Whether or not this extension is simply signaling behavior to the user
# or it actively modifies the attribute map.
IS_SHIM_EXTENSION = False
# Whether the extension is marking the adoption of standardattr model for
# legacy resources, or introducing new standardattr at... |
PARINetwork/pari | core/utils.py | Python | bsd-3-clause | 5,677 | 0.002818 | from __future__ import print_function
import datetime
from collections import OrderedDict
from django.urls import reverse
from django.http import JsonResponse
from django.utils.translation import get_language, activate
from wagtail.core import blocks
from wagtail.core.models import Page
from wagtail.core.rich_text imp... | s.extend(trans_holder.get_children().live().specific()) |
except Page.DoesNotExist:
# Check if page exists within the translation folder
parent = page.get_parent()
if parent.title == "Translations":
if parent.get_parent().live:
translations.append(parent.get_parent().specific)
live_children = parent.get_chil... |
jnayak1/osf-meetings | meetings/meetings/wsgi.py | Python | apache-2.0 | 393 | 0 | """
WSGI config for | meetings project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS | _MODULE", "meetings.settings")
application = get_wsgi_application()
|
albertz/music-player | mac/pyobjc-framework-Quartz/PyObjCTest/test_ciplugininterface.py | Python | bsd-2-clause | 488 | 0.006148 |
from PyObjCTools.TestSupport import *
from Quartz.QuartzCore import *
| from Quartz import *
class TestCIPluginInterfaceHe | lper (NSObject):
def load_(self, h): return 1
class TestCIPlugInInterface (TestCase):
def testMethods(self):
self.assertResultIsBOOL(TestCIPluginInterfaceHelper.load_)
def no_testProtocol(self):
p = objc.protocolNamed('CIPlugInRegistration')
self.assertIsInstancE(p, objc.formal_pro... |
brotchie/keepnote | keepnote/notebook/connection/__init__.py | Python | gpl-2.0 | 11,118 | 0.004767 | """
KeepNote
Low-level Create-Read-Update-Delete (CRUD) interface for notebooks.
"""
#
# KeepNote
# Copyright (c) 2008-2011 Matt Rasmussen
# Author: Matt Rasmussen <rasmus@alum.mit.edu>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Genera... | onnectionError.__init__(self, msg)
class FileError (ConnectionError):
def __init__(self, msg="file error", error=None):
ConnectionError.__init__(self, msg, error)
class UnknownFile (FileError):
def __init__(self, msg="unknown fi | le"):
FileError.__init__(self, msg)
class CorruptIndex (ConnectionError):
def __init__(self, msg="index error", error=None):
ConnectionError.__init__(self, msg, error)
#=============================================================================
# file path functions
def path_join(*parts):... |
Yelp/mycroft | mycroft/tests/backend/test_etl_helper.py | Python | mit | 2,789 | 0.000359 | # -*- coding: utf-8 -*-
import pytest
from tests.models.test_etl_record import etl_records # noqa
from tests.models.test_abstract_records import dynamodb_connection # noqa
from mycroft.backend.worker.etl_status_helper import ETLStatusHelper
import mock
RECORDS = [
{'status': 'error', 'date': '2014-09-01', 'star... |
# test case: no previous record
etl.etl_step_complete(MSG, date, step, r)
# test case: existing record
etl.etl_step_started(MSG, date, | step)
etl.etl_step_complete(MSG, date, step, r)
entry = etl.etl_db.get(hash_key='some-uuid', data_date=date)
entry_dict = entry.get(**KWARGS)
assert entry_dict['hash_key'] == 'some-uuid'
assert entry_dict['data_date'] == date
if entry_dict['etl_... |
jogo279/trobo | opponents/corey_abshire/tronmoves.py | Python | bsd-2-clause | 4,160 | 0.001442 | # tronmoves: Moves library for a Google AI 2010 TronBot entry.
# Copyright (C) 2010 Corey Abshire
#
# 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... | ef follow_path_move(board, path):
"Follow the given path."
return move_made(board.me(), path[1])
def same_dist_move(board, same_dist, order):
"Try to draw a line through the same distance tiles."
first_point = same_dist[0]
last_point = same_dist[-1]
if board.passable(first_point):
path... | path = shortest_path(board, board.me(), last_point)
return move_made(board.me(), path[1])
else:
return most_open_move(board, order)
#_____________________________________________________________________
# Experimental Moves (tried, but not in use)
#
def chunky_minimax_move(board, chunk_si... |
alaudet/hcsr04sensor | recipes/cylinder_volume_side_metric.py | Python | mit | 844 | 0 | """Calculate the liquid volume of a cylinder on its side"""
from hcsr04sensor import sensor
trig_pin = 17
echo_pin = 27
# default values
# temperature = 20 celcius
# unit = "metric"
# gpio_mode = GPIO | .BCM
# Get litres in a cylinder
cyl_length_metric = 300 # centimeters
cyl_radius_metric = 48 # centimeters
cyl_depth = 96 # cm from sensor to bottom
value = sensor.Measurement(trig_pin, echo_pin)
# for imperial add temp and unit and change all cm values to inches
# value = | sensor.Measurement(trig_pin, echo_pin, 68, 'imperial')
distance = value.raw_distance()
water_depth_metric = value.depth(distance, cyl_depth)
volume_litres = value.cylinder_volume_side(
water_depth_metric, cyl_length_metric, cyl_radius_metric
)
print(
"The liquid volume of the cylinder on its side {} litres".for... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.