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
tao12345666333/tornado-zh
tornado/test/twisted_test.py
Python
mit
27,525
0.000327
# Author: Ovidiu Predescu # Date: July 2011 # # 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 ...
er have_twisted = True except ImportError: have_twisted = False # The core of Twisted 12.3.0 is available on python 3, but twisted.web is not # so test for it separately. try: from twisted.web.client import Agent, readBody from twisted.web.resource import Resource from twisted.web.server import Sit...
version_info < (3,) except ImportError: have_twisted_web = False try: import thread # py2 except ImportError: import _thread as thread # py3 from tornado.escape import utf8 from tornado import gen from tornado.httpclient import AsyncHTTPClient from tornado.httpserver import HTTPServer from tornado.ioloo...
fepe55/RAMB0
python/huffman2.py
Python
mit
6,447
0.005119
#!/usr/bin/python # -*- encoding: utf-8 -*- import os import marshal import cPickle import array class HuffmanNode(object): recurPrint = False def __init__(self, ch=None, fq=None, lnode=None, rnode=None, parent=None): self.L = lnode self.R = rnode self.p = parent self.c = ch ...
8 class Encoder(object): def __init__(self, filename_or_long_str=None): if filename_or_long_str: if os.pat
h.exists(filename_or_long_str): self.encode(filename_or_long_str) else: #print '[Encoder] take \'%s\' as a string to be encoded.'\ # % filename_or_long_str self.long_str = filename_or_long_str def __get_long_str(self): return ...
Jc2k/libcloud
docs/examples/compute/openstack_simple.py
Python
apache-2.0
610
0
from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver import libcloud.security # T
his assumes you don't have SSL set up. # Note: Code like this poses a security risk (MITM attack) and # that's the reason why you should never use it for anything else # besides testing. You have been warned. libcloud.security.VERIFY_SSL_CERT = False OpenStack = get_driver(Provider.OPENSTACK) driver = OpenStack('your_...
force_auth_version='2.0_password')
catapult-project/catapult
telemetry/telemetry/story/expectations.py
Python
bsd-3-clause
9,428
0.005834
# Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import absolute_import from telemetry.core import os_version as os_version_module # TODO(rnephew): Since TestConditions are being used for ...
oard def ShouldDisable(self, platform, finder_options): return (platform.GetOSName() == 'fuchsia' and platform.GetDeviceTypeName() == self._board) def __str__(self): return 'Fuchsia on ' + self._board def GetSupportedPlatformNames(self): return {'fuchsia', 'fuchsia-board-' + self._board...
ndConditions(_TestCondition): def __init__(self, conditions, name): self._conditions = conditions self._name = name def __str__(self): return self._name def GetSupportedPlatformNames(self): platforms = set() for cond in self._conditions: platforms.update(cond.GetSupportedPlatformNames(...
andmos/ansible
test/units/modules/storage/netapp/test_na_ontap_lun_copy.py
Python
gpl-3.0
5,814
0.00172
# (c) 2018, NetApp, Inc # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ''' unit test template for ONTAP Ansible module ''' from __future__ import print_function import json import pytest from units.compat import unittest from units.compat.mock import patch, Mock from ans...
path, destination_path' expected = sorted(','.split(msg)) received = sorted(','.split(exc.value.args[0]['msg'])) assert expected == received def test_successful_copy(self): ''' Test successful create ''' # data = self
.mock_args() set_module_args(self.mock_args()) with pytest.raises(AnsibleExitJson) as exc: self.get_lun_copy_mock_object().apply() assert exc.value.args[0]['changed'] def test_copy_idempotency(self): ''' Test create idempotency ''' set_module_args(self.mock_args(...
aronsky/home-assistant
homeassistant/components/uptimerobot/entity.py
Python
apache-2.0
1,942
0.000515
"""Base UptimeRobot entity.""" from __future__ import annotations from pyuptimerobot import UptimeRobotMonitor from homeassistant.helpers.entity import DeviceInfo, EntityDescription from homeassistant.helpers.update_coordinator import ( CoordinatorEntity, DataUpdateCoordinator, ) from .const import ATTR_TARG...
r.friendly_name, manufacturer="UptimeRobot Team", entry_type="service", model=self.monitor.type.name, configuration_url=f"https://uptimerobot.com/dashboard#{self.monitor.id}", ) self._a
ttr_extra_state_attributes = { ATTR_TARGET: self.monitor.url, } self._attr_unique_id = str(self.monitor.id) @property def _monitors(self) -> list[UptimeRobotMonitor]: """Return all monitors.""" return self.coordinator.data or [] @property def monitor(self) -...
abonaca/gary
gary/util.py
Python
mit
3,607
0.001941
# coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging....
self._hash = None def __getitem__(self,
key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other)...
jopohl/urh
src/urh/controller/widgets/DeviceSettingsWidget.py
Python
gpl-3.0
24,781
0.00339
from statistics import median import numpy as np from PyQt5.QtCore import QRegExp, pyqtSlot, pyqtSignal from PyQt5.QtGui import QRegExpValidator, QIcon from PyQt5.QtWidgets import QWidget, QSpinBox, QLabel, QComboBox, QSlider from urh import settings from urh.dev import config from urh.dev.BackendHandler import Backe...
self.on_check_box_dc_correction_clicked) def set_gain_defaults(self): self.set_default_rf_gain() self.set_default_if_gain() self.set
_default_bb_gain() def set_default_rf_gain(self): conf = self.selected_device_conf pre
gkc1000/pyscf
pyscf/shciscf/examples/03_c2_diffsymm.py
Python
apache-2.0
1,773
0.002256
#!/usr/bin/env python
# Copyright 2014-2019 The PySCF Developers. 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 agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHO...
geimer/easybuild-framework
test/framework/toy_build.py
Python
gpl-2.0
33,739
0.004742
# # # Copyright 2013-2014 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en), # the Hercules foundation (ht...
rtTrue(success.search(outtxt), "COMPLETED message found in '%s" % outtxt) # if the module exists, it should be fine toy
_module = os.path.join(installpath, 'modules', 'all', 'toy', full_version) msg = "module for toy build toy/%s found (path %s)" % (full_version, toy_module) self.assertTrue(os.path.exists(toy_module), msg) # module file is symlinked according to moduleclass toy_module_symlink = os.path.j...
repotvsupertuga/repo
script.module.stream.tvsupertuga.addon/resources/lib/indexers/episodes.py
Python
gpl-2.0
65,914
0.011909
# -*- coding: utf-8 -*- ''' flixnet Add-on Copyright (C) 2016 flixnet 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...
fanart')[0]
except: fanart = '' if not fanart == '': fanart = self.tvdb_image + fanart else: fanart = '0' fanart = client.replaceHTMLCodes(fanart) fanart = fanart.encode('utf-8') if not poster == '0': pass elif not fanart == '0': poster = fanart ...
Erethon/synnefo
snf-astakos-app/astakos/im/views/target/redirect.py
Python
gpl-3.0
4,711
0
# Copyright (C) 2010-2014 GRNET S.A. # # 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 i...
parts = list(urlsplit(next)) parts[3] = urlencode({ 'uuid': request.user.uuid, 'token': request.user.auth_token }) url = urlunsplit(parts) response['Location'] = url response.status_code = 302 return response else: # redirect to login w...
t(parse_qsl(parts[3], keep_blank_values=True)) # delete force parameter if 'force' in params: del params['force'] parts[3] = urlencode(params) next = urlunsplit(parts) # build url location parts[2] = reverse('login') params = {'next': next} pa...
seanfisk/ecs
ecs/managers.py
Python
mit
8,344
0
"""Entity and System Managers.""" import six from ecs.exceptions import ( NonexistentComponentTypeForEntity, DuplicateSystemTypeError, SystemAlreadyAddedToManagerError) from ecs.models import Entity class EntityManager(object): """Provide database-like access to components based on an entity key.""" ...
ity, renderable_component in \ entity_manager.pairs_for_type(Renderable): pass # do something :param component_type: a type of created component :type component_type: :clas
s:`type` which is :class:`Component` subclass :return: iterator on ``(entity, component_instance)`` tuples :rtype: :class:`iter` on (:class:`ecs.models.Entity`, :class:`ecs.models.Component`) """ try: return six.iteritems(self._database[component_type]...
Hearen/OnceServer
Server/Eve/post.py
Python
mit
12,002
0.000167
# -*- coding: utf-8 -*- """ eve.methods.post ~~~~~~~~~~~~~~~~ This module imlements the POST method, supported by the resources endopints. :copyright: (c) 2015 by Nicola Iarocci. :license: BSD, see LICENSE for more details. """ from datetime import datetime from flask import current_app as a...
d. Support for new validation format introduced with Cerberus v0.5. .. versionchanged:: 0.2 Use the new STATUS setting. Use the new ISSUES setting. Raise '
on_pre_<method>' event. Explictly resolve default values instead of letting them be resolved by common.parse. This avoids a validation error when a read-only field also has a default value. Added ``on_inserted*`` events after the database insert .. versionchanged:: 0.1.1 auth.req...
hzlf/openbroadcast
website/apps/invitation/views.py
Python
gpl-3.0
7,841
0.000893
from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.template import RequestContext from django.shortcuts import render_to_response from django.utils.translation import ugettext from django.contrib.auth.decorators import login_required from django.contrib.admin.views.dec...
invitation_complete')) else: form = form_class() context = apply_extra_context(RequestContext(request), extra_context) return rende
r_to_response(template_name, {'form': form}, context_instance=context) def register(request, invitation_key, wrong_key_template='invitation/wrong_invitation_key.html', redirect_to_if_authenticated='/', succ...
sunlightlabs/horseradish
photolib/search_indexes.py
Python
bsd-3-clause
592
0.001689
from haystack import indexes from photolib.models import Photo class PhotoIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=Tru
e, use_template=True) alt = indexes.CharField(model_attr='alt', indexed=False) uuid = indexes.CharField(model_attr='uuid', indexed=False) thumbnail_url
= indexes.CharField(indexed=False, model_attr='image_thumbnail__url') def get_model(self): return Photo def get_updated_field(self): return 'last_updated' def index_queryset(self, using=None): return Photo.objects.visible()
HBEE/odoo-addons
account_journal_security/res_users.py
Python
agpl-3.0
741
0.008097
# -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in mod
ule root # directory ############################################################################## from openerp.osv
import osv, fields class users(osv.osv): _name = 'res.users' _inherit = 'res.users' _columns = { 'journal_ids': fields.many2many('account.journal', 'journal_security_journal_users','user_id', 'journal_id', 'Restricted Journals', help="This journals and t...
Microvellum/Fluid-Designer
win64-vc/2.78/scripts/addons/io_scene_ms3d/ms3d_utils.py
Python
gpl-3.0
5,817
0.002235
# ##### BEGIN GPL LICENSE BLOCK ##### # # 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 distrib...
_difference(mat_src, mat_dst): mat_dst_inv = mat_dst.inverted() return mat_dst_inv * mat_src ############################################################################### ############################################################################### #2345678901234567890123456789012345678901234567890123456...
4567890123456789 #--------1---------2---------3---------4---------5---------6---------7--------- # ##### END OF FILE #####
rochapps/django-datamaps
datamaps/__init__.py
Python
bsd-2-clause
103
0
""" Django-Datamaps
provides helper functions compatible with datamaps.js. """
__version__ = '0.2.2'
benjamin-hodgson/build
test/evaluate_callables_tests.py
Python
mit
2,020
0.001485
from build import evaluate_callables class WhenEvaluatingAD
ictWithNoCallables: def when_i_evaluate_the_dict(self): self.result = evaluate_callables
({"abc": 123, "def": 456, "xyz": 789}) def it_should_return_the_same_dict(self): assert self.result == {"abc": 123, "def": 456, "xyz": 789} class WhenEvaluatingADictWithCallables: def given_input_containing_lambdas(self): self.input = {"abc": lambda: 123, "def": lambda: 456, "xyz": 789} ...
guibernardino/mezzanine
mezzanine/core/defaults.py
Python
bsd-2-clause
18,350
0.004741
""" Default settings for the ``mezzanine.core`` app. Each of these can be overridden in your project's settings module, just like regular Django settings. The ``editable`` argument for each controls whether the setting is editable via Django's admin. Thought should be given to how a setting is actually used before mak...
ndo Wii", "Nitro", "Nokia", "Opera Mini", "Palm", "PlayStation Portable", "portalmmm", "Proxinet", "ProxiNet", "SHARP-TQ-GX10", "SHG-i900", "Small", "SonyEricsson", "Symbian OS", "SymbianOS", "TS21i-10", "UP.Browser", "UP.Link", "webOS", "Windows CE", "WinWAP"...
"BlackBerry9530", "LG-TU915 Obigo", "LGE VX", "webOS", "Nokia5800",) ), ), ) register_setting( name="FORMS_USE_HTML5", description=_("If ``True``, website forms will use HTML5 features."), editable=False, default=False, ) register_setting( name="EXTRA_MODEL_FIELDS", ...
LogicalDash/kivy
kivy/core/camera/__init__.py
Python
mit
4,415
0
''' Camera ====== Core class for acquiring the camera and converting its input into a :class:`~kivy.graphics.texture.Texture`. .. versionchanged:: 1.10.0 The pygst and videocapture providers have been removed. .. versionchanged:: 1.8.0 There is now 2
distinct Gstream
er implementation: one using Gi/Gst working for both Python 2+3 with Gstreamer 1.0, and one using PyGST working only for Python 2 + Gstreamer 0.10. ''' __all__ = ('CameraBase', 'Camera') from kivy.utils import platform from kivy.event import EventDispatcher from kivy.logger import Logger from kivy.core impor...
shtrom/gtg
GTG/core/plugins/api.py
Python
gpl-3.0
8,572
0.00035
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Getting Things GNOME! - a personal organizer for the GNOME desktop # Copyright (c) 2008-2013 - Lionel Dricot & Bertrand Rousseau # # This program is free software: you can redistribute it and/or modify it under # t...
changed_callback(self, func): if func not in self.selection_changed_callback_listeners: self.selection_changed_callback_listeners.append(func) def remove_active_selection_changed_callback(self, plugin_class): new_list = [func for func in self.selection_changed_callback_listeners ...
back_listeners = new_list # Changing the UI =========================================================== def add_menu_item(self, item): """Adds a menu entry to the Plugin Menu of the Main Window (task browser). @param item: The Gtk.MenuItem that is going to be added. """ wid...
costibleotu/czl-scrape
sanatate/scrapy_proj/helpers/romanian.py
Python
mpl-2.0
509
0.004132
# -*- coding: utf-8 -*- class RomanianHelper(object): @staticmethod def englishize_romanian(string): symbols = (u"țţȚŢșşȘŞăǎĂîÎâÂ", u"ttTTssSSaaAiIaA") tr = {ord(a):ord(b) for a, b in zip(*symbols)} return string.transl
ate(tr) @staticmethod def beautify_romanian(string): symbols = (u"ǎţşŢ
Ş", u"ățșȚȘ") tr = {ord(a):ord(b) for a, b in zip(*symbols)} return string.translate(tr)
robiame/AndroidGeodata
pil/PcxImagePlugin.py
Python
mit
4,834
0.005379
# # The Python Imaging Library. # $Id$ # # PCX file handling # # This format was originally used by ZSoft's popular PaintBrush # program for the IBM PC. It is also supported by many MS-DOS and # Windows applications, including the Windows PaintBrush program in # Windows 3. # # history: # 1995-09-01 fl Cr...
version__ = "0.6" import Image, ImageFile, ImagePalette def i16(c,o): return ord(c[o]) + (ord(c[o+1])<<8) def _accept(prefix): return ord(prefix[0]) == 10 and ord(prefix[1
]) in [0, 2, 3, 5] ## # Image plugin for Paintbrush images. class PcxImageFile(ImageFile.ImageFile): format = "PCX" format_description = "Paintbrush" def _open(self): # header s = self.fp.read(128) if not _accept(s): raise SyntaxError, "not a PCX file"...
jim-cooley/abletonremotescripts
remote-scripts/samples/APC_64_40_r1b/APC_64_40/EncoderUserModesComponent.py
Python
apache-2.0
6,872
0.005675
# http://remotescripts.blogspot.com """ Track Control User Modes component originally designed for use with the APC40. Copyright (C) 2010 Hanz Petrov <[email protected]> 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 Fre...
self._encoder_eq_modes.set_controls_and_buttons(self._param_controls, self._modes_buttons) elif (sel
f._mode_index == 3): self._encoder_eq_modes._ignore_buttons = True if self._encoder_eq_modes._track_eq != None: self._encoder_eq_modes._track_eq._ignore_cut_buttons = True self._encoder_device_modes._ignore_buttons = True for button in ...
holloway/docvert-python3
docvert-web.py
Python
gpl-3.0
12,330
0.007218
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import io import uuid import os.path import socket import optparse import cgi docvert_root = os.path.dirname(os.path.abspath(__file__)) inbuilt_bottle_path = os.path.join(docvert_root, 'lib/bottle') try: import bottle if not hasattr(bottle, 'static_file'...
id, response.default_document) for filename in list(files.keys()): thumbnail_path = "%s/thumbnail.png" % filename if thumbnail_path in response: thumbnail_path = None conversions_tabs[filename] = dict(friendly_name=response.get_friendly_name_if_available(filename), pipeline=pipel...
) try: session_manager.save(session) except OSError as e: import traceback traceback.print_exc(file=sys.stdout) conversions_tabs = {'Session file problem': dict(friendly_name='Session file problem', pipeline=None, auto_pipeline=None, thumbnail_path=None) } first_document_...
OCA/partner-contact
partner_contact_department/models/res_partner.py
Python
agpl-3.0
839
0
# © 2014-2015 Tecnativa S.L. - Jairo Llopis # © 2016 Tecnativa S.L. - Vicent Cubells # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class ResPartner(models.Model): _inherit = "res.partner" department_id = fields.Many2one("res.partner.department", "Depar...
nerDepartment(models.Model): _name = "res.partner.department" _order = "parent_path" _parent_order = "name" _parent_store = T
rue _description = "Department" name = fields.Char(required=True, translate=True) parent_id = fields.Many2one( "res.partner.department", "Parent department", ondelete="restrict" ) child_ids = fields.One2many( "res.partner.department", "parent_id", "Child departments" ) paren...
phillxnet/rockstor-core
src/rockstor/scripts/qgroup_clean.py
Python
gpl-3.0
2,273
0.0022
""" Copyright (c) 2012-2020 RockStor, Inc. <http://rockstor.com> This file is part of RockStor. RockStor 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 la...
y 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/>. """ import re from storageadmin.models import Pool from system.osi import run_command from fs.btrfs import mount_root BTRFS = "/usr/sbin/btr...
SUNET/eduid-common
src/eduid_common/config/workers.py
Python
bsd-3-clause
3,033
0.00033
# # Copyright (c) 2013-2016 NORDUnet A/S # Copyright (c) 2019 SUNET # 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 above copyrigh...
tributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANT...
Y AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS;...
brianr747/SFC_models
sfc_models/gl_book/__init__.py
Python
apache-2.0
2,795
0.003936
""" Models from Godley & Lavoie text. [G&L 2012] "Monetary Economics: An Integrated Approach to credit, Money, Income, Production and Wealth; Second Edition", by Wynne Godley and Marc Lavoie, Palgrave Macmillan, 2012. ISBN 978-0-230-30184-9 Copyright 2016 Brian Romanchuk Licensed under the Apache License, Version 2....
ttp://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and li...
models class GL_book_model(object): """ Base class for example models from [G&L 2012] for single-country models. Generates the sectors, either in a new model object, or an object that is passed in. The user supplies a country code. """ def __init__(self, country_code, model=None, use_book_...
IQSS/geoconnect
gc_apps/content_pages/migrations/0001_initial.py
Python
apache-2.0
1,770
0.003955
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-05-12 16:09 from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone import model_utils.fields class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ ...
('message', models.TextField(blank=True, help_text=b'Message to Display on Page. When ava
ilable, displayed instead of a template.')), ('template_name', models.CharField(default=b'content_pages/maintenance_message.html', help_text=b'Template with HTML snippet to display. Note: This field is ignored if a "message" is available.', max_length=255)), ('end_datetime', models.Date...
AbleCoder/pyjade_coffin
pyjade_coffin/template/loader.py
Python
mit
2,320
0
"""Replacement for ``django.template.loader`` that uses Jinja 2. The module provides a generic way to load templates from an arbitrary backend storage (e.g. filesystem, database). """ from coffin.template import Template as CoffinTemplate from jinja2 import TemplateNotFound def find_template_source(name, dirs=None)...
an equivalent, but no matter, it mostly for internal use # anyway - developers will want to start with # ``get_template()`` or ``get_template_from_string`` anyway. raise NotImplementedError() def get_template(template_name): # Jinja will handle this for us, and env also initializes # the loader b...
env.get_template(template_name) def get_template_from_string(source): """ Does not support then ``name`` and ``origin`` parameters from the Django version. """ from pyjade_coffin.common import env return env.from_string(source) def render_to_string(template_name, dictionary=None, context_ins...
sellberg/SACLA2016A8015
scripts/09_make_dark.py
Python
bsd-2-clause
3,025
0.018182
#!/home/software/SACLA_tool/bin/python2.7 import numpy as np import h5py import matplotlib import matplotlib.pyplot as plt import argparse import time #import pandas as pd import sys from argparse import ArgumentParser parser = ArgumentParser() parser = ArgumentParser(description="Plot intense ice shots") parser....
int[i],i,num_im,1.0/(time.time() - t1)) i += 1 im_avg /= num_im # -- save dark np.save(file_folder+'%d_dark.npy'%args.run, im_avg) # -- run mean total_mean = np.average(im_avg.flatten(
)) # -- mean hist hist_bins = np.arange(np.floor(mean_int.min()), np.ceil(mean_int.max()) + 2, 2) - 1 hist, hist_bins = np.histogram(mean_int, bins=hist_bins) hist_bins_center = [(hist_bins[i] + hist_bins[i+1])/2.0 for i in range(len(hist_bins) - 1)] # -- plot #plt.figure() #plt.plot(hist_bins_center, hist) #plt.titl...
chtyim/cdap
cdap-docs/faqs/source/conf.py
Python
apache-2.0
603
0.008292
# -*- coding: utf-8 -*- import sys import os # Import the common config file # Note that paths in the common config are interpreted as if they were # in the location of this file sys.path.insert(0, os.path.
abspath('../../_common')) from common_conf import * # Override the common config html_short_title_toc = manuals_dict["faqs"] html_short_title = u'CDAP %s' % html_short_title_toc html_context = {"html_short_title_toc":ht
ml_short_title_toc} # Remove this guide from the mapping as it will fail as it has been deleted by clean intersphinx_mapping.pop("faqs", None) html_theme = 'cdap-faqs'
Eksmo/calibre
src/calibre/ebooks/rb/rbml.py
Python
gpl-3.0
7,383
0.002844
# -*- coding: utf-8 -*- __license__ = 'GPL 3' __copyright__ = '2009, John Schember <[email protected]>' __docformat__ = 'restructuredtext en' ''' Transform OEB content into RB compatible markup. ''' import re from calibre import prepare_string_for_xml from calibre.ebooks.rb import unique_name TAGS = [ 'b', ...
ylizer from calibre.ebooks.oeb.base import XHTML output = [u''] for item in self.oeb_book.spine: self.log.deb
ug('Converting %s to RocketBook HTML...' % item.href) stylizer = Stylizer(item.data, item.href, self.oeb_book, self.opts, self.opts.output_profile) output.append(self.add_page_anchor(item)) output += self.dump_text(item.data.find(XHTML('body')), stylizer, item) return ''.join...
tihlde/TIHLDEscripts
userscripts/lan_users_ipa.py
Python
apache-2.0
1,614
0.001239
# coding: utf-8 import os import sys import time import tihldelib.userlib as lib __author__ = 'Harald Floor Wilhelmsen' def get_useramount(): formatstring =
'Format: python lan_users.py useramount' # Checking if there are sufficient arguments, if not exit if len(sys.argv) != 2: sys.exit('Invaild number of arguments. ' + formatstring) user_amount = sys.argv[1].strip() if not user_amount.isdigit(): sys.exit('Wrong number-format. ' + format...
ount() response = str(input(str(user_amount) + ' users to add. Continue? [y/N]')) if response.replace('\n', '').strip() != 'y': return 'User called exit before adding users' api = lib.get_ipa_api() username_format = 'lan-{}' credentials_file_path = '/root/lan_users{}.txt'.format(time.time...
ct-23/home-assistant
homeassistant/components/binary_sensor/mystrom.py
Python
apache-2.0
3,028
0
""" Support for the myStrom buttons. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/binary_sensor.mystrom/ """ import asyncio import logging from homeassistant.components.binary_sensor import (BinarySensorDevice, DOMAIN) from homeassistant.components.ht...
button.""" res = yield from self._handle(reques
t.app['hass'], request.query) return res @asyncio.coroutine def _handle(self, hass, data): """Handle requests to the myStrom endpoint.""" button_action = list(data.keys())[0] button_id = data[button_action] entity_id = '{}.{}_{}'.format(DOMAIN, button_id, button_action) ...
vritant/subscription-manager
src/subscription_manager/gui/firstboot/rhsm_login.py
Python
gpl-2.0
19,013
0.001788
import gettext import socket import sys import logging _ = lambda x: gettext.ldgettext("rhsm", x) import gtk gtk.gdk.threads_init() import rhsm sys.path.append("/usr/share/rhsm") # enable logging for firstboot from subscription_manager import logutil logutil.init_logger() log = logging.getLogger("rhsm-app." + _...
MANUALLY_SUBSCRIBE_PAGE) elif isinstance(error[1], AllProductsCoveredException): message = _("All installed products are fully subscribed.") self._parent.manual_message = message self._parent.pre_done(MANUALLY_SUBSCRIBE_PAGE) else: ...
) return (current_sla, unentitled_products, sla_data_map) = result self._parent.current_sla = current_sla if len(sla_data_map) == 1: # If system already had a service level, we can hit this point # when we cannot fix any unentitled products: if c...
ATIX-AG/ansible
lib/ansible/modules/cloud/ovirt/ovirt_vms.py
Python
gpl-3.0
93,016
0.002795
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2017, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCU...
- "Mapper which maps an external virtual NIC profile to one that exists in the engine when C(state) is registered. vnic_profile is described by the following dictionary:" - "C(sourc
e_network_name): The network name of the source network." - "C(source_profile_name): The prfile name related to the source network." - "C(target_profile_id): The id of the target profile id to be mapped to in the engine." version_added: "2.5" cluster_mappings: description: ...
bblacey/FreeCAD-MacOS-CI
src/Mod/Path/PathScripts/PathStop.py
Python
lgpl-2.1
5,748
0.00174
# -*- coding: utf-8 -*- # *************************************************************************** # * * # * Copyright (c) 2015 Dan Falck <[email protected]> * # * ...
ATE_NOOP("App::Property","Add Optional or Manda
tory Stop to the program")) obj.Stop=['Optional', 'Mandatory'] obj.Proxy = self mode = 2 obj.setEditorMode('Placement', mode) def __getstate__(self): return None def __setstate__(self, state): return None def onChanged(self, obj, prop): pass # ...
v-iam/azure-sdk-for-python
azure-servicefabric/azure/servicefabric/models/deployed_stateful_service_replica_info.py
Python
mit
3,502
0.001142
# 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 ...
nBuild', 'Standby', 'Ready', 'Down', 'Dropped' :type replica_status: str :param address: The last address returned by the replica in Open or ChangeRole. :type ad
dress: str :param service_package_activation_id: :type service_package_activation_id: str :param ServiceKind: Polymorphic Discriminator :type ServiceKind: str :param replica_id: Id of the stateful service replica. :type replica_id: str :param replica_role: Possible values include: 'Unknown',...
sanguinariojoe/FreeCAD
src/Mod/Path/PathScripts/PathHop.py
Python
lgpl-2.1
5,422
0.001844
# -*- coding: utf-8 -*- # *************************************************************************** # * Copyright (c) 2014 Yorik van Havre <[email protected]> * # * * # * This program is free software; you can redistribute it a...
, state): return None def execute(self, obj): nextpoint = FreeCAD.Vector() if obj.NextObject: if o
bj.NextObject.isDerivedFrom("Path::Feature"): # look for the first position of the next path for c in obj.NextObject.Path.Commands: if c.Name in ["G0", "G00", "G1", "G01", "G2", "G02", "G3", "G03"]: nextpoint = c.Placement.Base ...
NaohiroTamura/python-ironicclient
ironicclient/tests/functional/test_help_msg.py
Python
apache-2.0
2,193
0
# Copyright (c) 2015 Mirantis, 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 writin...
et-console', 'node-
get-supported-boot-devices', 'node-list', 'node-port-list', 'node-set-boot-device', 'node-set-console-mode', 'node-set-maintenance', 'node-set-power-state', 'node-set-provision-state', 'node-show', 'node-show-sta...
bitmovin/bitmovin-python
bitmovin/resources/models/encodings/live/auto_restart_configuration.py
Python
unlicense
785
0.003822
from bitmovin.utils import Serializable class AutoRestartConfiguration(Serializable): def __init__(self, segments_written_timeout: float = None, bytes_written_timeout: float = None, frames_written_timeout: float = None, hls_manifests_update_timeout: float = None, dash_manifests_u...
n_timeout self.framesWrittenTimeout = frames_written_timeout self.hlsManifestsUpdateTimeout = hls_manifests_update_timeout self.dashManifestsUpdateTimeout = dash_manifests_update_timeout self.scheduleExpression = schedule_expression
adexin/Python-Machine-Learning-Samples
Other_samples/Gradient_check/gradient_check.py
Python
mit
7,033
0.002702
import numpy as np from Other_samples.testCases import * from Other_samples.Gradient_check.gc_utils import sigmoid, relu, dictionary_to_vector, vector_to_dictionary, \ gradients_to_vector def forward_propagation(x, theta): """ Implement the linear forward propagation (compute J) presented in Figure 1 (J(...
b3": W1 -- weight matrix of shape (5, 4) b1 -- bias vector of shape (5, 1) W2 -- weight matrix of shape (3, 5) b2 -- bias vector of shape (3, 1) W3 -- weight matrix of shape (1, 3) b3 -- bias vector o...
for one example) """ # retrieve parameters m = X.shape[1] W1 = parameters["W1"] b1 = parameters["b1"] W2 = parameters["W2"] b2 = parameters["b2"] W3 = parameters["W3"] b3 = parameters["b3"] # LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID Z1 = np.dot(W1, X) + b1 ...
saintdragon2/python-3-lecture-2015
civil_mid_final/알았조/tetris a.py
Python
mit
15,222
0.004222
import random, time, pygame, sys from pygame.locals import * FPS = 25 WINDOWWIDTH = 640 WINDOWHEIGHT = 480 BOXSIZE = 20 BOARDWIDTH = 10 BOARDHEIGHT = 20 BLANK = '.' MOVESIDEWAYSFREQ = 0.15 MOVEDOWNFREQ = 0.1 XMARGIN = int((WINDOWWIDTH - BOARDWIDTH * BOXSIZE) / 2) TOPMARGIN = WINDOWHEIGHT - (BOARDHEIGHT * BOXSIZE) -...
ngPiece['rot
ation'] = (fallingPiece['rotation'] + 1) % len(PIECES[fallingPiece['shape']]) elif (event.key == K_DOWN or event.key == K_s): movingDown = True if isValidPosition(board, fallingPiece, adjY=1): fallingPiece['y'] += 1 la...
normalnorway/normal.no
django/apps/cms/urls.py
Python
gpl-3.0
831
0.009627
from django.conf.urls import url from django.contrib.auth.decorators import permission_required from . import views urlpatterns = [ url (r'^file/select/$', views.FileSelect.as_view(), name='file-select'),
# raise_exception=True => 403 Forbidden instead of redirect to /admin url (r'^page/(?P<pk>\d+)/update/$', permission_required ('cms.change_page', raise_exception=True)( views.PageUpdate.as_view()), name='page-update'), url (r'^content/(?P<pk>\d+)/update/$', permission_re...
st.as_view(), name='info-list'), url (r'^info/(?P<pk>\d+)/$', views.InfoDetail.as_view(), name='info-detail'), ]
buenrostrolab/proatac
tests/test_cli.py
Python
mit
575
0.015652
import pytest from click.testing import CliRunner from parkour im
port cli import md5 def file_checksums_equal(file1, file2): with open(file1
) as f: checksum1 = md5.new(f.read()).digest() with open(file2) as f: checksum2 = md5.new(f.read()).digest() return checksum1==checksum2 def test_trimmed_output(): runner = CliRunner() result = runner.invoke(cli.main, ['-a', 'fastq/s3_1.fastq.gz', '-b', 'fastq/s3_2.fastq.gz', '-u', 'trim'])...
acutesoftware/rawdata
rawdata/gather.py
Python
mit
1,024
0.027344
#!/usr/bin/python3 # gather.py lookup_terms = [ {'program' :'email_outlook.py', 'known_as':['email', 'mail', 'outlook', 'messages', 'sent items', 'inbox', 'spam'] }, {'program' :'sys_PC_usage.py', 'known_as':['PC usage', 'Application logging'] }, {'program' :'sys_process_windo...
, vais) know what is available and how to run it """ for l in lookup_terms: print(l['program'] + ' = ', ','.join([t for t in l['known_as']]))
TEST()
dgrat/ardupilot
Tools/autotest/autotest.py
Python
gpl-3.0
18,627
0.004832
#!/usr/bin/env python """ APM automatic test suite Andrew Tridgell, October 2011 """ from __future__ import print_function import atexit import fnmatch import glob import optparse import os import shutil import signal import sys import time import traceback import apmrover2 import arducopter import arduplane import ...
(%s) does not exist" % (binary,)) return binary def run_step(step): """Run one step.""" # remove old
logs util.run_cmd('/bin/rm -f logs/*.BIN logs/LASTLOG.TXT') if step == "prerequisites": return test_prerequisites() build_opts = { "j": opts.j, "debug": opts.debug, "clean": not opts.no_clean, "configure": not opts.no_configure, } if step == 'build.ArduPlane...
helixyte/TheLMA
thelma/entities/moleculetype.py
Python
mit
2,617
0.001146
""" This file is part of the TheLMA (THe Laboratory Management Application) project. See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information. MoleculeType entity classes. """ from everest.entities.base import Entity from everest.entities.utils import slug_from_string __docformat__ = "reStructured...
ecule_type_name): """ Checks whether the given molecule type name is a known one. """ return molecule_type_name in cls.__ALL class MoleculeType(Entity): """ Instances
of this class describe molecule types, such as \'siRna\'. """ #: The name of the molecule type. name = None #: A more detailed description. description = None #: An number indicating the time it takes for molecules of this type to #: thaw. thaw_time = None #: A list of modification ...
dannyperry571/theapprentice
script.module.pydevd/lib/runfiles.py
Python
gpl-2.0
11,560
0.004325
import os def main(): import sys # Separate the nose params and the pydev params. pydev_params = [] other_test_framework_params = [] found_other_test_framework_param = None NOSE_PARAMS = '--nose-params' PY_TEST_PARAMS = '--py-test-params' for arg in sys.argv[1:]: if not found...
t ImportError: if found_other_test_framework_param: sys.stderr.write('Warning: Could not import the test runner: %s. Running with the default pydev unittest runner instead.\n' % ( found_other_test_framework_param,)) test_framework = 0 # Clear any exception that may be t...
asattr(sys, 'exc_clear'): sys.exc_clear() if test_framework == 0: return pydev_runfiles.main(configuration) # Note: still doesn't return a proper value. else: # We'll convert the parameters to what nose or py.test expects. # The supported parameters are: # runfiles.py...
arecarn/dploy
tests/utils.py
Python
mit
2,296
0
""" Contains utilities used during testing """ import os import stat import shutil def remove_tree(tree): """ reset the permission of a file and directory tree and remove it """ os.chmod(tree, 0o777) shutil.rmtree(tree) def remove_file(file_name): """ reset the permission of a file and ...
irectory(directory_name): """ create an directory """ os.makedirs(directory_name) class ChangeDirectory: # pylint: disable=too-few-public-methods """ Context manager for changing the current working
directory """ def __init__(self, new_path): self.new_path = os.path.expanduser(new_path) self.saved_path = os.getcwd() def __enter__(self): os.chdir(self.new_path) def __exit__(self, etype, value, traceback): os.chdir(self.saved_path) def create_tree(tree): """ ...
jawilson/Flexget
flexget/plugins/operate/spy_headers.py
Python
mit
1,536
0.000651
from __future__ import unicode_literals, division, absolute_import from builtins import * # noqa pylint: disable=unused-import, redefined-builtin import logging from flexget import plugin from flexget.event import event log = logging.getLogger('spy_headers') class PluginSpyHeaders(object): """ Logs al...
------------------') for header, value in response.request.headers.items(): log.info('%s: %s' % (header, value)) log.info('--------------------------------------') return response def on_task_start(self, task, config): if not config:
return # Add our hook to the requests session task.requests.hooks['response'].append(self.log_requests_headers) def on_task_exit(self, task, config): """Task exiting, remove additions""" if not config: return task.requests.hooks['response'].remove(self.log_r...
toumorokoshi/vcver-python
vcver/version.py
Python
mit
2,963
0.000337
import os import re import logging from packaging.version import parse from .scm.git import Git from .scm.base import DEFAULT_TAG_VERSION from .exception import VersionerError from .version_string import make_string_pep440_compatible SCM_TYPES = [Git] LOG = logging.getLogger(__name__) RELEASE_FORMAT = "{main_version}"...
type {0} not found, or is not a valid repo.".format( scm_type ) rais
e VersionerError(msg) version = determine_version( scm, version_format=version_format, release_version_format=release_version_format, release_branch_regex=release_branch_regex, is_release=is_release, ) _write_version_file(version_file_path, version) return versi...
edmorley/treeherder
treeherder/log_parser/parsers.py
Python
mpl-2.0
20,165
0.002628
import json import logging import re from html.parser import HTMLParser import jsonschema from django.conf import settings logger = logging.getLogger(__name__) class ParserBase: """ Base class for all parsers. """ def __init__(self, name): """Setup the artifact to hold the extracted data.""...
be seen above, Taskcluster logs can have (a) log output that falls between step markers, and (b) content at the end of the log, that is not followed by a final finish step marker. We handle this by creating generic placeholder steps to hold the log output that is not enclosed by step markers, a...
s have been parsed. """ if not line.strip(): # Skip whitespace-only lines, since they will never contain an error line, # so are not of interest. This also avoids creating spurious unnamed steps # (which occurs when we find content outside of step markers) for the ...
pombreda/django-hotclub
libs/external_libs/ybrowserauth/setup.py
Python
mit
455
0.004396
# ybrowserauth installation script # from distutils.core import setup setup(name='ybrowserauth', version='1.2', py_modules=['ybrowserauth'], license='http://www.opensource.org/licenses/bsd-license.php
', url='http://developer.yahoo.com/auth', description='Lets you add Yahoo! Browser-Based authentication to your applications', author='Jason Levitt', contact='http://develo
per.yahoo.com/blog', )
specify/specify7
specifyweb/specify/autonumbering.py
Python
gpl-2.0
1,532
0.004569
from typing import List, Tuple, Sequence import logging logger = logging.getLogger(__name__) from .lock_tables import lock_tables from .uiformatters import UIFormatter, get_uiformatters, AutonumberOverflowException def autonumber_and_save(collection, user, obj) -> None: uiformatters = get_uiformatters(collectio...
%s fields: %s", obj, fields) # The autonumber action is prepared and thunked outside the locked table # context since it looks at other tables and that is
not allowed by mysql # if those tables are not also locked. thunks = [ formatter.prepare_autonumber_thunk(collection, obj.__class__, vals) for formatter, vals in fields ] with lock_tables(obj._meta.db_table): for apply_autonumbering_to in thunks: apply_autonumbering_...
timj/scons
test/D/HSTeoh/sconstest-singleStringCannotBeMultipleOptions_dmd.py
Python
mit
1,396
0
""" Test compiling and executing using the dmd tool. """ # # __COPYRIGHT__ # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to...
ng conditions: # # The above copyright notice and this permission noti
ce shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS ...
jcabdala/fades
tests/test_file_options.py
Python
gpl-3.0
6,427
0.000778
# Copyright 2016 Facundo Batista, Nicolás Demarchi # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ...
_cli(self, mocked_parser): mocked_parser.return_value = [('foo', 'false'), ('bar', 'hux'), ('no_in_cli', 'testing')] args = self.argparser.parse_args(['--foo', '--bar
', 'other', 'positional']) result = file_options.options_from_file(args) self.assertTrue(result.foo) self.assertEqual(result.bar, 'other') self.assertEqual(result.no_in_cli, 'testing') self.assertIsInstance(args, argparse.Namespace) @patch("fades.file_options.CONFIG_FILES",...
elkingtowa/pyrake
tests/test_utils_datatypes.py
Python
mit
3,592
0.000557
import copy import unittest from pyrake.utils.datatypes import CaselessDict __doctests__ = ['pyrake.utils.datatypes'] class CaselessDictTest(unittest.TestCase): def test_init(self): seq = {'red': 1, 'black': 3} d = CaselessDict(seq) self.assertEqual(d['red'], 1) self.assertEqual(...
e.fromkeys(keys)
self.assertEqual(d['A'], None) self.assertEqual(d['B'], None) d = instance.fromkeys(keys, 1) self.assertEqual(d['A'], 1) self.assertEqual(d['B'], 1) def test_contains(self): d = CaselessDict() d['a'] = 1 assert 'a' in d def test_pop(self): d = ...
luciencd/astrophotograpython
library/offsetter.py
Python
mit
667
0.014993
''' offsets = [[[originalx,originaly], [511,709],[498,707]],\ [[522,711], [508,709],[493,706]],\ [[522,714], [503,708],[488,705]]] ''' def offsetter(length,dim,dx,dy,sx,sy,fx,fy): x = x0 = sx y = y0 = sy arr = [] for i in range(dim): ...
x = int(x0+dx*i+dx*(j+1)) y = int(y0+dy*i+dy*(j+1)) arr[i].append([x,y]) for i in range(dim): for j in range(len(arr)): arr[i][j][0] += int(fx*i) arr[i][j][1] += int(fy*i)
return arr #print offsetter(3,3,-4,-1,532,713)
leppa/home-assistant
script/hassfest/config_flow.py
Python
apache-2.0
2,621
0.000382
"""Generate config flow file.""" import json from typing import Dict from .model import Config, Integration BASE = """ \"\"\"Automatically generated by hassfest. To update, run python3 -m script.hassfest \"\"\" # fmt: off FLOWS = {} """.strip() def validate_integration(integration: Integration): """Validate ...
p() != content: config.add_error( "config_flow", "File config_flows.py is not up to date. " "Run python3 -m script.hassfest", fixable=True, ) return def generate(integrations: Dict[str, Integration], config: Config): "...
erated/config_flows.py" with open(str(config_flow_path), "w") as fp: fp.write(config.cache["config_flow"] + "\n")
sirech/deliver
deliver/tests/test_send.py
Python
mit
852
0.004695
from test_base import BaseTest, load_msg from mock import patch from smtplib import SMTP from deliver.send import Sen
der class SendTest(BaseTest): def setUp(self)
: super(SendTest,self).setUp() self.sender = Sender(self.config) @patch('smtplib.SMTP') @patch.object(SMTP, 'sendmail') def test_send(self, smtp, sendmail): msg = load_msg('sample') self.sender.send(msg, u'[email protected]') self.assertEqual(sendmail.call_count, 1)...
swcarpentry/amy
amy/workshops/management/commands/instructors_activity.py
Python
mit
5,305
0
import os import logging from django.core.management.base import BaseCommand from django.core.mail import send_mail from django.template.loader import get_template from workshops.models import Badge, Person, Role logger = logging.getLogger() class Command(BaseCommand): help = 'Report instructors activity.' ...
n=person.badges.instructor_badges() ), 'tasks': zip(tasks, self.foreign_tasks(tasks, person, roles)), } result.append(record) return result def make_message(self, record): tmplt = get_template('mailing/instructor_...
, record): # in future we can vary the subject depending on the record details return 'Updating your Software Carpentry information' def recipient(self, record): return record['person'].email def send_message(self, subject, message, sender, recipient, for_real=False, ...
looopTools/sw9-source
.waf-1.9.8-6657823688b736c1d1a4e2c4e8e198b4/waflib/extras/wurf/store_lock_version_resolver.py
Python
mit
719
0.038943
#! /usr/bin/env python # encoding: utf-8 # WARNING! Do not edit! https:
//waf.io/book/index.html#_obtaining_the_waf_file import os import json import shutil from.error import Error class StoreLockVersionResolver(object): def __init__(self,resolver,lock_cache,dependency): self.resolver=resolver self.lock_cache=loc
k_cache self.dependency=dependency def resolve(self): path=self.resolver.resolve() checkout=None if self.dependency.git_tag: checkout=self.dependency.git_tag elif self.dependency.git_commit: checkout=self.dependency.git_commit else: raise Error('Not stable checkout information found.') self.lock...
stephane-martin/salt-debian-packaging
salt-2016.3.2/tests/integration/states/git.py
Python
apache-2.0
8,866
0.001241
# -*- coding: utf-8 -*- ''' Tests for the Git state ''' # Import python libs from __future__ import absolute_import import os import shutil import socket import subprocess import tempfile # Import Salt Testing libs from salttesting.helpers import ensure_in_syspath, skip_if_binaries_missing ensure_in_syspath('../../')...
shutil.rmtree(name, ignore_errors=True) def test_latest_unless_no_cwd_issue_6800(self): ''' cwd=target was being passed to _run_check which blew up if target dir did not already exist. ''' name = os.path.join(integration.TMP, 'salt_repo') if os.path.isdir(nam...
try: ret = self.run_state( 'git.latest', name='https://{0}/saltstack/salt-test-repo.git'.format(self.__domain), rev='develop', target=name, unless='test -e {0}'.format(name), submodules=True ) ...
brianmay/spud
spud/tests/a_unit/photos/test_models.py
Python
gpl-3.0
35
0
""" Ru
n tests on photo m
odels. """
andpe/minos
minos/sonos/__init__.py
Python
bsd-3-clause
3,903
0.003587
import soco from collections import namedtuple SonosTrack = namedtuple('SonosTrack', [ 'title', 'artist', 'album', 'album_art_uri', 'position', 'playlist_position', 'duration', 'uri', 'resources', 'album_art', 'metadata' ]) SonosTrack.__new__.__defaults__ = (None,) * len(SonosTrack._fields) class Track(S...
namedtuple('Resources', [ 'bitrate', 'bits_per_sample', 'color_depth', 'duration', 'import_uri', 'nr_audio_channels', 'protection', 'protocol_info', 'resolution', 'sample_frequency', 'size', 'uri' ]) Resources.__new__.__defaults__ = (None,)
* len(Resources._fields) class SonosWrapper(object): """ A wrapper around some SoCo calls to simplify things. """ debug = False speakers = None sonos = None def __init__(self, speakers): self.speakers = speakers def toggle_debug(self): self.debug = not(self.debug) def ...
liresearchgroup/submtr
submtr/lib/github3/search/code.py
Python
mit
1,087
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from github3.models import GitHubCore from github3.repos import Repository class CodeSearchResult(GitHubCore): def __init__(self, data, session=None): super(CodeSearchResult, self).__init__(data, session) self._api = data.get('url') ...
et('path') #: SHA in which the code can be found self.sha = data.get('sha') #: URL to the Git blob endpoint se
lf.git_url = data.get('git_url') #: URL to the HTML view of the blob self.html_url = data.get('html_url') #: Repository the code snippet belongs to self.repository = Repository(data.get('repository', {}), self) #: Score of the result self.score = data.get('score') ...
Versatilus/dragonfly
dragonfly/test/test_log.py
Python
lgpl-3.0
4,558
0.000658
# # This file is part of Dragonfly. # (c) Copyright 2007, 2008 by Christo Butcher # Licensed under the LGPL. # # Dragonfly 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 L...
= "".join(self._output.blocks
).splitlines() # output = prefix + ("\n" + prefix).join(output) # print output # if self._error.blocks: # prefix = "Error: " # text = "".join(self._error.blocks).splitlines() # text = prefix + ("\n" + prefix).join(text) # print text self...
mumuwoyou/vnpy-master
vnpy/trader/gateway/tkproGateway/TradeApi/__init__.py
Python
mit
279
0
# encoding: utf-8 """ Core trade api for simulated and live trading. """ from __future__ import absolute_import from __future__ import division from __future__ import print_func
tion from
__future__ import unicode_literals from .trade_api import TradeApi __all__ = ['TradeApi']
adrianmoisey/cptdevops
flask/cli.py
Python
bsd-3-clause
18,141
0.00022
# -*- coding: utf-8 -*- """ flask.cli ~~~~~~~~~ A simple command line application to run flask apps. :copyright: (c) 2015 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import os import sys from threading import Lock, Thread from functools import update_wrapper import click ...
' 'you sure it contains a Flask application? Maybe ' 'you wrapped it in a WSGI middleware or you are ' 'using a factory function.' % module.__name__)
def prepare_exec_for_file(filename): """Given a filename this will try to calculate the python path, add it to the search path and return the actual module name that is expected. """ module = [] # Chop off file extensions or package markers if os.path.split(filename)[1] == '__init__.py': ...
snudler6/time-travel
src/tests/utils.py
Python
mit
492
0
"""Utils for time travel testings.""" def _t(rel=0.0): """Return an absolute time from the relative time given. The minimal allowed time in windows is 86400 seconds, for some reason. In stead of doing the arithmetic in the tests themselves, this function should be used. The value `86400` is expo...
return 86400.0 + rel
FlorianWestphal/VMI-PL
front_end/client.py
Python
mit
2,163
0.039297
#!/usr/bin/python import argparse from vmipl_communication.network_connection import NetworkConnection def main(): parser = setup_options_parser() # parse given arguments args = parser.parse_args() validate_input(parser, args) port = args.port script_content = args.vmipl_script.read() args.vmipl_script.clos...
None: reconfigure_vm(args.vm_id, script_content, port) def setup_options_parser(): descr = ("Communicate with execution environment to start virtual" + " machine or reconfigure already running one") # initialize options parser parser = argparse.ArgumentParser(description=descr) parser.add_argument("-s",...
ption_file", metavar="<VM description file>") parser.add_argument("-r", "--reconfig", help= "reconfigure virtual machine given by <VM Id>"+ " using the monitoring configuration given in"+ " <VMI-PL script>", dest="vm_id", metavar="<VM Id>") parser.add_argument("vmipl_script", he...
nyaruka/django-hamlpy
hamlpy/test/test_parser.py
Python
mit
4,020
0.004764
import unittest from hamlpy.parser.core import ( ParseException, Stream, peek_indentation, read_line, read_number, read_quoted_string, read_symbol, read_whitespace, read_word, ) from hamlpy.parser.utils import html_escape class ParserTest(unittest.TestCase): def test_read_whit...
ine4" assert read_line(stream) == "" assert read_line(stream) is None assert read_line(Stream("last line ")) == "last line " def test_read_number(self): stream = Stream('123"') assert read_number(stream) == "123" assert stream.text[stream.ptr :] == '"' st...
= "123.4" assert stream.text[stream.ptr :] == "xx" stream = Stream("0.0001 ") assert read_number(stream) == "0.0001" assert stream.text[stream.ptr :] == " " def test_read_symbol(self): stream = Stream("=> bar") assert read_symbol(stream, ["=>", ":"]) == "=>" ...
leriomaggio/pycon_site
p3/migrations/0004_auto__chg_field_p3talk_sub_community.py
Python
bsd-2-clause
21,667
0.008123
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'P3Talk.sub_community' db.alter_column(u'p3_p3talk', 's...
ical': '
False', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superu...
abhinavp13/IITBX-edx-platform-dev
common/lib/xmodule/xmodule/modulestore/search.py
Python
agpl-3.0
4,563
0.001096
from itertools import repeat from xmodule.course_module import CourseDescriptor from .exceptions import (ItemNotFoundError, NoPathToItem) from . import Location def path_to_location(modulestore, course_id, location): ''' Try to find a course_id/chapter/section[/position] path to location in modulestore....
ence that's on tab 3 of a # sequence, the resulting position is 3_2. However, no positional modules # (e.g. sequential and videosequence) currently deal with this form of # representing nested positions. This needs to happen before jumping to a # module nested in more than one positional module will wor...
position_list = [] for path_index in range(2, n - 1): category = path[path_index].category if category == 'sequential' or category == 'videosequence': section_desc = modulestore.get_instance(course_id, path[path_index]) child_locs = [c.location for...
x2Ident/x2Ident_test
mitmproxy/mitmproxy/models/__init__.py
Python
gpl-3.0
753
0.001328
from __future__ import absolute_import, print_function, division from netlib.http import decoded from .connections import ClientConnection, ServerConnection from .flow import Flow, Error from .http import ( HTTPFlow, HTTPRequest, HTTPResponse, Headers, make_
error_response, make_connect_request, make_connect_response, expect_continue_response ) from .tcp import TCPFlow FLOW_TYPES = dict( http=HTTPFlow, tcp=TCPFlow, ) __all__ = [ "HTTPFlow", "HTTPRequest", "HTTPResponse", "Headers", "decoded", "make_error_response", "make_connect_request", ...
nnection", "ServerConnection", "Flow", "Error", "TCPFlow", "FLOW_TYPES", ]
ecliu110/SpotifyApp
welcome.py
Python
apache-2.0
8,683
0.004607
# Copyright 2015 IBM Corp. 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
FY_CLIENT_SECRET = 'fbe3a1d865e04fefa7e31b87dab6f04b' ALL_GENRES = ['acoustic', 'afrobeat', 'alt-rock', '
alternative', 'ambient', 'black-metal', 'bluegrass', 'blues', 'british', 'chill', 'classical', 'club', 'country', 'dance', 'deep-house', 'disco', 'disney', 'dubstep', 'edm', 'electro', 'electronic', 'folk', 'french', 'grunge', 'happy', 'hard-rock', 'heavy-metal', 'hip-hop', 'holidays', 'house', 'indie', 'indie-pop', 'j...
linusluotsinen/RPiAntiTheft
util/gps_handler/gps_controller.py
Python
mit
1,812
0.007174
f
rom gps import * import time import threading import math class GpsController(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.gpsd = gps(mode=WATCH_ENABLE) #starting the stream of info self.running = False def run(self): self.running = True ...
of gpsd info to clear the buffer self.gpsd.next() def stopController(self): self.running = False @property def fix(self): return self.gpsd.fix @property def utc(self): return self.gpsd.utc @property def satellites(self): return self.gpsd.sat...
BlackstoneEngineering/yotta
yotta/lib/settings.py
Python
apache-2.0
5,218
0.003066
# Copyright 2014 ARM Limited # # Licensed under the Apache License, Version 2.0 # See LICENSE file for details. # standard library modules, , , import logging import os import threading from collections import OrderedDict # fsutils, , misc filesystem utils, internal import fsutils # Ordered JSON, , read & write json,...
soon as a value is found for a variable, the search is stopped. # # # constants user_config_file = os.path.join(folders.userSettingsDirectory(), 'config.json') dir_config_file = os.path.join('.','.yotta.json') config_files = [ dir_config_file, user_config_file, ] if os.name == 'nt': config_files += [ ...
path.expanduser(os.path.join(folders.prefix(),'yotta.json')) ] else: config_files += [ os.path.expanduser(os.path.join(folders.prefix(),'etc','yotta.json')), os.path.join('etc','yotta.json') ] # private state parser = None parser_lock = threading.Lock() # private API # class for reading ...
dantebarba/docker-media-server
plex/Sub-Zero.bundle/Contents/Libraries/Shared/subliminal_patch/providers/legendastv.py
Python
gpl-3.0
10,819
0.003697
# coding=utf-8 import logging import rarfile import os from subliminal.exceptions import ConfigurationError from subliminal.providers.legendastv import LegendasTVSubtitle as _LegendasTVSubtitle, \ LegendasTVProvider as _LegendasTVProvider, Episode, Movie, guess_matches, guessit, sanitize, region, type_map, \ r...
ries if video.series and (sanitize(self.title) in ( sanitize(name) for name in [video.series] + video.alternative_series)): matches.add('series') # year if video.original_series and self.year is None or video.year and video.year == self.year: ...
eo.series_imdb_id: matches.add('series_imdb_id') # movie elif isinstance(video, Movie) and self.type == 'movie': # title if video.title and (sanitize(self.title) in ( sanitize(name) for name in [video.title] + video.alternative_titles)): ...
oVirt/vdsm
lib/vdsm/storage/volumemetadata.py
Python
gpl-2.0
11,350
0
# # Copyright 2016 Red Hat, Inc. # # 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 th...
olume contents should be considered valid self.legality = legality # Volume creation time (in seconds since the epoch) self.ctime = int(time.time()) if ctime is None else ctime # Generation increments each time certain operations complete self.generation = generation # Se...
new volume is # created in an image. self.sequence = sequence @classmethod def from_lines(cls, lines): ''' Instantiates a VolumeMetadata object from storage read bytes. Args: lines: list of key=value entries given as bytes read from storage meta...
NREL/glmgen
glmgen/run_gridlabd_batch_file.py
Python
gpl-2.0
850
0.04
# This function runs a .bat file that job handles mu
ltiple GridLAB-D files import subprocess #C:\Projects\GridLAB-D_Builds\trunk\test\input\batch test\13_node_fault2.glm def create_batch_file(glm_folder,batch_name): ba
tch_file = open('{:s}'.format(batch_name),'w') batch_file.write('gridlabd.exe -T 0 --job\n') #batch_file.write('pause\n') batch_file.close() return None def run_batch_file(glm_folder,batch_name): p = subprocess.Popen('{:s}'.format(batch_name),cwd=glm_folder) code = p.wait() #print(code) return None def main(...
csc8630Spring2014/Clusterizer
ete2/treeview/_open_newick.py
Python
mit
2,493
0.006418
# -*- coding: utf-8 -*- # #START_LICENSE########################################################### # # # This file is part of the Environment for Tree Exploration program # (ETE). http://ete.cgenomics.org # # ETE is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public ...
re.QMetaObject.connectSlotsByName(OpenNewick) def retranslateUi(self, OpenNewick): OpenNewick.setWindowTitle(QtGui.QApplication.translate("OpenNewick", "Dialog", None, QtGui.QApplication.Uni
codeUTF8))
docusign/docusign-python-client
docusign_esign/models/document_html_collapsible_display_settings.py
Python
mit
11,943
0.000084
# coding: utf-8 """ DocuSign REST API The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. # noqa: E501 OpenAPI spec version: v2.1 Contact: [email protected] Generated by: https://github.com/swagger-api/swagger-codegen.gi...
# noqa: E501 :return: The arrow_open of this DocumentHtmlCollapsibleDisplaySettings. # noqa: E501 :rtype: str """ return self._arrow_open @arrow_open.setter
def arrow_open(self, arrow_open): """Sets the arrow_open of this DocumentHtmlCollapsibleDisplaySettings. # noqa: E501 :param arrow_open: The arrow_open of this DocumentHtmlCollapsibleDisplaySettings. # noqa: E501 :type: str """ self._arrow_open = arrow_open ...
mozilla/relman-auto-nag
auto_nag/cache.py
Python
bsd-3-clause
1,902
0.000526
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. import json import os from libmozdata import utils as lmdutils from auto_nag import utils class Cache(object): d...
ems(): delta = lmdutils.get_date_ymd("today") - lmdutils.get_date_ymd( date ) if delta.days < self.max_days: self.data[str(bugid)] = date r
eturn self.data def add(self, bugids): if self.dryrun or (self.add_once and self.added): return data = self.get_data() today = lmdutils.get_today() for bugid in bugids: data[str(bugid)] = today with open(self.get_path(), "w") as Out: jso...
MungoRae/home-assistant
homeassistant/components/mailbox/__init__.py
Python
apache-2.0
7,809
0
""" Provides functionality for mailboxes. For more details about this component, please refer to the documentation at https://home-assistant.io/components/mailbox/ """ import asyncio import logging from contextlib import suppress from datetime import timedelta import async_timeout from aiohttp import web from aioht...
): """Return the media blob for the msgid.""" raise NotImplementedError() @asyncio.coroutine
def async_get_messages(self): """Return a list of the current messages.""" raise NotImplementedError() def async_delete(self, msgid): """Delete the specified messages.""" raise NotImplementedError() class StreamError(Exception): """Media streaming exception.""" pass c...
felipecorrea/python-pocket
examples/batch_actions.py
Python
apache-2.0
1,253
0.03352
#!/usr/bin/env python '''Batch se
veral changes to Pocket''' __author__ = 'Felipe Borges' import sys sys.path.append("..") import getopt impo
rt pocket USAGE = '''Usage: batch_actions [options] array_of_actions This script adds an Item to Pocket. Options: -h --help: print this help --consumer_key : the Pocket API consumer key --access_token : the user's Pocket Access Token ''' def print_usage_and_exit(): print USAGE sys.exit(2) def m...
pawl/Chinese-RFID-Access-Control-Library
rfid.py
Python
mit
9,417
0.000212
import binascii import socket import struct import sys def ten_digit_to_comma_format(badge): """Returns the comma-format RFID number (without the comma) from the 10-digit RFID number. Explanation: *On an EM4100/4001 spec RFID card, there will generally be two sets of numbers like this: 0015362878...
""" :param ip: IP address
of the controller :param timeout: settimeout value for the sockets connection :param port: the destination port of the socket, should always be 60000 """ try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0) s.connect((ip, port)) s.settimeout(t...
saaros/pghoard
pghoard/rohmu/object_storage/google.py
Python
apache-2.0
11,184
0.002414
""" rohmu - google cloud object store interface Copyright (c) 2016 Ohmu Ltd See LICENSE for details """ # pylint: disable=import-error, no-name-in-module # NOTE: this import is not needed per-se, but it's imported here first to point the # user to the most important possible missing dependency import googleapiclient ...
return data, self._metadata_for_key(clob, key) def _upload(self, upload_type, local_object, key, metadata, extra_props): key = self.f
ormat_key_for_backend(key) self.log.debug("Starting to upload %r", key) upload = upload_type(local_object, mimetype="application/octet-stream", resumable=True, chunksize=CHUNK_SIZE) body = {"metadata": metadata} if extra_props: body.update(extra_p...
armenzg/build-mozharness
configs/single_locale/macosx64.py
Python
mpl-2.0
2,942
0.00136
import os config = { # mozconfig file to use, it depends on branch and platform names "platform": "macosx64", "update_platform": "Darwin_x86_64-gcc3", "mozconfig": "%(branch)s/browser/config/mozconfigs/macosx-universal/l10n-mozconfig", "bootstrap_env": { "SHELL": '/bin/bash', "MOZ_O...
credentials_file': 'oauth.txt', # l10n "ignore_locales": ["en-US"], "l10n_dir": "l10n", "locales_file": "%(branch)s/browser/locales/all-locales", "locales_dir": "browser/locales", "hg_l10n_base": "https://hg.mozilla.org/l10n-central", "hg_l10n_tag": "default", "merge_locales": True, ...
AR "previous_mar_dir": "dist/previous", "current_mar_dir": "dist/current", "update_mar_dir": "dist/update", # sure? "previous_mar_filename": "previous.mar", "current_work_mar_dir": "current.work", "package_base_dir": "dist/l10n-stage", "application_ini": "Contents/Resources/application.ini"...
lkumar93/Deep_Learning_Crazyflie
src/deep_learning_crazyflie/src/lk_track.py
Python
mit
5,660
0.030035
#!/usr/bin/env python ''' Lucas-Kanade tracker ==================== Lucas-Kanade sparse optical flow demo. Uses goodFeaturesToTrack for track initialization and back-tracking for match verification between frames. Usage ----- lk_track.py [<video_source>] Keys ---- ESC - exit ''' # Python 2/3 compatibility from __...
, 'Velocity y: %f' % VelocityY) if self.frame_idx % self.detect_interval == 0: mask = np.zeros_like(frame_gray) mask[:] = 255
for x, y in [np.int32(tr[-1]) for tr in self.tracks]: cv2.circle(mask, (x, y), 5, 0, -1) p = cv2.goodFeaturesToTrack(frame_gray, mask = mask, **feature_params) if p is not None: for x, y in np.float32(p).reshape(-1, 2): ...
lanhel/pyzombie
test/pyzombie/handlers/HandlerInstanceStdoutTestCase.py
Python
apache-2.0
2,987
0.005022
#!/usr/bin/env python # -*- coding: UTF-8 -*- #-----------------------------------------------------------------------
-------- """pyzombie HTTP RESTful handler test cases.""" __author__ = ('Lance Finn Helsten',) __version__ = '1.0.1' __copyright__ = """Copyright 2009 Lance Finn Helsten ([email protected])""" __license__ = """ Lic
ensed 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 dist...
Abi1ity/uniclust2.0
SQLAlchemy-0.9.9/test/dialect/mysql/test_types.py
Python
bsd-3-clause
32,246
0.004626
# coding: utf-8 from sqlalchemy.testing import eq_, assert_raises from sqlalchemy import * from sqlalchemy import sql, exc, schema from sqlalchemy.util import u from sqlalchemy import util from sqlalchemy.dialects.mysql import base as mysql from sqlalchemy.testing import fixtures, AssertsCompiledSQL, AssertsExecutionR...
class TypesTest(fixtures.TestBase, AssertsExecutionResults, AssertsCompiledSQL): "Test MySQL column types" __dialect__ = mysql.dialect() __only_on__ = 'mysql' __backend__ = True def test_numeric(self): "E
xercise type specification and options for numeric types." columns = [ # column type, args, kwargs, expected ddl # e.g. Column(Integer(10, unsigned=True)) == # 'INTEGER(10) UNSIGNED' (mysql.MSNumeric, [], {}, 'NUMERIC'), (mysql.MSNumeric,...
Kunalpod/codewars
dubstep.py
Python
mit
163
0.02454
#Kunal Gautam #Codewars : @Kunal
pod #Problem name: Dubstep #Problem level: 6 kyu def song_decoder(song):
return " ".join(" ".join(song.split('WUB')).split())
HenryGBC/landing_company
landing/migrations/0001_initial.py
Python
mit
556
0.001799
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.
db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( nam
e='Prueba', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('nombre', models.CharField(max_length=100)), ], options={ }, bases=(models.Model,), ), ]
frc2423/2015
recycle_rush/commands/autonomous.py
Python
gpl-2.0
485
0.010309
import wpilib from wpilib.command.commandgroup import CommandGroup class Autonomous(Comma
ndGroup): def __init__(self, drive, grabber_lift): super().__init__() self.drive = drive self.grabber_lift = grabber_lift self.addSequential(ClawGrab(grabber_lift)) self.addSequential(MoveLift(grabber_lift, .5),
1.5) self.addParallel(TurnToSpecifiedAngle(drive, 180)) self.addSequential(ArcadeDrive(drive, 0, 1))