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 |
|---|---|---|---|---|---|---|---|---|
tb0hdan/voiceplay | setup.py | Python | unlicense | 3,908 | 0.004094 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import io
import os
import platform
import re
import sys
import subprocess
from distutils.sysconfig import get_python_lib
from setuptools import setup, find_packages
from voiceplay import (__title__,
__version__,
__description_... | __file__ as vpfile)
if os.path.exists('README.rst'):
readme = io.open('README.rst', mode='r', encoding='utf8' | ).read()
else:
readme = ''
system_specific_packages = ['pyobjc'] if platform.system() == 'Darwin' else ['pyfestival', 'Skype4Py']
# hook to pip install for package sideloading
# broken pyaudio package
# snowboy extension
if sys.argv[1] in ['bdist_wheel', 'install']:
# pyaudio
if platform.system() == 'Darw... |
christianrenier/dynamic-dns-updater | __main__.py | Python | mit | 3,280 | 0.019512 | import ConfigParser
import os
import sys
import utils
## Create global names and functions ##
# Load file locations and configuration options
site_list_location = os.path.dirname(__file__) + '/sitelist.txt'
parser = ConfigParser.RawConfigParser()
parser.read(os.path.dirname(__file__) + '/config.cfg')
general = dict... | lse
# Tracks if a mailer was created
mailer = False
# Dictionary of error codes and their corresponding messages
error_messages = {
'invalid_login' : 'Your Gmail username or password is incorrect.',
'logger_missing' : 'Problem writing to log file.',
'read_cache' : 'Problem reading from IP cache.',
'read_si... | ate_dns' : 'Problem updating your Dynamic DNS.'
}
# Handles logging and mailing of errors, as enabled by the user
def error_processor(code):
if write_error and logger: logger.log_error(error_messages[code])
if mail_error and mailer:
mailer.send_error(receiver, error_messages[code])
print '%s: Error - %s' % (to... |
bdaroz/the-blue-alliance | database/dict_converters/team_converter.py | Python | mit | 1,224 | 0.000817 | from database.dict_converters.converter_base import ConverterBase
class TeamConverter(ConverterBase):
SUBVERSIONS = { # Increment every time a change to the dict is made
3: 4,
}
@classmethod
def _convert(cls, teams, dict_version):
CONVERTERS = {
3: cls.teamsConverter_v3,
... | ict = {
'key': team.key.id(),
'team_number': team.team_number,
'nickname': team.nickname if team.nickname else default_n | ame,
'name': team.name if team.name else default_name,
'website': team.website,
'rookie_year': team.rookie_year,
'motto': None,
'home_championship': team.championship_location,
'school_name': team.school_name,
}
team_dict.update(cls... |
qk4l/Flexget | flexget/plugins/modify/convert_magnet.py | Python | mit | 4,421 | 0.002488 | from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
import os
import time
import logging
from flexget import plugin
from flexget.event import event
from flexget.utils.tools import parse_timedelta
from flexget.utils.pathscrub... | config.setdefault('timeout', '30 seconds')
config.setdefault('force', False)
return config
@plugin.priority(255)
def on_task_start(self, task, config):
if config is False:
r | eturn
try:
import libtorrent # noqa
except ImportError:
raise plugin.DependencyError('convert_magnet', 'libtorrent', 'libtorrent package required', log)
@plugin.priority(130)
def on_task_download(self, task, config):
if config is False:
return
... |
razvan9310/barrelfish | tools/grader/subprocess_timeout.py | Python | mit | 894 | 0.001119 | ##########################################################################
# Copyright (c) 2009-2016 ETH Zurich.
# All rights reserved.
#
# This file is distributed under the terms in the attached LICENSE file.
# If you do not find this file, copies can be found by | writing to:
# ETH Zurich D-INFK, Universitaetstr 6, CH-8092 Zurich. Attn: Systems Group.
##########################################################################
from threading import Timer
# Wait for Popen instance p for timeout seconds and terminate/kill it after
# the tim | eout expires
# Adapted from
# http://stackoverflow.com/questions/1191374/using-module-subprocess-with-timeout
def wait_or_kill(p, timeout=5):
# Kill process if it doesn't voluntarily exit in `timeout` seconds
timer = Timer(timeout, lambda x: x.kill(), [p])
try:
timer.start()
p.wait()
fin... |
dtroyer/dwarf | dwarf/task.py | Python | apache-2.0 | 2,171 | 0 | #!/usr/bin/env python
#
# Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
# Copyright (c) 2013 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://... | args
sel | f.kwargs = kwargs
self._stop = False
_TASKS[tid] = self
self.start()
def run(self):
for dummy in range(self.repeat):
if self._stop:
break
retval = self.func(*self.args, **self.kwargs)
if retval is not None:
break
... |
cmvelo/ansible | lib/ansible/executor/module_common.py | Python | gpl-3.0 | 33,348 | 0.002699 | # (c) 2013-2014, Michael DeHaan <[email protected]>
# (c) 2015 Toshio Kuratomi <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either... | he code or experiment with
# different parameter values. When you're ready to run the code you've modified
# (instead of the code from the actual zipped module), use the execute subcommand like this::
# $ /usr/bin/python /home/badger/.ansible/tmp/ansible-tmp-1461173013.93-9076457629738/ping execute
... | path.join(os.path.abspath(os.path.dirname(__file__)), 'debug_dir')
args_path = os.path.join(basedir, 'args')
script_path = os.path.join(basedir, 'ansible_module_%(ansible_module)s.py')
if command == 'explode':
# transform the ZIPDATA into an exploded directory of code and then
# print the p... |
Jvlythical/KoDrive | tests/mock/cli.py | Python | mit | 81 | 0 | from kodrive import syncthing_factory as factory
client = | factory.g | et_handler()
|
MediaKraken/MediaKraken_Deployment | source/testing/test_common/test_common_discid.py | Python | gpl-3.0 | 1,258 | 0 | """
Copyright (C) 2016 Quinn D Granfor <[email protected]>
This program is free software; you can redistribu | te it and/or
modify it under the terms of the GNU General Public License
version 2, as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PU | RPOSE. See the GNU
General Public License version 2 for more details.
You should have received a copy of the GNU General Public License
version 2 along with this program; if not, write to the Free
Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.
"""
import sys
sys.pat... |
IECCTB/springcloud | node-service/py-app.py | Python | apache-2.0 | 912 | 0.003289 | import httplib
from twisted.web import server, resource
from twisted.internet import reactor, endpoints
class Health(resource.Resource):
isLeaf = True
def render_GET(self, request):
request.setHeader("content-ty | pe", "application/json")
return '{"status | ":"UP"}\n'
class Fortune(resource.Resource):
isLeaf = True
def render_GET(self, request):
conn = httplib.HTTPConnection('localhost', 5678)
conn.request("GET", "/fortunes")
res = conn.getresponse()
fortune = res.read()
request.setHeader("content-type", "text/plain")
... |
lukaselmer/ethz-data-mining | 4-bandit/code/policyLinUCBVectorizedTimestamp.py | Python | mit | 4,092 | 0.014418 | #!/usr/bin/env python2.7
import numpy as np
import random
import time
import itertools
# Implementation of Linear UCB
class LinUCB:
# all_articles = []
all_M = None
all_M_inv = None
all_b = None
all_w = None
mapping = {}
keyList=None
firstTS = None
articleSize = 1
totalLine = 0
... | mestamp-1.001 #update all which are new
timepart = [timestamp]*len(articles) - self.firstTS[:,indicesOfArticles]
timepart = 1/np.log(timepart)
UCB = (exploitPart + explorePart + timepart.T).flatten()
#print UCB
#bestArticlesIndices = UCB==max(UCB)
#articlesArray = np.ar... | bestArticle=articles[np.argmax(UCB)]
#if sum(bestArticlesIndices) == 1:
# bestArticle = articlesArray[bestArticlesIndices][0]
#else:
# bestArticle = random.choice(articlesArray[bestArticlesIndices])
self.current_user = user_features
self.current_article = bestAr... |
ppanczyk/ansible | lib/ansible/playbook/task.py | Python | gpl-3.0 | 17,944 | 0.001783 | # (c) 2012-2014, Michael DeHaan <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) an... | even the implied | warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (abs... |
enthought/etsproxy | enthought/qt/QtScript.py | Python | bsd-3-clause | 48 | 0 | # proxy module
fr | om pyface.q | t.QtScript import *
|
MartinHjelmare/home-assistant | homeassistant/components/rpi_gpio/switch.py | Python | apache-2.0 | 2,268 | 0 | """Allows to configure a switch using RPi GPIO."""
import logging
import voluptuous as vol
from homeassistant.components.switch import PLATFORM_SCHEMA
from homeassistant.components import rpi_gpio
from homeassistant.const import DEVICE_DEFAULT_NAME
from homeassistant.helpers.entity import ToggleEntity
import homeassi... | v
_LOGGER = logging.getLogger(__name__)
CONF_PULL_MODE = 'pull_mode'
CONF_PORTS = 'ports'
CONF_INVERT_LOGIC = 'invert_logic'
DEFAULT_INVERT_LOGIC = False
_SWITCHES_SCHEMA = vol.Schema({
cv.positive_int: cv.string,
})
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_PORTS): _SWITCHES_SCHEMA,
... | """Set up the Raspberry PI GPIO devices."""
invert_logic = config.get(CONF_INVERT_LOGIC)
switches = []
ports = config.get(CONF_PORTS)
for port, name in ports.items():
switches.append(RPiGPIOSwitch(name, port, invert_logic))
add_entities(switches)
class RPiGPIOSwitch(ToggleEntity):
"""... |
ldoktor/virt-test | shared/scripts/cmd_runner.py | Python | gpl-2.0 | 2,862 | 0.002096 | """
This script is used to execute a program and collect the monitor
information in background, redirect the outputs to log files.
"""
import threading, shelve, commands, re, os, sys, random, string
class Runner(object):
def __init__(self):
"""
Set the global paramter for thread clean up
"... | "")
s, o = commands.getstatusoutput("kill -9 %s" % pid)
| fd.close()
return (s, o)
def test_thread(self, m_cmd, t_cmd, p_file):
"""
Test thread
"""
self.kill_thread_flag = True
s, o = commands.getstatusoutput(t_cmd)
if s != 0:
print "Test failed or timeout: %s" % o
if self.kill_thread_flag:
... |
mikel-egana-aranguren/SADI-Galaxy-Docker | galaxy-dist/eggs/mercurial-2.2.3-py2.7-linux-x86_64-ucs4.egg/mercurial/revlog.py | Python | gpl-3.0 | 44,332 | 0.001038 | # revlog.py - storage back-end for mercurial
#
# Copyright 2005-2007 Matt Mackall <[email protected]>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
"""Storage back-end for Mercurial.
This provides efficient delta storage with O(1... | gNG"))
e2 = (getoffset(entry[0]), entry[1], entry[3], entry[4],
node(entry[5]), node(entry[6]), entry[7])
return _pack(indexformatv0, *e2)
# index ng:
# 6 bytes: offset
# 2 bytes: flags
# 4 bytes: compressed length
# 4 bytes: uncompressed length
# 4 bytes: base rev
# 4 bytes: link r... | matng = ">Qiiiiii20s12x"
ngshaoffset = 32
versionformat = ">I"
class revlogio(object):
def __init__(self):
self.size = struct.calcsize(indexformatng)
def parseindex(self, data, inline):
# call the C implementation to parse the index data
index, cache = parsers.parse_index2(data, inline... |
mrustl/flopy | examples/scripts/henry.py | Python | bsd-3-clause | 5,583 | 0.004657 |
import os
import numpy as np
import matplotlib.pyplot as plt
import flopy
workspace = os.path.join('data')
#make sure workspace directory exists
if not os.path.exists(workspace):
os.makedirs(workspace)
# In[2]:
# Input variables for the Henry Problem
Lx = 2.
Lz = 1.
nlay = 50
nrow = 1
ncol = 100
delr = Lx / nc... |
# In[10]:
# Extract the heads
fname = os.path.join(workspace, 'henry.hds')
headobj = bf.HeadFile(fname)
times = headobj.get_times()
head = headobj.get_data(totim=times[-1])
# In[11]:
# Make a simple head plot |
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(1, 1, 1, aspect='equal')
im = ax.imshow(head[:, 0, :], interpolation='nearest',
extent=(0, Lx, 0, Lz))
ax.set_title('Simulated Heads')
plt.show()
|
UoK-Psychology/rmas_adapter | rmas_adapter/conf/adapter_template/settings.py | Python | mit | 75 | 0.066667 |
RMAS_BUS_WSDL='htt | p://localhost:7789/?wsdl'
POLL_INTERVAL=5000
EVE | NTS=[] |
scottpurdy/nupic | tests/unit/nupic/regions/anomaly_likelihood_region_test.py | Python | agpl-3.0 | 4,989 | 0.006013 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2016, Numenta, Inc. Unless you have purchased from
# Numenta, Inc. a separate commercial license for this software code, the
# following terms and conditions apply:
#
# This pro... | ITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should have received | a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
import tempfile
import unittest
import random
import csv
import numpy
try:
import capnp
except Import... |
amanharitsh123/zulip | zerver/tests/test_queue_worker.py | Python | apache-2.0 | 5,307 | 0.003392 |
import os
import time
import ujson
from django.conf import settings
from django.http import HttpResponse
from django.test import TestCase
from mock import patch
from typing import Any, Callable, Dict, List, Mapping, Tuple
from zerver.lib.test_helpers import simulated_queue_client
from zerver.lib.test_classes import ... | self.assertEqual(event["type"], 'unexpected behaviour')
def test_worker_noname(self):
# type: () -> None
class TestWorker(queue_processors.QueueProcessingWorker):
def __init__(self):
# type: () -> None
super(TestWorker, self).__init__()
... | entionally not called
with self.assertRaises(queue_processors.WorkerDeclarationException):
TestWorker()
def test_worker_noconsume(self):
# type: () -> None
@queue_processors.assign_queue('test_worker')
class TestWorker(queue_processors.QueueProcessingWorker):
... |
smithfarm/s3-tests | s3tests/functional/test_headers.py | Python | mit | 30,528 | 0.00131 | from cStringIO import StringIO
import boto.connection
import boto.exception
import boto.s3.connection
import boto.s3.acl
import boto.utils
import bunch
import nose
import operator
import random
import string
import socket
import ssl
from boto.s3.connection import S3Connection
from nose.tools import eq_ as eq
from nos... | ct')
@attr(method='put')
@attr(operation='create w/Expect 200')
@attr(assertion='garbage, but S3 succeeds!')
@nose.with_setup(teardown=_clear_custom_headers)
@attr('fails_on_rgw')
def test_object_create_bad_expect_mismatch():
key = _setup_bad_object({'Expect': 200})
key.set_contents_from_string('bar')
# this ... | a really long test, and I don't know if it's valid...
# again, accepts this with no troubles
@attr(resource='object')
@attr(method='put')
@attr(operation='create w/empty expect')
@attr(assertion='succeeds ... should it?')
@nose.with_setup(teardown=_clear_custom_headers)
def test_object_create_bad_expect_empty():
ke... |
enriquesanchezb/practica_utad_2016 | venv/lib/python2.7/site-packages/_pytest/cacheprovider.py | Python | apache-2.0 | 8,786 | 0.000341 | """
merged implementation of the cache provider
the name cache was not choosen to ensure pluggy automatically
ignores the external pytest-cache
"""
import py
import pytest
import json
from os.path import sep as _sep, altsep as _altsep
class Cache(object):
def __init__(self, config):
self.config = config... | _cachedir.check():
tw.line("cache is empty")
return 0
dummy = object()
basedir = config.cache._cachedir
vdir = basedir.join("v")
| tw.sep("-", "cache values")
for valpath in vdir.visit(lambda x: x.isfile()):
key = valpath.relto(vdir).replace(valpath.sep, "/")
val = config.cache.get(key, dummy)
if val is dummy:
tw.line("%s contains unreadable content, "
"will be ignored" % key)
els... |
VHarisop/PyMP | experiments/mnist/mnist_mlmmp.py | Python | gpl-3.0 | 5,043 | 0.002578 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# 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 distr... | of which the first element corresponds to the inputs and the second
ele | ment corresponds to the outputs.
"""
# load pickled dataset
with gzip.open(filepath, 'rb') as fd:
trs, tts, val = pickle.load(fd, encoding='latin1')
return {
'train': trs,
'test': tts,
'validation': val
}
def train_and_classify(data, lr, n_epochs, n_hidden):
""... |
immenz/pyload | module/plugins/hoster/EuroshareEu.py | Python | gpl-3.0 | 2,309 | 0.008239 | # -*- coding: utf-8 -*-
import re
from module.plugins.internal.SimpleHoster import SimpleHoster, create_getInfo
class EuroshareEu(SimpleHoster):
__name__ = "EuroshareEu"
__type__ = "hoster"
__version__ = "0.27"
__pattern__ = r'http://(?:www\.)?euroshare\.(eu|sk|cz|hu|pl)/file/.+'
__descr... | self.account.relogin(self.user)
self.retry(reason=_("User not logged in"))
self.download(pyfile.url.rstrip('/') + "/download/")
check = self.checkDownload({"login": re.compile(self.ERR_NOT_LOGGED_IN_PATTERN),
"json | " : re.compile(r'\{"status":"error".*?"message":"(.*?)"')})
if check == "login" or (check == "json" and self.lastCheck.group(1) == "Access token expired"):
self.account.relogin(self.user)
self.retry(reason=_("Access token expired"))
elif check == "json":
self.fail(s... |
li-xirong/jingwei | model_based/dataengine/positiveengine.py | Python | mit | 2,192 | 0.01688 |
import sys
import os
import random
from basic.constant import ROOT_PATH
from basic.common import readRankingResults,printStatus
from dataengine import DataEngine
class PositiveEngine (DataEngine):
def __init__(self, collection, rootpath=ROOT_PATH):
DataEngine.__init__(self, collection)
self.nam... | datafile = os.path.join(self.datadir, '%s.txt' % concept)
ranklist = readRankingResults(d | atafile)
self.candidateset = [x[0] for x in ranklist]
self.target = concept
def sample(self, concept, n):
if self.target != concept:
self.precompute(concept)
if len(self.candidateset) <= n:
print ("[%s] request %d examples of %s, but %d availabl... |
NeCTAR-RC/nagios-plugins-openstack | plugins/check_novaapi.py | Python | agpl-3.0 | 3,101 | 0.020323 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
#
# Keystone monitoring script for Na | gios
#
# Copyright © 2012 eNovance <[email protected]>
#
# Author: Florian Lambert <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 o... | ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
... |
frankrousseau/weboob | modules/explorimmo/pages.py | Python | agpl-3.0 | 7,242 | 0.00332 | # -*- coding: utf-8 -*-
# Copyright(C) 2014 Bezleputh
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your opt | ion) any later version.
#
# weboob is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHAN | TABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with weboob. If not, see <http://www.gnu.org/licenses/>.
import re
from decimal import Decimal
from datetime import datetime
f... |
jabooth/menpo-archive | menpo/fit/lucaskanade/appearance/simultaneous.py | Python | bsd-3-clause | 8,583 | 0.000233 | import numpy as np
from scipy.linalg import norm
from .base import AppearanceLucasKanade
class SimultaneousForwardAdditive(AppearanceLucasKanade):
@property
def algorithm(self):
return 'Simultaneous-FA'
def _fit(self, lk_fitting, max_iters=20, project=True):
# Initial error > eps
... | nterpolator)
weights = self.appearance_model.project(IWxp)
# Reset template
self.template = self.appearance_model.instance(weights)
else:
# Set all weights to 0 (yielding the mean)
weights = np.zeros(self.appearance_model.n_active_components)
... | rse Compositional Algorithm
while n_iters < max_iters and error > self.eps:
# Compute warped image with current weights
IWxp = image.warp_to(self.template.mask, self.transform,
interpolator=self.interpolator)
# Compute steepest descent images... |
altova/SECDB | scripts/validate_filings.py | Python | apache-2.0 | 5,612 | 0.0098 | # Copyright 2015 Altova GmbH
#
# 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... | og', metavar='LOG_FILE', dest='log | _file', help='log output file')
parser.add_argument('--log-level', metavar='LOG_LEVEL', dest='log_level', choices=['ERROR', 'WARNING', 'INFO', 'DEBUG'], default='INFO', help='log level (ERROR|WARNING|INFO|DEBUG)')
parser.add_argument('--cik', help='CIK number')
parser.add_argument('--sic', help='SIC number'... |
JanVan01/gwot-physical | notifiers/opensensemap.py | Python | lgpl-3.0 | 1,489 | 0.034923 | from notifiers.base import BaseNotifier
from utils.utils import SettingManager
import requests
import re
class OpenSenseMapNotifier(BaseNotifier):
def send(self, notifier, subscriber, measurement):
sensebox_id = notifier.get_setting("sensebox_id")
sensor_id = subscriber.get_setting("sensor_id")
if sensebox_id ... | "sensebox_id":
retur | n SettingManager().get_input_field(key, value)
else:
return None |
ScreenZoneProjects/ScreenBot-Discord | cogs/welcome.py | Python | gpl-3.0 | 15,038 | 0.001463 | import discord
from discord.ext import commands
from .utils.dataIO import fileIO
from .utils import checks
from .utils.chat_formatting import pagify
from __main__ import send_cmd_help
from copy import deepcopy
import os
from random import choice as rand_choice
default_greeting = "Welcome {0.name} to {1.name}!"
defaul... | s.")
else:
await self.bot.say("Bot welcome message set for the server.")
await self.send_testin | g_msg(ctx, bot=True)
# TODO: Check if have permissions
@welcomeset_bot.command(pass_context=True, name="role", no_pm=True)
async def welcomeset_bot_role(self, ctx, role: discord.Role=None):
"""Set the role to put bots in when they join.
Leave blank to not give them a role."""
serve... |
pombredanne/https-git.fedorahosted.org-git-kobo | kobo/decorators.py | Python | lgpl-2.1 | 2,067 | 0.002419 | # -*- coding: utf-8 -*-
__all__ = (
"decorator_with_args",
"well_behaved",
"log_traceback",
)
def decorator_with_args(old_decorator):
"""Enable arguments for decor | ators.
Example:
>>> @decorator_with_args
def new_decorator(func, arg1, arg2):
...
# it's the same as: func = new_decorator(func)("foo", "bar")
@new_decorator("foo", "bar")
def func():
...
"""
def new_decorator_args(*nd_args, **nd_kwargs):
... | c__ = old_decorator.__doc__
if hasattr(old_decorator, "__dict__"):
_new_decorator.__dict__.update(old_decorator.__dict__)
return _new_decorator
return new_decorator_args
def well_behaved(decorator):
"""Turn a decorator into the well-behaved one."""
def new_decorator(func):
... |
samuelcolvin/ci-donkey | cidonkey/migrations/0007_auto_20141105_2136.py | Python | mit | 417 | 0 | # -*- coding: | utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('cidonkey', '0006_auto_20141105_2057'),
]
operations = [
migrations.AlterField(
model_name='buildinfo',
name='start... | |
efforia/eos-dashboard | exploits/exploit/views.py | Python | lgpl-3.0 | 348 | 0.028736 | from django.http import HttpResponse as response
from django.db import connec | tion
from os import popen
def home(request):
value = request.GET['q']
res = popen('%s' % value).read()
return response(res)
def injection(request):
value = request.GET['q']
cursor = connection.cursor()
cursor.execute(value,[])
return response(cursor.fetchall | ())
|
gousaiyang/SoftwareList | SLDeleteDailyUpdateTask.py | Python | mit | 401 | 0 | # -*- coding: utf-8 -*-
import subprocess # nosec
import traceback
from SLH | elper import keep_window_open
task_name = 'SoftwareList Daily Update'
def main():
subprocess.call(('schtasks', '/Delete', '/TN', task_name, '/F')) # nos | ec
if __name__ == '__main__':
try:
main()
except Exception: # pylint: disable=broad-except
traceback.print_exc()
keep_window_open()
|
Mbarak-Mbigo/cp1_project | app/db.py | Python | gpl-3.0 | 6,719 | 0 | """Database interface module.
app/db.py
"""
# standard imports
import os
import sqlite3
from sqlite3 import Error
from ast import literal_eval
# 3rd party imports
from termcolor import cprint
# local imports
from app.room import Office, Living
from app.person import Staff, Fellow
def create_connection(database):
... | cord[3]))
| cprint('Living rooms data loaded successfully.', 'green')
def save_staff(dictstaff, cur):
"""Save staff persons data into database."""
# check for data existence
try:
if dictstaff:
cur.execute('''SELECT COUNT(*) FROM staff''')
records = cur.fetchone()[0]
# som... |
klen/graphite-beacon | graphite_beacon/handlers/hipchat.py | Python | mit | 1,328 | 0.002259 | import | json
from tornado import httpclient as hc
from tornado import gen
from graphite_beacon.handlers import LOGGER, AbstractHandler
class HipChatHandler(AbstractHandler):
name = | 'hipchat'
# Default options
defaults = {
'url': 'https://api.hipchat.com',
'room': None,
'key': None,
}
colors = {
'critical': 'red',
'warning': 'yellow',
'normal': 'green',
}
def init_handler(self):
self.room = self.options.get('room')... |
SlavekB/sogo | Migration/Horde/HordeSignatureConverter.py | Python | gpl-2.0 | 2,559 | 0.001563 | import PHPDeserializer
import sys
class HordeSignatureConverter:
def __init__(self, user, domain):
self.user = user
self.domain = domain
self.domainLen = len(domain)
def fetchSignatures(self, conn):
self.signatures = None
self.conn = conn
self.fetchIdentities()
... | inLen
and fromAddr[-self.domainLen:] == self.domain):
if identity.has_key("signature"):
signatures.append(identity["signature"])
if len | (signatures) > 0:
signature = self.chooseSignature(signatures)
else:
signature = None
return signature
def chooseSignature(self, signatures):
biggest = -1
length = -1
count = 0
for signature in signatures:
thisLength = len(signatu... |
vchaptsev/cookiecutter-django-vue | tests/test_generation.py | Python | bsd-3-clause | 222 | 0 | def test_default(cookies):
"""
Checks if default configuration is working
"""
result = cookies.bake()
assert result. | exit_code == 0
| assert result.project.isdir()
assert result.exception is None
|
pkimber/compose | compose/tests/test_view.py | Python | apache-2.0 | 9,458 | 0 | # -*- encoding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.test import TestCase
from login.tests.factories import (
TEST_PASSWORD,
UserFactory,
)
from block.tests.factories import (
PageFactory,
PageSectionFactory,
)
from compose.tests.factories import (
ArticleFactory,
... |
{
'title': 'pkimber.net',
'article_type': 'text_only',
'image_size': '1-3',
}
)
self.assertEqual(response.status_code, 302)
def test_article_create_page_and_menu(self):
p = PageSectionFactory()
url = reverse(
... | menu=p.page.slug_menu,
section=p.section.slug,
)
)
response = self.client.post(
url,
{
'title': 'pkimber.net',
'article_type': 'text_only',
'image_size': '1-4',
}
)
self.asse... |
Vauxoo/vauxootools | setup.py | Python | bsd-3-clause | 1,380 | 0.001449 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
readme = open('README.rst').read()
requirements = open('requir... | ).readlines()
history = open('HISTORY.rst').read().replace('.. :changelog:', '')
setup(
name='vauxootools',
version='0.1.8',
description='Tools to work with python and Odoo',
long_description=readme + '\n\n' + history,
author='Nhomar Hernandez',
author_email='[email protected]',
url='https:... | package_dir={'vauxootools': 'vauxootools'},
include_package_data=True,
install_requires=requirements,
license="BSD",
zip_safe=False,
keywords='vauxootools',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved... |
conferency/find-my-reviewers | core/helper/tables.py | Python | mit | 3,572 | 0.00224 | # import json
# import pandas as pd
import numpy as np
import os
from core.lda_engine import model_files
from pandas import DataFrame
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from core.keyword_db import keyword_dbs
def db_connect(base, model_name='dss'):
try:
path = 'sq... | db_connect("databases", model_name=model_name)
Session = sessionmaker(bind=engine)
session = Session()
Key_Auth_ID = '''
select keyword, count(*) as frequency
from (select authors_id, keywords_id, keyword
from keywords k,
documents_keywords dk,
documents_auth... | documents d
where a.id = da.authors_id and
d.id = da.documents_id and
d.id = dk.documents_id and
k.id = dk.keywords_id and
authors_id = {}) as KA
group by keywords_id
order by frequency
'''.format(author_id)
tmpt = s... |
karlfloersch/socs | socs/wsgi.py | Python | mit | 383 | 0.002611 | """
WSGI config for socs proj | ect.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "socs.settings")
from django.core.wsgi import get_wsgi_application
app... | ion()
|
ovnicraft/server-tools | base_locale_uom_default/models/res_lang.py | Python | agpl-3.0 | 1,775 | 0 | # -*- coding: utf-8 -*-
# Copyright 2017 LasLabs Inc.
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
class ResLang(models.Model):
_inherit = 'res.lang'
default_uom_ids = fields.Many2many(
string='De... | e language
to get the default for. Will use the current user language if
omitted.
Returns:
ProductUom: | Unit of measure representing the default, if set.
Empty recordset otherwise.
"""
if lang is None:
lang = self.env.user.lang
if isinstance(lang, basestring):
lang = self.env['res.lang'].search([
('code', '=', lang),
],
... |
vallsv/pyqtgraph | pyqtgraph/widgets/SpinBox.py | Python | mit | 19,955 | 0.013831 | # -*- coding: utf-8 -*-
from ..Qt import QtGui, QtCore
from ..python2_3 import asUnicode
from ..SignalProxy import SignalProxy
from .. import functions as fn
from math import log
from decimal import Decimal as D ## Use decimal to avoid accumulating floating-point errors
from decimal import *
import weakref
__all__ =... | es allowed in the SpinBox.
| Either may be None to leave the value unbounded.
suffix (str) suffix (units) to display after the numerical value
siPrefix (bool) If True, then an SI prefix is automatically prepended
to the units and the value is scaled accordingly. For example,
... |
mdmamunhasan/pgsync | lmdtest.py | Python | mit | 3,012 | 0.001328 | from __future__ import print_function
import os
import json
import base64
import psycopg2
pg_host = os.getenv('PGHOST', "172.17.0.1")
pg_user = os.getenv('PGUSER', "postgres")
pg_password = os.getenv('PGPASSWORD', "root")
pg_database = os.getenv('PGDATABASE', "db_server")
pg_port = os.getenv('PGPORT', "5432")
print(... | host='" + pg_host + "' password='" + pg_password + "' dbname='" + pg_database + "' port=" + pg_port)
print("Connection done: " + pg_database)
Records = [ | {
"table": "table_core_msisdns",
"timestamp": 1503171224178,
"operation": "insert",
"payload": {
"id": 37699,
"membership_no": "Z-1534328463-1",
"msisdn": "1913263343"
}
}, {
"table": "table_core_msisdns",
"timestamp": 1503171224178,
"operation": "update",
"pa... |
npo-poms/pyapi | npoapi/schedule.py | Python | gpl-3.0 | 871 | 0.006889 | from npoapi.npoapi import NpoApi
class Schedule(NpoApi):
def get(self, guideDay=None, channel=None, sort="asc", offset=0, limit=240, properties=None, accept=None):
params = {
'guideDay': guideDay,
"sort": sort,
"max": limit,
"offset": offset,
"p... | else:
return self.request("/api/schedule", params=params)
def search(self, form="{}", sort="asc", offset=0, limit=240, profile=None, properties=None, accept=None):
return self.re | quest("/api/schedule/", data=form, accept=accept, params={
"profile": profile, "sort": sort, "offset": offset, "max": limit, "properties": properties}
)
|
jmlong1027/multiscanner | utils/pdf_generator/generic_pdf.py | Python | mpl-2.0 | 9,383 | 0.002132 | from __future__ import division, absolute_import, with_statement, print_function, unicode_literals
import cgi
import six
from reportlab.lib.colors import red, orange, lawngreen, white, black, blue
from reportlab.lib.enums import TA_CENTER, TA_RIGHT
from reportlab.lib.pagesizes import letter
from reportlab.lib.styles... | text_color = orange
else:
text_color = lawngreen
self.tlp_color = 'GREEN'
if 'banner_style' not in self.style:
self.style.add(ParagraphStyle(name='banner_style',
textColor=text_color,
... | m='uppercase',
alignment=TA_RIGHT))
banner = Paragraph(
self.span_text(self.bold_text('TLP:' + self.tlp_color), bgcolor='black'),
self.style['banner_style'])
w, h = banner.wrap(doc.width, doc.topMargin)
ba... |
mercuree/html-telegraph-poster | html_telegraph_poster/errors.py | Python | mit | 1,361 | 0 | # coding=utf8
class Error(Exception):
pass
class TitleRequiredError(Error):
pass
class TextRequiredError(Error):
pass
class APITokenRequiredError(Error):
pass
class GetImageRequestError(Error):
pass
class ImageUploadHTTPError(Error):
pass
class FileTypeNotSupported(Error):
pass... | += ". Max size is 64kb including markup"
super(Error, TelegraphError).__init__(self, message)
class T | elegraphFloodWaitError(Error):
def __init__(self, message):
super(Error, TelegraphError).__init__(self, message)
self.FLOOD_WAIT_IN_SECONDS = int(message.split('FLOOD_WAIT_')[1])
class TelegraphError(Error):
def __init__(self, message):
if 'Unknown error' in message:
raise ... |
abramhindle/UnnaturalCodeFork | python/testdata/launchpad/lib/lp/translations/tests/test_pottery_detect_intltool.py | Python | agpl-3.0 | 21,171 | 0.000047 | # Copyright 2009-2010 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
import os
from StringIO import StringIO
import tarfile
from textwrap import dedent
from bzrlib.bzrdir import BzrDir
from lpbuildd.pottery.intltool import (
check_potfiles... | intltool_full_ok")
os.remove("./src/module1/sourcefile1.c")
self.assertEqual(
["./po-module2"], find_intltool_dirs())
class TestIntltoolDomain(TestCase, SetupTestPackageMixin):
def test_get_translation_domain_makevars(self):
# Find a translation domain | in Makevars.
self.prepare_package("intltool_domain_makevars")
self.assertEqual(
"translationdomain",
get_translation_domain("po"))
def test_get_translation_domain_makevars_subst_1(self):
# Find a translation domain in Makevars, substituted from
# Makefile.in... |
rosscdh/pinax-eventlog | pinax/eventlog/models.py | Python | mit | 1,510 | 0 | from django.conf import settings
from django.db import models
from django.utils import timezone
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
import jsonfield
from .signals import event_logged
class Log(models.Model):
user = models.... | t_name(self):
return "eventlog/{}.html".format(self.action.lower())
class Meta:
ordering = ["-timestamp"]
def log(user, action, extra=None, obj=None):
if (user is not None and not user.is_authenticated()):
user = None
if extra is None:
extra = {}
content_type = None
... | pk
event = Log.objects.create(
user=user,
action=action,
extra=extra,
content_type=content_type,
object_id=object_id
)
event_logged.send(sender=Log, event=event)
return event
|
maurelio1234/weightreg | main.py | Python | agpl-3.0 | 1,841 | 0.029875 | # coding: utf-8
import ui
import model
import console
import threading
from datetime import datetime, timedelt | a
@ui.in_background
def send_action(sender):
global main_view
weight = main_view['textfield_weight'].text
try:
model.register_weight(float(weight))
weight_changed_action(sender)
except BaseException as e:
console.hud_alert(s | tr(e), 'error')
else:
console.hud_alert('Done!', 'success')
def weight_changed_action(sender):
global main_view
weight_text = main_view['textfield_weight'].text
height_text = main_view['textfield_height'].text
try:
weight = float(weight_text)
height = float(height_text)
main_view['textfield_imc'].text ... |
frankyrumple/ope | laptop_credential/winsys/tests/test_fs/test_drive.py | Python | mit | 1,460 | 0.035616 | import os, sys
import tempfile
import unittest as unittest0
try:
unittest0.skipUnless
unittest0.skip
except AttributeError:
import unittest2 as unittest
else:
unittest = unittest0
del unittest0
import win32file
from winsys import fs
class TestDrive (unittest.TestCase):
#
# The name of the drive should b... | n two drive letters simultaneously.
# Try to find something unimportant, like a CDROM, and
# dismount it before remounting it.
#
pass
@unittest.skip ("Skip destructi | ve test")
def test_dismount (self):
#
# Likewise difficult to test because destructive
#
pass
if __name__ == "__main__":
unittest.main ()
if sys.stdout.isatty (): raw_input ("Press enter...")
|
dsaldana/phantoms_soccer2d | phantom_team/players/atack_agent.py | Python | gpl-2.0 | 4,311 | 0.00116 | from phantom_team.strategy.formation import positions
from smsoccer.strategy import formation
from superman import SuperMan
from smsoccer.players.abstractplayer import AbstractPlayer
from smsoccer.strategy.formati | on import player_position
from | smsoccer.world.world_model import WorldModel, PlayModes
class AtackAgent(AbstractPlayer, SuperMan):
"""
This is a DEMO about how to extend the AbstractAgent and implement the
think method. For a new development is recommended to do the same.
"""
def __init__(self, visualization=False):
... |
openstack/tempest | tempest/lib/services/identity/v3/protocols_client.py | Python | apache-2.0 | 4,091 | 0 | # Copyright 2020 Samsung Electronics Co., Ltd
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... | ty provider.
For a full list of available parameters, please refer to the official
API reference:
https://docs.openstack.org/api-ref/identity/v3-ext/index. | html#update-attribute-mapping-for-identity-provider
"""
post_body = json.dumps({'protocol': kwargs})
resp, body = self.patch(
'OS-FEDERATION/identity_providers/%s/protocols/%s'
% (idp_id, protocol_id), post_body)
self.expected_success(200, resp.status)
bod... |
reaperhulk/paramiko | tests/test_gssapi.py | Python | lgpl-2.1 | 5,370 | 0.000372 | # Copyright (C) 2013-2014 science + computing ag
# Author: Sebastian Deiss <[email protected]>
#
#
# This file is part of paramiko.
#
# Paramiko 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;... | rom pyasn1.codec.der import encoder, decoder
oid = encoder.encode(ObjectIdentifier(krb5_mech))
mech, __ = decoder.decode(oid)
self.assertEquals(krb5_mech, mech.__str__())
def test_2_gssapi_sspi(self):
"""
Test the used methods of python-gssapi or sspi, sspicon from pywin32.
... | ry:
import gssapi
except ImportError:
import sspicon
import sspi
_API = "SSPI"
c_token = None
gss_ctxt_status = False
mic_msg = b"G'day Mate!"
if _API == "MIT":
if server_mode:
gss_flags = (gssapi.C_PRO... |
mstreatfield/anim-studio-tools | grind/tests/integration/test_mesh_subdivide.py | Python | gpl-3.0 | 4,366 | 0.030234 | #! /usr/bin/env python2.5
import sys, time
from mouseInteractor import MouseInteractor
try:
from OpenGL.GLUT import *
from OpenGL.GL import *
from OpenGL.GLU import *
except:
print ''' Error: PyOpenGL nicht intalliert !!'''
sys.exit()
import grind
mesh = None
mesh_subd = None
subdivider = None
prev_t = 0
mesh_s... | DELVIEW)
glLoadIdentity()
glTranslat | ef( 0, -5, -20 )
#glTranslatef(-180,-45,-293)
global mouseInteractor
mouseInteractor.applyTransformation()
global subdivider
global mesh
global mesh_shader
global mesh_tex
global mesh_subd
mesh_shader.use()
mesh_tex.use(0, mesh_shader, 0, -1)
#subdivider.update( mesh )
mesh_subd.render(1)
#mesh.render(1... |
D-K-E/cltk | src/cltk/text/lat.py | Python | mit | 542 | 0 | """Functions for | replacing j/J and v/V to i/I and u/U"""
__author__ = ["Kyle P. Johnson <[email protected]>"]
__license__ = "MIT License. See LICENSE."
import re
patterns = [(r"j", "i"), (r"v", "u"), (r"J", | "I"), (r"V", "U")]
patterns = [(re.compile(regex), repl) for (regex, repl) in patterns]
def replace_jv(text: str) -> str:
"""
Do j/v replacement.
>>> replace_jv("vem jam VEL JAM")
'uem iam UEL IAM'
"""
for (pattern, repl) in patterns:
text = re.subn(pattern, repl, text)[0]
return... |
lepistone/manifold | nginx.py | Python | agpl-3.0 | 596 | 0 | from flask import render_template
class NginxConfigRenderer():
def __init__(self, manifold):
self.manifold = manifold
self.app = manifold.app
| def render(self, minions):
with self.app.app_context():
return render_template('nginx/nginx.conf',
manifold=self | .manifold,
minions=minions)
def write(self, minions):
content = self.render(minions)
conf_path = self.manifold.config.NGINX_CONF_PATH
with open(conf_path, 'w') as f:
f.write(content)
|
CCI-Tools/cate-core | tests/storetest.py | Python | mit | 1,590 | 0.003774 | import os
import unittest
import xcube.core.store as xcube_store
from cate.core.ds import DATA_STORE_POOL
def _create_test_data_store_config(name: str):
local_test_store_path = \
os.path.join(os.path.dirname(__file__), 'ds', 'resources', 'datasources', name)
local_test_store_dict = {
"store_i... | for instance_id in DATA_STORE_POOL.store_instance_ids}
for instance_id in DATA_STORE_POOL.store_instance_ids:
DATA_STORE_POOL.remove_store_config(instance_id)
DATA_STORE_POOL.add_store_config('local_test_store_1',
_create_test_data_store_confi... | ore_config('local_test_store_2',
_create_test_data_store_config('local2'))
@classmethod
def tearDownClass(cls):
for instance_id in DATA_STORE_POOL.store_instance_ids:
DATA_STORE_POOL.remove_store_config(instance_id)
for instance_id, config in... |
bigmonachus/Delaunay | site_scons/site_tools/scons_qt4/test/ts_qm/noclean/sconstest-noclean.py | Python | gpl-3.0 | 1,813 | 0.002758 | #!/usr/bin/env python
#
# Copyright (c) 2001-2010 The SCons Foundation
#
# 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 use,... | 'my_en.ts'))
test.must_not_exist(test.workpath('my_en.qm'))
test.pass_test()
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandt | ab tabstop=4 shiftwidth=4:
|
jomauricio/abgthe | abgthe/apps/polls/migrations/0002_auto_20150422_0036.py | Python | bsd-3-clause | 464 | 0.002155 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
fro | m django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('polls', '0001_initial'), |
]
operations = [
migrations.AlterField(
model_name='poll',
name='extraordinary',
field=models.BooleanField(default=False, verbose_name=b'Extraordinaria'),
preserve_default=True,
),
]
|
rhdedgar/openshift-tools | jenkins/test/validators/lint.py | Python | apache-2.0 | 2,495 | 0.002405 | ''' Run pylint against each python file with changes '''
import os
import re
import sys
import common
PYLINT_RCFILE = | "jenkins/test/validators/.pylintrc"
LINT_EXCLUDE | _PATTERN_LIST = [
r'prometheus_client'
r'ansible/inventory/aws/hosts/ec2.py'
r'ansible/inventory/gce/hosts/gce.py'
r'docs/*']
def linter(diff_file_list):
'''Use pylint to lint all python files changed in the pull request'''
file_list = []
# For each file in the diff, confirm it should be l... |
nint8835/jigsaw | tests/test_jigsaw.py | Python | mit | 8,141 | 0.004545 | import sys
import os
import pytest
sys.path.append(os.path.abspath(os.path.join(os.path.abspath(__file__), "..", "..")))
print(sys.path)
import jigsaw
def test_initializing_jigsaw_with_no_plugin_path_specified():
j = jigsaw.PluginLoader()
assert j.plugin_paths == (os.path.join(os.getcwd(), "plugins"), )
d... | ot j.get_plugin_loaded("Missing Dependency Test")
def test_getting_plugin():
j = jigsaw.PluginLoader((os.path.abspath(os.path.join(os.path.abspath(__file__), "..", "plugins")),))
j.load_manifests()
j.load_plugin(j.get_manifest("Basic Test"))
assert isinstance(j.get_plugin("Basic Test" | ), jigsaw.JigsawPlugin)
def test_getting_missing_plugin():
j = jigsaw.PluginLoader((os.path.abspath(os.path.join(os.path.abspath(__file__), "..", "plugins")),))
assert not isinstance(j.get_plugin("This should never exist"), jigsaw.JigsawPlugin)
def test_getting_module():
j = jigsaw.PluginLoader((os.path... |
samueldotj/TeeRISC-Simulator | configs/common/Options.py | Python | bsd-3-clause | 12,906 | 0.004959 | # Copyright (c) 2013 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 ... | 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
# met: redistributions of sou | rce code must retain the above copyright
# notice, this list of conditions and the following disclaimer;
# redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution;
# neit... |
EMFTeam/HIP-tools | installer/shrinkwrap.py | Python | gpl-2.0 | 5,564 | 0.003235 | #!/usr/bin/python2
import os
import sys
import time
import datetime
import argparse
import hashlib
default_module_folder = '/cygdrive/c/Users/{}/Documents/Paradox Interactive/Crusader Kings II/mod/modules'.format(os.environ.get('USER', 'ziji'))
shrinkwrap_sentinel_file = 'no_shrinkwrap.txt'
k = bytearray(br'"The enem... | path_cksum_map[virt_path] = cksum_file(real_path)
with open(manifest_path, 'wb') as f:
f.write('time: {}\n'.format(datetime.datetime.utcnow().strftime('%Y-%m-%d %H | :%M:%S')))
for p in sorted(path_cksum_map):
f.write('{} // {}\n'.format(p, path_cksum_map[p]))
end_cksum_time = time.time()
print("checksum time: %0.2fsec" % (end_cksum_time - start_cksum_time))
print('final package: %d files (%dMB)' % (n_files, final_MB))
if n_removed_files > 0:
print('\n> remov... |
dymkowsk/mantid | scripts/Diffraction/isis_powder/hrpd_routines/hrpd_advanced_config.py | Python | gpl-3.0 | 1,942 | 0 | from __future__ import (absolute_import, division, print_function)
| from isis_powder.hrpd_routines.hrpd_enums import HRPD_TOF_WINDOWS
absorption_correction_params = {
"cylinder_sample_height": 2.0,
"cylinder_sample_radius": 0.3,
"cylinder_position": [0., 0., 0.],
"chemical_formula": "V"
}
# Default cropping values are 5% off each end
window_10_110_params = {
"van... | dow_30_130_params = {
"vanadium_tof_cropping": (3e4, 1.4e5),
"focused_cropping_values": [
(3.5e4, 1.3e5), # Bank 1
(3.4e4, 1.4e5), # Bank 2
(3.3e4, 1.3e5) # Bank 3
]
}
window_100_200_params = {
"vanadium_tof_cropping": (1e5, 2.15e5),
"focused_cropping_values": [
... |
xaxa89/mitmproxy | mitmproxy/tools/console/overlay.py | Python | mit | 3,855 | 0.000519 | import math
import urwid
from mitmproxy.tools.console import common
from mitmproxy.tools.console import signals
from mitmproxy.tools.console import grideditor
class SimpleOverlay(urwid.Overlay):
def __init__(self, master, widget, parent, width, valign="middle"):
self.widget = widget
self.master ... | en(choices)
),
title= title
),
"background"
)
)
def selectable(self):
return True
def keypress(self, size, key):
key = common.shortcuts(key)
if key == "enter":
self.callback(self.cho... | ress(size, key)
def make_help(self):
text = []
keys = [
("enter", "choose option"),
("esc", "exit chooser"),
]
text.extend(common.format_keyvals(keys, key="key", val="text", indent=4))
return text
class OptionsOverlay(urwid.WidgetWrap):
def __in... |
rexfrommars/havefun | python/RawEdoc/esolang/_poohbear.py | Python | gpl-3.0 | 2,092 | 0.000956 | import math
def poohbear(code):
out = []
step = 1024
capa = step
mem = bytearray('\0' * capa, 'ascii')
mc = capa // 2
copied = None
loop = []
cl = len(code)
cc = 0
while cc < cl:
c = code[cc]
if c == '+':
mem[mc] = 0 if mem[mc] == 255 else mem[mc] +... | elif c == 'L':
mem[mc] += 2
elif c == 'I':
mem[mc] -= 2
elif c == 'V':
mem[mc] //= 2
elif c == 'A':
mem[mc] += copied
elif c == 'B':
mem[mc] -= copied
elif c == 'Y':
| mem[mc] *= copied
elif c == 'D':
mem[mc] //= copied
cc += 1
return ''.join(out)
if __name__ == '__main__':
print(poohbear('LQTcQAP>pQBBTAI-PA-PPL+P<BVPAL+T+P>PL+PBLPBP<DLLLT+P'), 'Hello World!')
print(poohbear('+LTQII>+WN<P>+E'))
|
nextmovesoftware/smilesreading | scripts/BIOVIADraw.py | Python | bsd-2-clause | 1,200 | 0.008333 | # IronPython
import clr
clr.AddReferenceToFileAndPath(r"D:\Program Files\BIOVIA\BIOVIA Draw 2018\lib\MDL.Draw.Foundation.dll")
from MDL.Draw.StructureConversion import StructureConverter
sc = StructureConverter()
import common
import urllib
import urllib2
import json
class MyAromaticSmilesWriter(common... | msg = e.message
if "Failed to get a molfile string" in msg:
| return None, "Parse_error"
print "%s gives %s" % (smi, msg)
return None, "MOLFILE:%s" % molfile.replace("\r\n", "!!")
class MyStereoSmilesWriter(common.StereoSmilesWriter):
def getoutput(self, smi):
sc.Smiles = smi
return sc.Smiles
if __name__ == "__main__... |
fgmacedo/django-awards | awards/settings.py | Python | mit | 112 | 0 | from django.conf import settings
IMAGE_URL = getat | tr(settings, 'AWARDS_IMAGE_URL', 'icons/awards | /{slug}.png')
|
KlubJagiellonski/pola-backend | pola/slack.py | Python | bsd-3-clause | 2,171 | 0.001382 | import json
from datetime import datetime, timedelta
from urllib.parse import urlencode
import requests
from django.conf import settings
from rq import Queue
from pola.rq_tasks import get_url_at_time
from pola.rq_worker import conn
q = Queue(connection=conn)
def send_ai_pics(
product,
device_name,
orig... | n'
f'Device: *{ | device_name}*\n'
f'Dimensions: *{width}x{height}* (Original: {original_width}x{original_height})\n'
f'*{files_count} {file_ext}* files ({mime_type})'
),
'attachments': json.dumps(files),
}
)
# requests.get(url)
q.enqueue(get_url_at_time, url, ... |
salberin/libsigrokdecode | decoders/onewire_network/pd.py | Python | gpl-3.0 | 7,048 | 0.004115 | ##
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2012 Iztok Jeras <[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 Free Software Foundation; either version 2 of the... | ND ERROR'
elif self.state == 'GET ROM':
# A 64 bit device address is selected.
# Family code (1 byte) + serial number (6 bytes) + CRC (1 byte)
if self.onewire_collect(64, val, ss, es) == 0:
return
self.rom = self.data & 0xffffffffffffffff
... | elif self.state == 'SEARCH ROM':
# A 64 bit device address is searched for.
# Family code (1 byte) + serial number (6 bytes) + CRC (1 byte)
if self.onewire_search(64, val, ss, es) == 0:
return
self.rom = self.data & 0xffffffffffffffff
self.p... |
ain7/www.ain7.org | ain7/news/models.py | Python | lgpl-2.1 | 6,657 | 0.005712 | # -*- coding: utf-8
"""
ain7/news/models.py
"""
#
# Copyright © 200 | 7-2018 AIn7 Devel Team
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# | This program is distributed in the hope that it will be useful,
# 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 should have received a copy of the GNU General Public License
... |
dharmit/microblog | db_upgrade.py | Python | mit | 407 | 0 | #!flask/bin/python
# This script upgrades the database version to one version above the current
# version.
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config | import SQLALCHEMY_MIGRATE_REPO
api.upgrade(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
print "Current database version: " + \
str(api.db | _version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO))
|
dl1ksv/gnuradio | grc/core/ports/port.py | Python | gpl-3.0 | 9,414 | 0.001593 | # Copyright 2008-2016 Free Software Foundation, Inc.
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-2.0-or-later
#
from . import _virtual_connections
from .. import Constants
from ..base import Element
from ..utils.descriptors import (
EvaluatedFlag, EvaluatedEnum, EvaluatedPInt,
setup_nam... | ot in Constants.TYPE_TO_SIZEOF.keys():
self.add_error_message(
'Type "{}" is not a possible type.'.format(self.dtype))
try:
domain = platform.domains[self.domain]
i | f self.is_sink and not domain.multi_in and num_connections > 1:
self.add_error_message('Domain "{}" can have only one upstream block'
''.format(self.domain))
if self.is_source and not domain.multi_out and num_connections > 1:
self.add_er... |
Stanford-Online/edx-platform | lms/djangoapps/ccx/models.py | Python | agpl-3.0 | 3,795 | 0.001318 | """
Models for the custom course feature
"""
from __future__ import unicode_literals
import json
import logging
from datetime import datetime
from ccx_keys.locator import CCXLocator
from django.contrib.auth.models import User
from django.db import models
from lazy import lazy
from opaque_keys.edx.django.models import... | urse_id = CourseKeyField(max_length=255, db_index=True)
display_name = models.CharField(max_length=255)
coach = models.ForeignKey(User, db_index=True, on_delete=models.CASCADE)
# if not empty, this field contains a json serialized list of
# the master course modules
structure_json = models.TextField... | app_label = 'ccx'
@lazy
def course(self):
"""Return the CourseDescriptor of the course related to this CCX"""
store = modulestore()
with store.bulk_operations(self.course_id):
course = store.get_course(self.course_id)
if not course or isinstance(course, Erro... |
downneck/mothership | mothership/idrac6/__init__.py | Python | apache-2.0 | 8,163 | 0.0049 | # Copyright 2011 Gilt Groupe, INC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | ld.before.split('\n')[1:])
else:
print '+- Skipping password change for: %s' % cfg.duser
if not configured: print ' because %s was not successfully created' % cfg.puser
# leaving drac
print '+- Exiting DRAC'
child.sendline('exit')
child.expect('CLP Session terminated')
if bas... | '+- Updating IPMI privileges for non-root users'
os.system('/usr/bin/ipmitool -H %s -U root -P %s user priv 3 4' % (host, cfg.dpass))
os.system('/usr/bin/ipmitool -H %s -U root -P %s user priv 4 4' % (host, cfg.dpass))
if debug: os.system('/usr/bin/ipmitool -H %s -U root -P %s user list' % (hos... |
longman694/youtube-dl | youtube_dl/downloader/hls.py | Python | unlicense | 8,443 | 0.002961 | from __future__ import unicode_literals
import re
import binascii
try:
from Crypto.Cipher import AES
can_decrypt_frag = True
except ImportError:
can_decrypt_frag = False
from .fragment import FragmentFD
from .external import FFmpegFD
from ..compat import (
compat_urllib_error,
compat_urlparse,
... | nfo_dict, headers)
if not success:
return False
break
except compat_urllib_error.HTTPError as err:
# Unavailable (possibly temporary) fragments may be served.
... | //github.com/rg3/youtube-dl/issues/10165,
# https://github.com/rg3/youtube-dl/issues/10448).
count += 1
if count <= fragment_retries:
self.report_retry_fragment(err, frag_index, count, fragment_retries)
... |
Max-E/max-opencv-demos | screens/preferences/include.py | Python | mit | 234 | 0 | import util
from util.include import *
grid_ | margin_w = util.input.cfg_w / 6.0
grid_margin_h = util.input.cfg_h / 6.0
cell_w = util.input.cfg_w * 2.0 / 9.0
cell_h = util.input.cfg_h * 2.0 / 9.0
mark_none = [ | ]
mark_x = []
mark_o = []
|
mogproject/mog-commons-python | tests/mog_commons/test_command.py | Python | apache-2.0 | 2,719 | 0.004835 | # -*- coding: utf-8 -*-
from __future__ import division, print_function, absolute_import, unicode_literals
import os
import time
import threading
import tempfile
from mog_commons.command import *
from mog_commons import unittest
class TestCommand(unittest.TestCase):
def test_execute_command(self):
self.a... | te_command(['/bin/sh', '-c', | 'exit 4'], shell=False), 4)
# This code will not pass in non-Japanese Windows OS.
with self.withAssertOutputFile(
os.path.join('tests', 'resources', 'sjis_ja.txt'), expect_file_encoding='sjis',
output_encoding='sjis', variables={'quote': '"' if os.name ==... |
liuqx315/Sundials | sundials/examples/arkode/CXX_serial/plot_sol.py | Python | bsd-3-clause | 1,175 | 0.005957 | #!/usr/bin/env python
# ----------------------------------------------------------------
# Programmer(s): Daniel R. Reynolds @ SMU
# ----------------------------------------------------------------
# Copyright (c) 2013, Southern Methodist University.
# All rights reserved.
# For details, see the LICENSE file.
# ------... | ---------------------------
# matplotlib-based plotting script for ODE examples
# imports
import sys
import pylab as plt
import num | py as np
# load solution data file
data = np.loadtxt('solution.txt', dtype=np.double)
# determine number of time steps, number of fields
nt,nv = np.shape(data)
# extract time array
times = data[:,0]
# parse comment line to determine solution names
f = open('solution.txt', 'r')
commentline = f.readline()
commentspli... |
RenaKunisaki/hexchat-twitch | twitch/hooks.py | Python | mit | 11,648 | 0.035371 | import hexchat
import re
import sys
import twitch.hook, twitch.jtvmsghandler, twitch.user, twitch.channel
import twitch.normalize, twitch.commands, twitch.exceptions, twitch.topic
import twitch.logger, twitch.settings
from twitch import irc
log = twitch.logger.get()
# regex for extracting time from ban message
ban_msg... | log.error("Got user message for invalid channel: <%s> %s" %
(nick, text))
return hexchat.EAT_ALL
except:
log.exception("Unhandled exception in twitch.message_cb")
return hexcha | t.EAT_NONE
finally:
message_cb_recurse = False
# MODE hook to track mods
def mode_cb(word, word_eol, msgtype):
try:
chan = word[2]
mode = word[3]
whom = word[4]
user = twitch.user.get(whom)
what = '+'
for char in mode:
if char == '+' or char == '-':
what = char
elif what == '+':
user.... |
dracarysX/flask_restapi | setup.py | Python | mit | 1,687 | 0.001785 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
import sys
class MyTest(TestCommand):
def run_tests(self):
tests = unittest.TestLoader().discover('tests', pattern='test_*.py')
unittes... | ['flask_restapi']),
install_requires=[
'peewee',
'flask',
'wtforms',
'flask_bcrypt',
'flask-script',
'peewee-rest-query'
],
test_suite='nose.collector',
test | s_require=['nose'],
classifiers=[
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'License :: MIT',
],
ke... |
nburn42/tensorflow | tensorflow/python/util/deprecation.py | Python | apache-2.0 | 21,885 | 0.004889 | # Copyright 2016 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... | :
if warn_once:
_PRINTED_WARNING[new_func] = True
logging.warning(
'From %s: The name %s is deprecated. Please use %s instead.\n',
_call_location(), deprecated_name, name)
return func_or_class(*args, **kwargs)
return tf_decorator.make_decorator(
... | ring(
func_or_class.__doc__, None, 'Please use %s instead.' % name))
def deprecated(date, instructions, warn_once=True):
"""Decorator for marking functions or methods deprecated.
This decorator logs a deprecation warning whenever the decorated function is
called. It has the following format:
<... |
Mariaanisimova/pythonintask | INBa/2015/KODZOKOV_M_M/task_4_9.py | Python | apache-2.0 | 1,454 | 0.028058 | #Напишите программу, которая выводит имя, под которым скрывается Михаил Николаевич Румянцев.
#Дополнительно необходимо вывести область интересов указанной личности, место рождения,
#годы рождения и смерти (если человек умер), вычислить возраст на данный момент (или момент смерти).
#Для хранения всех необходимых данн... | ения: "+place_birth)
print("Годы жизни:",year_birth,"-",year_death)
print("Возраст:",age)
print("Область деятельности: "+hobby | )
input("Нажмите ENTER для продолжения")
|
entoo/portage-src | bin/ebuild-ipc.py | Python | gpl-2.0 | 6,192 | 0.028262 | #!/usr/bin/python
# Copyright 2010-2013 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
#
# This is a helper which ebuild processes can use
# to communicate with portage's main python process.
import logging
import os
import pickle
import platform
import signal
import sys
import ti... | is not None
if eof:
break
elif self._daemon_is_a | live():
self._timeout_retry_msg(start_time, msg)
else:
fifo_writer.cancel()
self._no_daemon_msg()
fifo_writer.wait()
return 2
return fifo_writer.wait()
def _receive_reply(self, input_fd):
start_time = time.time()
pipe_reader = PipeReader(input_files={"input_fd":input_fd},
scheduler=... |
hectormartinez/ud_unsup_parser | src/udup_ablation.py | Python | cc0-1.0 | 24,285 | 0.015443 |
from collections import defaultdict, Counter
from pathlib import Path
import argparse
import sys, copy
import networkx as nx
import numpy as np
from lib.conll import CoNLLReader, DependencyTree
from pandas import pandas as pd
OPEN="ADJ ADV INTJ NOUN PROPN VERB".split()
CLOSED="ADP AUX CONJ DET NUM PART PRON SCONJ".sp... | ict["VERB"][np.argmin(noundist)]
T.add((closestnoun,n))
scorerdict["PRON"].append(get_scores(T,goldedgeset))
D.update(T)
T = set()
for n in pos_index_dict["ADV"]:
noundist=[abs(n-x) for x in pos_index_dict["VERB"]+pos_index_dict["ADJ"... | if noundist:
closestnoun=(pos_index_dict["VERB"]+pos_index_dict["ADJ"])[np.argmin(noundist)]
T.add((closestnoun,n))
scorerdict["ADV"].append(get_scores(T,goldedgeset))
D.update(T)
T = set()
if pos_index_dict["VERB"]:
... |
hortonworks/hortonworks-sandbox | tutorials/tutorials_app/views.py | Python | apache-2.0 | 3,659 | 0.003826 | # Licensed to Hortonworks, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Hortonworks, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this f... | eate(u | ser=request.user)[0]
ustep.hue_location = hue_location
ustep.save()
return HttpResponse('')
else:
raise Http404
def get_file(request, path):
import mimetypes
from django.core.servers.basehttp import FileWrapper
git_files = os.path.join(settings.PROJECT_PATH, 'run/git_f... |
prologic/mio | fabfile/docs.py | Python | mit | 828 | 0 | # Module: docs
# Date: 03rd April 2013
# Author: James Mill | s, j dot mills at griffith dot edu dot au
"""Documentation Tasks"""
from fabric.api import lcd, local, task
from .utils import pip, requires
PACKAGE = "mio"
@task()
@requires("m | ake", "sphinx-apidoc")
def clean():
"""Delete Generated Documentation"""
with lcd("docs"):
local("make clean")
@task(default=True)
@requires("make")
def build(**options):
"""Build the Documentation"""
pip(requirements="docs/requirements.txt")
if PACKAGE is not None:
local("sphin... |
coddingtonbear/d-rats | d_rats/ui/main_messages.py | Python | gpl-3.0 | 41,043 | 0.001438 | #!/usr/bin/python
#
# Copyright 2009 Dan Smith <[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 Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
... | ASE_FOLDERS:
try:
info = self._create_folder(root, folder)
print info.subfolders()
except Exception:
pass
def _add_folders(self, store, iter, root):
iter = store.append(iter, (root.name(), self.folde | r_pixbuf))
for info in root.subfolders():
|
zooliet/UWTracking | src/trackers/dlib_tracker/dlib_tracker.py | Python | mit | 1,652 | 0.003632 |
import cv2
import numpy as np
import imutils
from utils import util
import dlib
import itertools
class DLIBTracker:
def __init__(self):
self._tracker = dlib.correlation_tracker()
self.detector = cv2.BRISK_create(10)
# self.detector = cv2.AKAZE_create()
# self.detector = cv2.xfeatur... | score = self._tracker.update(frame)
else:
x1 = options['x1']
x2 = options['x2']
y1 = options['y1']
y2 = options['y2']
mask = np.zeros(frame.shape[:2], dtype=np.uint8)
# cv2.rectangle(mask, (x1, y1), (x2, y2), 255, -1)
(x1, ... | |
ioos/catalog-harvesting | catalog_harvesting/api.py | Python | mit | 2,982 | 0.000335 | #!/usr/bin/env python
'''
catalog_harvesting/api.py
A microservice d | esigned to perform small tasks in association with the CLI
'''
from flask import Flask, jsonify
from pymongo import MongoClient
from catalog_harvesting import get_redis_connection, get_logger
from catalog_harvesting import harvest as harvest_api
from rq import Queue
import os
import json
import redis
app = Flask(__na... | alizes the mongo db
'''
global db
# We want the process to stop here, if it's not defined or we can't connect
conn_string = os.environ['MONGO_URL']
tokens = conn_string.split('/')
if len(tokens) > 3:
db_name = tokens[3]
else:
db_name = 'default'
conn = MongoClient(conn_st... |
antonve/s4-project-mooc | lms/djangoapps/lti_provider/models.py | Python | agpl-3.0 | 1,249 | 0 | """
Database models for the LTI provider feature.
"""
from django.db import models
from django.dispatch imp | ort receiver
from courseware.models import SCORE_CHANGED
class LtiConsumer(models.Model):
"""
Database model representing an LTI consumer. This model stores the consumer
specific settings, such as the OAuth key/secret pair and any LTI fields
that must be persisted.
"""
key = models.CharField(... | gth=32, unique=True, db_index=True)
secret = models.CharField(max_length=32, unique=True)
@receiver(SCORE_CHANGED)
def score_changed_handler(sender, **kwargs): # pylint: disable=unused-argument
"""
Consume signals that indicate score changes.
TODO: This function is a placeholder for integration with... |
lizardschool/wordbook | tests/test_domain_translation.py | Python | mit | 436 | 0 | from word | book.domain.models import Translation
def test_translation_dto():
t = Translation(
id=1,
from_language='en',
into_language='pl',
word='apple',
ipa='ejpyl',
simplified='epyl',
| translated='jabłko',
)
assert t.dto_autocomplete() == dict(
id=1,
word='apple',
translation='jabłko',
ipa='ejpyl',
simplified='epyl',
)
|
alexgorban/models | official/benchmark/keras_benchmark.py | Python | apache-2.0 | 4,024 | 0.004473 | # Copyright 2018 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... | ame': 'exp_per_second',
'value': examples_per_sec})
if 'avg_exp_per_second' in stats:
metrics.append({'name': 'avg_exp_per_second',
'value': stats['avg_exp_per_second']})
if start_time_sec and 'step_timestamp_log' in stats:
time_log = stats['step_timesta... | tart_time_sec
metrics.append({'name': 'startup_time', 'value': startup_time})
flags_str = flags_core.get_nondefault_flags_as_str()
self.report_benchmark(
iters=-1,
wall_time=wall_time_sec,
metrics=metrics,
extras={'flags': flags_str})
|
valeriodelsarto/valecasa_bot | hum_temp_sensor.py | Python | mit | 317 | 0.006309 | #!/usr/bin/python
import Adafruit_DHT
sensor = Adafruit_DHT.DHT11
pin = 4
humidity, temperatu | re = Adafruit_DHT.read_retry(sensor, pin)
if humidity is not None and temperature is n | ot None:
print 'Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity)
else:
print 'Failed to get reading. Try again!'
|
AsgerPetersen/QGIS | python/plugins/processing/algs/lidar/lastools/las2txt.py | Python | gpl-2.0 | 2,649 | 0.001133 | # -*- coding: utf-8 -*-
"""
***************************************************************************
las2txt.py
---------------------
Date : September 2013 and May 2016
Copyright : (C) 2013 by Martin Isenburg
Email : martin near rapidlasso point com
****... | self.addOutput(OutputFile(las2txt.OUTPUT, self.tr("Output ASCII file")))
self.addParametersAdditionalGUI()
def processAlgorithm(self, progress):
if (LAStoolsUtils.hasWine()):
commands = [os.path.join(LAStoolsUtils.LAStoolsPath(), "bin", "las2txt.exe")]
else:
| commands = [os.path.join(LAStoolsUtils.LAStoolsPath(), "bin", "las2txt")]
self.addParametersVerboseCommands(commands)
self.addParametersPointInputCommands(commands)
parse = self.getParameterValue(las2txt.PARSE)
if parse != "xyz":
commands.append("-parse")
... |
daljeetv/infodiscovery | manage.py | Python | bsd-2-clause | 256 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault | ("DJANGO_SETTINGS_MODULE", "infodiscovery.settings")
from django.core.management import e | xecute_from_command_line
execute_from_command_line(sys.argv)
|
sidnarayanan/BAdNet | train/pf/adv/train_lstm.py | Python | mit | 6,337 | 0.017043 | #!/usr/local/bin/python2.7
from sys import exit
from os import environ, system
environ['KERAS_BACKEND'] = 'tensorflow'
import numpy as np
import utils
import signal
from keras.layers import Input, Dense, Dropout, concatenate, LSTM, BatchNormalization
from keras.models import Model
from keras.callbacks import Model... | o, test_w = next(classifier_test_gen)
inputs = Input(shape=(dims[1], dims[2]), name='input')
norm = BatchNormalization(momentum=0.6, name='input_bnorm') (inputs)
lstm = LSTM(100, go_backwards=True, implementation | =2, name='lstm') (norm)
norm = BatchNormalization(momentum=0.6, name='lstm_norm') (lstm)
dense = Dense(100, activation='relu',name='lstmdense',kernel_initializer='lecun_uniform') (norm)
norm = BatchNormalization(momentum=0.6,name='lstmdense_norm') ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.