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 |
|---|---|---|---|---|---|---|---|---|
RobertoPrevato/Humbular | tools/knight/core/literature/scribe.py | Python | mit | 1,844 | 0.003254 | import io
import sys
isPython3 = sys.version_info >= (3, 0)
class Scribe:
@staticmethod
def read(path):
with io.open(path, mode="rt", encoding="utf-8") as f:
s = f.read()
# go to beginning
f.seek(0)
return s
@staticmethod
de... | # truncate previous contents
f.truncate()
f.write(contents)
else:
with io.open(path, mode="wt", encoding="utf-8") as f:
# truncate previous contents
f.truncate()
f.write(contents.decode("utf8"))
@stati... | ython3:
with open(path, mode="wt", encoding="utf-8") as f:
f.writelines([l + "\n" for l in lines])
else:
with io.open(path, mode="wt") as f:
for line in lines:
f.writelines(line.decode("utf8") + "\n")
@staticmethod
def... |
batxes/4Cin | SHH_WT_models_highres/SHH_WT_models_highres_final_output_0.1_-0.1_5000/SHH_WT_models_highres8869.py | Python | gpl-3.0 | 88,246 | 0.024511 | import _surface
import chimera
try:
import chimera.runCommand
except:
pass
from VolumePath import markerset as ms
try:
from VolumePath import Marker_Set, Link
new_marker_set=Marker_Set
except:
from VolumePath import volume_path_dialog
d= volume_path_dialog(True)
new_marker_set= d.new_marker_set
marker_set... | r((-698.587, 4126.53, 1126.53), (0.7, 0.7, 0.7), 128.465)
if "particle_18 geometry" not in marker_sets:
s=new_marker_set('particle_18 geometry')
marker_sets["particle_18 geometry"]=s
s= marker_sets["particle_18 geometry"]
mark=s.place_marker((-753.257, 4285.81, 653.058), (0.7, 0.7, 0.7), 217.38)
if "particle_19 geo... | ry" not in marker_sets:
s=new_marker_set('particle_19 geometry')
marker_sets["particle_19 geometry"]=s
s= marker_sets["particle_19 geometry"]
mark=s.place_marker((-1168.05, 4431.5, 116.214), (0.7, 0.7, 0.7), 184.555)
if "particle_20 geometry" not in marker_sets:
s=new_marker_set('particle_20 geometry')
marker_s... |
dios-game/dios-cocos | src/oslibs/cocos/cocos-src/tools/jenkins-scripts/configs/cocos-2dx-pull-request-build-comment-trigger.py | Python | mit | 201 | 0.014925 | import os
#os.system('git check | out develop')
#os.system('git pull or | igin develop')
ret = os.system('python -u tools/jenkins-scripts/job-comment-trigger.py')
if ret == 0:
exit(0)
else:
exit(1)
|
kalebhartje/schoolboost | cms/djangoapps/course_creators/tests/test_admin.py | Python | agpl-3.0 | 2,658 | 0.002634 | """
Tests course_creators.admin.py.
"""
from django.test import TestCase
from django.contrib.auth.models import User
from django.contrib.admin.sites | import AdminSite
from django.http import HttpRequest
import mock
from course_creators.admin import CourseCreatorAdmin
from course_creators.models import CourseCreator
from auth.authz import is_user_in_creator_group
class CourseCreatorAdminTest(Test | Case):
"""
Tests for course creator admin.
"""
def setUp(self):
""" Test case setup """
self.user = User.objects.create_user('test_user', 'test_user+courses@edx.org', 'foo')
self.table_entry = CourseCreator(user=self.user)
self.table_entry.save()
self.admin = Us... |
go1dshtein/pgv | setup.py | Python | gpl-2.0 | 968 | 0 | #!/usr/bin/env python
from setuptools import setup
setup(name='pgv',
version='0.0.2',
description="PostgreSQL schema versioning tool",
long_description=open("README.rst").read(),
author='Kirill Goldshtein',
author_email='goldshtein.kirill@gmail.com',
packages=['pgv', 'pgv.utils', '... | icense='GPLv2',
url='https://github.com/go1dshtein/pgv',
classifiers=['Intended Audience :: Developers',
| 'Environment :: Console',
'Programming Language :: Python :: 2.7',
'Natural Language :: English',
'Development Status :: 1 - Planning',
'Operating System :: Unix',
'Topic :: Utilities'])
|
kdunn926/eunomia-django | Financers/views.py | Python | apache-2.0 | 856 | 0.025701 | # Create your views here.
from django.shortcuts import render, redirect
from django.views import generic
| from Financers.models import Financers
import re
import random
def financer_detail(request, name):
template_name = 'financer_detail.html'
financer = ''
if name != "Unknown":
name = name.replace(',', '')
financer = Financers().getFinancersContributions(name)
profile = {}
print financer
profile['name'] = nam... | name):
template_name = 'financer_contributions.html'
print name
candidates = Financers().getFinancersContributions(name)
print candidates
profile = {}
profile['name'] = name
#profile['financers_list'] = financers_list
context = {'profile': profile}
return render(request, template_name, context)
|
rafamanzo/colab | colab/plugins/management/commands/import_proxy_data.py | Python | gpl-2.0 | 1,015 | 0 | #!/usr/bin/env python
import importlib
impo | rt inspect
from django.core.management.base import BaseCommand
from django.conf import settings
from colab.plugins.utils.proxy_data_api import ProxyDataAPI
class Command(BaseCommand):
help = "Import proxy data into colab database"
def handle(self, *args, **kwargs):
print "Executing extraction comma... | .{}.data_api'.format(module_name.split('.')[-1])
module = importlib.import_module(module_path)
for module_item_name in dir(module):
module_item = getattr(module, module_item_name)
if not inspect.isclass(module_item):
continue
i... |
bonnieblueag/farm_log | livestock/views.py | Python | gpl-3.0 | 571 | 0.005254 | from django.shortcuts import render
from core.views import get_add_model_form
from livestock.models import EggCollection, AnimalReport
from livestock.forms import EggCollectionForm, AnimalReportF | orm
ADD_LIVESTOCK_TEMPLATE = 'livestock/add_livestock_model.html'
def add_egg_collection(request):
return get_add_model_form(request, ADD_LIVESTOCK_TEMPLATE, EggCollection, 'Eggs', 'datetime', EggCollectionForm)
def add_animal_report(request):
| return get_add_model_form(request, ADD_LIVESTOCK_TEMPLATE, AnimalReport, 'Animal Report', 'datetime', AnimalReportForm) |
frePPLe/frePPLe | djangosettings.py | Python | agpl-3.0 | 19,163 | 0.001148 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2015 by frePPLe bv
#
# This library 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 option) any later versio... | dump exposes all data, enabling this functionality should only be done
# for system administrators that know what they are doing.
SUPPORT_USERS = []
# If passwords are set in this file they will be used instead of the ones set in the database parameters table
ODOO_PASSWORDS = {"default": "", "scenario1": "", "scenario... | nstallation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must b... |
landism/pants | src/python/pants/backend/jvm/tasks/nailgun_task.py | Python | apache-2.0 | 4,969 | 0.00644 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
from pant... | 0.9.1'),
])
@classmethod
def subsystem_dependencies(cls):
return super(NailgunTaskBase, cls).subsystem_dependencies() + (Subprocess | .Factory,)
def __init__(self, *args, **kwargs):
"""
:API: public
"""
super(NailgunTaskBase, self).__init__(*args, **kwargs)
id_tuple = (self.ID_PREFIX, self.__class__.__name__)
self._identity = '_'.join(id_tuple)
self._executor_workdir = os.path.join(self.context.options.for_global_scop... |
fossilet/project-euler | pe1.py | Python | mit | 1,110 | 0.023423 | #! /usr/bin/env python3
# encoding: utf-8
'''
http://projecteuler.net/problem=1
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
'''
# Since May 22 2012
from projecteuler import c... |
# v2
# Generator expression faster than for loop
def v2():
return sum( i for i in range(n) if i%a == 0 or i%b == 0 )
# v3
# Almost as fast as v2
def v3():
return sum( i for i in range(n) if not i%a or not i%b )
# v4
# Almost as fast as v | 2
def v4():
return sum( i for i in range(n) if not (i%a and i%b) )
# v5
# Time is O(1), the fastest
def v5():
n = 999
return sum((n//k*k+k)*(n//k)/2*v for k,v in {a:1, b:1, a*b:-1}.items())
if __name__ == '__main__':
for i in range(1, 6):
fname = 'v%d' % i
print(locals()[fname]())
... |
swoodford/twitter | status-tweet.py | Python | apache-2.0 | 663 | 0.001508 | #!/usr/bin/env python
# This script will tweet the text that is passed as an argument
# Requires Twython, API credentials set as env vars
# Usage: python status-tweet.py "Hello Everyone, this is my | Raspberry Pi tweeting you more nonsense"
import sys
import os
from twython import Twython
import twitter_api_creds
# Set Twitter Credentials from environment variables
CONSUMER_KEY = os.getenv("CONSUMER_KEY")
CONSUMER_SECRET = os.getenv("CONSUMER_SECRET")
A | CCESS_KEY = os.getenv("ACCESS_KEY")
ACCESS_SECRET = os.getenv("ACCESS_SECRET")
api = Twython(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, ACCESS_SECRET)
# Tweet
api.update_status(status=sys.argv[1][:140])
|
mohamed-ali-affes/oojuba | src/blog/models.py | Python | mit | 476 | 0 | from django.db import models
from django.utils import timezone
class Post(models.Model):
author = models.Forei | gnKey('auth.User')
title = models.CharField(m | ax_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
|
ali/mopidy | mopidy/mpd/protocol/playback.py | Python | apache-2.0 | 13,957 | 0 | from __future__ import absolute_import, unicode_literals
from mopidy.core import PlaybackState
from mopidy.internal import deprecation
from mopidy.mpd import exceptions, protocol
@protocol.commands.add('consume', state=protocol.BOOL)
def consume(context, state):
"""
*musicpd.org, playback section:*
... | ecibels):
"""
*musicpd.org, playback section:*
``mixrampdb {deciBels}``
Sets the threshold at which songs will be overlapped. Like crossfa | ding but
doesn't fade the track volume, just overlaps. The songs need to have
MixRamp tags added by an external tool. 0dB is the normalized maximum
volume so use negative values, I prefer -17dB. In the absence of mixramp
tags crossfading will be used. See http://sourceforge.net/projects/mixramp
"""
... |
tdimiduk/groupeng | src/__init__.py | Python | agpl-3.0 | 724 | 0 | #!/usr/bin/python
# Copyright 2011, Thomas G. Dimiduk
#
# This file is part of GroupEng.
#
# Holopy 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 option... | r more details.
#
# You should have received a copy of t | he GNU Affero General Public License
# along with GroupEng. If not, see <http://www.gnu.org/licenses/>.
|
luotao1/Paddle | python/paddle/fluid/tests/unittests/test_imperative_signal_handler.py | Python | apache-2.0 | 5,136 | 0 | # Copyright (c) 2019 PaddlePaddle 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 appli... | :
self.func_child_process_killed_by_sigbus()
self.func_child_process_killed_by_sigbus()
def func_child_process_killed_by_sigterm(self):
def __test_process__():
| core._set_process_signal_handler()
time.sleep(10)
test_process = multiprocessing.Process(target=__test_process__)
test_process.daemon = True
test_process.start()
set_child_signal_handler(id(self), test_process.pid)
time.sleep(1)
def test_child_process_killed... |
reneisrael/coursera | Rock-paper-scissors-lizard-Spock.py | Python | gpl-2.0 | 1,947 | 0.007191 | # Rock-paper-scissors-lizard-Spock
import random
# helper functions
def name_to_number(name):
if name == "rock":
name = 0
elif name == "Spock":
name = 1
elif name == "paper":
name = 2
elif name == "lizard":
name = 3
elif name == "scissors":
name = 4
els... | _to_name()
comp_choice = number_to_name(comp_number)
# print out the message for computer's choice
print "Computer chooses", comp_choice
# compute difference of comp_number and player_nu | mber modulo five
a = (player_number - comp_number) % 5
# use if/elif/else to determine winner, print winner message
if player_number == comp_number :
print "Player and computer tie!"
elif a <= 2:
print "Player wins!"
else :
print "Computer wins!"
# test your code - THESE... |
denys-duchier/Scolar | safehtml.py | Python | gpl-2.0 | 361 | 0.030471 |
from stripogram import html2text, html2safehtml
# permet de conse | rver quelques tags html
def HTML2SafeHTML( text, convert_br=True ):
text = html2safehtml( text, valid_tags=('b', 'a', 'i', 'br', 'p'))
if convert_br:
return newline_to_br(text)
else:
return text
def new | line_to_br( text ):
return text.replace( '\n', '<br/>' )
|
Doctor-love/kkross | playground/kkross/modules/module_loader.py | Python | gpl-2.0 | 919 | 0.003264 | from kkross.exceptions import ModuleError, LoaderError
from kkross.module import Module
from glob import glob
from yaml import safe_load
import os
def module_loader(module_dirs):
'''Loads module YAML from ...'''
module_paths = []
for module_dir in module_dirs:
| module_paths.extend(glob(os.path.join(module_dir, '*.y*ml')))
if not modul | e_paths:
return []
modules = []
for module_path in module_paths:
try:
module_raw = safe_load(open(module_path, 'r'))
except Exception as error_msg:
raise LoaderError(
'Failed to load module YAML data from "%s": "%s"' % (module_path, error_msg))
... |
gawel/irc3 | examples/wsgiapp.py | Python | mit | 726 | 0 | # -*- coding: utf | -8 -*-
import asyncio
from aiohttp import wsgi
from irc3 import plugin
import json
@plugin
class Webapp:
requires = ['irc3.plugins.userlist']
def __init__(self, bot):
def server():
return wsgi.WSGIServerHttpProtocol(self.wsgi)
self.bot = bot
loop = asyncio.get_event_loop(... | se):
start_response('200 OK', [('Content-Type', 'application/json')])
plugin = self.bot.get_plugin('userlist')
data = json.dumps(list(plugin.channels.keys()))
return [data.encode('utf8')]
|
cournape/numscons | numscons/scons-local/scons-local-1.2.0/SCons/Node/Python.py | Python | bsd-3-clause | 4,216 | 0.002135 | """scons.Node.Python
Python nodes.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 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... | is_under(self, dir):
# Make Value nodes get built regardless of
# what directory scons was run from. Value nodes
# are outside the filesystem:
return 1
def write(self, built_value):
"""Set the value of the | node."""
self.built_value = built_value
def read(self):
"""Return the value. If necessary, the value is built."""
self.build()
if not hasattr(self, 'built_value'):
self.built_value = self.value
return self.built_value
def get_text_contents(self):
""... |
Ye-Yong-Chi/xortool | xortool/libcolors.py | Python | mit | 2,323 | 0.001291 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import os
BASH_ATTRIBUTES = {"regular": "0",
"bold": "1", "underline": "4", "strike": "9",
"light": "1", "dark": "2",
"invert": "7"} # invert bg and fg
BASH_COLORS = {"black": "30", "red": "31", "green": "32", "yel... | ellow": "43",
"blue": "44", "purple": "45", "cyan": "46", "white": "47"}
def | _main():
header = color("white", "black", "dark")
print
print header + " " + "Colors and backgrounds: " + color()
for c in _keys_sorted_by_values(BASH_COLORS):
c1 = color(c)
c2 = color("white" if c != "white" else "black", bgcolor=c)
print (c.ljust(10) +
... |
AriZuu/micropython | tests/float/complex1.py | Python | mit | 2,231 | 0.003586 | # test basic complex number functionality
# constructor
print(complex(1))
print(complex(1.2))
print(complex(1.2j))
print(complex("1"))
print(complex("1.2"))
print(complex("1.2j"))
print(complex(1, 2))
print(complex(1j, 2j))
# unary ops
print(bool(1j))
print(+(1j))
print(-(1 + 2j))
# binary ops
print(1j + False)
prin... | ans.imag))
ans = (-1.2) ** -3.4; print("%.5g %.5g" % (ans.real, ans.imag))
# check printing of inf/nan
print(float('nan') * 1j)
print(float('-nan') * 1j)
print(float('inf') * (1 + 1j))
print(float('-inf') * (1 + 1j))
# can't assign to attributes
try:
(1j).imag = 0
except AttributeError:
print('AttributeError'... | convert rhs to complex
try:
1j + []
except TypeError:
print("TypeError")
# unsupported unary op
try:
~(1j)
except TypeError:
print("TypeError")
# unsupported binary op
try:
1j // 2
except TypeError:
print("TypeError")
# unsupported binary op
try:
1j < 2j
except TypeError:
print("Type... |
shaise/FreeCAD_FastenersWB | Init.py | Python | gpl-2.0 | 1,063 | 0.007526 | # -*- coding: utf-8 -*-
###################################################################################
#
# Init.py
#
# Copyright 2015 Shai Seger <shaise at gmail dot com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License ... | l Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1 | 301, USA.
#
#
###################################################################################
# print "Fasteners workbench Loaded"
|
mdeff/ntds_2017 | projects/reports/arab_springs/lib/models.py | Python | mit | 40,998 | 0.002829 | from . import graph
import tensorflow as tf
import sklearn
import scipy.sparse
import numpy as np
import os, time, collections, shutil
#NFEATURES = 28**2
#NCLASSES = 10
# Common methods for all models
class base_model(object):
def __init__(self):
self.regularizers = []
# High-level interface wh... | t_sess | ion(sess)
for begin in range(0, size, self.batch_size):
end = begin + self.batch_size
end = min([end, size])
batch_data = np.zeros((self.batch_size, data.shape[1]))
tmp_data = data[begin:end,:]
if type(tmp_data) is not np.ndarray:
tmp_... |
lunixbochs/SublimeXiki | edit.py | Python | mit | 2,725 | 0.000367 | # edit.py
# buffer editing for both ST2 and ST3 that "just works"
import inspect
import sublime
import sublime_plugin
try:
sublime.sublimexiki_edit_storage
except AttributeError:
sublime.sublimexiki_edit_storage = {}
def run_callback(func, *args, **kwargs):
spec = inspect.getfullargspec(func)
if spec... | ve(view, edit)
args.app | end(arg)
return args
class Edit:
def __init__(self, view):
self.view = view
self.steps = []
def __nonzero__(self):
return bool(self.steps)
@classmethod
def future(self, func):
return EditFuture(func)
def step(self, cmd, *args):
step = EditStep(cmd... |
der-michik/c3bottles | c3bottles/views/forms.py | Python | mit | 1,168 | 0.000856 | from flask_wtf import FlaskForm
from wtforms.fields import StringField, PasswordField, HiddenField, IntegerField, BooleanField
from wtforms.validators import DataRe | quired
from wtforms.widgets import HiddenInput
class LoginForm(FlaskForm):
username = StringField("username", validators=[DataRequired()])
password = PasswordField("password", validators=[DataRequired()])
back = HiddenField("back")
args = HiddenField("args")
class UserIdForm(FlaskForm):
user_id ... | Form(UserIdForm):
can_visit = BooleanField("can_visit")
can_edit = BooleanField("can_edit")
is_admin = BooleanField("is_admin")
class PasswordForm(UserIdForm):
password_1 = PasswordField("password_1", validators=[DataRequired()])
password_2 = PasswordField("password_2", validators=[DataRequired()]... |
marthall/accounting | moneymaker/admin.py | Python | mit | 496 | 0 | from django.contrib import admin
from moneymaker.models import Product
from moneymaker.models import Income
from moneymaker.models import Expense
f | rom moneymaker.models import ExpenseCategory
from moneymaker.models import IncomeCategory
class ExpenseAdmin(admin.ModelAdmin):
list_display = ('date', '__unicode__')
admin.site.register(Product)
admin.site.register(Income)
admin.site.register(Expense, ExpenseAdmin)
admin.site | .register(ExpenseCategory)
admin.site.register(IncomeCategory)
|
mdcic/ssp | ssp/netconfig.py | Python | gpl-3.0 | 5,352 | 0.037937 | # -*- coding: utf-8 -*-
#
# Copyright © 2012-2013 Yury Konovalov <YKonovalov@gmail.com>
#
# This file is part of SSP.
#
# SSP 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, o... | :
LOG.error("Cannot run ping command.")
raise
def get_iface_by_route(ip):
"""Return the local interface name for spe | cific IP address. None for indirectly routed addresses"""
try:
s = subprocess.Popen(["ip","r","g",ip], stderr=open('/dev/null', 'w'), stdout=subprocess.PIPE).communicate()[0]
for r in re.finditer(r"(?m)^"+ip+"\s+dev\s+(?P<iface>[^\s]+).*$",s):
return r.groupdict()['iface']
except:
LOG.error("Cannot run 'ip r... |
abdollatiif/NetCoding | wifi/bindings/callbacks_list.py | Python | gpl-2.0 | 1,855 | 0.00593 | callback_classes = [
['void', 'ns3::Ptr<ns3::Packet const>', 'double', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['void', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['... | ddress', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['void', ' | ns3::Mac48Address', 'unsigned char', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['void', 'ns3::Mac48Address', 'unsigned char', 'bool', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
]
|
acq4/acq4 | acq4/util/igorpro.py | Python | mit | 10,366 | 0.002315 | from __future__ import print_function
import sys
import win32com.client
import pywintypes
import pythoncom
import numpy as np
import subprocess as sp
import concurrent.futures
import atexit
import json
import zmq
import os
from six.moves import range
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..')... | future.set_exception(IgorCallError("Send timed out",
IgorCallError.TIMEDOUT))
return future
def _checkRecv(self):
try:
reply = json.loads(self._socket.recv_multipart()[-1])
messageID = reply.get("messageID", None)
future = self._unresol... | = self.parseReply(reply)
future.set_result(reply)
except IgorCallError as e:
future.set_exception(e)
except zmq.error.Again:
pass
def _getMessageID(self):
mid = self._currentMessageID
self._currentMessageID += 1
return str(mid... |
unlessbamboo/grocery-shop | language/python/src/flask/flaskr/flaskr.py | Python | gpl-3.0 | 3,444 | 0 | # -*- coding: utf-8 -*-
"""
Flaskr
~~~~~~
A microblog example application written as Flask tutorial with
Flask and sqlite3.
:copyright: (c) 2010 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
from sqlite3 import dbapi2 as sqlite3
from flask import (Flask, request, session... | 的db条目"""
db = get_db()
cur = db.execute('select title, text from entries order by id desc')
entries = cur.fetchall()
return render_template('show_entries.html', entries=entries)
@app.route('/add', methods=['POST'])
def add_entry():
if not session.get('logged_in'):
abort(401)
db = get_d... | sh('New entry was successfully posted')
return redirect(url_for('show_entries'))
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] != app.config['USERNAME']:
error = 'Invalid username'
elif request.f... |
NullHypothesis/active-probing-tools | source_port_analysis.py | Python | gpl-3.0 | 1,711 | 0.00526 | #!/usr/bin/env python
import sys
import time
import scapy.all as scapy
SEQ_MAX = 2**32 - 1
previous_packets = set()
def is_retransmission(packet):
packet_key = "%d%d%d" % (packet[scapy.TCP].sport,
packet[scapy.TCP].dport,
packet[scapy.TCP].seq)
i... | 0
for packet in scapy.PcapReader(pcap_file):
# Weed out SYN retransmissions.
if (not scapy.TCP in packet) or (not packet[scapy.TCP].flags == 2):
continue
if packet[scapy.IP].src == "211.155.86.135":
continue
print packet[scapy.IP].src
continue
... | d_port
#if diff < 0:
# diff = 65535 - abs(diff)
#print diff
#old_port = packet[scapy.TCP].sport
#for opt_name, opt_val in packet[scapy.TCP].options:
# if opt_name == "Timestamp":
#print packet.time, opt_val[0]
if packet[scapy.IP].src == "2... |
ShashkovS/plus_reader | setup.py | Python | mit | 3,445 | 0.000872 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Note: To use the 'upload' functionality of this file, you must:
# $ p | ip install twine
import io
import os
import sys
from shutil import rmtree
from setuptools import find_packages, setup, Command
# Package meta-data.
NAME = 'plus_reader'
DESCRIPTION = 'Recognition of tables with pluses or marks'
URL = 'https://github.com/ShashkovS/plus_reader'
EMAIL = 'sh57@yandex.ru'
AUTHOR = 'Serge... | ch too much :)
# ------------------------------------------------
# Except, perhaps the License and Trove Classifiers!
# If you do change the License, remember to change the Trove Classifier for that!
here = os.path.abspath(os.path.dirname(__file__))
# Import the README and use it as the long-description.
# Note: thi... |
pbarton666/buzz_bot | djangoproj/djangoapp/crawler/findDate.py | Python | mit | 12,201 | 0.016638 | '''Tools to guess a blog's posting date without knowing the blog site's layout, using BeautifulSoup.
FindDateInSoup::findDate_main(<BS object>, <ancestorDepth = integer> returns a datetime object or None
It begins from the BS object passed in and works its way up the parse tree until it finds a date or it ... | + '/' + LOG_NAME
logging.basicCon | fig(level=LOG_LEVEL,
format='%(module)s %(funcName)s %(lineno)d %(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
filename=log_filename,
filemode='w')
def buildTest... |
georgejlee/croptrends | browser/admin.py | Python | mit | 91 | 0.010989 | fro | m browser.models import Crop
from django.contrib import admin
admin.site | .register(Crop) |
ChristianKniep/QNIB | serverfiles/usr/local/lib/networkx-1.6/networkx/algorithms/bipartite/projection.py | Python | gpl-2.0 | 15,424 | 0.008169 | # -*- coding: utf-8 -*-
"""Create one-mode (unipartite) projections from bipartite graphs.
"""
import networkx as nx
# Copyright (C) 2011 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
__author__ = """Aric ... | > B.add_edges_from([('a', 1), ('b', 1), ('a', 2), ('b', 2)])
>>> G = bipartite.projected_graph(B, ['a', 'b'], multigraph=True)
>>> print(G.edges(keys=True))
[('a', 'b', 1), ('a', 'b', 2)]
Notes
------
No attempt is made to verify that the input grap | h B is bipartite.
Returns a simple graph that is the projection of the bipartite graph B
onto the set of nodes given in list nodes. If multigraph=True then
a multigraph is returned with an edge for every shared neighbor.
Directed graphs are allowed as input. The output will also then
be a directe... |
mandli/multilayer-examples | 1d/plot_shelf_contour.py | Python | mit | 3,904 | 0.024334 | #!/usr/bin/env python
import sys
import os
import numpy as np
import matplotlib.pyplot as plt
from clawpack.pyclaw.solution import Solution
import clawpack.visclaw.data as data
rho = [1025.0,1045.0]
eta_init = [0.0,-300.0]
def plot_contour(data_dir="./_output",out_dir='./',num_layers=2,num_frames=1000,ref_lines=[-1... | name__=="__main__":
if len(sys.argv) > 1:
plot_contour(sys.argv[1],ref_lines=[-130e3,-30e3],num_frames=300)
else:
ref_lines = ( [-30e3], [-130e3,-30e3] )
for (i,shelf_type) in enumerate(['jump_shelf','sloped_shelf']):
path = os.path.join(os.environ['DATA_PATH'],shelf_type,'ml... | path,ref_lines=ref_lines[i])
|
nidhididi/CloudBot | plugins/time_plugin.py | Python | gpl-3.0 | 1,073 | 0.00466 | import time
from cloudbot import hook
@hook.command(autohelp=False)
def beats(text):
"""bea | ts -- Gets the current time in .beats (Swatch Internet Time). """
if text.lower() == "wut":
return "Instead of hours and minutes, the mean solar day is divided " \
"up into 1000 parts called \".beats\". Each .beat lasts 1 minute and" \
" 26.4 seconds. Times are | notated as a 3-digit number out of 1000 af" \
"ter midnight. So, @248 would indicate a time 248 .beats after midni" \
"ght representing 248/1000 of a day, just over 5 hours and 57 minute" \
"s. There are no timezones."
elif text.lower() == "guide":
return "1 day ... |
nirmeshk/oh-mainline | mysite/missions/models.py | Python | agpl-3.0 | 1,422 | 0.000703 | # This file is part of OpenHatch.
# Copyright (C) 2010 John Stumpo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later versi... | ty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR P | URPOSE. 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/>.
from django.db import models
import mysite.search.models
class Step(models.Model):
name = mod... |
blstream/ut-arena | ut_arena_py_api/ut_arena/envs/test/settings.py | Python | apache-2.0 | 31 | 0.032258 | fr | om ut_arena.settings impo | rt * |
dselsam/lean-python-bindings | lean/lang/env.py | Python | apache-2.0 | 1,567 | 0 | import lean
import lang.expr as expr
# =========================================================
# Declaration Views
class DeclView(lean.declaration):
def __init__(self, decl):
self.decl = decl
def destruct(self):
# type: DeclView -> (lean.name, ?, ?, lean.expr, lean.expr)
return (s... | t_of_decls(self, decls):
# type: [lean.declaration] -> dict<lean.name, lean.expr>
d_thm = {}
for decl in decls:
if decl.is_theorem():
n, up, nup, t, v = DeclV | iew(decl).destruct()
d_thm[n] = v
return d_thm
|
openaps/dexcom_reader | dexcom_reader/packetwriter.py | Python | mit | 1,120 | 0 | import struct
from . import crc16
class PacketWriter:
MAX_PAYLOAD = 1584
MIN_LEN = 6
MAX_LEN = 1590
SOF = 0x01
OFFSET_SOF = 0
OFFSET_LENGTH = 1
OFFSET_CMD = 3
OFFSET_PAYLOAD = 4
def __init__(self):
self._packet = None
def Clear(self):
self._packet = None
... | 6.crc16(ps, 0, len(ps))
for | x in struct.pack("H", crc):
self._packet.append(x)
def SetLength(self):
self._packet[1] = chr(len(self._packet) + 2)
def _Add(self, x):
try:
len(x)
for y in x:
self._Add(y)
except: # noqa: E722
self._packet.append(x)
... |
OpenGenus/cosmos | code/filters/src/median_filter/median_filter.py | Python | gpl-3.0 | 1,398 | 0.003577 | ##Author - Sagar Vakkala (@codezoned)
import numpy
from PIL import Image
def median_filter(data, filter_size):
temp_arr = []
index = filter_size // 2
data_final = []
data_final = numpy.zeros((len(data), len(data[0])))
for i in range(len(data)):
# Iterate over the Image Array
for j... | the filter will be 3x3 size. Change 3 to 5 for a 5x5 filter
removed_noise = median_filter(arr, 3)
img = Image.fromarray(removed_n | oise)
img.show()
if __name__ == "__main__":
main()
|
Andrew-McNab-UK/DIRAC | WorkloadManagementSystem/PilotAgent/pilotTools.py | Python | gpl-3.0 | 18,034 | 0.032051 | ########################################################################
# $Id$
########################################################################
""" A set of common tools to be used in pilot commands
"""
import sys
import time
import os
import pickle
import getopt
import imp
import types
import urllib2
import... | , *impData )
if impData[0]:
impData[0].close()
except ImportError, excp:
if str( excp ).find( "No module named %s" % modName[0] ) == 0:
return None, None
errMsg = "Can't load %s in %s" % ( ".".join( modName ), parentModule.__path__[0] )
if not hideExceptions:
self.log... | one, None
if len( modName ) == 1:
return impModule, parentModule.__path__[0]
return self.__recurseImport( modName[1:], impModule,
hideExceptions = hideExceptions )
def loadObject( self, package, moduleName, command ):
""" Load an object from inside a module
"""... |
macobo/python-grader | grader/utils.py | Python | mit | 1,858 | 0.001615 | """ An utility module containing utility functions used by the grader module
and some useful pre-test hooks.
"""
import json
import traceback
def import_module(path, name=None):
if name is None:
name = path
import importlib.machinery
loader = importlib.machinery.SourceFileLoader(name, path)
... | try:
return hasattr(value, '__call__')
except:
return False
## Function descriptions
def beautifyDescription(description):
""" Converts docstring of a function to a test description
by removing excess whitespace and joining the answer on one
line """
| lines = (line.strip() for line in description.split('\n'))
return " ".join(filter(lambda x: x, lines))
def setDescription(function, description):
import grader
old_description = grader.get_test_name(function)
if old_description in grader.testcases:
grader.testcases.remove(old_description)
... |
beeverycreative/beeconnect | Loaders/PrinterInfoLoader.py | Python | gpl-2.0 | 5,218 | 0.012457 | #!/usr/bin/env python3
"""
* Copyright (c) 2015 BEEVC - Electronic Systems This file is part of BEESOFT
* 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... | .lblValFont = self.GetFont(lblValFontType,lblValFontSize)
lblValFColor = self.lblValJson['FontColor']
splitColor = lblValFColor.split(",")
self.lblValFontColor = pygame.Color(int(splitColor[0]),int(splitColor[1]),int(splitColor[2]))
"""
Load Labels Configuration
... | = []
self.lblXPos = []
self.lblYPos = []
self.lblFont = []
self.lblFontColor = []
for lbl in self.lblJson:
lblFontType = lbl['FontType']
lblFontSize = int(float(lbl['FontSize'])*self.displayHeight)
lblFColor = lbl['FontColor']
... |
willseward/cattle | tests/integration/cattletest/core/test_docker.py | Python | apache-2.0 | 31,065 | 0.000032 | import re
import uuid as py_uuid
from common_fixtures import * # NOQA
TEST_IMAGE = 'ibuildthecloud/helloworld'
TEST_IMAGE_LATEST = TEST_IMAGE + ':latest'
TEST_IMAGE_UUID = 'docker:' + TEST_IMAGE
if_docker = pytest.mark.skipif("os.environ.get('DOCKER_TEST') == 'false'",
reason='DOCKER_T... | time.time() - start
assert con | tainer.state == 'stopped'
assert delta < 10
@if_docker
def test_docker_purge(docke |
liverbirdkte/searchlight | searchlight/tests/utils.py | Python | apache-2.0 | 18,006 | 0 | # Copyright 2010-2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless... | ix.moves import BaseHTTPServer
import testtools
import webob
from searchlight.common import config
from s | earchlight.common import exception
from searchlight.common import property_utils
from searchlight.common import utils
from searchlight.common import wsgi
from searchlight import context
CONF = cfg.CONF
class BaseTestCase(testtools.TestCase):
def setUp(self):
super(BaseTestCase, self).setUp()
# ... |
rosatolen/CTFd | serve.py | Python | apache-2.0 | 117 | 0 | import sys
from CTFd import create_app
app = cr | eate_app()
app.run(debug=True, host="0.0.0.0", port=int(sys.arg | v[1]))
|
google/aiyprojects-raspbian | src/examples/vision/dish_classification.py | Python | apache-2.0 | 1,303 | 0.000767 | #!/usr/bin/env python3
# Copyright 2017 Google 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... | r implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Dish classification library demo."""
import argparse
from PIL import Image
from aiy.vision.inference import ImageInference
from aiy.vision.models import dish_classification
def main():
parser = ar... | ser.add_argument('--input', '-i', dest='input', required=True)
args = parser.parse_args()
with ImageInference(dish_classification.model()) as inference:
image = Image.open(args.input)
classes = dish_classification.get_classes(
inference.run(image), top_k=5, threshold=0.1)
fo... |
chispita/epiwork | apps/sander/views.py | Python | agpl-3.0 | 486 | 0.012346 | from urllib import urlencode
from urllib2 import urlopen
from django.shortcuts import render
from django.http import HttpResponse, Http404
from cms. | utils.html import clean_html
def index(request):
url = "http://results.influenzanet.info/results.php?" + urlencode(request.GET)
try:
content = urlopen(url, timeout=5).read()
except:
content = ""
#content = clean_html(content, full=False)
return render(request | , 'sander/sander.html' , locals())
|
avtomato/HackerRank | Python/_04_Sets/_04_Set .add()/solution.py | Python | mit | 53 | 0 | print(len({(inpu | t()) for _ | in range(int(input()))}))
|
JackieLan/djangocms-container | app/myapp/urls.py | Python | mit | 820 | 0.00122 | from __future__ import print_function
#from cms.sitemaps import CMSSitemap
from django.conf.urls import * # NOQA
from django.conf.urls.i18n import i18n_patterns
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from django.conf import settings
admin.autodiscover()
u... | uggest/', include('taggit_autosuggest.urls')),
)
# This is only needed when using runserver.
if settings.DEBUG:
urlpatterns = patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', # NO | QA
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
) + staticfiles_urlpatterns() + urlpatterns # NOQA
|
ltowarek/budget-supervisor | third_party/nordigen/test/test_token_api.py | Python | mit | 896 | 0 | # coding: utf-8
"""
Nordigen Account Information Services API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 2.0 (v2)
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ i... |
class TestTokenApi(unittest.TestCase):
"""TokenApi | unit test stubs"""
def setUp(self):
self.api = TokenApi() # noqa: E501
def tearDown(self):
pass
def test_j_wt_obtain(self):
"""Test case for j_wt_obtain
"""
pass
def test_j_wt_refresh(self):
"""Test case for j_wt_refresh
"""
pass
i... |
jpat82792/EloTab | logic.py | Python | gpl-3.0 | 6,308 | 0.005707 | from reportlab.pdfgen import canvas as pdf_container
from reportlab.lib.pagesizes import letter, A4
from reportlab.lib.units import inch
'''Contains methods to split lengthy sections so that they are able to fit within the pdf. After splitting the
sections, it appends the newly formed sections to the "to_pdf_hold... | section.section[0][start_index:end_index])
new_song_section.section.append(access_to_section.section[1][start_index:end_index])
new_song_section.section.append(access_to_section.section[2][start_index:end_index])
new_song_section.section.append(access_to_section.sectio... | d_index])
new_song_section.section.append(access_to_section.section[5][start_index:end_index])
start_index += 62
end_index += 58
else:
new_song_section.section.append("e|" + access_to_section.section[0][start_index:end_index])
... |
ayoubg/gem5-graphics | gem5/configs/ruby/MI_example.py | Python | bsd-3-clause | 8,604 | 0.009182 | # Copyright (c) 2006-2007 The Regents of The University of Michigan
# Copyright (c) 2009 Advanced Micro Devices, Inc.
# 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 source co... | uby_system.network.slave
l1_cntrl.responseFromCache = MessageBuffer(ordered = True)
l1_cn | trl.responseFromCache.master = ruby_system.network.slave
l1_cntrl.forwardToCache = MessageBuffer(ordered = True)
l1_cntrl.forwardToCache.slave = ruby_system.network.master
l1_cntrl.responseToCache = MessageBuffer(ordered = True)
l1_cntrl.responseToCache.slave = ruby_system.network.master... |
SpeedProg/eve-inc-waitlist | waitlist/blueprints/api/teamspeak.py | Python | mit | 473 | 0 |
from flask.blueprints import Blueprint
import logging
from flask_login impo | rt login_required, current_user
from waitlist.ts3.connection impo | rt send_poke
from flask import jsonify
bp = Blueprint('api_ts3', __name__)
logger = logging.getLogger(__name__)
@bp.route("/test_poke")
@login_required
def test_poke():
send_poke(current_user.get_eve_name(), "Test Poke")
resp = jsonify(status_code=201, message="Poke was send!")
resp.status_code = 201
... |
GGFHF/NGScloud | Package/cmenu.py | Python | gpl-3.0 | 58,331 | 0.00396 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
'''
This software has been developed by:
GI Genética, Fisiología e Historia Forestal
Dpto. Sistemas y Recursos Naturales
ETSI Montes, Forestal y del Medio Natural
Universida... | uration')
# print the menu options
print('Options:')
print()
print(' 1. Recreate NGScloud config file')
print(' 2. View NGScloud config file')
print()
print(' 3. List cluster templates')
print()
print(' 4. Update connection data and co... | e region and zone')
print()
print(' 6. Link volume in a cluster template')
print(' 7. Delink volume in a cluster template')
print(' 8. Review volumes linked to cluster templates')
print()
print(' X. Return to menu Cloud control')
print()
# get... |
zstackorg/zstack-woodpecker | integrationtest/vm/simulator/public_billing/test_check_vm_lifecycle_with_cpu_billing.py | Python | apache-2.0 | 3,329 | 0.029438 | '''
New Test For cpu bill Operations
1.test vm stop
2.test vm destory
3.test vm live migration
4.test vm clean
@author Antony WeiJiang
'''
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.operations.b... | total().total,cpuNum * bill_cpu.get_price()))
test_util.test_logger("stop vm instance")
vm.stop()
bill_cpu.compare(" | stop")
test_util.test_logger("destory vm instance")
vm.destroy()
bill_cpu.compare("destory")
test_util.test_logger("recover vm instance")
vm.recover()
vm.start()
bill_cpu.compare("recover")
test_util.test_logger("get host total and primarystorge type")
Host_uuid = test_stub.get_resource_from_vmm(res_ops.HOS... |
baojiwei/flasky | app/auth/views.py | Python | mit | 136 | 0 | from | flask import render_template
from . import auth
@auth.route('/login')
def login():
return render_template('auth/logi | n.html')
|
okfn/bibserver | test/test_web.py | Python | mit | 3,627 | 0.003033 | from nose.tools import assert_equal
import urllib
from base import *
from bibserver import web, ingest
import os
class TestWeb(object):
@classmethod
def setup_class(cls):
web.app.config['TESTING'] = True
cls.app = web.app.test_client()
# fixture data
recdict = fixtures['records... | ist to this method. Not sure how to fix this ...
def _test_upload_post_401(self):
bibtex_data = open('test/data/sample.bibtex').read()
res = self.app.post('/upload',
data=dict(
format='bibtex',
collection='My Test Collection',
data=bibtex_d | ata,
)
)
assert res.status == '401 UNAUTHORIZED', res.status
def test_query(self):
res = self.app.get('/query')
assert res.status == '200 OK', res.status
res = self.app.get('/query?q=title:non-existent')
assert res.status == '200 OK', res.status
... |
qll/autoCSP | testsuite/testcases/fixhtml.py | Python | mit | 1,054 | 0.003795 | #!/usr/bin/env python2
""" Quick helper to add HTML5 DOCTYPE and <title> to every testcase. """
impo | rt os
import re
import sys
def fixhtml(folder):
changed = 0
for dirpath, _, filenames in os.walk(folder):
for file in filenames:
name, ext = os.path.splitext(file)
if ext != '.html':
continue
path = '%s/%s' % (dirpath, file)
title = ' '.j... | itle>\n' % title
with open(path, 'r') as f:
content = f.read()
if content.startswith(shouldbe):
continue
changed += 1
content = re.sub('\s*<!DOCTYPE[^>]*>\s*<title>[^<]*</title>\s*', '',
content)
wit... |
WarrenWeckesser/scipy | scipy/constants/__init__.py | Python | bsd-3-clause | 12,116 | 0.001073 | r"""
==================================
Constants (:mod:`scipy.constants`)
==================================
.. currentmodule:: scipy.constants
Physical and mathematical constants and units.
Mathematical constants
======================
================ ===========================================================... | ----
================= ============================================================
``atm`` standard atmosphere in pascals
``atmosphere`` standard atmosphere in pascals
``bar`` | one bar in pascals
``torr`` one torr (mmHg) in pascals
``mmHg`` one torr (mmHg) in pascals
``psi`` one psi in pascals
================= ============================================================
Area
----
================= ======================================================... |
zstackio/zstack-woodpecker | integrationtest/vm/mini/multiclusters/paths/multi_path131.py | Python | apache-2.0 | 2,990 | 0.01806 | import zstackwoodpecker.test_state as ts_header
import os
TestAction = ts_header.TestAction
def path():
return dict(initial_formation="template5", checking_point=1, faild_point=100000, path_list=[
[TestAction.create_mini_vm, 'vm1', 'cluster=cluster2'],
[TestAction.create_volume, 'volume1', 'cluster=cluster2', ... | _vm, 'vm2'],
[TestAction.create_vm_backup, 'vm2', 'vm2-backup7'],
[TestAction.stop_vm, 'vm2'],
[TestAction.use_vm_backup, 'vm2-backup7'],
])
'''
The final status:
Running:['vm1', 'vm3', 'vm4']
Stopped:['vm2']
Enadbled:['volume1-backup1', 'volume4-backup4', 'volume2-back | up5', 'volume5-backup6', 'vm2-backup7', 'volume2-backup7', 'vm2-image2']
attached:['volume1', 'volume2', 'volume5']
Detached:['volume3']
Deleted:['vm1-backup2', 'volume1-backup2']
Expunged:['volume4', 'image1']
Ha:['vm1']
Group:
vm_backup1:['vm2-backup7', 'volume2-backup7']---vm2@volume2
''' |
qwhelan/asv | test/test_repo_template/setup.py | Python | bsd-3-clause | 434 | 0 | impo | rt os
from setuptools import setup
with open('asv_test_repo/build_time_env.py', 'w') as f:
f.write("env = {{}}\n".format(repr(dict(os.environ))))
setup(name='asv_test_repo',
version="{version}",
packages=['asv_test_repo'],
# The following forces setuptools to generate .egg-info directory,
... | ss
include_package_data=True,
)
|
catapult-project/catapult | third_party/gsutil/gslib/vendored/boto/boto/cloudhsm/__init__.py | Python | bsd-3-clause | 1,726 | 0 | # Copyright (c) 2015 Amazon.com, Inc. or its affiliates.
# All Rights Reserved
#
# 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... | bute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROV... | ARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN T... |
harpribot/deep-summarization | train_scripts/train_script_gru_simple_attn.py | Python | mit | 879 | 0.004551 | import os
import sys
sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..'))
from models import gru_simple
from helpers import checkpoint
# Get the review summary file
review_summary_file = 'extracted_data/review_summary.csv'
# Initialize Checkpointer to ensure checkpointing
checkpointer = checkpoint... | tention')
checkpointer.steps_per_checkpoint(1000)
checkpointer.steps_per_prediction(1000)
# Do using GRU cell - with attention mechanism
out_file = 'result/simple/gru/attention.csv'
checkpointer.set_result_location(out_file)
gru_net = gru_s | imple.GruSimple(review_summary_file, checkpointer, attention=True)
gru_net.set_parameters(train_batch_size=128, test_batch_size=128, memory_dim=128, learning_rate=0.05)
gru_net.begin_session()
gru_net.form_model_graph()
gru_net.fit()
gru_net.predict()
gru_net.store_test_predictions()
|
jiahaoliang/group-based-policy | gbpservice/nfp/service_vendor_agents/vyos/oc_config_server/vpn_api_server.py | Python | apache-2.0 | 17,163 | 0.000932 | #!/usr/bin/env python
import logging
import json
import netifaces
import netaddr
import socket
import fcntl
import struct
import array
import time
import ast
import copy
import subprocess
import os
from netaddr import IPNetwork, IPAddress
from operations import configOpts
from vyos_session import utils
from netifaces i... | -site peer %s authentication remote-id %s',
'set vpn ipsec site-to-site peer %s tunnel %d local prefix %s',
'set vpn ipsec site-to-site peer %s tunnel %d remote prefix %s',
'set vpn ipsec site-to-site peer %s authentication id %s'],
'delete': [
'delete vpn ipsec site-to-site pe | er %s',
'delete vpn ipsec site-to-site peer %s tunnel %s',
'delete vpn ipsec'],
'show': [
'show vpn ipsec sa peer %s']}
SSL_VPN_COMMANDS = {
'create': [
'set interfaces openvpn %s',
'set interfaces openvpn %s mode server',
'set interfaces openvpn %s server subnet... |
desecho/movies | src/moviesapp/tmdb.py | Python | mit | 5,407 | 0.00074 | from datetime import datetime
from operator import itemgetter
import tmdbsimple
from babel.dates import format_date
from django.conf import settings
from .exceptions import MovieNotInDb
from .models import get_poster_url
def get_tmdb(lang=None):
tmdbsimple.API_KEY = settings.TMDB_KEY
tmdbsimple.LANGUAGE = l... | filter_movies_only(person.cast)
else:
movies = filter_movies_only(person.crew)
movies = [m for m in movies if m["job"] == "Director"]
return movies
movies_data = get_data(query, search_type)
movies = []
i = 0
if movies_data:
user_movies_tmdb_... | tmdb_id = movie["id"]
i += 1
if i > settings.MAX_RESULTS:
break
if tmdb_id in user_movies_tmdb_ids:
continue
poster = get_poster_from_tmdb(movie["poster_path"])
# Skip unpopular movies if this option is enabled.
... |
geminy/aidear | oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_parser_unittest.py | Python | gpl-3.0 | 10,336 | 0.003289 | # Copyright (C) 2013 Adobe Systems Incorporated. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above
# copyright notice, this list of con... | OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
# LIABLE FOR ANY DIRECT, I | NDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
# OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLI... |
sinesiobittencourt/explainshell | explainshell/shlext.py | Python | gpl-3.0 | 8,869 | 0.001128 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2012-2013 Vinay M. Sajip. See LICENSE for licensing inform | ation.
#
# Enhancements in shlex to tokenize closer to the way real shells do
#
from collections import deque
import shlex
import sys
# We need to behave differently on 2,x and 3,x, because on 2.x
# shlex barfs on Unicode, and must be given str.
if sys.version_info[0] < 3:
PY3 = False
text_type = unicode
else... | e:
control = kwargs.pop('control')
if control is True:
control = '();<>|&'
# shlex on 2.x doesn't like being passed Unicode :-(
if not PY3 and isinstance(instream, text_type):
instream = instream.encode('utf-8')
shlex.shlex.__init__(self, instr... |
e-koch/spectral-cube | spectral_cube/tests/test_projection.py | Python | bsd-3-clause | 27,131 | 0.003317 | from __future__ import print_function, absolute_import, division
import warnings
import pytest
import numpy as np
from astropy import units as u
from astropy.wcs import WCS
from astropy.io import fits
from radio_beam import Beam, Beams
from .helpers import assert_allclose
from .test_spectral_cube import cube_and_ra... | y_1d, copy=False, beams=exp_beams)
assert (p.beams == exp_beams).all()
new_beams = Beams(np.arange(2, twelve_qty_1d.size + 2) * u.arcsec)
p = p.with_beams(new_beams)
assert np.all(p.beams == new_beams)
def test_VRODS_slice_with_beams():
exp_beams = Beams(np.arange(1, twelve_qty_1d.size + 1) * u... | wcs=WCS(naxis=1),
beams=exp_beams)
assert np.all(p[:5].beams == exp_beams[:5])
def test_VRODS_arith_with_beams():
exp_beams = Beams(np.arange(1, twelve_qty_1d.size + 1) * u.arcsec)
p = VaryingResolutionOneDSpectrum(twelve_qty_1d, c... |
The-Fonz/adventure-track | backend/transcode/transcoder.py | Python | mit | 8,880 | 0.004392 | import os
import re
import asyncio
import tempfile
import os.path as osp
import asyncio.subprocess
from concurrent.futures import ThreadPoolExecutor
from PIL import Image
from ..utils import getLogger
from .mediaconfig import *
logger = getLogger('transcode.transcoder')
class Transcoder:
"Nice object-oriented ... | def _transcode(self, src, dest, conf):
"""
Run this blocking function in ThreadPoolExecutor.
Not sure how and when the termination signal propagates to child threads.
"""
logger.debug("Running _transcode")
| im = Image.open(src)
newim = im.copy()
# Modifies in-place
newim.thumbnail(conf['wh'])
newim.save(dest, format='JPEG')
# TODO: Find src file timestamp
# TODO: Find dest file width/height
return {'timestamp': None, 'width': None, 'height': None}
async d... |
Storj/storjtorrent | storjtorrent/__init__.py | Python | mit | 1,271 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# The MIT License (MIT)
#
# Copyright (c) 2014 Josh Brandoff
#
# 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 wi... |
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY ... | MENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from storjtorrent import *
from session import... |
byronlin92/django_local_library | catalog/models.py | Python | apache-2.0 | 4,639 | 0.006682 | from django.db import models
from django.contrib.auth.models import User
from datetime import date
# Create your models here.
class Genre(models.Model):
"""
Model representing a b | ook genre (e.g. Science Fiction, Non Fiction).
" | ""
name = models.CharField(max_length=200, help_text="Enter a book genre (e.g. Science Fiction, French Poetry etc.)")
def __str__(self):
"""
String for representing the Model object (in Admin site etc.)
"""
return self.name
from django.urls import reverse #Used to generate URL... |
SmotritelTerve/python_training | test/test_modify_contact.py | Python | apache-2.0 | 2,179 | 0.000918 | # -*- coding: utf-8 -*-
from model.contact import Contact
from random import randrange
def test_modify_so | me_contact(app, db, check_ui):
| random_value = str(app.get_random_int())
if app.contact.count() == 0:
app.contact.add(Contact(first_name="First Contact"))
# old_contacts = app.contact.get_contact_list()
old_contacts = db.get_contact_list()
index = randrange(len(old_contacts))
contact = Contact(first_name="name" + random_... |
tigerking/pyvision | src/samples/TutFaceEyes.py | Python | bsd-3-clause | 3,860 | 0.010363 | # PyVision License
#
# Copyright (c) 2006-2010 David S. Bolme
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, thi... | l")
# Create a OpenCV cascade face detector object
cd = CascadeDetector()
# Create an eye detector object
el = FilterEyeLocator()
# Call the face detector like a function to get a list of face rectangles
rec | ts = cd(im)
# print the list of rectangles
print "Face Detection Output:",rects
# Also call the eye detector like a function with the original image and
# the list of face detections to locate the eyes.
eyes = el(im,rects)
# print the list of eyes. Format [ [ face_rect, left_eye,... |
godber/pds3label | pds3label/vendor/pds3_python/ODLv21Listener.py | Python | mit | 5,308 | 0.008478 | # Generated from java-escape by ANTLR 4.5
from antlr4 import *
# This class defines a complete listener for a parse tree produced by ODLv21Parser.
class ODLv21Listener(ParseTreeListener):
# Enter a parse tree produced by ODLv21Parser#label.
def enterLabel(self, ctx):
pass
# Exit a parse tree prod... | lf, ctx):
pass
# Exit a parse tree produced by ODLv21Parser#sequence_2D.
def exitSequence_2D(self, ctx):
pass
# Enter a parse tree produced by ODLv21Parser#set_value.
def enterSet_value(self, ctx):
pass
# Exit a parse tree produced by ODLv21Parser#set_value.
def exitS... | rser#ScalarInteger.
def enterScalarInteger(self, ctx):
pass
# Exit a parse tree produced by ODLv21Parser#ScalarInteger.
def exitScalarInteger(self, ctx):
pass
# Enter a parse tree produced by ODLv21Parser#ScalarBasedInteger.
def enterScalarBasedInteger(self, ctx):
pass
... |
GrognardsFromHell/TemplePlus | deploy_symbols_s3.py | Python | mit | 1,455 | 0.002749 |
import sys
import os.path
import lzma
import time
import os
import subprocess
if "APPVEYOR_REPO_TAG" not in os.environ or os.environ["APPVEYOR_REPO_TAG"] != "true":
print("Not u | ploading symbols since build is not tagged")
sys.exit()
symbol_filename = sys.argv[1]
with open(symbol_filename, "rt") as fh:
first_line = next(fh).strip()
tokens = first_line.split()
expected_tokens = ['MODULE', 'windows', 'x86']
if tokens[0:3] != expected | _tokens:
raise RuntimeError("Expected first tokens to be " + str(expected_tokens) + ", but was: " + str(tokens[0:3]))
file_hash = tokens[3]
file_name = tokens[4]
basename = os.path.basename(symbol_filename)
target_path = "%s/%s/%s.xz" % (file_name, file_hash, basename)
# Compress symbols with LZMA to save bandw... |
googleads/google-ads-python | google/ads/googleads/v9/services/services/custom_audience_service/transports/grpc.py | Python | apache-2.0 | 12,186 | 0.001067 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | t
else api_mtls_endpoint + ":443"
)
if credentials is None:
credentials, _ = google.auth.default(
scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
)
# Create SSL credentials with client_cert_source or app... | l_credentials(
certificate_chain=cert, private_key=key
)
else:
ssl_credentials = SslCredentials().ssl_credentials
# create a new channel. The provided one is ignored.
self._grpc_channel = type(self).create_channel(
... |
SujaySKumar/bedrock | bedrock/firefox/helpers.py | Python | mpl-2.0 | 8,166 | 0.000245 | from collections import OrderedDict
from django.core.cache import cache
from django.conf import settings
import jingo
import jinja2
from bedrock.firefox.models import FirefoxOSFeedLink
from bedrock.firefox.firefox_details import firefox_desktop, firefo | x_android
from bedrock.base.urlresolvers import reverse
from lib.l10n_utils import get_locale
def android_builds(channel, builds=None):
builds = builds or []
variations = OrderedDict([
('api-9', 'Gingerbread'),
('api-11', 'Honeycomb+ ARMv7+'),
('x86', 'x86'),
])
if c | hannel == 'alpha':
for type, arch_pretty in variations.iteritems():
link = firefox_android.get_download_url('alpha', type)
builds.append({'os': 'android',
'os_pretty': 'Android',
'os_arch_pretty': 'Android %s' % arch_pretty,
... |
minrk/sympy | sympy/functions/special/gamma_functions.py | Python | bsd-3-clause | 10,069 | 0.002086 | from sympy.core import Add, S, C, sympify, oo, pi
from sympy.core.function import Function, ArgumentIndexError
from zeta_functions import zeta
from sympy.functions.elementary.exponential import log
from sympy.functions.elementary.integers import floor
from sympy.functions.elementary.miscellaneous import sqrt
from sympy... |
return S.One - C.exp(-x)
| elif a.is_Integer:
b = a - 1
if b.is_positive:
return b*cls(b, x) - x**b * C.exp(-x)
class uppergamma(Function):
"""Upper incomplete gamma function"""
nargs = 2
def fdiff(self, argindex=2):
if argindex == 2:
a, z = self[0:2]
... |
cosmicAsymmetry/zulip | api/integrations/trac/zulip_trac.py | Python | apache-2.0 | 5,443 | 0.003308 | # -*- coding: utf-8 -*-
# Copyright © 2012 Zulip, Inc.
#
# 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, copy, modify, ... | ' % (key, markdown_block(old_values.get(key)),
markdown_block(ticket.values.get(key)))
elif old_values.get(key) == "":
field_changes.append('%s: => **%s**' % (key, ticket.values.get(key)))
elif ticket.values.get(key) =... | * => **%s**' % (key, old_values.get(key),
ticket.values.get(key)))
content += ", ".join(field_changes)
send_update(ticket, content)
def ticket_deleted(self, ticket):
# type: (Any) -> None
"""Called when a ticket is dele... |
minghu6/csdn | csdn/csdn_offline/csdn_offline_common.py | Python | bsd-3-clause | 313 | 0.00639 | # -*- coding:utf-8 -*-
#!/usr/bin/env python3
"""
"""
from collections import | namedtuple
from minghu6.internet.proxy_ip import proxy_ip
from minghu6.text.seq_enh import filter_invalid_char
URL_LIST_FILE_PATH = 'URList-{username:s}.txt'
UrlNameTuple = namedtuple('UrlNameTuple', ['url', | 'title']) |
chdecultot/erpnext | erpnext/accounts/report/profitability_analysis/profitability_analysis.py | Python | gpl-3.0 | 5,688 | 0.031997 | # Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import flt, getdate, formatdate, cstr
from erpnext.accounts.report.financial_statements import filter_accou... | it,
is_opening, (select root_type from `tabAccount` where name = account) as type
from `tabGL Entry` where company=%(company)s
{additional_conditions}
and posting_date <= %(to_date)s
and {based_on} is not null
order by {based_on}, posting_date""".format(additi | onal_conditions="\n".join(additional_conditions), based_on= based_on),
{
"company": company,
"from_date": from_date,
"to_date": to_date
},
as_dict=True)
for entry in gl_entries:
gl_entries_by_account.setdefault(entry.based_on, []).append(entry)
return gl_entries_by_account |
lucasrangit/twitter-winner | twitter-winner/oauthlib/oauth1/rfc5849/parameters.py | Python | mit | 4,909 | 0.000407 | # -*- coding: utf-8 -*-
"""
oauthlib.parameters
~~~~~~~~~~~~~~~~~~~
This module contains methods related to `section 3.5`_ of the OAuth 1.0a spec.
.. _`section 3.5`: http://tools.ietf.org/html/rfc5849#section-3.5
"""
from __future__ import absolute_import, unicode_literals
try:
from urlparse import urlparse, url... | -body MAY include other request-specific
# parameters, in which case, the protocol parameters SHOU | LD be appended
# following the request-specific parameters, properly separated by an "&"
# character (ASCII code 38)
merged.sort(key=lambda i: i[0].startswith('oauth_'))
return merged
def prepare_form_encoded_body(oauth_params, body):
"""Prepare the Form-Encoded Body.
Per `section 3.5.2`_ of ... |
portableant/open-context-py | opencontext_py/apps/ocitems/projects/metadata.py | Python | gpl-3.0 | 15,649 | 0.001342 | import json
import numpy as np
from numpy import vstack, array
from scipy.cluster.vq import kmeans,vq
from django.db import models
from django.db.models import Avg, Max, Min
from opencontext_py.libs.general import LastUpdatedOrderedDict
from opencontext_py.apps.ocitems.geospace.models import Geospace
from opencontext_p... | d = ent.dereference(par_id)
if(found):
p_item = LastUpdatedOrderedDict()
p_item['id'] = ent.uri
| p_item['slug'] = ent.slug
p_item['label'] = ent.label
if(ent.data_type is not False):
p_item['type'] = ent.data_type
else:
p_item['type'] = '@id'
output.append(p_item)
retu... |
yuanming-hu/taichi | python/taichi/__main__.py | Python | mit | 32 | 0 | from | ._main | import main
main()
|
luosch/leetcode | python/Add Binary.py | Python | mit | 964 | 0.004149 | class Solution(object):
def addBinary(self, a, b):
len_a = len(a)
len_b = len(b)
length = max(len_a, len_b)
c = [0] * (length + 1)
if len_a < len_b:
a, b = b, a
len_a, len_b = len_b, len_a
for i in range(0, length):
if len_a - 1 - ... | m_b)
c[i + 1] += c[i] / 2
c[i] %= 2
elif len_a - 1 - i >= 0 and len_b - 1 - i < 0 | :
num_a = int(a[len_a - 1 - i])
c[i] += num_a
c[i + 1] += c[i] / 2
c[i] %= 2
else:
break
while len(c) > 1 and c[-1] == 0:
c.pop()
answer =
while c:
answer += str... |
joakim-hove/ert | ert_gui/ert_splash.py | Python | gpl-3.0 | 2,664 | 0 | import sys
from qtpy.QtCore import Qt
from qtpy.QtWidgets import QSplashScreen, QApplication
from qtpy.QtGui import QColor, QPen, QFont
from ert_gui.ertwidgets import resourceImage
class ErtSplash(QSplashScreen):
def __init__(self, version_string="Version string"):
QSplashScreen.__init__(self)
... | top_offset += text_size + 4 * margin
text_size = 20
font. | setPixelSize(text_size)
painter.setFont(font)
painter.drawText(
text_x,
top_offset,
text_area_width,
text_size,
int(Qt.AlignHCenter | Qt.AlignCenter),
self.version,
)
|
cbettemb/askomics | askomics/libaskomics/TripleStoreExplorer.py | Python | agpl-3.0 | 7,283 | 0.009886 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
import logging
from askomics.libaskomics.ParamManager import ParamManager
from askomics.libaskomics.rdfdb.SparqlQueryBuilder import SparqlQueryBuilder
from askomics.libaskomics.rdfdb.QueryLauncher import QueryLauncher
class TripleStoreExplorer(ParamManager):
"""
... | lQueryBuilder(self.settings, self.session)
ql = QueryLauncher(self.settings, self.session)
sparql_template = self.get_template_sparql(self.ASKOMICS_initial_query)
query = sqb.load_from_file(sparql_template, {}).query
results = ql.process_query(query)
for result in results:
... | nodes.append({ 'uri': uri, 'label': label })
return nodes
def getUserAbstraction(self):
"""
Get the user abstraction (relation and entity as subject and object)
:return:
:rtype:
"""
data = {}
listEntities = {}
self.log.debug(" =========== T... |
pdawson1983/Python-F5-AFM-App | F5AFMApp.py | Python | mit | 2,130 | 0.022535 | import os
from flask import Flask, url_for, send_from_directory, flash, get_flashed_messages, session, request, render_template, redirect
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from configure_database import Base, F5Device, AFMStat, StatValue
engine = create_engine('sqlite:///F5AF... | ef newDevice():
if request.method == 'POST':
post = request.get_json()
device = F5Device(hostName = post.get('hostName'), ipAddress = post.get('ipAddress'), details = post.get('details'), apiUserName = post.get('a | piUserName'), apiPassword = post.get('apiPassword'))
session.add(device)
session.commit()
flash("Added New Device - %s" %device.hostName)
return redirect(url_for('deviceList'))
else:
return render_template('newdevice.html')
@app.route('/device/<int:device_id>')
def device(device_id):
device = session.qu... |
xmikos/hangupsbot | hangupsbot/handlers/forwarding.py | Python | gpl-3.0 | 1,493 | 0.00134 | import hangups
from hangupsbot.utils import text_to_segments
from hangupsbot.handlers import handler
@handler.register(priority=7, event=hangups.ChatMessageEvent)
def handle_forward(bot, event):
"""Handle message forwarding"""
# Test if message is not empty
if not event.text:
return
# Test i... | ny forwarding destinations
forward_to_list = bot.get_config_suboption(event.conv_id, 'forward_to')
if not forward_to_list:
return
# Prepare attachments
image_id_list = yield from bot.upload_images(event.conv_event.attachments)
# Forward message to all destinations
for dst in forward_to... | conv = bot._conv_list.get(dst)
except KeyError:
continue
# Prepend forwarded message with name of sender
link = 'https://plus.google.com/u/0/{}/about'.format(event.user_id.chat_id)
segments = text_to_segments('**[{}]({}):** '.format(event.user.full_name, link))
# C... |
root-mirror/root | interpreter/llvm/src/tools/clang/docs/conf.py | Python | lgpl-2.1 | 9,185 | 0.006641 | # -*- coding: utf-8 -*-
#
# Clang documentation build configuration file, created by
# sphinx-quickstart on Sun Dec 9 20:01:55 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All c... | or, documentclass [howto/manual]).
latex_documents = [
('index', 'Clang.tex', u'Clang Documentation',
u'The Clang Team', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" | documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#... |
MaxRobinson/CS449 | project7/extra.py | Python | apache-2.0 | 494,316 | 0.000004 | """ Created by Max 12/10/2017 """
from ValueIteration import ValueIteration
from Game import Game
x = {(0, 32, -5, -5): None,
(0, 32, -5, -4): None,
(0, 32, -5, -3): None,
(0, 32, -5, -2): None,
(0, 32, -5, -1): None,
(0, 32, -5, 0): None,
(0, 32, -5, 1): None,
(0, 32, -5, 2): None,
(0, 32, -5, 3): None,
(0,... | -1, -5): None,
(0, 34, -1, -4): None,
(0, 34, -1, -3): None,
(0, 34, -1, -2): None,
(0, 34, -1, -1): None,
(0, 34, -1, 0): None,
(0, 34, -1, 1): None,
(0, 34, -1, 2): None,
(0, 34, -1, 3): None,
(0, 34, -1, 4): None,
(0, 34, -1, 5): None,
(0, 34, 0, -5): None,
(0, 34, 0, -4): None,
(0, 34, 0, -3): None,
(... | e,
(0, 34, 0, 4): None,
(0, 34, 0, 5): None,
(0, 34, 1, -5): None,
(0, 34, 1, -4): None,
(0, 34, 1, -3): None,
(0, 34, 1, -2): None,
(0, 34, 1, -1): None,
(0, 34, 1, 0): None,
(0, 34, 1, 1): None,
(0, 34, 1, 2): None,
(0, 34, 1, 3): None,
(0, 34, 1, 4): None,
(0, 34, 1, 5): None,
(0, 34, 2, -5): None,
(0... |
testerofpens/parameterpatrol | linkConsumer.py | Python | gpl-3.0 | 1,022 | 0.018591 | ######################################################################################
# class: LinkConsumer
# purpose: consumes items in the outQueue and sends to parameterFetcher for processing
#################### | ##################################################################
import logging
import Queue
import threading
import parameterFetcher
import results
class LinkConsumer(threading.Thread):
def __init__(self, outQueue, projectDirectory, results):
threading.Thread.__init__(self)
self.outQueue = outQueue
... | = self.outQueue.get()
self.logger.debug('Consumer: getting parameters for ' + page)
paramFetcher = parameterFetcher.ParameterFetcher(page, self.projectDirectory)
paramFetcher.saveParameters(self.results) #parse parameters
self.outQueue.task_done()
|
soshial/text-normalization | numword/numword_en_gb.py | Python | lgpl-3.0 | 1,631 | 0.011649 | # coding: utf-8
#This file is part of numword. The COPYRIGHT file at the top level of
#th | is repository contains the full copyright notices and license terms.
'''
numword for EN_GB
'''
from numword_en import NumWordEN
class NumWordENGB(NumWordEN):
'''
NumWord EN_GB
'''
de | f currency(self, val, longval=True):
'''
Convert to currency
'''
return self._split(val, hightxt=u"pound/s", lowtxt=u"pence",
jointxt=u"and", longval=longval)
_NW = NumWordENGB()
def cardinal(value):
'''
Convert to cardinal
'''
return _NW... |
openstack/taskflow | releasenotes/source/conf.py | Python | apache-2.0 | 9,270 | 0 | # -*- coding: utf-8 -*-
# Copyright (C) 2020 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | dual page | s for each letter.
# html_split_index = False
# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is Tru... |
sgmap/openfisca-core | openfisca_core/reforms.py | Python | agpl-3.0 | 13,388 | 0.00478 | # -*- coding: utf-8 -*-
import collections
import copy
from . import formulas, legislations, periods, taxbenefitsystems, columns
class AbstractReform(taxbenefitsystems.AbstractTaxBenefitSystem):
"""A reform is a variant of a TaxBenefitSystem, that refers to the real TaxBenefitSystem as its reference."""
CU... | = None):
"""Return a Reform class inherited from AbstractReform."""
assert isinstance(key, basestring)
assert isinstance(name, basestring)
assert isinstance(reference, taxbenefitsystems.AbstractTaxBenefitSystem)
reform_entity_class_by_key_plural = {
key_plural: clone_entity_class(entity_cla... | ):
_constructed = False
DECOMP_DIR = decomposition_dir_name
DEFAULT_DECOMP_FILE = decomposition_file_name
entity_class_by_key_plural = reform_entity_class_by_key_plural
def __init__(self):
super(Reform, self).__init__()
# TODO Remove this mechanism.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.