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 |
|---|---|---|---|---|---|---|---|---|
jabesq/home-assistant | tests/components/cloud/__init__.py | Python | apache-2.0 | 935 | 0 | """Tests for the cloud component."""
from unittest.mock import patch
from homeassistant.setup import async_setup_component
from homeassistant.components import cloud
from homeassistant.components.cloud import const
from tests.common import mock_coro
async def mock_cloud(hass, config=None):
"""Mock cloud."""
... | )):
awa | it cloud_inst.start()
def mock_cloud_prefs(hass, prefs={}):
"""Fixture for cloud component."""
prefs_to_set = {
const.PREF_ENABLE_ALEXA: True,
const.PREF_ENABLE_GOOGLE: True,
const.PREF_GOOGLE_SECURE_DEVICES_PIN: None,
}
prefs_to_set.update(prefs)
hass.data[cloud.DOMAIN].cl... |
henrik645/txt-rpg | merchant.py | Python | mit | 1,919 | 0.005732 | from item import Item
class Merchant:
def __init__(self, markup=1.2, markdown=0.8):
self.inventory = []
self.markup = markup
self.markdown = markdown
def add_item(self, item):
# Adds an item to the merchant's inventory
if (not isinstance(item, Item)):
... | else:
player.bank[item] = 1
return True
def remove_item(self, player, item):
if (not isinstance(item, Item)):
raise TypeError("Unexpected " + type(item))
if item in player.bank:
if player.bank[item] == 1:
player.ba... | |
sbesson/zeroc-ice | py/test/Ice/faultTolerance/run.py | Python | gpl-2.0 | 1,423 | 0.005622 | #!/usr/bin/env python
# **********************************************************************
#
# Copyright (c) 2003-2013 ZeroC, Inc. All rights reserved.
#
# This copy of Ice is licensed to you under the terms described in the
# ICE_LICENSE file included in this distribution.
#
# *************************************... | ./../..", "../../../.." ]
head = os.path.dirname(sys.argv[0])
if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
raise RuntimeError("can't find toplevel directory!")
sys.path.ap... | verProc = []
for i in range(0, num):
sys.stdout.write("starting server #%d... " % (i + 1))
sys.stdout.flush()
serverProc.append(TestUtil.startServer(server, "%d" % (base + i)))
print("ok")
ports = ""
for i in range(0, num):
ports = "%s %d" % (ports, base + i)
sys.stdout.write("starting client... ")... |
rosix-ru/django-reportapi | docs/conf.py | Python | agpl-3.0 | 10,878 | 0.000368 | # -*- coding: utf-8 -*-
#
# ReportAPI documentation build configuration file, created by
# sphinx-quickstart on Wed Mar 18 12:56:04 2015.
#
# 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.
#
#... | r title for the navigation ba | r. Default is the same as html_title.
html_short_title = '%s v%s' % (project, version)
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows... |
Kaniabi/l5r-character-manager-3 | l5r/dialogs/newrankdlg.py | Python | gpl-3.0 | 3,023 | 0.000662 | # -*- coding: utf-8 -*-
# Copyright (C) 2014 Daniele Simonetti
#
# 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.
#
# Thi... | PC is following an alternate path
if is_path:
# the PC want to go back to the old school.
# find the first school that is not a path
api.character.rankadv.leave_path()
else:
api.character.rankadv.advance_rank()
self.accept()
def test():
imp... | sys.exit(app.exec_())
if __name__ == '__main__':
test()
|
leethargo/geonet | tests/test_optimization.py | Python | mit | 995 | 0.01005 | import pytest
from geonet.network import SteinerTree
from geonet.optimization import Instance, Solution, enum_fsts
def test_enum_fst():
'''Call and | check the structure of result (but not content).'''
term_pos = {'a':(0,0), 'b':(10,0), 'c':(0,10)}
demand = {'a':-30, 'b':20, 'c':10}
diams = [0. | 4, 0.6, 0.8, 1., 1.2]
costs = [680., 910., 1200., 1550., 1960.]
pres = [40, 80]
C = 1.0
inst = Instance(term_pos, demand, diams, costs, pres[0], pres[1], C)
sols = enum_fsts(inst)
assert len(sols) == 1, 'there is just 1 topology on 3 terminals'
sol = sols[0]
assert isinstance(sol.tree,... |
rogerfan/simpleml | simpleml/neural/__init__.py | Python | mpl-2.0 | 134 | 0 | from .perceptron import MultilayerPerceptron
from .autoencoder import AutoEncoder
__all__ = ('Mult | ilayerPerceptron', 'AutoEnc | oder',)
|
techfutureslab/laughing-octo-system | main.py | Python | gpl-3.0 | 2,246 | 0.009795 | from pickletools import uint8
import socket
import cv2 as c
import numpy as np
IP = "192.168.102.47"
UDP_port = 5000
# Changes here
cam = c.VideoCapture(0);
rBlock = 4
cBlock = 3
ret, frame = cam.read()
h, w = frame.shape[:2]
wBlock = w // cBlock
hBlock = h // rBlock
b = 5;
P1 = [h // 2 - b, w // 2 - b]
P2 = [h ... | ), (0, 165, 255), 1)
c.imshow("Frames", frame)
c.destroyAllWindows()
cam.release()
print(Q)
pr | int(T)
sock.sendto(T, (IP, UDP_port))
|
befelix/GPy | GPy/testing/meanfunc_tests.py | Python | bsd-3-clause | 3,340 | 0.016766 | # Copyright (c) 2015, James Hensman
# Licensed under the BSD 3-clause license (see LICENSE.txt)
import unittest
import numpy as np
import GPy
class MFtests(unittest.TestCase):
def test_simple_mean_function(self):
"""
The simplest possible mean function. No parameters, just a simple Sinusoid.
... | ikelihood=lik, mean_function=mf)
self.assertTrue(m.checkgrad())
def test_parametric_mean_function_composition(self):
"""
| A linear mean function with parameters that we'll learn alongside the kernel
"""
X = np.linspace(0,10,50).reshape(-1,1)
Y = np.sin(X) + 0.5*np.cos(3*X) + 0.1*np.random.randn(*X.shape) + 3*X
mf = GPy.mappings.Compound(GPy.mappings.Linear(1,1),
... |
QuLogic/tephi | docs/tephi/source/sphinxext/generate_package_rst.py | Python | lgpl-3.0 | 7,363 | 0.010186 | # (C) British Crown Copyright 2010 - 2012, Met Office
#
# This file is part of Iris.
#
# Iris is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any l... | document_these = r.__all__
document_these = [[obj, r.__getattribute__(obj)] for obj in document_these]
else:
document_these = [[obj, r.__getattribute__(obj)] for obj in elems | if not obj.startswith('_') and not inspect.ismodule(r.__getattribute__(obj))]
is_from_this_module = lambda x, this_module=r.__name__: hasattr(x[1], '__module__') and x[1].__module__ == r.__name__
document_these = filter(is_from_this_module, document_these)
sort_order = {'class': 2, 'functi... |
benjamin-hodgson/poll | test/circuit_breaker_tests.py | Python | mit | 8,673 | 0.000577 | import contexts
from unittest import mock
from poll import circuitbreaker, CircuitBrokenError
class WhenAFunctionWithCircuitBreakerDoesNotThrow:
def given_a_call_counter(self):
self | .x = 0
self.expected_args = (1, 4, "hello")
self.expected_kwargs = {"blah": "bloh", "bleh": 5}
self.expected_return_value = "some thing that was returned"
def when_i_call_the_circuit_breaker_function(self):
self.result = self.function_to_break(*self.expected_args, **self.expected_kw... | rward_the_keyword_arguments(self):
assert self.kwargs == self.expected_kwargs
def it_should_call_it_once(self):
assert self.x == 1
def it_should_return_the_result_of_the_function(self):
assert self.result is self.expected_return_value
@circuitbreaker(ValueError, threshold=3, reset... |
mic-e/eventdigest | eventdigest/feed.py | Python | gpl-3.0 | 940 | 0.002128 | from .event import Event, EventSource
from .util import shorten
import feedparser
import traceback
def query_feed(name, url, formatstring='{shortlink} {title}', limit=None):
yield EventSource(name)
feed = feedparser.parse(url)
if feed['stat | us'] != 200:
raise Exception('status != 200')
entries = feed['entries']
if limit:
| entries = entries[:limit]
for entry in entries:
title = entry['title']
if len(title) > 120:
title = title[:120] + '...'
try:
link = entry['feedburner_origlink']
except:
link = entry['link']
try:
uid = entry['id']
e... |
googleads/google-ads-python | google/ads/googleads/v9/services/services/feed_item_set_link_service/__init__.py | Python | apache-2.0 | 694 | 0 | # -*- 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.or | g/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitation... | etLinkServiceClient",)
|
CompileInc/stormtrooper | stormtrooper/stormtrooper/wsgi.py | Python | mit | 401 | 0 | """
WSGI confi | g for stormtrooper project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODUL... | ation = get_wsgi_application()
|
txemagon/1984 | modules/Telegram-bot-python/setup.py | Python | gpl-3.0 | 2,168 | 0.000461 | #!/usr/bin/env python
"""The setup and build script for the python-telegram-bot library."""
import codecs
import os
from setuptools import setup, find_packages
def requirements():
"""Build the requirements list for this project"""
requirements_list = []
with open('requirements.txt') as requirements:
... | :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Lesser General Public License v3 ( | LGPLv3)',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Communications :: Chat',
'Topic :: Internet',
'Programming Language :: Python',
'Programming Language :: Python ::... |
lucianp/dotfiles | link/.vim/ftplugin/orgmode/plugins/Todo.py | Python | mit | 12,249 | 0.02343 | # -*- coding: utf-8 -*-
import vim
import itertools as it
from orgmode._vim import echom, ORGMODE, apply_count, repeat, realign_tags
from orgmode import settings
from orgmode.liborgmode.base import Direction
from orgmode.menu import Submenu, ActionEntry
from orgmode.keybinding import Keybinding, Plug
from orgmode.exc... | -1 not 2
next_dir = -1 if direction == Direction.BACKWARD else 1
# work only with top level index
if next_set:
top_set = next((
todo_set[0] for todo_set in enumerate(cleaned_todos)
if current_state in todo_set[1]), -1)
ind = (top_set + next_dir) % len(cleaned_todos)
if ind != len(cleaned_todos) ... | o next set, cycle around everything
else:
ind = next((
todo_iter[0] for todo_iter in enumerate(flattened_todos)
if todo_iter[1] == current_state), -1)
return flattened_todos[(ind + next_dir) % len(flattened_todos)]
@classmethod
@realign_tags
@repeat
@apply_count
def toggle_todo_state(
cls, direc... |
chengduoZH/Paddle | python/paddle/fluid/tests/unittests/mkldnn/test_concat_mkldnn_op.py | Python | apache-2.0 | 1,692 | 0.000591 | # Copyright (c) 2018 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 app... | pass
def init_kernel_type(self):
self.use_mkldnn = True
class TestMKLDNNConcatOp2(TestConcatOp2):
def setUp(self):
super(TestMKLDNNConcatOp2, self).setUp()
self.attrs["use_mkldnn"] = True
self._cpu_only = True
def test_check_grad(self):
pass
def init_kernel... | se_mkldnn = True
class TestMKLDNNConcatOp3(TestConcatOp3):
def setUp(self):
super(TestMKLDNNConcatOp3, self).setUp()
self.attrs["use_mkldnn"] = True
self._cpu_only = True
def test_check_grad(self):
pass
def init_kernel_type(self):
self.use_mkldnn = True
if __nam... |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_11_01/operations/_ip_groups_operations.py | Python | mit | 27,449 | 0.004809 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | error = self._deserialize.failsafe_deserialize(_models.Error, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('IpGroup', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, ... | criptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ipGroups/{ipGroupsName}'} # type: ignore
def _create_or_update_initial(
self,
resource_group_name, # type: str
ip_groups_name, # type: str
parameters, # type: "_models.IpGroup"
**kwargs # type: A... |
cloudbase/coriolis | coriolis/policies/replica_tasks_executions.py | Python | agpl-3.0 | 2,399 | 0 | # Copyright 2018 Cloudbase Solutions Srl
# All Rights Reserved.
from oslo_policy import policy
from coriolis.policies import base
REPLICA_EXECUTIONS_POLICY_PREFIX = "%s:replica_executions" % (
base.CORIOLIS_POLICIES_PREFIX)
REPLICA_EXECUTIONS_POLICY_DEFAULT_RULE = "rule:admin_or_owner"
def get_replica_executi... | ions_policy_label('cancel'),
REPLICA_EXECUTIONS_POLICY_DEFAULT_RULE,
"Cancel a Replica execution",
[
{
"path": (
"/replicas/{re | plica_id}/executions/"
"{execution_id}/actions"),
"method": "POST"
}
]
),
policy.DocumentedRuleDefault(
get_replica_executions_policy_label('delete'),
REPLICA_EXECUTIONS_POLICY_DEFAULT_RULE,
"Delete an execution for a given Replica"... |
rehassachdeva/pydsa | pydsa/merge_sort.py | Python | bsd-3-clause | 683 | 0.002928 | # Merge Sort
# Complexity: O(nlog(n))
def _merge(L, R):
m, i, j = [], 0, 0
while i < len(L) and j < l | en(R):
if L[i] <= R[j]:
m.append(L[i])
i += 1
else:
m.append(R[j])
j += 1
if i == len(L):
| m.extend(R[j:])
else:
m.extend(L[i:])
return m
def merge_sort(a):
"""
Sorts the list 'a' using Merge sort algorithm
>>> from pydsa import merge_sort
>>> a = [3, 4, 2, 1, 12, 9]
>>> merge_sort(a)
[1, 2, 3, 4, 9, 12]
"""
l = len(a)
if l >= 2:
L = a[0:l /... |
rrooij/youtube-dl | youtube_dl/utils.py | Python | unlicense | 126,259 | 0.000832 | #!/usr/bin/env python
# coding: utf-8
from __future__ import unicode_literals
import base64
import binascii
import calendar
import codecs
import contextlib
import ctypes
import datetime
import email.utils
import email.header
import errno
import functools
import gzip
import io
import itertools
import json
import local... | fail if the filename contains non ascii characters unless we
# use a unicode object
path_basename = lambda f: os.path.basename(fn).decode(encoding)
# the same for os.path.dirname
path_dirname = lambda f: os.path.dirname(fn).decode(encoding)
else:
p | ath_basename = os.path.basename
path_dirname = os.path.dirname
args = {
'suffix': '.tmp',
'prefix': path_basename(fn) + '.',
'dir': path_dirname(fn),
'delete': False,
}
# In Python 2.x, json.dump expects a bytestream.
# In Python 3.x, it writes to a character st... |
MacHu-GWU/constant-project | constant/test/dev/food_example.py | Python | mit | 2,617 | 0.002293 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This code is the correct implementation about constant.
"""
from const.base import Base
class Apple(Base):
__attrs__ = ["id", "name"]
def __init__(self, id=None, name=None):
self.id = id
self.name = name
class Banana(Base):
__attrs__ =... | f __init__(self, id=None, name=None):
self.id = id
self.name = name
# Apple
apple_name__ | __red_apple = Apple(id=1, name="red apple")
apple_name____green_apple = Apple(id=2, name="green apple")
class AppleCol(Fruit):
_collection = list()
_collection.append(apple_name____red_apple)
name____red_apple = apple_name____red_apple
_collection.append(apple_name____green_apple)
name____green_... |
sio2project/oioioi | oioioi/dashboard/menu.py | Python | gpl-3.0 | 286 | 0.003497 | from django.utils.translation import ugettext_lazy as _
from o | ioioi | .base.menu import MenuRegistry
from oioioi.base.permissions import not_anonymous
from oioioi.contests.utils import contest_exists
top_links_registry = MenuRegistry(_("Top Links Menu"), contest_exists & not_anonymous)
|
pixelated/pixelated-user-agent | service/pixelated/adapter/services/draft_service.py | Python | agpl-3.0 | 1,456 | 0 | #
# Copyright (c) 2014 ThoughtWorks, Inc.
#
# Pixelated is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Soft | ware Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pixe | lated 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# a... |
NJ-zero/Android | Request/Test_pd/TestCase_Web_Baspd.py | Python | mit | 1,855 | 0.010447 | #coding=utf-8
#author='Shichao-Dong'
import unittest
import Web_Method_Baspd
import Public_Base_Method
import requests
import time
import HTMLTestRunner
class ST_Bas_pd(unittest.TestCase):
u'商品功能性测试'
def setUp(self):
global cookie
r = Public_Base_Method.login_func("172.31.3.73:6020", "dongshi... | LTestRunner(stream=fp,title='test result',description=u'测试情况:')
#
# #执行测试
# runner.run | (suite)
# fp.close() |
keii11/TIL | effective_python/yields.py | Python | mit | 1,215 | 0.005889 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""yield式とgeneratorについてのまとめ
参考: https://qiita.com/tomotaka_ito/items/35f3eb108f587022fa09
- next()の使い方がいまいち把握しきれてない
- 一番重要なポイントは,generator関数はイテレータオブジェクトを作成するということ
"""
def generator_brief_check():
"""ジェネレータ関数の作成"""
yield 0
yield 1
yield 2
def brief_check_trial... | my_iter = generator_brief_check()
# この場合はStopIterationが発生した時点で処理が止まる.
# ジェネレータ式でイテレータオブジェクトを作成したら,オブジェクトからループで値を取り出す.
for i in range(3):
print("Trial is {}, Value is {}".format(i | , next(my_iter)))
return None
if __name__ == "__main__":
#brief_check_trial()
check_next()
|
pylint-bot/astroid-unofficial | astroid/util.py | Python | gpl-2.0 | 3,781 | 0.000793 | # copyright 2003-2015 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This file is par | t of astroid.
#
# astroid 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 Sof | tware Foundation, either version 2.1 of the License, or (at your
# option) any later version.
#
# astroid is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
... |
Dangetsu/vnr | Frameworks/Sakura/py/apps/reader/qml/kagami.py | Python | gpl-3.0 | 21,000 | 0.018238 | # coding: utf8
# kagami.py
# 10/10/2012 jichi
#
# Gospel, Gossip, Grimoire, Omajinai, and Mirage
#import textwrap
from functools import partial
from PySide.QtCore import Signal, Slot, Property, QObject, QTimer
from PySide.QtGui import QFont, QFontMetrics
from sakurakit import skdatetime
from sakurakit.skclass import c... | {}
features = d.features if colorize else None
return ''.join(
mecabman.rendertable(t, features=features, rubyType=rubyType, rubyKana=rubyKana, charPerLine=charPerLine, rubySize=rubySize, rubyInverted=rubyInverted, colorize=colorize, highlight=highlight, annotated=annotated, center=center)
for t... | oat, bool, bool, bool, bool, bool, result=unicode)
def renderKoreanRuby(self, text, charPerLine, rubySize, invertRuby, colorize, center,
romajaRubyEnabled, hanjaRubyEnabled):
"""
@return unicode html
"""
import uniroman
text = textutil.remove_html_tags(text).strip()
return uniroman.ren... |
arthurdejong/python-pskc | pskc/mac.py | Python | lgpl-2.1 | 4,522 | 0 | # mac.py - module for checking value signatures
# coding: utf-8
#
# Copyright (C) 2014-2018 Arthur de Jong
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the Li... | key if it can be decrypted
"""
def __init__(self, pskc):
self.pskc = pskc
self._algorithm = None
@property
def key(self):
"""Provide access to the MAC key binary value if available."""
value = getattr(self, '_key', | None)
if hasattr(value, 'get_value'):
return value.get_value(self.pskc)
elif value:
return value
else:
# fall back to encryption key
return self.pskc.encryption.key
@key.setter
def key(self, value):
self._key = value
@property... |
LLNL/spack | var/spack/repos/builtin/packages/perl-test-more/package.py | Python | lgpl-2.1 | 940 | 0.006383 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PerlTestMore(PerlPackage):
"""Test2 is a new testing framework produced by forking Test::B... | st-more/archive/v1.302183.tar.gz"
version('1.302183', sha256='1356ec24c5ab3f7ad8327091ddc6ace164a27767be10325776bf9743360ab4f7')
version('1.302182', sha256='60727db9435cb244f6dcf4ca598c8ef39ac3035a0c36fd5c9c5b89be4f138366')
version('1.302181', sha256='acb3c990d646928e7571c140510d7424716d3281c4064b1787294e7... | version('1.302180', sha256='4dbed31e9434d74427b41a17ca3e0511a81ee5cb1240408c7f439c6449672a20')
|
CT-Data-Collaborative/edi-v2 | edi/content/old_mig/0005_auto_20170808_1832.py | Python | mit | 584 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-08 18:32
from __future__ impo | rt unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('content', '0004_ediimages'),
]
operations = [
migrations.AlterModelOptions(
name='ediimages',
options={'ordering': ('sort_order',)},
),
... | name='sort_order',
field=models.PositiveIntegerField(default=0),
),
]
|
mehulsbhatt/phone-iso3166 | setup.py | Python | mit | 980 | 0.00102 | from setuptools import setup, find_packages
from os.path import dirname, join
import phone_iso3166
def readfile(filename):
with open(join(dirname(__file__), filename), 'r') as f:
return f.read()
setup(
name="phone-iso3166",
description="Phonenumber to ISO 3166-1 mapping",
install_requires=[
... | SI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Prog | ramming Language :: Python :: 3.5',
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Natural Language :: English'
)
)
|
vmthunder/nova | nova/tests/virt/libvirt/test_imagebackend.py | Python | apache-2.0 | 53,414 | 0.000505 | # Copyright 2012 Grid Dynamics
# 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... | self.INSTANCES_PATH = tempfile.mkdtemp(suffix='instances')
self.flags(disable_process_locking=True,
instances_path=self.INSTANCES_PATH)
self.INSTANCE = {'name': 'instance',
'uuid': uuidutils.generate_uuid() | }
self.DISK_INFO_PATH = os.path.join(self.INSTANCES_PATH,
self.INSTANCE['uuid'], 'disk.info')
self.NAME = 'fake.vm'
self.TEMPLATE = 'template'
self.CONTEXT = context.get_admin_context()
self.OLD_STYLE_INSTANCE_PATH = \
fake_... |
moagstar/python-uncompyle6 | test/simple_source/bug36/01_extended_arg.py | Python | mit | 143 | 0.006993 | if __file__:
0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+ | 0+0+0 | +0+0+0+0+0+0+0+0+0+0+0+0
|
whbruce/upm | examples/python/gprs.py | Python | mit | 3,287 | 0.003651 | #!/usr/bin/python
# Author: Jon | Trulson <jtrulson@ics.com>
# Copyr | ight (c) 2015 Intel Corporation.
#
# 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, merge, publish,
# distr... |
go-bears/Final-Project | weblogo-3.4_rd/corebio/seq_io/intelligenetics_io.py | Python | mit | 6,081 | 0.011018 | #!/usr/bin/env python
# Copyright (c) 2005 Gavin E. Crooks <gec@threeplusone.com>
#
# This software is distributed under the MIT Open Source License.
# <http://www.opensource.org/licenses/mit-license.html>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and as... | SE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
"""Read and write sequence information in IntelliGenetics format.
A sequence file in IG format can contain several sequences, each consisting of a
number of comment lines that must begin with a semicolon (";"), a line with the
sequence name and the sequence itself term... | es
HSFAU
ttcctctttctcgactccatcttcgcggtagctgggaccgccgttcagtc
actcttaagtcttttgtaattctggctttctctaataaaaaagccactta
gttcagtcaaaaaaaaaa1
;H.sapiens fau 1 gene, 2016 bases
HSFAU1
ctaccattttccctctcgattctatatgtacactcgggacaagttctcct
gatcgaaaacggcaaaactaaggccccaagtaggaatgccttagttttcg
gggttaacaatgattaacactgagcctcacacccacgcgatgccct... |
PayloadSecurity/VxAPI | api/callers/search/__init__.py | Python | gpl-3.0 | 254 | 0 | from api.callers.search.api_s | earch_hash import ApiSearchHash
from api.callers.search.api_search_hashes import ApiSearchHashes
from api.callers.search.api_search_states i | mport ApiSearchStates
from api.callers.search.api_search_terms import ApiSearchTerms
|
yugang/crosswalk-test-suite | stability/wrt-stablonglast3d-tizen-tests/inst.wgt.py | Python | bsd-3-clause | 7,390 | 0.0023 | #!/usr/bin/env python
import os
import shutil
import glob
import time
import sys
import subprocess
import string
from optparse import OptionParser, make_option
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
PKG_NAME = os.path.basename(SCRIPT_DIR)
PARAMETERS = None
#XW_ENV = "export DBUS_SESSION_BUS_ADDRESS=... | = False
break
# Do some special copy/delete... steps
'''
(return_code, output) = doRemoteCMD(
"mkdir -p %s/tests" % PKG_SRC_DIR)
if return_code != 0:
action_status = False
| if not doRemoteCopy("specname/tests", "%s/tests" % PKG_SRC_DIR):
action_status = False
'''
for item in glob.glob("%s/*" % SCRIPT_DIR):
if item.endswith("inst.py"):
continue
else:
item_name = os.path.basename(item)
if not doRemoteCopy(item, PKG_SRC_DIR... |
chenfengyuan/mcurl | python3/get_info.py | Python | mit | 751 | 0.003995 | #!/usr/bin/env python
# coding=utf-8
from mcurl.utils import monkey_patch
import zmq.green as zmq
import sys
import json
__author__ = 'chenfengyuan'
monkey_patch.dummy()
def client(port):
host = '127.0.0.1'
context = | zmq.Context()
socket = context.socket(zmq.REQ)
socket.connect("tcp://%s:%s" % (host, port))
socket.send(b'')
message = socket.recv()
socket.close()
data = json.loads(message.decode('utf-8'))
""":type: list"""
data.sort(key=lambda x: x['filename'])
for info in data:
print('%... | ain__':
main()
|
GoogleCloudPlatform/PerfKitBenchmarker | tests/providers/aws/aws_vpc_endpoint_test.py | Python | apache-2.0 | 4,139 | 0.001933 | # Copyright 2019 PerfKitBenchmarker 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... | uper(AwsVpcS3EndpointTest, self).setUp()
self.mock_vpc = mock.Mock()
self.mock_vpc.region = REGION
self.mock_run_cmd = self.enter_context(
mock.patch.object(aws_vpc_endpoint.AwsVpcS3Endpoint, '_RunCommand'))
def _InitEndpoint(self, vpc_id):
self.mock_vpc.id = vpc_id
return aws_vpc_endpoin... |
self.assertIsNone(endpoint.id)
endpoint._RunCommand.assert_not_called()
def testEndPointIdHasVpc(self):
# initialize with a VPC does an immediate call to find existing endpoints
endpoint = self._InitEndpoint(VPC_ID)
self.assertIsNone(endpoint.id, 'Endpoint id always None on initialization')
... |
wkcn/mobula | examples/LeNet5.py | Python | mit | 1,026 | 0.031189 | from defines import *
import numpy as np
import mobula
import mobula.layers as L
class LeNet5:
def __init__(self, X, labels):
data, label = L.Data([X, labels], "data", batch_size = 100)
conv1 = L.Conv(data, dim_out = 20, kernel = 5)
pool1 = L.Pool(conv1, pool = L.Pool.MAX, kernel = 2, stri... | red"].Y
@property
def loss(self):
return self.net["loss"].loss
@property
def label(self):
return self.net[" | data"](1).Y
|
datalogics/scons | test/Fortran/FORTRANMODDIR.py | Python | mit | 2,735 | 0.004022 | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software w | ithout restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell 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 ... | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHE... |
nextime/pcbdrill | pcbdrill.py | Python | gpl-3.0 | 20,051 | 0.043689 | import Tkinter as tk
import tkFileDialog as fd
import tkMessageBox as mbox
import numpy as np
import re
import cv2
import excellon
import serial
from PIL import ImageTk,Image
import sys, os
import pickle
global coordinates, camdev, printerdev, ser
FPATH = None
FILEOPENED=False
app = tk.Tk()
app.title('P... | k.Label(offsetPopup,text='Please insert the camera offset')
coordinates=tk.Entry(offsetPopup)
ok=tk.Button(offsetPopup,text='Ok',command=lambda: myBoard.setOffset(capture,offsetPopup,(coordinates.get().upper().replace('X','').replace('Y','').split())))
coordinates.insert(0, "X0.00 Y0.00")
canvas = tk.Ca... | canvas.grid()
coordinates.grid()
ok.grid()
update_frame(offsetPopup, capture, canvas)
def update_serial(btn):
global ser
if ser:
out=''
while ser.inWaiting() > 0:
out += ser.read(1)
if out:
print 'SERIAL IN->', out
btn.after(500, update_serial, ... |
tcstewar/sceneweave | setup.py | Python | gpl-2.0 | 363 | 0 | from setu | ptools import setup
setup(
name='sceneweave',
packages=['sceneweave'],
version='0.0.1',
entry_points=dict(
console_scripts=['sw.play = sceneweave.play_text:run'],
),
author='Terry Stewart',
description='Scene-based interactive sto | rytelling',
author_email='terry.stewart@gmail.com',
license='GPLv3',
)
|
jimkiiru/james-kiiru-bc17-week1 | day1/TestPrimeNumbers.py | Python | mit | 1,018 | 0.01277 |
import unittest
from GeneratePrimeNumbers import GeneratePrimeNumbers
class TestPrimeGenerator(unittest.TestCase):
def TestCorrectness(self):
#test whether the function generates correct prime numbers
self.assertEqual(GeneratePrimeNumbers(20), [2, 3, 5, 7, 11, 13, 17, 19])
def TestZero(sel... | nly integers are allowed.")
def TestNegativeNumbers(self):
#makes sure that only positive numbers are processed if the number is negative an error is displayed
self.assertEqual(GeneratePrimeNumbers(-1), "Not possible to generate prime numbers for integers less than 2.")
if __name__ == "__main__":... | ittest.main()
|
sem-geologist/hyperspy | examples/data_navigation/2D_image_stack.py | Python | gpl-3.0 | 1,130 | 0 | """Creates a 4D image and plots it
"""
import numpy as np
import hyperspy.api as hs
import matplotlib.pyplot as plt
# Create a 2D image stack with random data
im = hs.signals.Signal2D(np.random.random((16, 16, 32, 32)))
# Define the axis properties
im.axes_manager.signal_axes[0].name = ''
im.axes_manager.signal_axes... | _axes[0].units = 'nm'
im.axes_manager.navigation_axes[0].scale = 0.3
im.axes_manager.navigation_axes[0].offset = 100
im.axes_manager.navigation_axes[1].name = 'Y'
im.axes | _manager.navigation_axes[1].units = 'nm'
im.axes_manager.navigation_axes[1].scale = 0.3
im.axes_manager.navigation_axes[1].offset = 100
# Give a title
im.metadata.General.title = 'Random 2D image stack'
im.plot()
plt.show() # No necessary when running in the HyperSpy's IPython profile
|
jproffitt/fabric-bolt | fabric_bolt/projects/management/commands/populate_demo_data.py | Python | mit | 3,708 | 0.001348 | from django.core.management.base import BaseCommand
from django.core.files.base import ContentFile
from fabric_bolt.hosts.models import Host, SSHConfig
from fabric_bolt.projects.models import Project, St | age, Configuration
class Command(BaseCommand):
ssh_private_key = """-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEArBsTE4MxG/x5PVcL4bNgvcIVJPdS2xWzmZkMZMeOkKx5y+Ew
DWT0nxU6iZn59M4p5B+xcxCzilnu0ljzeooxUbFR | R/2jdvuAVEQRXcAFi17WtHP3
Up7U/t+vBmv2ZNLAlOn6U10rw36+wPmiG/yKTp9kYNfCE9B0+RS/5DPHbR2FS84D
49vxruJKMH9zW0A0Me+PskOQtKCcDxT966Z2MsNZiPBti5ZK4yrjDYBM8E9PfXzJ
tlL/j6G8Z8ALm/MA4VypVMUEaRuRu8TfoMoTAeB2ixRYjoTJMi6r8s7WLOXaGmuV
g3Z1Gj20sdo2Fi5ordBSm+DDxVHxIBE4iRWkAQIDAQABAoIBAB1u4+xKW3O10eYz
pMyMqNbLAmK4CWt... |
CI-WATER/tethysapp-ssw_downloader | setup.py | Python | bsd-2-clause | 1,153 | 0.006071 | import os
import sys
from setuptools import setup, find_packages
from tethys_apps.app_installation import custom_develop_command, custom_install_command
### Apps Definition ###
app_package = 'ssw_downloader'
release_package = 'tethysapp-' + app_package
app_class = 'ssw_downloader.app:SswDownloader'
app_package_dir = o... |
version='0.0.0',
description="Downloads and aggregates netCDF files from NASA's Simple Subset Wizard",
long_description='',
keywords='',
author='Scott Christensen',
auth | or_email='sdc50@byu.net',
url='',
license='BSD2',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
namespace_packages=['tethysapp', 'tethysapp.' + app_package],
include_package_data=True,
zip_safe=False,
install_requires=dependencies,
cmdclass={
'install': custo... |
DrOctogon/unwash_ecom | tests/functional/customer/auth_tests.py | Python | bsd-3-clause | 4,811 | 0.000416 | import re
from django.core import mail
from django.core.urlresolvers import reverse
from django_webtest import WebTest
from oscar.test.testcases import WebTestCase
from oscar.core.compat import get_user_model
User = get_user_model()
class TestAUserWhoseForgottenHerPassword(WebTest):
def test_can_reset_her_pa... | sword'
page = form.submit()
self.assertEqual(len(mail.outbox), 1)
self.assertIn("your password has been changed", mail.outbox[0].body)
def test_cannot_access_reset_password_page(self):
response = self.get(reverse('password-reset'), status=403)
self.assertEqual(403, response... | rofile-update'))
form = page.forms['profile_form']
form['first_name'] = "Terry"
form.submit()
self.assertEqual(len(mail.outbox), 0)
def test_receives_an_email_when_their_email_address_is_changed(self):
page = self.get(reverse('customer:profile-update'))
form = page.f... |
plotly/python-api | packages/python/plotly/plotly/validators/scatter3d/error_y/_symmetric.py | Python | mit | 472 | 0.002119 | impor | t _plotly_utils.basevalidators
class SymmetricValidator(_plotly_utils.basevalidators.BooleanValidator):
def __init__(
self, plotly_name="symmetric", parent_name="scatter3d.error_y", **kwargs
):
super(SymmetricValidator, self).__init__(
plotly_name=plotly_name,
parent_na... | |
pacificIT/mopidy | mopidy/__init__.py | Python | apache-2.0 | 357 | 0 | fr | om __future__ import absolute_import, print_function, unicode_literals
import platform
import sys
import warnings
if not (2, 7) <= sys.version_info < (3,):
sys.exit(
'ERROR: Mopidy requires Python 2.7, but found %s.' %
platform.python_version())
warnings.filterwarnings('ignore', 'could not open... | = '1.1.1'
|
rvazarkar/Empire | setup/setup_database.py | Python | bsd-3-clause | 5,322 | 0.00451 | #!/usr/bin/python
import sqlite3, os, string, hashlib
from Crypto.Random import random
###################################################
#
# Default values for the config
#
###################################################
# Staging Key is set up via environmental variable
# or via command line. By setting RAND... | )[0:-1])+"/"
# the version version to appear as
SERVER_VERSION = "Microsoft-IIS/7.5"
# an IP white list to ONLY accept clients from
# format is 192.168.1.1,192.168.1.10-192.168.1.100,10.0.0.0/8
IP_WHITELIS | T = ""
# an IP black list to reject accept clients from
# format is 192.168.1.1,192.168.1.10-192.168.1.100,10.0.0.0/8
IP_BLACKLIST = ""
#number of times an agent will call back without an answer prior to exiting
DEFAULT_LOST_LIMIT = 60
###################################################
#
# Database setup.
#
##... |
timj/scons | test/QT/empty-env.py | Python | mit | 2,252 | 0.002664 | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
... | ndif
}
""")
# we can receive warnings about a non detected qt (empty QTDIR)
# these are not critical, but may b | e annoying.
test.run(stderr=None)
test.run(program = test.workpath('main' + TestSCons._exe),
stderr = None,
stdout = 'qt/include/foo6.h\n')
test.pass_test()
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
|
BBouzigues/plugin.video.cpasbien | test.py | Python | gpl-3.0 | 20,868 | 0.004648 | # coding: utf-8
__author__ = 'Ruben'
data = '''
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Index->Torrents</title>
<if:seo_enabled>
<tag:cano />
<tag:meta />
<tag:analytic ... | ype="text/javascript" src="http://leetxtorrents.org/jscript/animatedcollapse.js"></script>
<script type="text/javascript" src="http://leetxtor | rents.org/jscript/1.4.2_jquery.min.js"></script>
<script type="text/javascript" src="http://leetxtorrents.org/jscript/jquery.min.js"></script>
<!-- // -->
<script type="text/javascript" src="http://leetxtorrents.org/jscript/jquery.js"></script>
<script type="text/javascript" src="http://leetxtorrents.org/jscr... |
SINGROUP/pycp2k | pycp2k/classes/_fit_kgpot1.py | Python | lgpl-3.0 | 795 | 0.002516 | from pycp2k.inputsection import InputSection
from ._each428 import _each428
class _fit_kgpot1(InputSection):
def __init__(self):
InputSection.__init__(self)
self.Section_parameters = None
self.Add_last = None
self. | Common_iteration_levels = None
self.Filename = None
self.Log_print_key = None
self.Num_gaussian = None
self.Num_polynom = None
self.EACH = _each428()
self._name = "FIT_KGPOT"
self._keywords = {'Num_polynom': 'NUM_POLYNOM', | 'Log_print_key': 'LOG_PRINT_KEY', 'Num_gaussian': 'NUM_GAUSSIAN', 'Common_iteration_levels': 'COMMON_ITERATION_LEVELS', 'Add_last': 'ADD_LAST', 'Filename': 'FILENAME'}
self._subsections = {'EACH': 'EACH'}
self._attributes = ['Section_parameters']
|
Aleks31/pychess | lib/pychess/ic/managers/OfferManager.py | Python | gpl-3.0 | 10,580 | 0.013327 | import re
#from gobject import GObject, SIGNAL_RUN_FIRST
from gi.repository import GObject
from pychess.Utils.const import *
from pychess.Utils.Offer import Offer
from pychess.System.Log import log
from pychess.ic import *
from pychess.ic.FICSObjects import *
names = "\w+(?:\([A-Z\*]+\))*"
rated = "(rated|unrated)"
... | ourn | ed" in wildtype) or \
(adjourned and "adjourned" in adjourned):
is_adjourned = True
if wildtype and "wild" in wildtype:
gametype = wildtype
try:
gametype = GAME_TYPES[gametype]
... |
Signbank/NGT-signbank | signbank/dictionary/models.py | Python | bsd-3-clause | 101,134 | 0.004568 | from django.db.models import Q
from django.db import models, OperationalError
from django.conf import settings
from django.http import Http404
from django.utils.encoding import escape_uri_path
from django.contrib.auth.models import User
from django.dispatch import receiver
from django.db.models.signals import post_save... | rch_fields = ['gloss__idgloss']
class Keyword(models.Model):
"""A Dutch keyword that is a possible translation equivalent of a sign"""
def __str__(self):
return self.text
text = models.CharField(max_length=100, unique=True)
def inWeb(self):
"""Return True if some gloss associated wi... | ter(gloss__inWeb__exact=True)) != 0
class Meta:
ordering = ['text']
class Admin:
search_fields = ['text']
def match_request(self, request, n):
"""Find the translation matching a keyword request given an index 'n'
response depends on login status
Returns a tuple (tr... |
Andrew0701/coursework-web | progress/home/migrations/0001_initial.py | Python | apache-2.0 | 4,089 | 0.002446 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Create... | ('surname', models.CharField(max_length=100)),
('group', models.ForeignKey(null=True, to='home.Group')),
('jobs', models.ManyToManyField(to='home.Job', through='home.Log')),
],
),
migrations.CreateModel(
name='Student_Subject',
fields... | True, primary_key=True)),
('student', models.ForeignKey(to='home.Student')),
],
),
migrations.CreateModel(
name='Subject',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
... |
chrismattmann/apple | distribution/src/main/resources/bin/checker_client.py | Python | apache-2.0 | 2,189 | 0.020101 | import string
import os, sys
try:
import json
except ImportError:
import simplejson as json
import subprocess
### url = 'http://bubba.jpl.nasa.gov:8083'
url = 'http://cmacws.jpl.nasa.gov:8083'
# function to print out mesg
def print_mesg(mesg, keyword):
if keyword is 'Error':
keyword1 = 'Err'
else:
k... | )
print 'cmdstring: ', cmdstring
proc=subprocess.Popen(cmd, cwd='.', stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
# wait for the process to finish
stdout_value, stderr_value = proc.communicate()
if stderr_value.find('couldn\'t connect to host') >= 0:
print 'error: stderr_value: '... | out_value
"""
result_dict = json.loads(stdout_value)
mesg = result_dict['message'] # get the message part of dict
mesg = mesg.encode('utf-8') # encode to get string from unicode
### print mesg
# print any mesg with keyword
print_mesg(mesg, 'Error')
print_mesg(mesg, 'Warning')
print_mesg(mesg, 'Info'... |
humdings/zipline | zipline/data/data_portal.py | Python | apache-2.0 | 51,743 | 0 | #
# Copyright 2016 Quantopian, 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 wr... | Convertible,
Equity,
Future,
PricingDataAssociable,
)
from zipline.assets.continuous_futures import ContinuousFuture
from zipline.data.continuous_future_reader import (
ContinuousFutureSessionBarReader,
ContinuousFutureMinuteBarReader
)
from zipline.ass | ets.roll_finder import (
CalendarRollFinder,
VolumeRollFinder
)
from zipline.data.dispatch_bar_reader import (
AssetDispatchMinuteBarReader,
AssetDispatchSessionBarReader
)
from zipline.data.resample import (
DailyHistoryAggregator,
ReindexMinuteBarReader,
ReindexSessionBarReader,
)
from zip... |
BradburyLab/show_tv | show_tv/s_.py | Python | gpl-3.0 | 1,964 | 0.006231 | #!/usr/bin/env python
# coding: utf-8
import sys
#
# Код работы со строками
# Название s_ выбрано исходя их краткости и того, что оно
# непохоже на имя переменной (по крайней мере для Python;
# стереотип, что в C++ так обозначают приватные имена атрибутов
# классов, очень мешал, но все равно)
#
# И да, понимаю, что э... | p("utf_8").encode
# ...
# return encoder_func(s)
def to_utf8(s):
""" unicode => str """
return s.encode("utf_8")
def to_uni(s):
""" str => unicode """
return s.decode("utf_8")
class EvalFormat:
""" locals() не подходит для глобальных переменных и вызова функций """
def init_context(self):... | y(self, key):
return eval(key, self.globs, self.locs)
def __init__(self):
self.init_context()
def __getitem__(self, key):
return self.eval_key(key)
def make_stream():
import StringIO
return StringIO.StringIO()
def timedelta2str(tdelta):
days = tdelta.days
res = ""... |
talhaobject90/HUNGRY-OBJECT90 | checkout/app.py | Python | mit | 218 | 0.009174 | from dj | ango.apps import AppConfig
class CheckoutConfig(AppConfig):
name = 'checkout'
label = 'my.checkout' # <-- this is the important line - change it to anything other than the default ('foo' in this case)
| |
Loisel/colorview2d | colorview2d/__init__.py | Python | bsd-2-clause | 679 | 0 | """
*colorview2d* is a plotting tool intended to be used with
scientific data (with dimensionful axes)
with an easily extendable data modification (or filtering) toolbox.
Tested with Python 2.7 and Python 3.
Dependencies
------------
numpy, scipy, matplotlib, pyyaml, scikit.image
Homepage
--------
https://github.com... | from colorview2d.data impor | t Data
from colorview2d.view import View
from colorview2d.imod import IMod
import colorview2d.fileloaders
|
NeuroDataDesign/seelviz | Jupyter/cherrypy/clviz_web_token_albert.py | Python | apache-2.0 | 15,295 | 0.004511 | import os
import os.path
import cherrypy
from cherrypy.lib import static
from cherrypy.lib.static import serve_file
import shutil
import tempfile
import glob
from clarityviz import claritybase
localDir = os.path.dirname(__file__)
absDir = os.path.join(os.getcwd(), localDir)
# print absDir
def imag... | <a class="page-scroll" href="https://neurodatadesign.github.io/seelviz/#About">About Us</a>
</li>
<li>
<a class="page-scroll" href="https://neurodatadesign.github.io/seelviz/#Ackno | wledgments">Acknowledgements</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container-fluid -->
</nav>
<header>
<div class="head... |
chutsu/robotics | prototype/control/__init__.py | Python | gpl-3.0 | 160 | 0 | import prototype.control.gimbal
import prototype.c | ontrol.quadrotor
import prototype.control.carrot
i | mport prototype.control.pid
import prototype.control.utils
|
jmcarp/marshmallow | tests/test_serializer.py | Python | mit | 35,818 | 0.002931 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import random
import pytest
from marshmallow import Schema, fields, utils, MarshalResult, UnmarshalResult
from marshmallow.exceptions import MarshallingError
from marshmallow.compat import unicode, binary_type
from tests.base import * # noqa
random.seed(1... | com")
s = SchemaClass(u)
assert s.data['email'] == "john@example.com"
def test_stored_invalid_email():
u = User("John", email="johnexample.com")
s = UserSchema(u)
assert "email" in s.errors
assert s.errors['email'] == '"johnexample.com" is not a valid email address.'
def test_integer_field():
... | Schema(u)
assert type(serialized.data['age']) == int
assert serialized.data['age'] == 42
def test_integer_default():
user = User("John", age=None)
serialized = UserIntSchema(user)
assert type(serialized.data['age']) == int
assert serialized.data['age'] == 0
def test_fixed_field():
u = User... |
krikru/tensorflow-opencl | tensorflow/python/kernel_tests/confusion_matrix_test.py | Python | apache-2.0 | 7,382 | 0.006502 | # 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... | labels)
def testOutputIsInt32(self):
labels = np.arange(2)
predictions = np.arange(2)
with self.test_session():
cm = confusion_matrix.confusion_matrix(
labels, predictions, dtype=dtypes.int32)
tf_cm = cm.eval()
self.assertEqual(tf_cm.dtype | , np.int32)
def testOutputIsInt64(self):
labels = np.arange(2)
predictions = np.arange(2)
with self.test_session():
cm = confusion_matrix.confusion_matrix(
labels, predictions, dtype=dtypes.int64)
tf_cm = cm.eval()
self.assertEqual(tf_cm.dtype, np.int64)
if __name__ == "__main... |
googleads/google-ads-python | google/ads/googleads/v9/services/services/account_budget_proposal_service/client.py | Python | apache-2.0 | 26,197 | 0.001222 | # -*- 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... | oint.replace(".googleapis.com | ", ".mtls.googleapis.com")
DEFAULT_ENDPOINT = "googleads.googleapis.com"
DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore
DEFAULT_ENDPOINT
)
@classmethod
def from_service_account_info(cls, info: dict, *args, **kwargs):
"""Creates an instance of this clie... |
abilian/abilian-sbe | src/abilian/sbe/apps/social/models.py | Python | lgpl-2.1 | 2,645 | 0.000378 | """Social content items: messages aka status updates, private messages, etc."""
from __future__ import annotations
import re
from sqlalchemy.orm import relationship
from sqlalchemy.orm.query import Query
from sqlalchemy.schema import Column, ForeignKey
from sqlalchemy.types import Integer, UnicodeText
from abilian.c... | "Group", primaryjoin=(group_id == Group.id), lazy="joined")
query = db.session.query_property(MessageQuery)
@property
def tags(self) -> list[str]:
return re.findall(r"(?u)#([^\W]+)", self.content)
# TODO: inheritin | g from Entity is overkill here
class TagApplication(Entity):
__tablename__ = "tag_application"
tag = Column(UnicodeText, index=True)
message_id = Column(Integer, ForeignKey("message.id"))
class PrivateMessage(Entity):
"""Private messages are like messages, except they are private."""
__tablename... |
LosFuzzys/CTFd | CTFd/forms/teams.py | Python | apache-2.0 | 7,277 | 0.001099 | from wtforms import BooleanField, PasswordField, SelectField, StringField
from wtforms.fields.html5 import EmailField, URLField
from wtforms.validators import InputRequired
from CTFd.forms import BaseForm
from CTFd.forms.fields import SubmitField
from CTFd.models import TeamFieldEntries, TeamFields
from CTFd.utils.cou... | en")
banned = BooleanField("Banned")
submit = SubmitField("Submit")
def TeamCreateForm(*args, **kwargs):
class _TeamCreateForm(TeamBaseForm):
pass
@property
def extra(self):
return build_custom_team_fields(self, include_entries=False)
attach_custom_team_fields(_Te... | class _TeamEditForm(TeamBaseForm):
pass
@property
def extra(self):
return build_custom_team_fields(
self,
include_entries=True,
fields_kwargs=None,
field_entries_kwargs={"team_id": self.obj.id},
)
... |
mediafactory/tryton_core_daemon | trytond/webdav/webdav.py | Python | gpl-3.0 | 33,594 | 0.00125 | #This file is part of Tryton. The COPYRIGHT file at the top level of
#this repository contains the full copyright notices and license terms.
import os
import time
import urllib
import urlparse
import socket
import encodings
import uuid
import datetime
from dateutil.relativedelta import relativedelta
from trytond.model... | '.png': 'image/png',
'.odt': 'application/vnd.oasis.opendocument | .text',
'.pdf': 'application/pdf',
}
def default_domain(self):
return '[]'
def get_rec_name(self, ids, name):
if not ids:
return {}
names = {}
def _name(collection):
if collection.id in names:
return names[collection.... |
ray-project/ray | rllib/examples/models/action_mask_model.py | Python | apache-2.0 | 4,271 | 0.001405 | from gym.spaces import Dict
from ray.rllib.models.tf.fcnet import FullyConnectedNetwork
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.models.torch.torch_modelv2 import TorchModelV2
from ray.rllib.models.torch.fcnet import FullyConnectedNetwork as TorchFC
from ray.rllib.utils.framework import try_... | ace,
num_outputs,
model_config,
name + "_internal",
)
| # disable action masking --> will likely lead to invalid actions
self.no_masking = model_config["custom_model_config"].get("no_masking", False)
def forward(self, input_dict, state, seq_lens):
# Extract the available actions tensor from the observation.
action_mask = input_dict["obs"]... |
anupkdas-nus/global_synapses | pyNN-dispackgaes/neuron/projections.py | Python | gpl-3.0 | 7,227 | 0.005535 | # encoding: utf-8
"""
nrnpython implementation of the PyNN API.
:copyright: Copyright 2006-2016 by the PyNN team, see AUTHORS.
:license: CeCILL, see LICENSE for details.
"""
from copy import deepcopy
import numpy
import logging
try:
from itertools import izip
except ImportError:
izip = zip # Python 3 zip ret... | mon.Projection):
__doc__ = common.Projection.__doc__
_simulator = simulator
_static_synapse_class = StaticSynapse
def __init__(self, presynaptic_population, postsynaptic_population,
connect | or, synapse_type=None, source=None, receptor_type=None,
space=Space(), label=None):
__doc__ = common.Projection.__init__.__doc__
common.Projection.__init__(self, presynaptic_population, postsynaptic_population,
connector, synapse_type, source, receptor... |
pyocd/pyOCD | pyocd/target/pack/cmsis_pack.py | Python | apache-2.0 | 31,189 | 0.00404 | # -*- coding: utf-8 -*-
# pyOCD debugger
# Copyright (c) 2019-2020 Arm Limited
# Copyright (c) 2020 Men Shiyun
# Copyright (c) 2020 Fraunhofer-Gesellschaft zur Förderung der angewandten Forschung e.V.
# Copyright (c) 2021 Chris Reed
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.... | """
return self._pack
@property
def devices(self) -> List["CmsisPackDevice"]:
"""@brief A list of CmsisPackDevice objects for every part number defined in the pack."""
return sel | f._devices
def _parse_devices(self, parent: Element) -> None:
# Extract device description elements we care about.
newState = _DeviceInfo(element=parent)
children: List[Element] = []
for elem in parent:
if elem.tag == 'memory':
newState.memories.append(el... |
dalou/django-extended | django_extended/fields/uuid_field.py | Python | bsd-3-clause | 815 | 0.008589 | from django.db import models
import | uuid
class UUIDField(models.CharField) :
def __init__(self, *args, **kwargs):
kwargs['max_length'] = kwargs.get('max_length', 64 )
kwargs['blank'] = True
super(UUIDField, self).__init__(*args, **kwargs)
def _generate_uuid(self):
return str(uuid.uuid4())
def pre_save(sel... | ame, value)
return value
else:
return super(models.CharField, self).pre_save(model_instance, add)
try:
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^django_extended\.fields\.UUIDField"])
except:
pass |
dtaylor84/pysnapsync | pysnapsync/client/__init__.py | Python | gpl-3.0 | 427 | 0 | # coding=utf-8
"""PySnapSync client.
This package implements the pysnapsync client.
The package | exports the following modules:
o `snapsync` main backup script.
See the module doc strings for more information.
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from pysnapsync.client import snapsync
_ | _all__ = [x.__name__.split(".")[-1] for x in [snapsync]]
|
UdK-VPT/Open_eQuarter | mole3/stat_corr/window_wall_ratio_south_MFH_by_building_age_correlation.py | Python | gpl-2.0 | 521 | 0.040307 | # OeQ autogenerated correlation for 'Window/Wall Ratio South in Correlation to the Building Age'
import math
import numpy | as np
from . import oeqCorrelation as oeq
def get(*xin):
# OeQ autogenerated correlation for 'Window to Wall Ratio in Southern Direction'
A_WIN_S_BY_AW= oeq.correlation(
const= 20818.6194135,
a= -42.6513518642,
b= 0.0327511835635,
c= -1.1171805883 | 4e-05,
d= 1.42836626434e-09,
mode= "lin")
return dict(A_WIN_S_BY_AW=A_WIN_S_BY_AW.lookup(*xin))
|
szha/mxnet | python/mxnet/gluon/contrib/data/vision/transforms/bbox/utils.py | Python | apache-2.0 | 16,043 | 0.002867 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | size) == 2:
raise ValueError("size requires length 2 tuple, given {}".format(len(size)))
width, height = size
bbox = bbox.copy()
if flip_y:
ymax = height - bbox[:, 1]
ymin = height - bbox[:, 3]
bbox[:, 1] = ymin
bbox[:, 3] = ymax
if flip_x:
xmax = width - ... | """Resize bouding boxes according to image resize operation.
Parameters
----------
bbox : numpy.ndarray
Numpy.ndarray with shape (N, 4+) where N is the number of bounding boxes.
The second axis represents attributes of the bounding box.
Specifically, these are :math:`(x_{min}, y_... |
eldarion/braintree_python | braintree/subscription.py | Python | mit | 8,098 | 0.003334 | from decimal import Decimal
from braintree.util.http import Http
import braintree
import warnings
from braintree.add_on import AddOn
from braintree.descriptor import Descriptor
from braintree.discount import Discount
from braintree.exceptions.not_found_error import NotFoundError
from braintree.resource_collection impor... | tion statusues. Av | ailable statuses are:
* braintree.Subscription.Status.Active
* braintree.Subscription.Status.Canceled
* braintree.Subscription.Status.Expired
* braintree.Subscription.Status.PastDue
* braintree.Subscription.Status.Pending
"""
Active = "Active"
Canceled =... |
cbitterfield/JobCard | example/code_blocks.py | Python | gpl-3.0 | 1,238 | 0.016155 | # Variables for standard use:
config = {}
jobcard = {}
noexec = True
command = {}
command_status = {}
command_name = "example"
CMD = ''
item_src = ''
# Standard Imports
import os
import job
import logging
import subprocess
logger = logging.getLogger(__name__)
# Code Block - Run a command an check results
#
com... | + item_src + " Started" )
# Check if Command executed
logger.info("Check if " + str(command_name) + " Completed")
std | outdata, stderrdata = command[command_name].communicate()
command_status[command_name] = command[command_name].returncode
if command_status[command_name] == 0:
logger.info(str(command_name) + " Completed, returned Status: " + str(command_status[command_name]))
else:
logger.error(str(command_name) + "failed, wi... |
rleigh-dundee/openmicroscopy | components/validator/Backend/RunAndCheck.py | Python | gpl-2.0 | 988 | 0.029352 | #!/usr/bin/env python
# encoding: utf-8
"""
RunAndCheck.py
Created by Andrew Patterson on 2007-07-30.
Copyright (C) 2007-2012 University of Dundee & Open Microscopy Environment.
All Rights Reserved.
"""
im | port sys
import os
|
import OmeValidator
def main():
for aFilename in ["samples/completesamplenopre.xml","samples/completesample.xml",
"samples/sdub.ome", "samples/sdub-fix.ome", "samples/sdub-fix-pre.ome",
"samples/2010-04.ome", "samples/2010-06.ome",
"samples/tiny.ome", "samples/broke.ome"]:
print "============ XML file %s ==... |
JonnyWong16/plexpy | plexpy/classes.py | Python | gpl-3.0 | 2,312 | 0.000865 | # -*- coding: utf-8 -*-
# This file is part of Tautulli.
#
# Tautulli 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.
#
# Tautul... | ublic License
# along with Tautulli. If not, see <http://www.gnu.org/licenses/>.
#########################################
## Stolen from Sick-Beard's classes.py ##
#########################################
from __future__ import unicode_literals
from future.moves.urllib.request import FancyURLopener
import plex... | ass AuthURLOpener(PlexPyURLopener):
"""
URLOpener class that supports http auth without needing interactive password entry.
If the provided username/password don't work it simply fails.
user: username to use for HTTP auth
pw: password to use for HTTP auth
"""
def __init__(self, user, pw):
... |
GarySparrow/mFlaskWeb | venv/Lib/site-packages/foreman/environments.py | Python | mit | 937 | 0 | #!/usr/bin/python3
# -*- co | ding: utf-8 -*-
# Licensed under the Apache License, Vers | ion 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" B... |
hachreak/zenodo | tests/unit/deposit/test_api_editflow.py | Python | gpl-2.0 | 17,478 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo 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 v... | e community
c = Community.get('c1')
_, record = resolver.resolve(str(record_id))
c.accept_record(record)
record.commit()
db.session.commit()
# Get record to confirm if both communities should be visible now
assert get_json(client.get(
url_for('invenio_records_rest.recid_item', pi | d_value=record_id),
headers=json_headers,
), code=200)['metadata']['communities'] == [
{'identifier': 'c1'},
{'identifier': 'c3'},
]
# Publish
response = client.post(links['publish'], headers=auth_headers)
data = get_json(response, code=202)
current_search.flush_and_refr... |
myarjunar/inasafe | safe/gis/generic_expressions.py | Python | gpl-3.0 | 7,673 | 0 | # coding=utf-8
"""QGIS Expressions which are available in the QGIS GUI interface."""
from qgis.core import (
qgsfunction,
QgsMapLayerRegistry,
QgsExpressionContextUtils,
)
import datetime
from safe.definitions.provenance import provenance_layer_analysis_impacted_id
from safe.utilities.i18n import tr
fro... | displaced count.
It also can be used by pure number (int, float).
"""
_ = feature, parent # NOQA
if number < 0:
return None
percentage_format = '{percentage}%'
percentage = round((float(number) / float(total)) * 100, 1)
return percentage_format.format(percentage=percentage)
desc... | xamples = {
'beautify_date( @start_datetime )': tr(
'will convert datetime provided by qgis_variable.')
}
help_message = generate_expression_help(description, examples)
@qgsfunction(
args='auto', group='InaSAFE', usesGeometry=False, referencedColumns=[],
help_text=help_message.to_html(), helpText=... |
smenon8/AlgDataStruct_practice | practice_problems/StringIntersection.py | Python | mit | 702 | 0.07265 | def StringIntersect(str1,str2):
intr = []
for i in str1:
if i in str2 and i not in intr:
intr.append(i)
d = {}
for i in intr:
d[i] = min(str1.count(i),str2.count(i))
output = []
for i in d.keys():
output.append(i*d[i])
output.sort()
return ''.join(output)
def CountBit(num):
... | //= 2
if bit == 1:
count += 1
return count
def maxProd(numbers):
m1 = -1
m2 = - | 1
for i in range(len(numbers)):
if numbers[i] > m2:
m2 = numbers[i]
ind2 = i
for j in l[0:ind2]: # the first factor is strictly smaller and occurs before the second number
if j > m1:
m1 = j
return m1*m2 |
burnhamup/tinyquery | tinyquery/typed_ast.py | Python | mit | 5,461 | 0 | """A set of AST classes with types and aliases filled in."""
import collections
import type_context
class Select(collections.namedtuple(
'Select', ['select_fields', 'table', 'where_expr', 'group_set',
'limit', 'type_ctx'])):
"""A compiled query.
Fields:
select_fields: A l... | uple('Table', ['name', 'type_ctx']),
TableExpression):
def with_ | type_ctx(self, type_ctx):
return Table(self.name, type_ctx)
class TableUnion(collections.namedtuple('TableUnion', ['tables', 'type_ctx']),
TableExpression):
pass
class Join(collections.namedtuple('Join', ['table1', 'table2',
'conditions', 'is_l... |
goinnn/django-multiselectfield | example/app/migrations/0001_initial.py | Python | lgpl-3.0 | 1,535 | 0.003257 | # Generated by Django 2.2.6 on 2019-10-31 08:31
from django.db import migrations, models
import multiselectfield.db.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Book',
fields=[
... | sting'), ('huge', 'Huge'), ('nice', 'Nice')], max_length=54, null=True)),
('published_in', multiselectfield.db.fields.MultiSelectField(choices=[('Canada - Provinces', (('AB', 'Alberta'), ('BC', 'British Columbia'))), ('USA - States', (('AK', 'Alaska'), ('AL', 'Alabama'), ('AZ', 'Arizona')))], max_length... | ('chapters', multiselectfield.db.fields.MultiSelectField(choices=[(1, 'Chapter I'), (2, 'Chapter II')], default=1, max_length=3)),
],
),
]
|
VirusTotal/content | Packs/PassiveTotal/Scripts/RiskIQPassiveTotalSSLForSubjectEmailWidgetScript/RiskIQPassiveTotalSSLForSubjectEmailWidgetScript.py | Python | mit | 1,613 | 0.00434 | from CommonServerPython import *
import traceback
from typing import Dict, Union, Any
def set_arguments_for_widget_view(indicator_data: Dict[str, Any]) -> Union[Dict[str, str], str]:
"""
Prepare argument for commands or message to set custom layout of indicator
"""
indicator_type = indicator_data... | dress',
'query': indicator_data.get('value', '')
}
else:
return 'No SSL certificate(s) were found for the given argument(s).'
else:
return {
'field': 'subjectEmailAddress',
'query': indicato | r_data.get('value', '')
}
def main() -> None:
try:
arguments = set_arguments_for_widget_view(demisto.args().get('indicator'))
if isinstance(arguments, str):
demisto.results(arguments)
else:
demisto.results(demisto.executeCommand('pt-ssl-cert-search', argumen... |
honeynet/ghost-usb-honeypot | win7/Webadmin/serve.py | Python | gpl-3.0 | 1,528 | 0.037304 | #!/bin/env python
import bottle
import pymongo
from pymongo.objectid import ObjectId
import datetime
@bottle.route('/')
def index():
return bottle.static_file('/index.html', root = '.')
@bottle.route('/machinetable')
def machinetable():
machines = db.machines.find()
rows = []
categories = []
reports = {}
for m... | k'
categories.append('success')
else:
status = 'Detection ({} reports)'.format(detections.count())
categories.append('error')
reports[machine['ident']] = detections[0]
rows.append((machine['ident'], machine['hostname'], str(machine['last_seen']), status))
ret | urn bottle.template('templates/machine_table', rows = rows, categories = categories, reports = reports)
@bottle.route('/dismiss/<obj_id>')
def dismiss(obj_id):
report = db.reports.find_one({'_id': ObjectId(obj_id)})
report['Dismissed'] = True
db.reports.save(report)
@bottle.route('/report/<machine_ident>')
def r... |
PhantomGhosts/BigBrother | lib/bbro/core/update.py | Python | mit | 3,968 | 0.002016 | #!/usr/bin/env python
'''
Module that update the software and its databases
'''
import os
import shutil
from sys import exit
import os.path
import tarfile
import requests
from bs4 import BeautifulSoup
from ...base import *
from ...sentry import sentry
from ...clint import progress
class Updater(object):
def __i... | {ver}".format(ver=version)) + " found"))
# install
if self.install(self.inst_path, download_url):
print(color.info.info("Need to be restarted for changes to be effective"))
exit()
def install(self, path, url):
try:
# downloaded file name
... | ownload(url, path)
# change directory
os.chdir(path)
# extract in path directory
inst_module = self.extract(dl_file)
# normalize name
inst_module_norm = inst_module[:inst_module.find('-')]
if inst_module_norm in os.listdir():
... |
Le-Bot/cerebro | cerebro/neuron/entities.py | Python | mit | 123 | 0 | class Command(o | bject):
def __init__(self, keyword, args=None):
self.keyword = keyword |
self.args = args
|
dims/suds-jurko | tests/test_plugin.py | Python | lgpl-3.0 | 4,173 | 0.000719 | # -*- coding: utf-8 -*-
# This program is free software; you can redistribute it and/or modify it under
# the terms of the (LGPL) GNU Lesser General Public License as published by the
# Free Software Foundation; either version 3 of the License, or (at your
# option) any later version.
#
# This program is distri... | lugin(),
MessagePlugin(),
DocumentPlugin(),
InitPlugin(),
MessagePlugin(),
object(),
DocumentPlugin(),
MessagePlugin(),
object(),
InitPlugin(),
Plugin(),
Plugin(),
MyInitPlugin()]
container = PluginContainer... | lt = getattr(container, domain).plugins
assert result == expected_plugins
def test_exception_passing():
class FailingPluginException(Exception):
pass
class FailingPlugin(MessagePlugin):
def marshalled(self, context):
raise FailingPluginException
container = Pl... |
mtlchun/edx | cms/djangoapps/contentstore/management/commands/tests/test_cleanup_assets.py | Python | agpl-3.0 | 3,407 | 0.004109 | """
Test for assets cleanup of courses for Mac OS metadata files (with filename ".DS_Store"
or with filename which starts with "._")
"""
from django.core.management import call_command
from opaque_keys.edx.locations import SlashSeparatedCourseKey
from xmodule.contentstore.content import XASSET_LOCATION_TAG
from xmodul... | txt'] in contentstore for imported course
all_assets, count = self.content_store.get_all_content_for_course(course.id)
self.assertEqual(count, 2)
self.assertEqual(set([asset['_id']['name'] for asset in all_assets]), set([u'.example.txt', u'example.txt']))
# manually add redundant assets... | course.id.make_asset_key("asset", None)
query = location_to_query(course_filter, wildcard=True, tag=XASSET_LOCATION_TAG)
query['_id.name'] = all_assets[0]['_id']['name']
asset_doc = self.content_store.fs_files.find_one(query)
asset_doc['_id']['name'] = u'._example_test.txt'
self... |
xiaoqing1993/kaggle_abstract_classification | try_scikit_package.py | Python | mit | 1,211 | 0.003303 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 07 16:23:24 2016
@author: Xiaoqing
"""
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import BernoulliNB
from sklearn.naive_bayes import MultinomialNB
from sklearn.linear_model import LogisticRegression
from NaiveBayes_sp import ... | in_test_split(X, y, test_size=0.3, random_state=42)
'''
clf_lr = LogisticRegression()
clf_lr.fit(X_train,y_train)
print 'Logistic:', accuracy_score(y_test,clf_lr.predict(X_test))
'''
clf_nbB = BernoulliNB()
clf_nbB.fit(X_train,y_train)
y_b = clf_nbB.predict( | X_test)
print 'Bernoulli:', accuracy_score(y_test, y_b)
clf_nbM = MultinomialNB()
clf_nbM.fit(X_train,y_train)
y_m = clf_nbM.predict(X_test)
print 'Multinomial:', accuracy_score(y_test, y_m)
clf_hm1 = NaiveBayes()
clf_hm1.fit(X_train, y_train)
y_pre = clf_hm1.predict(X_test)
print 'naive bayes by mxq:', ac... |
faassen/morepath | morepath/tests/test_model.py | Python | bsd-3-clause | 4,600 | 0 | import dectate
try:
from urllib.parse import urlencode
except ImportError:
# Python 2
from urllib import urlencode
from morepath.path import get_arguments
from morepath.converter import Converter, IDENTITY_CONVERTER, ConverterRegistry
import morepath
import webob
def consume(mount, path, parameters=None):... | o(a, b=1):
pass
assert get_arguments | (foo, []) == {'a': None, 'b': 1}
def test_get_arguments_exclude():
def foo(a, b, request):
pass
assert get_arguments(foo, ['request']) == {'a': None, 'b': None}
def test_argument_and_explicit_converters_none_defaults():
class MyConverterRegistry(ConverterRegistry):
def converter_for_type... |
dtrip/wafw00f | setup.py | Python | bsd-3-clause | 940 | 0 | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='wafw00f',
version=__import__('wafw00f | ').__version__,
description=('WAFW00F identifies and fingerprints '
'Web Application Firewall (WAF) products.'),
author='sandrogauci',
author_email='sandro@enablesecurity.com',
license='BSD License',
url='https://github.com/sandrogauci/wafw00f',
packages=find_packages(),
scr... | 'dev': [
'prospector==0.10.1',
],
'test': [
'httpretty==0.8.10',
'coverage==3.7.1',
'coveralls==0.5',
'python-coveralls==2.5.0',
'nose==1.3.6',
],
'docs': [
'Sphinx==1.3.1',
],
},
test_... |
Seekatar/GpioPlayground | UsbReadWrite/HttpServerDumper.py | Python | mit | 1,207 | 0.017399 | import http.server
import socketserver
import webbrowser as web
from urllib.parse import urlparse
import serial
import time
alertMsg = bytearray([2,0,0,0])
path = "C:\\code\\GpioPlayground\\UsbReadWrite\\" # need trailing slash
class GetHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
| parsed_path = urlparse(self.pa | th)
print( "Headers are ",self.headers)
print( "Parsed path is",parsed_path.path)
self.send_response(200)
self.end_headers()
self.wfile.write("ok".encode())
return
def do_POST(self):
parsed_path = urlparse(self.path)
print( "Headers are ",self.he... |
TalkingData/owl | src/controller/scripts/actions/send_tencent_sms.py | Python | apache-2.0 | 5,749 | 0.003192 | #! /usr/bin/env python2
# encoding:utf-8
# python 2.7 测试通过
# python 3 更换适当的开发库就能使用,在此我们不额外提供
import httplib
import json
import hashlib
import random
import time
import argparse
class SmsSingleSender:
""" 单发类定义"""
appid = 0
appkey = ""
url = "https://yun.tim.qq.com/v5/tlssmssvr/sendsms"
template = ... | "result": 0,
"errmsg": "OK",
"ext": "",
"sid": "xxxxxxx",
"fee": 1
}
"""
rnd = self.util.get_random()
cur_time = self.util.get_cur_time()
data = {}
tel = {"nationcode": nation_code, "mobile": ph... | ndom=" + str(rnd)
+ "&time=" + str(cur_time) + "&mobile=" + phone_number).hexdigest()
data["time"] = cur_time
data["extend"] = extend
data["ext"] = ext
whole_url = self.url + "?sdkappid=" + str(self.appid) + "&random=" + str(rnd)
result = se... |
staneyffer/cnsoft_image | app/api_1_0/images.py | Python | mit | 2,522 | 0.027071 | # -*- coding: utf-8 -*-
from flask import jsonify, request, g, abort, url_for, current_app
from ..models import Img, Permission
from . import api
from .decorators import permission_required
from .errors import bad_request
from ..img.tag_image import up_R_Img_Label
'''
@api.route('/images/')
#@auth.login_required
def ... | ired(Permission.TAGS)
def tag_image(id):
if(request.json is None):
return | bad_request('没有标签信息')
image = Img.query.get_or_404(id)
if image.accepted:
return bad_request('该图片不能修改')
image.tag_from_json(g.current_user, request.json)
up_R_Img_Label()
return jsonify(image.to_json())
@api.route('/modify-images/<int:id>', methods=['PUT'])
@permission_required(Permission.TAGS)
def modify_image... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.