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 |
|---|---|---|---|---|---|---|---|---|
edx/edx-platform | openedx/core/djangoapps/api_admin/tests/test_models.py | Python | agpl-3.0 | 6,287 | 0.003022 | # pylint: disable=missing-docstring
from smtplib import SMTPException
from unittest import mock
import pytest
import ddt
from django.db import IntegrityError
from django.test import TestCase
from openedx.core.djangoapps.api_admin.models import ApiAccessConfig, ApiAccessRequest
from openedx.core.djangoapps.api_admin... | 'Error sending API user notification email for request [%s].', self.api_access_request.id
)
# Verify object saved
assert self.api_access_request.id is not None
with mock.patch(mail_function, side_effect=SMTPException):
with mock.patch.object(model_log, 'exception')... | Verify that updating request status logs email errors properly
mock_model_log_exception.assert_called_once_with(
'Error sending API user notification email for request [%s].', self.api_access_request.id
)
# Verify object saved
assert self.api_access_request.status == ApiAcces... |
huntxu/fuel-web | nailgun/nailgun/rpc/__init__.py | Python | apache-2.0 | 2,731 | 0.000366 | # -*- coding: utf-8 -*-
# Copyright 2013 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 requi... | conn, naily_service_exchange, naily_service_queue,
naily_exchange, naily_queue)
| publish()
|
ralhei/PyHDB | tests/test_cursor.py | Python | apache-2.0 | 9,174 | 0.000545 | # Copyright 2014, 2015 SAP SE.
#
# 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,
#... | statement
cursor = connection.cursor()
cursor.execute("SELECT 1 FROM DUMMY")
# Result is very small we got everything direct into buffer
assert cursor._received_last_resultset_part
cursor.execute("SELECT VIEW_NAME FROM PUBLIC.VIE | WS")
# Result is not small enouth for single resultset part
assert not cursor._received_last_resultset_part
@pytest.mark.hanatest
@pytest.mark.parametrize("method", [
'fetchone',
'fetchall',
'fetchmany',
])
def test_fetch_raises_error_after_close(connection, method):
cursor = connection.cursor... |
smartkiwi/interval_calculator | interval_calculator/bx/quicksect.py | Python | mit | 6,110 | 0.016858 | """
Intersects ... faster. Suports GenomicInterval datatype and multiple
chromosomes.
Copyright: James Taylor james@jamestaylor.org
This code is part of the bx-python package
license: bsd licensed
https://bitbucket.org/james_taylor/bx-python/src/ebf9a4b352d3267303657afd57bd184f379eaf28/lib/bx/intervals/operations/qui... | for x in range(5000):
start = random.randint(0, 10000000)
end = start + random.randint(1, 1000)
result = []
test.intersect( start, end, lambda x: result.append(x.linenum) )
print "%f for tree method" % (time.clock() - starttime)
starttime = time.clock()
for x in range(5000... | ) - starttime)
def test_func( node ):
print "[%d, %d), %d" % (node.start, node.end, node.maxend)
def bad_sect( lst, int_start, int_end ):
intersection = []
for start, end in lst:
if int_start < end and int_end > start:
intersection.append( (start, end) )
return intersection
if __n... |
TaliesinSkye/evennia | src/players/manager.py | Python | bsd-3-clause | 6,119 | 0.001307 | """
The managers f | or the custom Player object and permissions.
"""
import datetime
from functools import update_wrapper
from django.contrib.auth.models import User
from src.typeclasses.managers import returns_typeclass_list, returns_typeclass, TypedObjectManager
from src.utils import logger
__all__ = ("PlayerManager",)
#
# Player Mana... | ator that makes sure that a method
returns a Player object instead of a User
one (if you really want the User object, not
the player, use the player's 'user' property)
"""
def func(self, *args, **kwargs):
"This *always* returns a list."
match = method(self, *args, **kwargs)
i... |
huyphan/pyyawhois | test/record/parser/test_response_whois_nic_asia_status_available.py | Python | mit | 2,079 | 0.002886 |
# This file is autogenerated. Do not edit it manually.
# If you want change the content of this file, edit
#
# spec/fixtures/responses/whois.nic.asia/status_available
#
# and regenerate the tests with the following script
#
# $ scripts/generate_tests.py
#
from nose.tools import *
from dateutil.parser import parse... | host)
self.record = yawhois.record.Record(None, [part])
def test_status(self):
eq_(self.record.status, [])
def test_available(self):
eq_(self.record.available, True)
def test_domain(self):
eq_(self.record.domain, None)
def test_reserved(self):
eq_(self.record... | rd.nameservers.__class__.__name__, 'list')
eq_(self.record.nameservers, [])
def test_admin_contacts(self):
eq_(self.record.admin_contacts.__class__.__name__, 'list')
eq_(self.record.admin_contacts, [])
def test_registered(self):
eq_(self.record.registered, False)
def test_... |
jbalogh/jingo | run_tests.py | Python | bsd-3-clause | 522 | 0 | import os
import nose
import django
NAME = os.path.basename(os.path.dirname(__file__))
ROOT = os.path.abspath(os.path.dirname(__file__))
os.environ['DJANGO_SETTINGS_MODU | LE'] = 'fake_settings'
os.environ['PYTHONPATH'] = os.pathsep.join([ROOT,
os.path.join(ROOT, 'examples')])
if __name__ == '__main__':
if hasattr(django, 'setup'):
# Django's app registry was added in 1.7. We need to c | all `setup` to
# initiate it.
django.setup()
nose.main()
|
cgstudiomap/cgstudiomap | main/parts/product-attribute/product_customer_code/product.py | Python | agpl-3.0 | 3,314 | 0 | # -*- coding: | utf-8 -*-
###########################################################################
# Module Writen to OpenERP, Open Source Management Solution
#
# Copyright (c) 2012 Vauxoo - http://www.vauxoo.com
# All Rights Rese | rved.
# info@vauxoo.com
############################################################################
# Coded by: Rodo (rodo@vauxoo.com),Moy (moylop260@vauxoo.com)
############################################################################
#
# This program is free software: you can redistribute it and/or modif... |
HelloTechie/tweeting_turkey | turkey_tweet.py | Python | mit | 1,243 | 0.00885 | #!/usr/bin/python
import sys
sys.path.insert(0, '/usr/local/lib/python2.7/site-packages/')
import mraa
import time
from twython import | Twython
# Authentication - Obtain Authorization URL
APP_KEY = 'lXZFwVtC8CGPKs4LOuv2m7WGS'
APP_SECRET = 'AoToSyNNyhzg2EhN38Edx6bQ59wPSLH8ztLZNZkWt1us7IzKUl'
OAUTH_TOKEN = '2892359329-fcC7F5l7Jx9CutiQACVrsTAUHN6GilG6RjmJPaH'
OAUTH_TOKEN_SECRET = '7HakyTT0SxwM8jAXjT8IPs73GW9QECRp3WnjUxXVNkmQZ'
twitter = Twython(APP_KEY,... | sor = mraa.Aio(0)
thresholds ={
60: 'Guys, it is starting to get warm in here...',
80: 'Boys, do I smell good',
100: 'Yum time! @hello_techie'
}
while 1:
temp = tempSensor.read() / 2.048
print('Current Temperature: %.3fC' % temp)
... |
BrandonLMorris/auacm-cli | src/auacm/main.py | Python | mit | 2,810 | 0.001068 | """
main.py
The central entry point of the auacm app.
"""
import requests, sys, textwrap
import auacm
import auacm.utils as utils
from auacm.exceptions import ConnectionError, ProblemNotFoundError, UnauthorizedException, InvalidSubmission, CompetitionNotFoundError
def main(args):
"""
Entry point for the auac... | :
print(utils.callbacks[args[0]](args[1:]) or '')
except (ProblemNotFoundError,
UnauthorizedException,
InvalidSubmission,
CompetitionNotFoundError) as exp: |
print(exp.message)
exit(1)
except (requests.exceptions.ConnectionError, ConnectionError):
print('There was an error connecting to the server: {}'
.format(auacm.BASE_URL))
exit(1)
else:
print('Whoops, that subcommand isn\'t supported... |
hurricup/intellij-community | python/testData/codeInsight/liveTemplates/context/general.py | Python | apache-2.0 | 13 | 0.230769 | p< | caret>
pass | |
tamasgal/controlhost | setup.py | Python | mit | 751 | 0.003995 | from setuptools import setup
from controlhost import version
setup(name='controlhost',
version=version,
url='https://github.com/tamasgal/controlhost/',
descri | ption='A set of classes and tools wich uses the ControlHost protocol.',
author='Tamas Gal',
author_email='himself@tamasgal.com',
packages=['controlhost'],
include_package_data=True,
platforms='any',
install_requires=[
],
entry_points={
'console_scripts': [
... | ogramming Language :: Python',
],
)
__author__ = 'Tamas Gal'
|
guykisel/inline-plz | tests/parsers/test_jsonlint.py | Python | isc | 753 | 0.003984 | # -*- coding: utf-8 -*-
import inlineplz.linters.jsonlint as jsonlint
def test_jsonlint():
input = [
("21.json", "21.json: line 1, col 25, found: ',' - expected: ':'. | "),
(
"25.json",
"25.json: line 1, col 1, found: 'INVALID' - expected: 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', ']'.",
),
(
"23.json",
"23.json: line 1, col 13, found: 'INVALID' - expected: 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE',... | assert messages[0][2] == "21.json: line 1, col 25, found: ',' - expected: ':'."
assert messages[0][1] == 1
assert messages[0][0] == "21.json"
|
cloudysunny14/CloudySwitch | cloudyswitch/app/topology_util.py | Python | apache-2.0 | 2,860 | 0.003846 | #!/usr/bin/env python
#
# Copyright 2013 cloudysunny14.
#
# 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... | r
# implied.
# See the License for | the specific language governing permissions and
# limitations under the License.
import logging
from ryu.exception import RyuException
def find_all_paths(graph, start, end, path=[]):
path = path + [start]
if start == end:
return [path]
if not graph.has_key(start):
return []
paths = []
... |
superdesk/superdesk-ntb | server/ntb/commands/update_items.py | Python | agpl-3.0 | 2,412 | 0.001244 |
import bson
import bson.errors
import superdesk
from .update_topics import UpdateTopicsScript
from .update_places import UpdatePlacesScript
RESOURCES = ('events', 'planning', 'archive', 'published', 'archived')
SCRIPTS = [
("topics", UpdateTopicsScript()),
("places", UpdatePlacesScrip | t()),
]
def get_id(id):
try:
return bson.ObjectId(id)
except bson.errors.InvalidId:
return id
class UpdateItemsCommand(superdesk.Command):
"""Update Items"""
option_list = [
superdesk.Option('--resource', '-r', dest='resources', action='append', choices=RESOURCES),
s... | elf, resources=None, last=None):
if not resources:
resources = RESOURCES
for resource in resources:
print("updating {resource}".format(resource=resource))
service = superdesk.get_resource_service(resource)
last_id = None
if last:
... |
robertwatsonbath/gr-specest-3.7 | python/specest_mtm.py | Python | gpl-3.0 | 4,472 | 0.006485 | #!/usr/bin/env python
#
# Copyright 2010 Communications Engineering Lab, KIT
#
# This 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, or (at your option)
# any later version.
#
# This softwar... | h Product usually is of value 2, 2.5, 3.0, 3.5, or 4
# @param[in] K: Numbers of Tapers to use. K should be smaller than 2*NW
# @param[in] weighting: Which type of weighting to use for the eigenspectra. Choices can be 'unity','eigenvalues' or adaptive
class mtm(gr.hier_block2):
""" Esti | mates PSD using Thomson's multitaper method. """
def __init__(self, N=512 , NW=3 , K=5, weighting='adaptive', fftshift=False):
gr.hier_block2.__init__(self, "mtm",
gr.io_signature(1, 1, gr.sizeof_gr_complex),
gr.io_signature(1, 1, gr.sizeof_float*N))
self.check_parame... |
AnselCmy/ARPS | report_crawler/report_crawler/spiders/spiders_001/_H/HNU001.py | Python | mit | 1,423 | 0.020334 | # -*- coding:utf-8 -*-
import scrapy
from report_crawler.spiders.__Global_function import get_localtime
from report_crawler.spiders.__Global_variable import now_time, end_time
class HNU001_Spider(scrapy.Spider):
name = 'HNU001'
start_urls = ['http://csee.hnu.edu.cn/Front/TZXX_List?LMXX_BH=20130728174138ec48068e-48b... | 南大学大学信息科学与工程学院",
'faculty': self.name, 'link': response.meta['link'], 'publica | tion': response.meta['publication'],
'location': u"华中:湖南省-长沙市", 'title': response.meta['title']}
|
northern-bites/nao-man | noggin/playbook/Strategies.py | Python | gpl-3.0 | 4,793 | 0.005216 | from .. import NogginConstants
from . import PBConstants
from . import Formations
def sReady(team, workingPlay):
workingPlay.setStrategy(PBConstants.S_READY)
Formations.fReady(team, workingPlay)
def sNoFieldPlayers(team, workingPlay):
workingPlay.setStrategy(PBConstants.S_NO_FIELD_PLAYERS)
Formations.... | ay):
"""
We attempt to keep one robot forward and one back
They become chaser if the ball is closer to them
"""
sTwoField(te | am, workingPlay)
def sWin(team, workingPlay):
workingPlay.setStrategy(PBConstants.S_WIN)
# Kickoff Formations
if useKickoffFormation(team):
Formations.fKickoff(team,workingPlay)
# Formation for ball in our goal box
elif shouldUseDubD(team):
Formations.fTwoDubD(team, workingPlay)
... |
sgabe/Enumerator | enumerator/lib/services/snmp.py | Python | mit | 2,455 | 0.002037 | #!/usr/bin/env python
"""
The SNMP module performs snmp-related
enumeration tasks.
@author: Gabor Seljan (gabor<at>seljan.hu)
@version: 1.0
"""
import sys
from ..config import Config
from ..process_manager import ProcessManager
from ..generic_service import GenericService
class SnmpEnumeration(GenericService, Proces... | t)s',
'normal': '-T4',
'stealth': '-T2',
}, {
'command': 'onesixtyone -o %(output_dir)s/%(host)s-snmp-%(port)s-onesixtyone.txt %(host)s',
'normal': '',
'stealth': '',
}, {
'command': 'snmpwalk -c public -v1 %(host)s 1 > %(output_dir)s/%(host)s-snmp-%(port)s-snmpwa... | mand': 'snmpcheck -t %(host)s > %(output_dir)s/%(host)s-snmp-%(port)s-snmpcheck.txt',
'normal': '',
'stealth': '',
}]
def scan(self, directory, service_parameters):
"""Iterates over PROCESSES and builds
the specific parameters required for
command line execution of each ... |
sontung/pick_a_number | sound/click_sound.py | Python | mit | 116 | 0 | import pygame
py | game.mixer.init()
sound_object = pygame.mixer.Sound("sound/beep1.ogg")
sou | nd_object.set_volume(1)
|
HydrelioxGitHub/home-assistant | homeassistant/components/mysensors/sensor.py | Python | apache-2.0 | 2,939 | 0 | """Support for MySensors sensors."""
from homeassistant.components import mysensors
from homeassistant.components.sensor import DOMAIN
from homeassistant.const import TEMP_CELSIUS, TEMP_FAHRENHEIT
SENSORS = {
'V_TEMP': [None, 'mdi:thermometer'],
'V_HUM': ['%', 'mdi:water-percent'],
'V_DIMMER': ['%', 'mdi:p... | atform(
hass, config, async_add_entities, discovery_info=None):
"""Set up the My | Sensors platform for sensors."""
mysensors.setup_mysensors_platform(
hass, DOMAIN, discovery_info, MySensorsSensor,
async_add_entities=async_add_entities)
class MySensorsSensor(mysensors.device.MySensorsEntity):
"""Representation of a MySensors Sensor child node."""
@property
def forc... |
caktus/django-opendebates | opendebates/tests/test_admin.py | Python | apache-2.0 | 4,608 | 0.001085 | from functools import partial
from django.contrib.admin.sites import AdminSite
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse
from django.test import TestCase
from mock import patch
from opendebates.admin import SubmissionAdmin
from opendebates.models import Submission
from ... | lf.assertEqual(untouched_submission.count(), 1)
# and 2 emails have been sent
self.assertEqual(mock_send_email.call_count, 2)
@patch('opendebates.admin.send_email')
def test_dont_send_email_if_already_unapproved(self, moc | k_send_email):
"If submission was already unapproved, don't bug the user again."
data = {
'post': 'Yes',
'action': 'remove_submissions',
'_selected_action': [SubmissionFactory(approved=False).pk]
}
rsp = self.client.post(self.changelist_url, data=data)... |
craws/OpenAtlas-Python | openatlas/views/model.py | Python | gpl-2.0 | 9,096 | 0 | from typing import Any, Dict, Optional
from flask import g, render_template, url_for
from flask_babel import format_number, lazy_gettext as _
from flask_wtf import FlaskForm
from wtforms import (
BooleanField, IntegerField, SelectMultipleField, StringField, SubmitField,
widgets)
from wtforms.validators import ... | ange', [InputRequired()])
save = SubmitField(uc_first(_('test')))
@app.route('/overview/model', methods=["GET", "POST"])
@required_group('readonly')
def model_index() -> str:
form = LinkCheckForm()
form_classes = \
{code: f'{code} {class_.name}'
for code, class_ in g.cidoc_classes.items()... | nge.choices = form_classes
form.cidoc_property.choices = {
code: f'{code} {property_.name}'
for code, property_ in g.properties.items()}
result = None
if form.validate_on_submit():
domain = g.cidoc_classes[form.cidoc_domain.data]
range_ = g.cidoc_classes[form.cidoc_range.data... |
tuanchien/tascc | modules/ReadSensorsOwfs.py | Python | gpl-2.0 | 796 | 0.016332 | # ReadSensorsOwfs.py
###########################################################
# Class handles loading of thermometer sensor information #
# from the interface exposed by the owfs fuse #
# module. #
##########################################################... | lass ReadSensorsOwfs:
def __init__(self, sensors, sensorData, owfsPath):
self.sensors = sensors
self.sensorData = sensorData
self.directory = owfsPath
def refreshSensors(self):
for sensor in self.sensors:
self.updateSensor(sensor)
def updateSensor(self, sensor):
sensorFile = open('%s/%s/temperature' %... | or] = str(int(float(temperature)*1000))
|
joachimmetz/plaso | plaso/parsers/sqlite_plugins/firefox_history.py | Python | apache-2.0 | 19,252 | 0.003324 | # -*- coding: utf-8 -*-
"""SQLite parser plugin for Mozilla Firefox history database files."""
from dfdatetime import posix_time as dfdatetime_posix_time
from plaso.containers import events
from plaso.containers import time_events
from plaso.lib import definitions
from plaso.parsers import sqlite
from plaso.parsers.s... |
"""Firefox page visited event data.
Attributes:
from_visit (str): URL that referred to the visited page.
hidden (str): value to indicated if the URL was hidden.
host (str): visited hostname.
offset (str): identifier of the row, from which the event data was
extracted.
query (str): SQL ... | ed page.
visit_count (int): visit count.
visit_type (str): transition type for the event.
"""
DATA_TYPE = 'firefox:places:page_visited'
def __init__(self):
"""Initializes event data."""
super(FirefoxPlacesPageVisitedEventData, self).__init__(
data_type=self.DATA_TYPE)
self.from_visit... |
Oisota/Breakout | breakout/editor/editor.py | Python | gpl-3.0 | 3,858 | 0.005962 | """
Editor Module
This module defines the Editor class. This module runs
the game's level editor.
"""
import sys, os
import tkinter as tk
from tkinter.filedialog import askopenfilename, asksaveasfilename
from .. import asset
from ..config import START_LEVEL, LEVEL_PATH
from .brick import BrickFrame
from .entry impo... | veasfilename(initialdir=LEVEL_PATH, initialfile=self.level_filename)
if filename != '':
self.level_filename = filename
level = {
'name': self.entry_frame.level_name.get(),
'ball_speed': sel | f.entry_frame.ball_speed.get(),
'next': self.entry_frame.next_level.get(),
'bricks': self.brick_frame.bricks
}
asset.save_level(level, self.level_filename)
def open_level(self):
"""Open the level file."""
filename = askopenfil... |
ChaseSnapshot/smcity | smcity/models/aws/aws_data.py | Python | unlicense | 6,158 | 0.006983 | ''' Data model and factory implementations that are backed by Amazon Web Service's DynamoDB2 NoSQL database '''
from boto.dynamodb2.table import Table
from time import strftime, strptime
from smcity.misc.errors import CreateError, ReadError
from smcity.misc.logger import Logger
from smcity.models.data import Data, Da... |
return (lon, lat)
def get_set_id(self):
''' {@inheritDocs} '''
return self.record['set_id']
def get_timestamp(self):
''' {@inheritDocs} '''
return strptime(self.record['timestamp'], '%Y-%m-%d %H:%M:%S')
def get_type(self):
''' {@inheritDocs} '''
re... | ig Configuration settings. Expected definition:
Section: database
Key: data_table
Type: string
Desc: Name of the Data model table
@paramType ConfigParser
@returns n/a
'''
self.global_table = Table(config.get('database', 'global_data_table'))
... |
oblique-labs/pyVM | rpython/jit/backend/llsupport/test/ztranslation_test.py | Python | mit | 11,930 | 0.004946 | import os, sys, py
from rpython.tool.udir import udir
from rpython.rlib.jit import JitDriver, unroll_parameters, set_param
from rpython.rlib.jit import PARAMETERS, dont_look_inside
from rpython.rlib.jit import promote, _get_virtualizable_token
from rpython.rlib import jit_hooks, rposix, rgc
from rpython.rlib.objectmode... | ualizable_ = ['i']
def __init__(self, i):
self.i = i
from rpython.rlib.libffi import types, CDLL, ArgChain
from rpython.rlib.test.test_clibffi import get_libm_name
libm_name = get_libm_name(sys.platform)
jitdriver2 = JitDriver(greens=[], reds = ['v2', 'func', ... | r('fabs', [types.double], types.double)
res = 0.0
x = float(j)
v2 = Virt2(i)
while v2.i > 0:
jitdriver2.jit_merge_point(v2=v2, res=res, func=func, x=x)
promote(func)
argchain = ArgChain()
argchain.arg(x)
... |
sbellver/rdiffweb | rdiffweb/page_prefs.py | Python | gpl-3.0 | 5,423 | 0 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# rdiffweb, A web interface to rdiff-backup repositories
# Copyright (C) 2014 rdiffweb contributors
#
# 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, ei... |
"userEmail": email,
"notificationsEnabled": False,
"backups": [],
"sampleEmail": self.sampleEmail
}
if email_notification.emailNotif | ier().notificationsEnabled():
repos = self.getUserDB().get_repos(self.getUsername())
backups = []
for repo in repos:
maxAge = self.getUserDB().get_repo_maxage(
self.getUsername(), repo)
notifyOptions = []
for i in ra... |
CharlieCorner/pymage_downloader | argparsers.py | Python | apache-2.0 | 5,447 | 0.00257 | from argparse import ArgumentParser
VERSION = "2.0.0"
def parse_args():
"""Parse args with argparse
:returns: args
"""
parser = ArgumentParser(description=f"Pymage Downloader {VERSION} - Download pics from different sites")
build_site_subparsers(parser)
parser.add_argument('--destination', ... | dest="page_limit",
metavar='N',
type=int,
default=4,
help="Maximum amount of pages to get.")
reddit_argparser.add_argument('--start-from', '-sf',
| dest="start_from",
metavar='ID',
help="Post ID from which to get a listing.")
# Subreddit mode
subreddit_mode = reddit_modes.add_parser("subreddit",
description="Mani... |
zhaopu7/models | nmt_without_attention/nmt_without_attention.py | Python | apache-2.0 | 8,713 | 0.000574 | #!/usr/bin/env python
import sys
import gzip
import paddle.v2 as paddle
### Parameters
word_vector_dim = 620
latent_chain_dim = 1000
beam_size = 5
max_length = 50
def seq2seq_net(source_dict_dim, target_dict_dim, generating=False):
'''
Define the network structure of NMT, including encoder and decoder.
... | a(
name='target_language_next_word',
type=paddle.data_type.integer_value_sequence(target_dict_dim))
cost = paddle.layer.classification_cost(input=decoder, label=lbl)
return cost
else:
trg_embedding = paddle.layer.GeneratedInput(
size=target_dict_dim,
... | _search(
name=decoder_group_name,
step=gru_decoder_without_attention,
input=group_inputs,
bos_id=0,
eos_id=1,
beam_size=beam_size,
max_length=max_length)
return beam_gen
def train(source_dict_dim, target_dict_dim):
'''
... |
willicab/instalador | instalador/clases/particiones.py | Python | gpl-2.0 | 15,469 | 0.001685 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# =============================================================================
# PAQUETE: instalador
# ARCHIVO: instalador/config.py
# COPYRIGHT:
# (C) 2012 William Abrahan Cabrera Reyes <william@linux.es>
# (C) 2012 Erick Manuel Birbe Salazar <erickcion@gmai... |
try:
disk.commit()
i += 1
except Exception, e:
print e
if i == 5:
if pedtype == _ped.PARTITION_EXTENDED:
return True
else:
if fs in FSPROGS:
fo | r pid in FSPROGS[fs][3]:
pnum = self.num_particion(drive, partype, start, end)
if ProcessGenerator(pid.format(drive, pnum)).returncode == 0:
k += 1
if k == len(FSPROGS[fs][3]):
if format:
... |
NeurodataWithoutBorders/api-python | nwb/check_schema.py | Python | bsd-3-clause | 2,669 | 0.010116 | # script to validate h5gate schema files using json schema
import os.path
import sys
# import json
import jsonschema
import ast
def load_schema(file_name):
""" Load Python file that contains JSON formatted as a Python dictionary.
Files in this format are used to store the schema because, unlike pure JSON,
... | tents = f.read()
f.close()
#
# with file(file_ | name) as f:
# file_contents = f.read()
try:
# use use ast.literal_eval to parse
pydict = ast.literal_eval(file_contents)
except Exception as e:
print ("** Unable to parse file '%s' (should be mostly JSON)" % file_name)
print ("Error is: %s" % e)
sys.exit(1)
as... |
openhdf/enigma2-wetek | keyids.py | Python | gpl-2.0 | 5,381 | 0.057053 | KEYIDS = {
"KEY_RESERVED": 0,
"KEY_ESC": 1,
"KEY_1": 2,
"KEY_2": 3,
"KEY_3": 4,
"KEY_4": 5,
"KEY_5": 6,
"KEY_6": 7,
"KEY_7": 8,
"KEY_8": 9,
"KEY_9": 10,
"KEY_0": 11,
"KEY_MINUS": 12,
"KEY_EQUAL": 13,
"KEY_BACKSPACE": 14,
"KEY_TAB": 15,
"KEY_Q": 16,
"KEY_W": 17,
"KEY_E": 18,
"KEY_R": 19,
"KEY_T": 20,
"KEY_Y": 21,
"KEY_U... | ": 364,
"KEY_EPG": 365,
"KEY_PVR": 366,
"KEY_MHP": 367,
"KEY_LANGUAGE": 368,
"KEY_TITLE": 369,
"KEY_SUBTITLE": 370,
"KEY_ANGLE": 371,
"KEY_ZOOM": 372,
"KEY_MODE": 373,
"KEY_KEYBOARD": 374,
"KEY_SCREEN": 375,
"KEY_PC": 376,
"KEY_TV": 377,
"KEY_TV2": 378,
"KEY_VCR": 379,
"KEY_VCR2": 380,
"KEY_SAT": 381,
"KEY_SAT2": 382,
... | "KEY_VIDEO": 393,
"KEY_DIRECTORY": 394,
"KEY_LIST": 395,
"KEY_MEMO": 396,
"KEY_CALENDAR": 397,
"KEY_RED": 398,
"KEY_GREEN": 399,
"KEY_YELLOW": 400,
"KEY_BLUE": 401,
"KEY_CHANNELUP": 402,
"KEY_CHANNELDOWN": 403,
"KEY_FIRST": 404,
"KEY_LAST": 405,
"KEY_AB": 406,
"KEY_NEXT": 407,
"KEY_RESTART": 408,
"KEY_SLOW": 409,
"KEY_... |
vaibhav-singh/django-travis-setup | django_travis_setup/example/apps.py | Python | mit | 154 | 0 | # | -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.apps import AppConfig
class ExampleConfig(AppConfig):
name = 'exa | mple'
|
DaanHoogland/cloudstack | systemvm/debian/opt/cloud/bin/cs_forwardingrules.py | Python | apache-2.0 | 3,239 | 0.000617 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | g,
# software distributed under the License i | s distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
def merge(dbag, rules):
for rule in rules["rules"]:
source_ip = rule["source_ip_address"]
... |
Fale/ansible | lib/ansible/modules/debug.py | Python | gpl-3.0 | 2,420 | 0.003719 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2012 Dag Wieers <dag@wieers.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = r'''
---
module: debug
short_... | ostname }} has gateway {{ ansible_default_ipv4.gateway }}
when: ansible_default_ipv4.gateway is defined
- name: Get uptime information
ansible.builtin.shell: /usr/bin/uptime
register: result
- name: Print return information from the previous task
ansible.builtin.debug:
var: result
verbosity: 2
- name... | wo lines of messages, but only if there is an environment value set
ansible.builtin.debug:
msg:
- "Provisioning based on YOUR_KEY which is: {{ lookup('env', 'YOUR_KEY') }}"
- "These servers were built using the password of '{{ password_used }}'. Please retain this for later use."
'''
|
arju88nair/projectCulminate | venv/lib/python3.5/site-packages/astroid/brain/brain_subprocess.py | Python | apache-2.0 | 3,314 | 0.001509 | # Copyright (c) 2016 Claudiu Popa <pcmanticore@gmail.com>
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER
import sys
import textwrap
import six
import astroid
PY33 = sys.version_info >= (3, 3)
PY36 = s... | ode = textwrap.dedent('''
class Popen(object):
returncode = pid = 0
stdin = stdout = stderr = file()
%(communicate_signature)s:
return %(communicate)r
%(wait_signature)s:
return self.returncode
def poll(self):
return self.returncode
... | def terminate(self):
pass
def kill(self):
pass
%(ctx_manager)s
''' % {'communicate': communicate,
'communicate_signature': communicate_signature,
'wait_signature': wait_signature,
'ctx_manager': ctx_manager})
init_lines... |
ryfeus/lambda-packs | pytorch/source/caffe2/python/layers/last_n_window_collector.py | Python | mit | 2,543 | 0.000393 | ## @package last_n_window_collector
# Module caffe2.python.layers.last_n_window_collector
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, schema
from caffe2.python.layers.layers import M... | use PackRecords to pack it before using this layer.
This layer is not thread safe.
"""
def __init__(self, model, input_record, num_to_collect,
| name='last_n_window_collector', **kwargs):
super(LastNWindowCollector, self).__init__(
model, name, input_record, **kwargs)
assert num_to_collect > 0
self.num_to_collect = num_to_collect
assert isinstance(input_record, schema.Scalar), \
"Got {!r}".format(inp... |
deepmind/pysc2 | pysc2/lib/buffs.py | Python | apache-2.0 | 2,114 | 0.022706 | # Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | 3
BlindingCloudStructure = 38
CarryHarvestableVespeneGeyserGas = 273
CarryHarvestableVespeneGeyserGasProtoss = 274
CarryHarvestableVespeneGeyserGasZerg = 275
CarryHighYieldMineralFieldMinerals = 272
CarryMineralFieldMinerals = 271
ChannelSnipeCombat = 145
Charging = 30
ChronoBoostEnergyCost = 281
Cl... | ontaminated = 36
EMPDecloak = 16
FungalGrowth = 17
GhostCloak = 6
GhostHoldFire = 12
GhostHoldFireB = 13
GravitonBeam = 5
GuardianShield = 18
ImmortalOverload = 102
InhibitorZoneTemporalField = 289
LockOn = 116
LurkerHoldFire = 136
LurkerHoldFireB = 137
MedivacSpeedBoost = 89
NeuralParasite ... |
asimshankar/tensorflow | tensorflow/python/data/experimental/benchmarks/rejection_resample_benchmark.py | Python | apache-2.0 | 2,449 | 0.004492 | # 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... | IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Benchmarks for `tf.data.experimental.rejection... | m __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import numpy as np
from six.moves import xrange # pylint: disable=redefined-builtin
from tensorflow.python.data.experimental.ops import resampling
from tensorflow.python.data.ops import dataset_ops
... |
nnabeyang/MY_jinja2 | MY_jinja2/visitor.py | Python | bsd-3-clause | 247 | 0.016194 | class NodeVisitor:
def visit(self, node, *args):
try:
retu | rn getattr(self, 'visit_' + node.__class__.__name__)(node, *args)
except AttributeError:
| pass
for child in node.iter_child_nodes():
self.visit(child, *args)
|
KlausPopp/Moddy | setup.py | Python | lgpl-3.0 | 1,397 | 0 | # created based on
# https://python-packaging.readthedocs.io/en | /latest/minimal.html
# But instead of python setup.py register sdist upload,
# use https://pypi.org/p/twine/
#
from setuptools import setup
import sys
import os
import re
sys.path.append("src")
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except IOError:
... | ndall(r"([0-9]+)", txt)
print("ver=%s" % ver)
return ver[0] + "." + ver[1] + "." + ver[2]
setup(
name="moddy",
install_requires=["svgwrite"],
version=readVersion(),
description="A discrete event simulator generating sequence diagrams",
long_description=read("README.rst"),
url="https://... |
MokaCreativeLLC/XNATSlicer | XNATSlicer/XnatSlicerLib/ui/FolderMaker.py | Python | bsd-3-clause | 18,465 | 0.006986 | __author__ = "Sunil Kumar (kumar.sunil.p@gmail.com)"
__copyright__ = "Copyright 2014, Washington University in St. Louis"
__credits__ = ["Sunil Kumar", "Steve Pieper", "Dan Marcus"]
__license__ = "XNAT Software License Agreement " + \
"(see: http://xnat.org/about/license.php)"
__version__ = "2.1.1"
__main... | if (event.type() == 3 or event.type() == 7) and widget == lineEdit:
#print "CLICK!"
if widget.enabled:
self.__onLineEditTextChanged(level, lineEdit.text)
def __getSelectedXnatLevel(self):
"""
Get the current XNAT level of the selec... | el valid for adding a folder. (Usually between
'projects' and 'experiments')
@rtype: string
"""
selectedXnatLevel = ''
try:
selectedXnatLevel = self.View.getItemLevel()
if not selectedXnatLevel in self.xnatLevels:
selectedXnatLevel = s... |
amhokies/Timetable-Stalker | course_search.py | Python | mit | 2,048 | 0.000488 | from bs4 import BeautifulSoup
from models.course import Course
import requests
default_postdata = {
'CAMPUS': '0',
'TERMYEAR': '201709',
'CORE_CODE': 'AR%',
'subj_code': '',
'CRSE_NUMBER': '',
'crn': '',
'open_only': 'on',
'BTN_PRESSED': 'FIND class sections',
}
url = 'https://banweb.b... | )
label = cell | s_text[1].strip()
title = cells_text[2].strip()
professor = cells_text[6].strip()
open_courses.append(Course(crn, label, title, professor))
return open_courses
def get_open_courses_by_course(subj, num, semester):
""" Get the open courses that match the course subject and ... |
marklescroart/bvp | bvp/utils/__init__.py | Python | bsd-2-clause | 165 | 0.012121 | """
Initialization of util | s.
Couple handy-dandy functions:
"""
from __future__ import absolute_import
from | . import basics
from . import blender
from . import math |
balolam/university-mpi-python | practical_task_1/task2.py | Python | apache-2.0 | 516 | 0.001938 | from mpi4py | import MPI
from utils.mpi_helper import finalize
from utils.mpi_helper import init
init()
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
print "process [", rank, "] - running"
if rank == 0:
data = {'name': "PROCESS-" + str(rank), 'msg': "Hello"}
req = comm.isend(data, dest=1, tag=11)
... | ", data['name'], "say", data['msg']
finalize()
|
huzq/scikit-learn | examples/gaussian_process/plot_gpr_prior_posterior.py | Python | bsd-3-clause | 8,547 | 0.001989 | """
==========================================================================
Illustration of prior and posterior Gaussian process for different kernels
==========================================================================
This example illustrates the prior and posterior of a
:class:`~sklearn.gaussian_process.Ga... | rows=2, sharex=True, sharey=True, figsize=(10, 8))
# plot prior
plot_gpr_samples(gpr, n_samples=n_samples, ax=axs[0])
axs[0].set_title("Samples from prior distribution")
# plot posterior
gpr.fit(X_train, y_train)
plot_gpr_samples(gpr, n_samples=n_samples, ax=axs[1])
axs[1].scatter(X_train[:, 0], y | _train, color="red", zorder=10, label="Observations")
axs[1].legend(bbox_to_anchor=(1.05, 1.5), loc="upper left")
axs[1].set_title("Samples from posterior distribution")
fig.suptitle("Periodic kernel", fontsize=18)
plt.tight_layout()
# %%
print(f"Kernel parameters before fit:\n{kernel})")
print(
f"Kernel paramete... |
gallantlab/pycortex | cortex/dataset/dataset.py | Python | bsd-2-clause | 8,008 | 0.003746 | import tempfile
import numpy as np
import h5py
from ..database import db
from ..xfm import Transform
from .braindata import _hdf_write
from .views import normalize as _vnorm
from .views import Dataview, Volume, _from_hdf_data
class Dataset(object):
"""
Wrapper for multiple data objects. This often does not n... | uniques = set()
for name, view in self:
for sv in view.uniques(collapse=collapse):
uniques.add(sv)
return uniques
def save(self, filename=None, pack=False):
if filename is not None:
self.h5 = h5py.File(filename, 'a')
elif self.h5 is No... | ame, view in self.views.items():
view._write_hdf(self.h5, name=name)
if pack:
subjs = set()
xfms = set()
masks = set()
for view in self.views.values():
for data in view.uniques():
subjs.add(data.subject)... |
citibeth/twoway | stieglitz/gic2stieglitz.py | Python | gpl-3.0 | 1,293 | 0.010054 | import os
import sys
import numpy as np
from giss.ncutil import copy_nc
import netCDF4
import argparse
from modele.constants import SHI,LHM,RHOI,RHOS,UI_ICEBIN,UI_NOTHING
parser = argparse.ArgumentParser(description= | 'Convert GIC file for old snow/firn model to one for Stieglitz.')
parser.add_argument('igic',
help="Name of classic GIC file to read")
parser.add_argument('--dir', '-d', dest='dir', default=' | .',
help='Directory in which to look for input file and --output dir')
parser.add_argument('--output', '-o', dest='ogic', required=True,
default=None,
help="Name of output Stieglitz GIC file to write. (Or directory if it ends in a slash)")
#parser.add_argument('--nlice', '-n', dest='nlice', type=int, defau... |
dgelessus/pythonista-scripts | wannabetabs.py | Python | mit | 2,450 | 0.006531 | # -*- coding: utf-8 -*-
###############################################################################
# wannabetabs by dgelessus
###############################################################################
import editor
import os
import ui
def full_path(path):
# Return absolute path with expanded ~ and symli... | ui.ButtonItem(title=" ", action=tb_button_action),
tab_list.right_button_items = (ui.ButtonItem(title=" ", action=tb_button_action), ui.ButtonItem(title="Edit", action=tb_button_action), ui.ButtonItem(image=ui.Image.named("ionicons-ios7 | -plus-empty-32"), action=tb_button_action))
nav = ui.NavigationView(tab_list, flex="WH")
nav.navigation_bar_hidden = False
root_view.add_subview(nav)
root_view.present("sidebar")
nav.width = root_view.width
nav.height = root_view.height
|
depop/celery-message-consumer | event_consumer/test_utils/handlers.py | Python | apache-2.0 | 1,527 | 0 | import logging
from event_consumer.conf import settings
from event_consumer.errors import PermanentFailure
from event_consumer.handlers import message_handler
_logger = logging.getLogger(__name__)
class IntegrationTestHandlers(object):
"""
Basic message handlers that log or raise known exceptions to allow
... | g)
if settings.TEST_ENABLED:
# Add tasks for interactive testing (call decorators directly)
message_handler('py.integration.ok')(
| IntegrationTestHandlers.py_integration_ok)
message_handler('py.integration.raise')(
IntegrationTestHandlers.py_integration_raise)
message_handler('py.integration.raise.permanent')(
IntegrationTestHandlers.py_integration_raise_permanent)
|
szha/mxnet | tests/python/gpu/test_kvstore_gpu.py | Python | apache-2.0 | 6,074 | 0.003787 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | np.random.randint(num_rows, size=num_rows)
row_ids = [mx.nd.array(row_id)] * count
elif use_slice:
total_row_ids = mx.nd.array(np.random.randint(num_rows, size=count*num_rows))
row_ids = [total_row_ids[i*num_rows : (i+1)*num_rows] for i in range(count)]
... | ids.append(mx.nd.array(row_id))
row_ids_to_pull = row_ids[0] if (len(row_ids) == 1 or is_same_rowid) else row_ids
vals_to_pull = vals[0] if len(vals) == 1 else vals
kv.row_sparse_pull('e', out=vals_to_pull, row_ids=row_ids_to_pull)
for val, row_id in zip(vals, row_ids):
... |
nre/Doxhooks | tests/unit_tests/conftest.py | Python | mit | 1,575 | 0 | import io
from pytest import fixture
class _FakeOutputFile(io.StringIO):
def close(self):
self.contents = self.getvalue()
super().close()
@fixture
def fake_output_file():
return _FakeOutputFile()
type_example_values = {
"none": (None,),
"callable": (lambda: None,),
"bool": (T... | aining_basic_types = basic_types.difference(*excluded_basic_types)
example_values = []
for basic_type in remaining_basic_types:
example_values.extend(type_example_values[basic_type]) |
return example_values
@fixture(params=values_not_from_types("int", "none"))
def not_int_or_none(request):
return request.param
@fixture(params=values_not_from_types("str"))
def not_str(request):
return request.param
|
keon/algorithms | algorithms/search/jump_search.py | Python | mit | 1,064 | 0.00565 | """
Jump Search
Find an element in a sorted array.
"""
import math
def jump_search(arr,target):
"""
Worst-case Complexity: O(√n) (root(n))
All items in list must be sorted like binary search
Find block that contains target value and search it linearly in that block
It returns a first target valu... | """
length = len(arr)
block_size = int(math.sqrt(length))
block_prev = 0
block= block_size
# return -1 means that array doesn't contain target value
# find block that contai | ns target value
if arr[length - 1] < target:
return -1
while block <= length and arr[block - 1] < target:
block_prev = block
block += block_size
# find target value in block
while arr[block_prev] < target :
block_prev += 1
if block_prev == min(block, length) :
... |
YannChemin/wxGIPE | RS_functions/evapo_pot_rs.py | Python | unlicense | 2,337 | 0.035944 | """
Generic remote sensing based ET potential using radiation
"""
def solarday(latitude, doy, tsw ):
"""
Average Solar Diurnal Radiation after Bastiaanssen (1995)
tsw = 0.7 generally clear-sky Single-way transmissivity of the atmosphere [0.0-1.0]
solarday(latitude, doy, tsw )
"""
PI=3.1415927
ds = 1.0 + 0.01672 ... | 80.0
asprad = aspect * PI / 180.0
ws = acos(-tan(latrad)*tan(deltarad))
temp1 = sin(deltarad) * sin(latrad) * cos(slrad)
temp2 = sin(deltarad) * cos(latrad) * sin(slrad) * cos(asprad)
temp3 = cos(deltarad) * cos(latrad) * cos(slrad) * cos(ws*PI/180.0)
temp4 = cos(deltarad) * sin(slrad) * cos(asprad) * cos(ws*PI/1... | 0.0)
temp5 = cos(deltarad) * sin(slrad) * sin(asprad) * sin(ws*PI/180.0)
costheta = (temp1 - temp2 + temp3 + temp4 + temp5) / cos(slrad)
result = ( costheta * 1367 * tsw ) / ( PI * ds * ds )
return result
def rnetday( albedo, solarday, tsw ):
"""
Average Diurnal Net Radiation after Bastiaanssen (1995)
tsw = 0.7... |
sanja7s/EEDC | src/timelines/node_plug_timeline.py | Python | apache-2.0 | 10,157 | 0.033278 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
author: sanja7s
---------------
plot the distribution
"""
import os
import datetime as dt
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from collections import defaultdict
from matplotlib import colors
from pylab import MaxN... | = line.strip().split('"')
t = dt.datetime.fromtimestamp(in | t(t))
CPU1 = float(CPU1)
CPU2 = float(CPU2)
distr[t] = (CPU1, CPU2)
return distr
def read_in_MEM_data(node):
f_in = 'node_' + node +'_CPUMEM.csv'
distr = defaultdict(int)
with open(f_in, 'r') as f:
for line in f:
n, n, n, t, n, n, n, n, n, n, n, MEM1, n, MEM2, n = line.strip().split('"')
t = dt.... |
AnthonyCalandra/modern-cpp-features | auto-generate-readme.py | Python | mit | 2,305 | 0.000868 | from pathlib import Path
class MarkdownParser():
def __init__(self, text):
self.text = text
se | lf.lines = text.split('\n')
def title(self):
return self.lines[0].split(' ')[1]
def header(self, name, level, include_header=False):
start = False
end = False
content = []
mark = '#' * level
for line in self.lines:
if start and not end:
... | else:
content.append(line)
else:
start = (f'{mark} {name}' in line)
if start:
end = False
if include_header:
content.append(line)
content = '\n'.join(content)
return con... |
gramhagen/emojibot | tests/utils/test_response.py | Python | mit | 164 | 0 | # -*- coding: utf-8 -*-
from emojibot.utils.response import Response
d | ef test_constructor():
response = Response()
assert i | sinstance(response, Response)
|
JiapengLi/pqcom | pqcom/util.py | Python | mit | 387 | 0.002584 |
import sys
import os
import pk | g_resources
VERSION = 0.5
script_path = os.path.dirname(sys.argv[0])
def resource_path(relative_path):
base_path = getattr(sys, '_MEIPASS', script_path)
full_path = os.path.join(base_path, rel | ative_path)
if os.path.isfile(full_path):
return full_path
else:
return pkg_resources.resource_filename(__name__, relative_path)
|
duke605/RunePy | commands/portables.py | Python | mit | 4,554 | 0.002855 | from secret import GOOGLE_API_KEY
from datetime import datetime
from util.arguments import Arguments
from discord.ext import commands
from shlex import split
from util.choices import enum
from collections import namedtuple
import util
import re
import urllib
import discord
class Portables:
def __init__(self, bot... | from google sheet
portables = await Portables._get_portables(self.bot.whttp)
if not portables:
await self.bot.say('Google sheet could not be reached.')
return
# Building message
e = discord.Embed()
e.colour = 0x3572a7
e.timestamp = portables.time... | .author,
icon_url='http://services.runescape.com/m=avatar-rs/%s/chat.png' % urllib.parse.quote(portables.author))
# Adding portable locations
for portable, locations in portables.locations.items():
# Skipping if no the portable requested
if args.portable an... |
robocomp/robocomp | tools/cli/robocompdsl/robocompdsl/templates/templateCPP/plugins/agm/functions/src/specificworker_cpp.py | Python | gpl-3.0 | 3,615 | 0.018534 | import datetime
from string import Template
import robocompdsl.dsl_parsers.parsing_utils as p_utils
from robocompdsl.templates.templateCPP.plugins.base.functions import function_utils as utils
from robocompdsl.templates.common.templatedict import TemplateDict
AGM_INNERMODEL_ASSOCIATION_STR = """\
innerModel = std::ma... | def agm_specific_ | code(self):
result = ""
if ('agmagent' in [x.lower() for x in self.component.options]) and (
'innermodelviewer' in [x.lower() for x in self.component.options]):
result += REGENERATE_INNERMODEL
if 'agmagent' in [x.lower() for x in self.component.options]:
... |
florisvb/multi_tracker | examples/demo/demo_2/src/raw_data_bag_config.py | Python | mit | 177 | 0 | class Config:
def __init__(self):
self | .basename = 'raw_data_N2'
self.directory = '~/orchard/data'
self.topic | s = ['/multi_tracker/2/tracked_objects']
|
zhaofengli/refill | backend/refill/models/citation.py | Python | bsd-2-clause | 5,016 | 0.001595 | import dateparser
from datetime import date
class Citation:
FIELDS = {
'type': str,
'url': str,
'title': str,
'date': date,
'accessdate': date,
'year': int,
'authors': list,
'editors': list,
'publisher': str,
'work': str,
'web... | lif not type(value) is ftype:
raise ValueError('Invalid value {} for field {}'.format(value | , field))
if type(value) is str:
value = value.strip()
return value
def __resetField(self, field):
ftype = Citation.FIELDS[field]
if ftype is date:
self._data[field] = None
else:
self._data[field] = ftype()
|
apul1421/table-client-side-app-retake | src/ecommerce2/views.py | Python | gpl-3.0 | 237 | 0.016878 | from django.s | hortcuts import render
def about(request):
return render(request, "about.html", {})
def location(request):
return render(request, "location.html", { | })
def failure(request):
return render(request, "failure.html", {})
|
rh-s/heat | heat/engine/scheduler.py | Python | apache-2.0 | 18,011 | 0.000056 | #
# 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
# ... | "
text = 'Task %s' % self.name
return six.text_type(text)
def _sleep(self, wait_time):
"""Sleep for the specified number of seconds."""
if ENABLE_SLEEP and wait_time is not None:
LOG.debug('%s sleeping' % six.text_type(self))
eventlet.sleep(wait_time)
de... | mpletion.
The task will first sleep for zero seconds, then sleep for `wait_time`
seconds between steps. To avoid sleeping, pass `None` for `wait_time`.
"""
self.start(timeout=timeout)
# ensure that zero second sleep is applied only if task
# has not completed.
if... |
WebArchivCZ/Seeder | Seeder/harvests/forms.py | Python | mit | 3,363 | 0.000297 | from multiupload.fields import MultiUploadMetaField, MultiUploadMetaInput
from django import forms
from dal import autocomplete
from . import models
# Django 2 fix (https://github.com/Chive/django-multiupload/issues/31)
class PatchedMultiUploadMetaInput(MultiUploadMetaInput):
def render(self, name, value, attrs=... | 'target_frequency',
'custom_seeds',
'custom_sources',
# 'slug',
'keywords',
"attachments",
)
widgets = {
'custom_sources': autocomplete.ModelSelect2Multiple(
url='source:source_public_autocomplete'
... | elSelect2Multiple(
url='source:keyword_autocomplete'
),
}
class TopicCollectionEditForm(TopicCollectionForm):
files_to_delete = forms.MultipleChoiceField(required=False)
def clean_order(self):
updated_order = self.cleaned_data['order']
if updated_order < 1:... |
ucloud/uai-sdk | uaitrain_tool/caffe/caffe_tool.py | Python | apache-2.0 | 3,505 | 0.003138 | # Copyright 2017 The UAI-SDK 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 applicable... | 'commands'] == 'bill':
bill_op.cmd_run(cmd_args)
elif cmd_args['commands'] == 'rename':
rename_op.cmd_run(cmd_args) |
elif cmd_args['commands'] == 'conf':
conf_op.cmd_run(cmd_args)
elif cmd_args['commands'] == 'topic':
topic_op.cmd_run(cmd_args)
else:
print("Unknown CMD, please use python caffe_tool.py -h to check")
|
sunlightlabs/django-nonprofit | nonprofit/mailroom/admin.py | Python | bsd-3-clause | 207 | 0.024155 | from django.contri | b import admin
from nonprofit.mailroom.models import Slot
class SlotAdmin(admin.ModelAdmin):
list_display = ('description','forward_to','enabled')
admin.site.re | gister(Slot, SlotAdmin) |
LaoQi/icode | mypylib/remoto/lib/vendor/execnet/multi.py | Python | gpl-2.0 | 10,046 | 0.001294 | """
Managing Gateway Groups and interactions with multiple channels.
(c) 2008-2014, Holger Krekel and others
"""
import sys, atexit
from execnet import XSpec
from execnet import gateway_io, gateway_bootstrap
from execnet.gateway_base import reraise, trace, get_execmodel
from threading import Lock
NO_ENDMARKER_WANTE... | oxyIO(proxy_channel, self.execmodel)
gw = gateway_bootstrap.bootstrap(proxy_io_master, spec)
elif spec.popen or spec.ssh:
io = gateway_io.create_io(spec, execmodel=self.execmodel)
gw = gateway_bootstrap.bootstrap(io, spec)
elif spec.socket:
from execnet im... |
else:
raise ValueError("no gateway type found for %r" % (spec._spec,))
gw.spec = spec
self._register(gw)
if spec.chdir or spec.nice or spec.env:
channel = gw.remote_exec("""
import os
path, nice, env = channel.receive()
... |
sbergot/invok | invok/DependencyNode.py | Python | bsd-3-clause | 552 | 0.001812 | import inspect
import functools
class DependencyNode:
def __init_ | _(self, cls, cached):
self.cls = cls
self.deps = self.get_deps(cls)
self.cached = cached
def get_deps(self, cls):
try:
return inspect.getargspec(cls.__init__).args[1:]
except AttributeError:
# no __init__ --> no dep
return []
... | ve(name)
self.cls = functools.partial(self.cls, **kwargs)
|
LAIRLAB/libpyarr | find_epd.py | Python | bsd-3-clause | 2,436 | 0.007389 | #! /usr/bin/env python
'''
Recursively looks for EPD
Writes to STDOUT and STDERR the found library and the found include directory. In this way,
this script can be executed within CMAKE and the Python Libraries and Includes can be set to the STDOUT and STDERR streams
Checks for a minimum version of Python, default 2.... | lib_version = '.'.join(lib.split('.')[:2])
if lib_version >= min_py_version:
lib_exists = True
break
if not lib_exists:
break
lib = '%s/lib/%s.so' % (fu... | include_dir = '%s/include/%s' % (full_dir, min_py_version[3:])
#success if this passes
if os.path.isfile(lib) and os.path.isdir(include_dir):
bin_path = '%s/bin/python' % (full_dir)
unicode_support = os.system("%s -c... |
sniemi/SamPy | sandbox/src1/examples/dash_control.py | Python | bsd-2-clause | 264 | 0.015152 | #!/usr/bin/env python
| """
You can precisely specify dashes with an on/off ink rect sequence in
points.
"""
from pylab import *
dashes = [5,2,10,5] # 5 points on, 2 off, 3 on, 1 off
l, = plot(arange(20), '--')
l. | set_dashes(dashes)
savefig('dash_control')
show()
|
desaster/uusipuu | modules/memo.py | Python | bsd-2-clause | 3,945 | 0.001267 | # -*- coding: ISO-8859-15 -*-
from core.Uusipuu import UusipuuModule
import random, time
class Module(UusipuuModule):
def startup(self):
if 'memo' not in self.config:
self.config['memo'] = {}
def privmsg(self, user, target, msg):
if target != self.channel:
return
... | ed'])))
def meta_addmemo(self, user, params):
nick = user.split('!', 1)[0]
pieces = params.strip().split(' ', 1)
| if len(pieces) < 2:
self.chanmsg('Insufficient parameters')
return
key, value = pieces[0].strip(), pieces[1].strip()
if key in self.config['memo']:
self.chanmsg('%s: An entry by that name already exists' % nick)
return
self.config['memo']... |
richardbeare/SimpleITK | Examples/SliceBySliceDecorator/SliceBySliceDecorator.py | Python | apache-2.0 | 2,991 | 0.002675 | #!/usr/bin/env python
# =========================================================================
#
# Copyright NumFOCUS
#
# 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.txt
#
# 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... | =======
from __future__ import print_function
import SimpleITK as sitk
import sys
import itertools
from functools import wraps
def slice_by_slice_decorator(func):
"""
A function decorator which executes func on each 3D sub-volume and *in-place* pastes the results into the
input image. The input image t... |
gmatteo/pymatgen | pymatgen/io/tests/test_zeopp.py | Python | mit | 11,239 | 0.000623 | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
__author__ = "Bharat Medasani"
__copyright__ = "Copyright 2013, The Materials Project"
__version__ = "0.1"
__maintainer__ = "Shyue Ping Ong"
__email__ = "bkmedasani@lbl.gov"
__date__ = "Aug 2, 2013"
import os... | zeocssr = ZeoCssr.from_file(filename)
self.assertIsInstance(zeocssr.structure, Structure)
@unittest.skipIf(not zeo, "zeo not present.")
class ZeoVoronoiXYZTest(unittest.TestCase):
def setUp(self):
coords = [
[0.000000, 0.000000, 0.000000],
[0.000000, 0.000000, 1.089000],... | 2]
self.mol = Molecule(["C", "H", "H", "H", "H"], coords, site_properties={"voronoi_radius": prop})
self.xyz = ZeoVoronoiXYZ(self.mol)
def test_str(self):
ans = """5
H4 C1
C 0.000000 0.000000 0.000000 0.400000
H 1.089000 0.000000 0.000000 0.200000
H -0.363000 1.026719 0.000000 0.200000
H -0... |
zinderud/ysa | sklearn/3.py | Python | apache-2.0 | 655 | 0.044615 | import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
num | _arsa=120
np.random.seed(40)
x = np.random.randint(low=200,high=2000,size=num_arsa)
np.random.seed(40)
y = x*100.0+np.random.randint(low=10000,high=100000,size=num_arsa)
print(x)
print(y)
plt.scatter(x,y)
m,b = np.polyfit(x,y,1) # np.polyfit(x ekseni, y ekseni, kaçıncı dereceden polinom denklemi)
a = np.a... | d",marker=">")
plt.show()
print("y=",m,"x+",b) |
reclosedev/requests-cache | examples/generate_test_db.py | Python | bsd-2-clause | 4,628 | 0.002377 | #!/usr/bin/env python
"""An example of generating a test database with a large number of semi-randomized responses.
This is useful, for example, for reproducing issues that only occur with large caches.
"""
import logging
from datetime import datetime, timedelta
from os import urandom
from os.path import getsize
from r... |
# TODO: If others would find it useful, these settings could be turned into CLI args
BACKEND = 'sqlite'
CACHE_NAME = 'rubbish_bin'
|
BASE_RESPONSE = requests.get('https://httpbin.org/get')
HTTPBIN_EXTRA_ENDPOINTS = [
'anything',
'bytes/1024' 'cookies',
'ip',
'redirect/5',
'stream-bytes/1024',
]
MAX_EXPIRE_AFTER = 30 # In seconds; set to -1 to disable expiration
MAX_RESPONSE_SIZE = 10000 # In bytes
N_RESPONSES = 100000
N_INVALI... |
tiagormk/gem5-hmp | configs/common/Caches.py | Python | bsd-3-clause | 3,250 | 0.001231 | # Copyright (c) 2012 ARM Limited
# All rights reserved.
| #
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality of the software
# licensed hereunder. You may use the s... | ons of the software,
# modified or unmodified, in source code or in binary form.
#
# Copyright (c) 2006-2007 The Regents of The University of Michigan
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# ... |
ucb-sejits/ctree | test/test_lambda.py | Python | bsd-2-clause | 2,548 | 0.009812 | import unittest
import ctypes as ct
import ast
import sys
from ctree.transformations import PyBasicConversions
from ctree.transforms import DeclarationFiller
from ctree.c.nodes import *
class TestAssigns(unittest.TestCase):
def mini_transform(self, node):
"""
This method acts as a simulation of... | ) method. It's the bare minimum required of
a transform() method by the specializer writer.
:param node: the node to transform
:return: the node transformed through PyBasicConversions into a rough C-AST.
"""
transformed_node = PyBasicConversions().visit(node)
transforme... | oat()
for param in transformed_node.params:
param.type = ct.c_float()
return transformed_node
def mini__call__(self, node):
"""
This method acts as a simulation of jit.py's __call__() method. The specializer writer does not have to write
this method.
:... |
appcelerator/titanium_mobile_tooling | templates/plugin/build.py | Python | apache-2.0 | 2,990 | 0.049498 | #!/usr/bin/env python
#
# Appcelerator Titanium Plugin Packager
#
#
import os, sys, glob, string
import zipfile
cwd = os.path.dirname(__file__)
required_plugin_keys = ['version','pluginid','description','copyright','license','minsdk']
plugin_defaults = {
'description':'My plugin',
'author': 'Your Name',
'license' :... | " % key)
if plugin_defaults.has_key(key):
defvalue = plugin_defaults[key]
curvalue = manifest[key]
if curvalue==defvalue: warn("please update the manifest key: '%s' to a non-default value" % key)
return manifest,path
ignoreFiles = ['.DS_Store','.gitignore','README','build.py']
ignoreDirs = ['.DS_Store','.... | ed directories
for file in files:
if file in ignoreFiles: continue
e = os.path.splitext(file)
if len(e)==2 and e[1]=='.pyc':continue
from_ = os.path.join(root, file)
to_ = from_.replace(dir, basepath, 1)
zf.write(from_, to_)
def package_plugin(manifest,mf):
pluginid = manifest['pluginid'].lo... |
jehama/OSINThadoop | FieldModifiers/edit_heartbleed_timestamp.py | Python | mit | 4,926 | 0.005075 | # --------------------------------------------------------------------------------------------
# Copyright (c) jehama. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -----------------------------------------------------------------------------------... | # So a second try is used to check for the second format if the first one is incorrect.
json_element["custom.heartbleed.timesta | mp"] = json_element["source1.timestamp"]
old_date_format = "%Y-%m-%dT%H:%M:%S.%f"
try:
date = datetime.datetime.strptime(json_element["custom.heartbleed.timestamp"], old_date_format)
except ValueError:
... |
pythonprobr/pythonpro-website | pythonpro/memberkit/migrations/0002_create_relationship_with_payment_config_item.py | Python | agpl-3.0 | 1,292 | 0.004644 | # Generated by Django 3.2.4 on 2021-06-05 15:46
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('django_pagarme', '0004_pagarme_item_co | nfig_available_until'),
('memberkit', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='subscriptiontype',
options={'verbose_name': 'Tipo de Assinatura', 'verbose_name_plural': 'Tipos de Assinaturas'},
),
migrations.CreateModel(
... | utoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('payment_item', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE,
related_name='subscription_type_relation',
... |
cloud-ark/cloudark | server/gcloud_handler.py | Python | apache-2.0 | 4,809 | 0.001248 | import ast
from os.path import expanduser
from stevedore import extension
from common import common_functions
from common import fm_logger
from dbmodule.objects import app as app_db
from dbmodule.objects import environment as env_db
from server.server_plugins.gcloud import gcloud_helper
home_dir = expanduser("~")
A... | cont_name, cont_info):
repo_type = cont_info['dep_target']
for name, ext in GCloudHandler.res_mgr.items():
if name | == repo_type:
ext.obj.create(cont_name, cont_info)
def delete_container(self, cont_name, cont_info):
repo_type = cont_info['dep_target']
for name, ext in GCloudHandler.res_mgr.items():
if name == repo_type:
ext.obj.delete(cont_name, cont_info)
# App ... |
fxdemolisher/frano | frano/templatetags/frano_filters.py | Python | mit | 2,315 | 0.015119 | from django import template
from django.template.defaultfilters import stringfilter
import locale
register = template.Library()
#-----------\
# FILTERS |
#-----------/
@register.filter
@stringfilter
def num_format(value, places = 2, min_places = 2):
return format(value, '.', int(places), 3, ',', int(min_places))... | ositions
* grouping: Number of digits in every group limited by thousand separator
* thousand_sep: Thousand separator symbol (for example ",")
"""
# sign
if float(number) < 0:
sign = '-'
else:
sign = ''
# decimal part
str_number = unicode("%.8f" % float(number))
if ... | ber.split('.')
if decimal_pos:
dec_part = dec_part[:decimal_pos]
else:
int_part, dec_part = str_number, ''
# do not zero pad when its not needed
#if decimal_pos:
# dec_part = dec_part + ('0' * (decimal_pos - len(dec_part)))
# zero pad to minimum decimal p... |
stlpublicradio/ferguson-project | fabfile/flat.py | Python | mit | 3,519 | 0.002558 | #!/usr/bin/env python
import copy
from cStringIO import StringIO
from fnmatch import fnmatch
import gzip
import hashlib
import mimetypes
import os
import boto
from boto.s3.key import Key
from boto.s3.connection import OrdinaryCallingFormat
import app_config
GZIP_FILE_TYPES = ['.html', '.js', '.json', '.css', '.xml'... | skip = False
for pattern in ignore:
if fnmatch(src_ | path, pattern):
skip = True
break
if skip:
continue
if rel_path == '.':
dst_path = os.path.join(dst, name)
else:
dst_path = os.path.join(dst, rel_path, name)
to_deploy.append((src_p... |
Zulko/pompei | examples/typical_script.py | Python | mit | 4,324 | 0.006475 | """
This is a ty | pical script to reconstruct one frame of a movie using a mosaic
of other frames with the Python package Pompei. It generates this picture of
general Maximus in Gladiator using 1100+ frames of the movie.
http://i.imgur.com/Eoglcof.jpg
This script goes in five steps:
1. Extract one frame every 5 second of the movie. C... | is frame into subregions and compute the signature of each region.
4. Run an algorithm to find (using the signatures) wich frames of the movie
match best with the different regions of the picture to reconstruct.
The algorithm also ensures that many different frames are used.
5. Assemble the selected best-matching... |
r39132/airflow | tests/test_utils.py | Python | apache-2.0 | 3,597 | 0.001112 | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... | ://bucket/path/to/blob'),
('bucket', 'path/to/blob'))
# invalid URI
self.assertRaises(
AirflowException,
glog.parse_gcs_url,
'gs:/bucket/path/to/blob')
# trailing slash
self.assertEqual(
glog.parse_gcs_url('gs://bucket/path/to... | ket/'),
('bucket', ''))
class OperatorResourcesTest(unittest.TestCase):
def setUp(self):
configuration.load_test_config()
def test_all_resources_specified(self):
resources = Resources(cpus=1, ram=2, disk=3, gpus=4)
self.assertEqual(resources.cpus.qty, 1)
self.asse... |
maxamillion/ansible | lib/ansible/plugins/inventory/auto.py | Python | gpl-3.0 | 2,372 | 0.005481 | # Copyright (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = '''
name: auto
author:
- Matt Davis (@nitzmahone)
version_added: "... | config file with a
C(plugin) key at its root will automatically cause the named plugin to be loaded and executed with that
config. This effectively provides automatic whitelisting of all installed/accessible inventory plugins.
- To disable this behavior, remove C(auto) from the C(INVENTORY_... | irect use; it is a fallback mechanism for automatic whitelisting of
# all installed inventory plugins.
'''
from ansible.errors import AnsibleParserError
from ansible.plugins.inventory import BaseInventoryPlugin
from ansible.plugins.loader import inventory_loader
class InventoryModule(BaseInventoryPlugin):
NAME ... |
celery/cyme | cyme/settings.py | Python | bsd-3-clause | 1,738 | 0 | """Since cyme works as a contained Django APP, this is the default settings
file used when cyme is used outside of a Django project context."""
from __future__ import absolute_import
import os
import djcelery
djcelery.setup_loader()
DEBUG = True
# Broker settings.
BROKER_HOST = 'amqp://127.0.0.1:5672//'
BROKER_POOL... | e.api.urls'
# Time and localization.
TIME_ZONE = 'UTC'
LANGUAGE_CODE = 'en-us'
USE_I18N = USE_L10N = True
# Apps and middleware.
INSTALLED_APPS = ('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'cyme', # cyme must be before admin... | 'django.contrib.admindocs')
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
# Make this uniq... |
jnewland/home-assistant | homeassistant/components/mysensors/binary_sensor.py | Python | apache-2.0 | 1,398 | 0 | """Support for MySensors binary sensors."""
from homeassistant.components import mysensors
from homeassistant.components.binary_sensor import (
DEVICE_CLASSES, DOMAIN, BinarySensorDevice)
from homeassistant.const import STATE_ON
SENSORS = {
'S_DOOR': 'door',
'S_MOTION': 'motion',
'S_SMOKE': 'smoke',
... | mysenso | rs.setup_mysensors_platform(
hass, DOMAIN, discovery_info, MySensorsBinarySensor,
async_add_entities=async_add_entities)
class MySensorsBinarySensor(
mysensors.device.MySensorsEntity, BinarySensorDevice):
"""Representation of a MySensors Binary Sensor child node."""
@property
def ... |
lbouma/Cyclopath | pyserver/item/item_user_watching.py | Python | apache-2.0 | 18,252 | 0.014464 | # Copyright (c) 2006-2013 Regents of the University of Minnesota.
# For licensing terms, see the file LICENSE.
import traceback
import conf
import g
from grax.access_level import Access_Level
from gwis.exception.gwis_nothing_found import GWIS_Nothing_Found
from item import item_base
from item import item_user_access... | """)
qb.sql_clauses.inner.group_by += (
"""
, ievt.messaging_id
"""
)
else:
qb.sql_clauses.inner.select += (
| """
, NULL AS item_read_id
"""
)
qb.sql_clauses.outer.shared += (
"""
, group_item.item_read_id
"""
)
#
def qb_join_item_event_read(self, qb):
g.assurt(False) # Deprecated.
# See: qb_add_item_even... |
Rogentos/legacy-anaconda | iw/bootloader_main_gui.py | Python | gpl-2.0 | 8,647 | 0.004048 | #
# bootloader_main_gui.py: gui bootloader configuration dialog
#
# Copyright (C) 2001, 2002 Red Hat, Inc. All rights reserved.
#
# 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... | tall boot loader on /dev/%s.") %
(self.bldev,))
def getScreen(self, anaconda):
self.dispatch = anaconda.dispatch
self.bl = anaconda.bootloader
self.intf = anaconda.intf
self.driveorder = self.bl.drivelist
if len(self.driveorder) == 0:
... | partitioned = anaconda.storage.partitioned
disks = anaconda.storage.disks
self.driveorder = [d.name for d in disks if d in partitioned]
if self.bl.getPassword():
self.usePass = 1
self.password = self.bl.getPassword()
else:
self.usePass = 0
... |
pahaz/prospector | prospector/run.py | Python | gpl-2.0 | 4,952 | 0.000808 | from __future__ import absolute_import
import os.path
import sys
from datetime import datetime
from prospector import tools, blender, postfilter
from prospector.config import ProspectorConfig, configuration as cfg
from prospector.finder import find_python
from prospector.formatters import FORMATTERS
from prospector.m... | sys.exit(2)
# Make it so
prospector = Prospector(co | nfig)
prospector.execute()
prospector.print_messages()
if config.exit_with_zero_on_success():
# if we ran successfully, and the user wants us to, then we'll
# exit cleanly
return 0
# otherwise, finding messages is grounds for exiting with an error
# code, to make it easier ... |
samrussell/sippy | sippy/ESipHeaderIgnore.py | Python | gpl-2.0 | 1,217 | 0 | # Copyright (c) 2003-2005 Maxim Sobolev. All rights reserved.
# Copyright (c) 2006-2007 Sippy Software, Inc. All rights reserved.
#
# This file is part of SIPPY, a free RFC3261 SIP stack and B2BUA.
#
# SIPPY is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License a... | use the SIPPY software under conditions
# other than those described here, or to purchase support for this
# software, please contact Sippy Softw | are, Inc. by e-mail at the
# following addresses: sales@sippysoft.com.
#
# SIPPY is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You shou... |
b0ttl3z/SickRage | lib/github/Organization.py | Python | gpl-3.0 | 29,379 | 0.00337 | # -*- coding: utf-8 -*-
# ########################## Copyrights and license ############################
# #
# Copyright 2012 Steve English <steve.english@navetas.com> #
# Copyright 2012 Vincent Jacques <vincent@vincent-ja... | rence can be found here http://developer.github.com/v3/orgs/
"""
def __repr__(self):
return self.get__repr__({"id": self._id.value, "name": self._name.value})
@property
def | avatar_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._avatar_url)
return self._avatar_url.value
@property
def billing_email(self):
"""
:type: string
"""
self._completeIfNotSet(self._billing_email)
return self._billin... |
diorcety/translate | translate/storage/test_mo.py | Python | gpl-2.0 | 4,281 | 0.003504 | import os
import subprocess
import sys
from io import BytesIO
from translate.storage import factory, mo, test_base
class TestMOUnit(test_base.TestTranslationUnit):
UnitClass = mo.mounit
def test_context(self):
unit = self.UnitClass("Message")
unit.setcontext('context')
assert unit.ge... | n\n"
"convert"
msgstr "bekeerling"
msgctxt "verb"
msgid ""
"convert"
msgstr "omskakel"
msgid "tree"
msgid_plural "trees"
msgstr[0] ""
''',
] |
class TestMOFile(test_base.TestTranslationStore):
StoreClass = mo.mofile
def get_mo_and_po(self):
return (os.path.abspath(self.filename + '.po'),
os.path.abspath(self.filename + '.msgfmt.mo'),
os.path.abspath(self.filename + '.pocompile.mo'))
def remove_po_and_mo... |
titipata/pubmed_parser | pubmed_parser/utils.py | Python | mit | 4,118 | 0.001943 | import calendar
import collections
try:
from collections.abc import Iterable
except:
from collections import Iterable
from time import strptime
from six import string_types
from lxml import etree
from itertools import chain
def remove_namespace(tree):
"""
Strip namespace from parsed XML
"""
fo... | ten-an-irregular-list-of-lists-in-python
"""
parts = | _recur_children(node)
parts_flatten = list(_flatten(parts))
return " ".join(parts_flatten).strip()
def _flatten(l):
"""
Flatten list into one dimensional
"""
for el in l:
if isinstance(el, Iterable) and not isinstance(el, string_types):
for sub in _flatten(el):
... |
yupbank/onekeyvpn | ensure.py | Python | bsd-3-clause | 690 | 0.015942 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
ensure.py
Author: yupbank
Email: yupbank@gmail.com
Created on
2013 | -09-30
'''
import sh
import os
import sys
def ubuntu_install(package):
return os.popen( | 'sudo apt-get install %s -y'%package)
OP_F = {
"Linux": ubuntu_install
}
OP_PACKAGE = {
"Linux": ['openswan', 'xl2tpd', 'ppp'][::-1]
}
def install_package(package, sys_type):
return OP_F[sys_type](package)
def main():
os_type = sh.uname().strip()
for p in OP_PACKAGE[os_type]:
... |
vecnet/vnetsource | datawarehouse/mixins.py | Python | mpl-2.0 | 1,115 | 0.007175 | from collections import OrderedDict
from django.http import HttpResponse
import simplejson
class JSONMixin(object):
"""This class was designed to be inherited and used to return JSON objects from an Ordered Dictionary
"""
## Ordered Dictionary used to create serialized JSON object
# return_rderedDic | t() #This will enforce the ordering that we recieve from the database
def __init__(self):
"""
Init function for the JSON Mixin class
"""
self.return_list=OrderedDict()
return
def render_to_response(self, context):
"""Extends default render to response to return... | args):
"""Returns JSON to calling object in the form of an http response.
"""
return HttpResponse(content,content_type='application/json',**httpresponse_kwargs)
def convert_to_json(self):
"""Serialized the return_list into JSON
"""
return simplejson.dumps(self.return... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.