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 |
|---|---|---|---|---|---|---|---|---|
EUDAT-B2SHARE/invenio-old | modules/miscutil/lib/mailutils.py | Python | gpl-2.0 | 17,746 | 0.00231 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012 CERN.
##
## Invenio 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
## ... | toaddr = ','.jo | in(toaddr)
if not isinstance(replytoaddr, (unicode, str)):
replytoaddr = ','.join(replytoaddr)
toaddr = remove_temporary_emails(toaddr)
if user is None:
user = fromaddr
if other_bibtasklet_arguments is None:
other_bibtasklet_arguments = []
else:
other_bibtasklet_arg... |
dita-programming/dita-access | view/ui_sign_in.py | Python | gpl-2.0 | 6,113 | 0.014068 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'sign_in.ui'
#
# Created: Mon Jun 22 00:34:42 2015
# by: PyQt5 UI code generator 5.2.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_sign_inDialog(object):
def setupUi... | reject)
QtCore.QMetaObject.connectSlotsByName(sign_inDialog)
def retranslateUi(self, sign_inDialog):
_translate = QtCore.QCoreApplication.tra | nslate
sign_inDialog.setWindowTitle(_translate("sign_inDialog", "Sign In Dialog"))
self.lb_serial.setText(_translate("sign_inDialog", "Serial No."))
self.lb_id.setText(_translate("sign_inDialog", "ID No."))
self.cbx_laptop.setText(_translate("sign_inDialog", "No laptop?"))
|
bitmazk/django-libs | django_libs/tests/widget_tests.py | Python | mit | 488 | 0 | """Tests for the widgets of the ``django_libs`` app."""
fro | m django.test import TestCase
from ..widgets import ColorPickerWidget
class ColorPickerWidgetTestCase(TestCase):
"""Tests for the ``ColorPickerWidget`` widget."""
longMessage = True
def setUp(self):
self.widget = ColorPickerWidget()
def test_render_tag(self):
self.assertIn('value="f... | input form.'))
|
vabs22/zulip | zilencer/views.py | Python | apache-2.0 | 4,479 | 0.003572 | from __future__ import absolute_import
from django.utils.translation import ugettext as _
from django.utils import timezone
from django.http import HttpResponse, HttpRequest
from zilencer.models import Deployment, RemotePushDeviceToken, RemoteZulipServer
from zerver.decorator import has_request_variables, REQ
from z... | er,
kind=token_kind,
token=token,
defaults=dict(
ios_app_id=ios_app_id,
last_updated=timezone.now()))
return json_success()
@has_request_variables
def remote_server_ | unregister_push(request, entity, token=REQ(),
token_kind=REQ(validator=check_int), ios_app_id=None):
# type: (HttpRequest, Union[UserProfile, RemoteZulipServer], bytes, int, Optional[Text]) -> HttpResponse
validate_bouncer_token_request(entity, token, token_kind)
server = c... |
matthieu-meaux/DLLM | modules/DLLM/DLLMKernel/DLLMMesh.py | Python | gpl-2.0 | 3,858 | 0.023587 | # -*-mode: python; py-indent-offset: 4; tab-width: 8; coding: iso-8859-1 -*-
# DLLM (non-linear Differentiated Lifting Line Model, open source software)
#
# Copyright (C) 2013-2015 Airbus Group SAS
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Pub... | et_grad_active(self):
return self.__LLW.get_grad_active()
def get_K(sel | f):
return self.__K
def get_dK_dchi(self):
return self.__dK_dchi
#-- Methods
def recompute(self):
self.__N = self.get_geom().get_n_sect()
# Set computational geometry
self.__K = None
self.__dK_dchi = None
self.__setGeom()
... |
Azure/azure-sdk-for-python | sdk/eventhub/azure-eventhub/tests/livetest/synctests/test_reconnect.py | Python | mit | 4,935 | 0.003647 | #-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#--------------------------------------------------------------------------
import time... | fault", "0", "-1", on_event_received)
with consumer:
consumer._open()
time.sleep(11)
ed = EventData("Event")
senders[0].send(ed)
consumer._handler.do_work()
assert consumer._handler._connection._state == c_uamqp.ConnectionState.DISCARDING... | sumer.receive()
time.sleep(0.01)
now_time = time.time()
assert on_event_received.event.body_as_str() == "Event"
|
summer-liu/events_cache_scripts | report/cache10.py | Python | mit | 9,568 | 0.000941 | from pymongo import MongoClient
import multiprocessing
import threading
import datetime
import time
cache = MongoClient(host='10.8.8.111', port=27017, connect=False)['cache25']
db30 = MongoClient(host='10.8.8.111', port=27017, connect=False)['onionsBackupOnline']
events = db30['events']
userAttr = cache['userAttr']
d... | _event, allowDiskUse=True))
if len(event_flow):
eventFlow.insert_many(event_flow)
# deviceAttr: device, activateDate, recentSession, platform, users
pipeline_device = [
{
"$match": | {
# "platform2": {"$in": mobile},
"platform": {"$in": ["web", "app"]},
"device": {"$exists": True, "$nin": ["", None]},
"serverTime": {"$gte": start_time, "$lt": end_time}
}
},
... |
dnxbjyj/python-basic | concurrence/multi_threading.py | Python | mit | 4,446 | 0.007172 | # coding:utf-8
# 测试多线程
import threading
import time
from utils import fn_timer
from multiprocessing.dummy import Pool
import requests
from utils import urls
# 耗时任务:听音乐
def music(name):
print 'I am listening to music {0}'.format(name)
time.sleep(1)
# 耗时任务:看电影
def movie(name):
print 'I am wa... | # 创建一个线程,target参数为任务处理函数,args为任务处理函数所需的参数元组
threads.append(threading.Thread(target = music,args = (i,)))
for i in range(2):
threads.append(threading.Thread(target = movie,args = (i,)))
for t in threads:
# 设为守护线程
t.setDaemon(True)
# | 开始线程
t.start()
for t in threads:
t.join()
# 使用线程池执行:听10首音乐,看2部电影
@fn_timer
def use_pool():
# 设置线程池大小为20,如果不设置,默认值是CPU核心数
pool = Pool(20)
pool.map(movie,range(2))
pool.map(music,range(10))
pool.close()
pool.join()
# 应用:使用单线程下载多个网页的内容
@fn_timer
def download_... |
bianchimro/django-search-views | sample_app/manage.py | Python | mit | 808 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "_ | _main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sample_app.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid ... | 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
... |
jamalex/kolibri | kolibri/tasks/management/commands/base.py | Python | mit | 2,905 | 0.000688 | from collections import namedtuple
from django.core.management.base import BaseCommand
from tqdm import tqdm
Progress = namedtuple(
'Progress',
[
'progress_fraction',
'message',
'extra_data',
'level',
]
)
class ProgressTracker():
def __init__(self, total=100, level=0... | self.update_callback = update_callback
# initialize the tqdm pr | ogress bar
self.progressbar = tqdm(total=total)
def update_progress(self, increment=1, message="", extra_data=None):
self.progressbar.update(increment)
self.progress += increment
self.message = message
self.extra_data = extra_data
if callable(self.update_callbac... |
benhoff/ava | src/manage.py | Python | gpl-3.0 | 246 | 0 | #!/usr/bin/env python
import os
| import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ava. | settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
ovcrash/geoip-attack-map | DataServer/const.py | Python | gpl-3.0 | 1,888 | 0.039725 | META = [{
'lookup': 'city',
'tag': 'city',
'path': ['names','en'],
},{
'lookup': 'continent',
'tag': 'continent',
'path': ['names','en'],
},{
'lookup': 'continent_code',
'tag': 'continent',
'path': ['code'],
},{
'loo... | ath': ['iso_code'],
},{
'lookup': 'latitude',
'tag': 'location',
'path': ['latitude'],
},{
'lookup': 'longitude',
'tag': 'location',
'path': ['longitude'],
},{
'lookup': 'metro_code',
'tag': 'location',
'path': ['metro_code'... | p': 'postal_code',
'tag': 'postal',
'path': ['code'],
}]
PORTMAP = {
0:"DoS", # Denial of Service
1:"ICMP", # ICMP
20:"FTP", # FTP Data
21:"FTP", # FTP Control
22:"SSH", # SSH
23:"TELNET", # Telnet
25:"EMAIL", # SMTP
43:"W... |
wettenhj/mytardis-swift-uploader | openrc.py | Python | bsd-3-clause | 994 | 0.001006 | #!/usr/bin/python
import os
# With the addition of Keystone, to use an openstack cloud you should
# authenticate against keystone, which returns a **Token** and **Service
# Catalog**. The catalog contains the endpoint for all services the
# user/tenant has access to - including nova, glance, keystone, swift.
#
# *NO... | pass the keystone password.
os.environ['OS_PASSWORD'] = "???????????????????? | "
|
zsjohny/jumpserver | apps/assets/api/node.py | Python | gpl-2.0 | 8,992 | 0.00045 | # ~*~ coding: utf-8 ~*~
from collections import namedtuple
from rest_framework import status
from rest_framework.serializers import ValidationError
from rest_framework.response import Response
from django.utils.translation import ugettext_lazy as _
from django.shortcuts import get_object_or_404, Http404
from common.u... | t = [node.as_tree_nod | e() for node in queryset]
queryset = self.add_assets_if_need(queryset)
queryset = sorted(queryset)
return queryset
def add_assets_if_need(self, queryset):
include_assets = self.request.query_params.get('assets', '0') == '1'
if not include_assets:
return queryset
... |
tickbg/skaer | naming/test_parser.py | Python | gpl-3.0 | 2,913 | 0.00309 | import parser
import unittest
import sys
class TestVideoParser(unittest.TestCase):
def test_parse_video(self):
if sys.platform.startswith('win'):
path = '\\server\\Movies\\Brave (2007)\\Brave (2006).mkv'
else:
path = '/server/Movies/Brave (2007)/Brave (2006).mkv'
vi... | = (
"Bad Boys (2006).part1.stv.unrated.multi.1080p.bluray.x264-rough.mkv",
"Bad Boys (2006).part2.stv.unrated.multi.1080p.bluray.x264-rough.mkv",
"Bad Boys (2006).part3.stv.unrated.multi.1080p.blu | ray.x264-rough.mkv",
"Bad Boys (2006).part4.stv.unrated.multi.1080p.bluray.x264-rough.mkv",
"Bad Boys (2006)-trailer.mkv"
)
stack = parser.parse_video_stack(files)
print(stack)
self.assertEqual(len(stack), 1)
#TestStackInfo(result.Stacks[0], "Bad Boys (200... |
incuna/feincms-extensions | feincms_extensions/render_json.py | Python | bsd-2-clause | 1,559 | 0.000641 | from django.core import checks
from feincms import extensions
class Extension(extensions.Extension):
def handle_model(self):
cls = self.model
def render_json(self, request):
"""Render the feincms regions into a dictionary."""
def region_data(region):
conte... | ave a `.json` method."""
message = (
'Feincms content has no `json` method, but the ' +
'`render_json` extension is acti | ve for model `{}`.'
).format(cls)
for content_type in cls._feincms_content_types:
if not hasattr(content_type, 'json'):
yield checks.Error(
message,
obj=content_type,
id='feincms_extension... |
leppa/home-assistant | homeassistant/components/pi_hole/sensor.py | Python | apache-2.0 | 2,321 | 0.000431 | """Support for getting statistical data from a Pi-hole system."""
import logging
from homeassistant.helpers.entity import Entity
from .const import (
ATTR_BLOCKED_DOMAINS,
DOMAIN as PIHOLE_DOMAIN,
SENSOR_DICT,
SENSOR_LIST,
)
LOGGER = logging.getLogger(__name__)
async def async_setup_platform(hass, ... | he pi-hole sensor."""
if discovery_info is None:
return
sensors = []
for | pi_hole in hass.data[PIHOLE_DOMAIN].values():
for sensor in [
PiHoleSensor(pi_hole, sensor_name) for sensor_name in SENSOR_LIST
]:
sensors.append(sensor)
async_add_entities(sensors, True)
class PiHoleSensor(Entity):
"""Representation of a Pi-hole sensor."""
def __... |
appsembler/edx-platform | openedx/core/djangoapps/user_api/accounts/tests/test_views.py | Python | agpl-3.0 | 46,567 | 0.002966 | # -*- coding: utf-8 -*-
"""
Test cases to cover Accounts-related behaviors of the User API application
"""
import datetime
import hashlib
import json
from copy import deepcopy
import unittest
import ddt
import mock
import pytz
import six
from django.conf import settings
from django.test.testcases import TransactionT... | on_data, content_type="application/merge-patch+json", expected_status=200):
"""
Helper method for sending a patch to the server, defaulting to application/merge-patch+json content_type.
Verifies the expected status and returns the response.
"""
# pylint: disable=no-member
... | .dumps(json_data), content_type=content_type)
self.assertEqual(expected_status, response.status_code)
return response
def send_get(self, client, query_parameters=None, expected_status=200):
"""
Helper method for sending a GET to the server. Verifies the expected status and returns t... |
andyneff/voxel-globe | voxel_globe/ingest/views.py | Python | mit | 4,787 | 0.022143 | import distutils.dir_util
import os
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
### Rest API setup
import rest_framework.routers
import rest_framework.viewsets
import rest_framework.filters
import... | PES[uploadSession.metadata_type].ingest.s(uploadSession_id, imageDir)
task3 = voxel_globe.ingest.tasks.cleanup.si(uploadSession_id)
tasks = task0 | task1 | task2 | task3 #create chain
result = tasks.apply_async()
return render(request, 'ingest/html/ingest_started.html',
{'task_ | id':result.task_id})
|
lukeroge/CloudbotX | plugins/help.py | Python | gpl-3.0 | 2,905 | 0.002754 | import asyncio
import re
from operator import attrgetter
from stratus.loader import hook
plugin_info = {
"plugin_category": "core",
"command_category_name": "Informational"
}
@asyncio.coroutine
@hook.command("help", autohelp=False)
def help_command(text, conn, bot, notice, has_permission):
"""[command] ... | # check permissions
allowed = False
| for perm in plugin.permissions:
if has_permission(perm, notice=False):
allowed = True
break
if not allowed:
# skip adding this command
continue
# add the command to lin... |
jhamman/pyresample | pyresample/test/test_plot.py | Python | lgpl-3.0 | 3,440 | 0.002907 | import unittest
import os
import numpy as np
from pyresample import plot, geometry, utils, kd_tree
try:
import matplotlib
matplotlib.use('Agg')
except ImportError:
pass # Postpone fail to individual tests
def tmp(f):
f.tmp = True
return f
class Test(unittest.TestCase):
filename = os.pat... | th.join(os.path.dirname(__file__),
'test_files', 'areas.cfg'), 'ease_sh')[0]
swath_def = geometry.SwathDefinition(self.lons, self.lats)
result = kd_tree.resample_nearest(swath_def, self.tb37v, area_def,
radiu... | (self):
area_def = utils.parse_area_file(os.path.join(os.path.dirname(__file__),
'test_files', 'areas.cfg'), 'ortho')[0]
swath_def = geometry.SwathDefinition(self.lons, self.lats)
result = kd_tree.resample_nearest(swath_def, self.tb37v, area_... |
mancoast/CPythonPyc_test | crash/265_test_re.py | Python | gpl-3.0 | 37,806 | 0.003095 | import sys
sys.path = ['.'] + sys.path
from test.test_support import verbose, run_unittest
import re
from re import Scanner
import sys, os, traceback
from weakref import proxy
# Misc tests from Tim Peters' re.doc
# WARNING: Don't change details in these tests if you don't know
# what you're doing. Some of these test... | ertEqual(re.sub('(.)', re.escape(s), 'x'), s)
self.assertEqual(re.sub('(.)', lambda m: s, 'x'), s)
self.assertEqual(re.sub('(?P<a>x)', '\g<a>\g<a>', 'xx'), 'xxxx')
self.assertEqual(re.sub('(?P<a>x)', '\g<a>\g<1>', 'xx'), 'xxxx')
| self.assertEqual(re.sub('(?P<unk>x)', '\g<unk>\g<unk>', 'xx'), 'xxxx')
self.assertEqual(re.sub('(?P<unk>x)', '\g<1>\g<1>', 'xx'), 'xxxx')
self.assertEqual(re.sub('a',r'\t\n\v\r\f\a\b\B\Z\a\A\w\W\s\S\d\D','a'),
'\t\n\v\r\f\a\b\\B\\Z\a\\A\\w\\W\\s\\S\\d\\D')
self.assertE... |
hotpxl/mxnet | tests/python/train/test_autograd.py | Python | apache-2.0 | 2,949 | 0.00373 | # pylint: skip-file
from __future__ import print_function
import mxnet as mx
from mxnet import gluon
from mxnet.gluon import nn
import numpy as np
import logging
fro | m common import get_data
from mxnet import autograd
logging.basicConfig(level=logging.DEBUG)
# define network |
def get_net():
net = nn.Sequential()
net.add(nn.Dense(128, activation='relu', prefix='fc1_'))
net.add(nn.Dense(64, activation='relu', prefix='fc2_'))
net.add(nn.Dense(10, prefix='fc3_'))
return net
get_data.GetMNIST_ubyte()
batch_size = 100
train_data = mx.io.MNISTIter(
image="data/train... |
Yelp/kafka-utils | tests/util/zookeeper_test.py | Python | apache-2.0 | 15,746 | 0.000889 | # -*- coding: utf-8 -*-
# Copyright 2016 Yelp 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 ... | _topic',
True,
)
def test_get_my_subscribed_partitions(self, _):
with mock.patch.object(
ZK,
'get_children',
autospec=True,
) as mock_children:
with ZK(self.cluster_config) as zk:
zk.get_my_subscribe... | 'some_topic',
)
mock_children.assert_called_once_with(
zk,
'/consumers/some_group/offsets/some_topic',
)
def test_get_topic_config(self, mock_client):
with ZK(self.cluster_config) as zk:
zk.zk.get = mo... |
ronekko/chainer | tests/chainer_tests/test_link.py | Python | mit | 71,956 | 0.00025 | import copy
import unittest
import warnings
import mock
import numpy
import chainer
from chainer.backends import cuda
from chainer.backends import intel64
from chainer import initializers
from chainer import testing
from chainer.testing import attr
class TestLink(unittest.TestCase):
def setUp(self):
x_... | ameter)
self.assertEqual(var.name, name)
self.assertIsNone(var.data)
if initializer is not None:
self.assertIs(var.initializer, initializer)
def test_init(self):
self.check_param_init('x', (2, 3), 'd')
self.check_param_init('y', (2,), 'f')
self.check_para... | t('u', (2, 3), 'd')
self.check_param_uninit('v')
self.link.v.initialize((2, 3))
self.check_param_init('v', (2, 3), 'f')
def test_assign_param_outside_of_init_scope(self):
p = chainer.Parameter()
self.link.p = p
self.assertTrue(all(p is not param for param in self.lin... |
fmuzf/python_hk_glazer | setup.py | Python | mit | 566 | 0.008834 | from setuptools import setup, find_packages
setup(
name='hk_glazer',
version='0.0.8',
description='Convert compatible JSON configs to DeBAM/DeTIM config.dat files',
url='https://github.com/fmuzf/python_hk_glazer',
author='Ly | man Gillispie',
author_email='[email protected]',
packages=find_packages(),
scripts=['bin/hk_glazer'],
license='MIT',
long_description=open('README.md').read(),
install_requires = ['argparse'],
test_suite='nose.collector',
tests_require=['nose'],
include_pac | kage_data = True
)
|
TheTimmy/spack | var/spack/repos/builtin/packages/perl-font-ttf/package.py | Python | lgpl-2.1 | 1,567 | 0.001914 | ##############################################################################
# Copyright (c) 2013-2016, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, [email protected], All rights reserved.
# LLNL-CODE-64... | cense along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class PerlFontTtf(PerlPackage):
"""Perl module for TrueType Font hacking"""... | /Font/TTF.pm"
url = "http://search.cpan.org/CPAN/authors/id/B/BH/BHALLISSY/Font-TTF-1.06.tar.gz"
version('1.06', '241b59310ad4450e6e050d5e790f1b21')
|
agx/git-buildpackage | gbp/format.py | Python | gpl-2.0 | 2,429 | 0.000824 | # vim: set fileencoding=utf-8 :
#
# (C) 2014 Guido Günther <[email protected]>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; eith | er version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more ... | ee
# <http://www.gnu.org/licenses/>
"""Format a message"""
from gbp.errors import GbpError
def format_str(msg, args):
"""
Format a string with the given dict. Be a bit more verbose than
default python about the error cause.
>>> format_str("%(foo)", {})
Traceback (most recent call last):
.... |
AnshulYADAV007/Lean | Algorithm.Python/OptionDataNullReferenceRegressionAlgorithm.py | Python | apache-2.0 | 1,485 | 0.007417 | # QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# 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 Lice... | ("DUST")
| option = self.AddOption("DUST")
option.SetFilter(self.UniverseFunc)
def UniverseFunc(self, universe):
return universe.IncludeWeeklys().Strikes(-1, +1).Expiration(timedelta(25), timedelta(100))
|
kalaspa/mc-eliece | src/arith.py | Python | gpl-3.0 | 891 | 0.042745 | #*-coding:Utf-8 -*
#!/usr/bin/python3.2
"""Fichier contenant la classe generale d'objet algébriques contenant + * et eventuellement /"""
class arith(object):
"""Classe generique contenant les methodes redondantes"""
def __ne__(self,autre):
"""Definition de !="""
return not(self == autre)
def __radd__(self,au... | """Methode de *="""
return self * autre
def __sub__(self,autre):
"""Methode de soustraction"""
return self + (-1 * autre)
def __rsub__(self,autre):
"""Methode de soustraction dans l'autre sens"""
return autre +(-1 * self)
def __neg__(self):
"""Methode de p | assage a l'opposé"""
return -1 * self |
tonybreak/Registered | plugins/csdn.py | Python | gpl-3.0 | 675 | 0.001481 | # coding: utf-8
from common import base
class Plugin(base.BASE):
__name__ = 'csdn'
__title__ = 'CSDN'
__url__ = 'http://www.csdn.net/'
def regist | er(self, target):
self.information = {
'email': {
'url': 'http://passport.csdn.net/account/register',
| 'method': 'get',
'settings': {
'params': {
'action': 'validateEmail',
'email': target
}
},
'result': {
'type': 'str',
'value': 'false'
... |
mozilla/mozilla-ignite | apps/awards/views.py | Python | bsd-3-clause | 2,471 | 0 | from awards.forms import AwardForm
from awards.models import JudgeAllowance
from awards.models import Award
from challenges.decorators import judge_required
from challenges.models import Submission
from django.contrib import messages
from django.http import Http404, HttpResponseRedirect
from django.views.decorators.htt... | _award = (judge_allowance.submissionaward_set
.filter(submission=submission))
if submission_award:
submission_award. | delete()
message = _("You have successfuly removed the award from this"
" submission")
messages.success(request, message)
return HttpResponseRedirect(submission.get_absolute_url())
if is_allocated:
message = _("You have succ... |
e-gob/plataforma-kioscos-autoatencion | scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/modules/cloud/amazon/lambda_policy.py | Python | bsd-3-clause | 13,776 | 0.00363 | #!/usr/bin/python
# Copyright (c) 2016, Pierre Jodouin <[email protected]>
# Copyright (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
... | 'function_arn']
state:
description:
- Describes the desired state.
required: true
default: "present"
choices: ["present", "absent"]
alias:
description:
- Name of the function alias. Mutually exclusive with C(version).
version:
description:
- Version of the Lambda func... | d']
action:
description:
- "The AWS Lambda action you want to allow in this statement. Each Lambda action is a string starting with
lambda: followed by the API name (see Operations ). For example, lambda:CreateFunction . You can use wildcard
(lambda:* ) to grant permission for all AWS La... |
VagosAplas/GEO1005-Fire | SpatialDecision/utility_functions.py | Python | gpl-2.0 | 32,661 | 0.003827 | # -*- coding: utf-8 -*-
"""
/***************************************************************************
SpatialDecision
A QGIS plugin
This is a SDSS template for the GEO1005 course
-------------------
begin : 2015-11-02
git... | features = layer.selectedFeatures()
else:
request = QgsFeatureRequest().setSubsetOfAttributes([getFieldIndex(layer, fieldname)])
features = layer.getFeatures(request)
if null:
for feature in features:
attributes.append(feature.attribute(fieldname))
... | ULL:
attributes.append(val)
ids.append(feature.id())
return attributes, ids
def addFields(layer, names, types):
# types can be QVariant.Int, QVariant.Double, QVariant.Str |
tchellomello/home-assistant | homeassistant/components/demo/sensor.py | Python | apache-2.0 | 2,682 | 0.001119 | """Demo platform that has a couple of fake sensors."""
from homeassistant.const import (
ATTR_BATTERY_LEVEL,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_TEMPERATURE,
PERCENT | AGE,
TEMP_CELSIUS,
)
from homeas | sistant.helpers.entity import Entity
from . import DOMAIN
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Demo sensors."""
async_add_entities(
[
DemoSensor(
"sensor_1",
"Outside Temperature",
... |
project-chip/connectedhomeip | scripts/tools/memory/memdf/util/pretty.py | Python | apache-2.0 | 957 | 0 | #
# Copyright (c) 2021 Project CHIP Authors
#
# 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 i... | level):
for line in pprint.pformat(x).split('\n'):
logging.log(level, line)
def info(x: Any) - | > None:
log(logging.INFO, x)
def debug(x: Any) -> None:
log(logging.DEBUG, x)
|
TeddyDesTodes/pyflipdot | pyflipdot/web/admin/__init__.py | Python | bsd-3-clause | 559 | 0.003578 | from flask import render_template
from pyflipdot.plugins import get_pluginmanager
from pyflipdot.web.view import MenuFlaskView
__author__ = 'teddydestodes'
class AdminView(MenuFlaskVi | ew):
route_base = "admin"
menu_name = "Admin"
def index(self):
return render_template('base.html')
class PluginView(MenuFlaskView):
route_base = "plugins"
menu_name = "Plugins"
def index(self):
pm = get_pluginmanager()
return render_templat | e('plugins.html', plugins=pm.get_plugin_index())
AdminView.plugins = PluginView
|
u-engine/UIforETW | bin/ETWPackSymbols.py | Python | apache-2.0 | 4,627 | 0.016425 | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | "[RSDS] PdbSig: {7b2a9028-87cd-448d-8500-1a18cdcf6166}; A | ge: 753; Pdb: u:\buildbot\dota_staging_win32\build\src\game\client\Release_dota\client.pdb"
scan = re.compile(r' 0x(.*), 0x(.*), "(.*)", "\[RSDS\].*; Pdb: (.*)"')
matchCount = 0
matchExists = 0
ourModuleCount = 0
# Get the users build directory
vgame = os.getenv("vgame")
if vgame == None:
print("... |
uezo/minette-python | minette/serializer.py | Python | apache-2.0 | 6,581 | 0 | import json
from datetime import datetime
import re
from .utils import date_to_str, str_to_date
def _is_datestring(s):
return isinstance(s, str) and \
re.match(r"(\d{4})-(\d{2})-(\d{2})T(\d{2})\:(\d{2})\:(\d{2})", s)
def _encode_datetime(obj):
if isinstance(obj, datetime):
return date_to_str... |
def __repr__(self):
return "<{} at {}>\n{}".format(
self.__class__.__name__,
hex(id(self)),
self.to_json(indent=2, ensure_ascii=F | alse))
@classmethod
def create_object(obj_cls, d):
return obj_cls()
def to_dict(self):
"""
Convert this object to dict
Returns
-------
d : dict
Object as dict
"""
return dumpd(self)
def to_json(self, **kwargs):
"""
... |
ee-book/api | api/v1/users.py | Python | apache-2.0 | 416 | 0.004808 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from ..lib.decorators import json
from . import api
@api.route("/test", methods=["GET"])
@json
def test():
return {}
@api.route("/auth/register", ... | return {}
@api.route("/auth/exist", methods=["get"])
| |
chanceraine/nupic.research | tests/classification/test_sensor_data_classification.py | Python | agpl-3.0 | 7,592 | 0.004478 | #!/usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2015, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions ... | upEnabled):
self.assertEqual(predictionAccuracy, 100.00)
elif (noiseAmplitude == 1.0
and signalMean == 1.0
and signalAmplitude == 1.0
and signalPeriod == 20.0
and classifierType == CLA_CLASSIFIER_TYPE
... | and not upEnabled):
# using AlmostEqual until the random bug issue is fixed
self.assertAlmostEqual(predictionAccuracy, 80, delta=1)
elif (noiseAmplitude == 1.0
and signalMean == 1.0
and signalAmplitude == 1.0
... |
duaraghav8/Corque | demo.py | Python | mit | 2,535 | 0.013807 | import os
# We'll render HTML templates and access data sent by POST
# using the request object from flask. Redirect and url_for
# will be used to redirect the user once the upload is done
# and send_from_directory will help us to send/show on the
# browser the file that the user just uploaded
from flask import Flask, ... | we are accepting to be uploaded
app. | config['ALLOWED_EXTENSIONS'] = set(['png', 'jpg', 'jpeg'])
# For a given file, return whether it's an allowed type or not
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']
# This route will show a form to perform an AJAX request
# jQ... |
comic/comic-django | app/grandchallenge/evaluation/serializers.py | Python | apache-2.0 | 1,856 | 0 | from django.contrib.auth import get_user_model
from rest_framework.fields import CharField
from rest_framework.serializers import ModelSerializer
from grandchallenge.challenges.models import Challenge
from grandchallenge.components.serializers import (
ComponentInterfaceValueSerializer,
)
from grandchallenge.evalu... | "phase",
"created",
"creator",
"comment",
"predictions_file",
"supplementary_file",
"supplementary_url",
)
class EvaluationSerializer(ModelSerializer):
submission = SubmissionSerializer()
outputs = ComponentInterfaceValue... | us = CharField(source="get_status_display", read_only=True)
title = CharField(read_only=True)
class Meta:
model = Evaluation
fields = (
"pk",
"method",
"submission",
"created",
"published",
"outputs",
"rank",
... |
vileopratama/vitech | src/addons/delivery/__openerp__.py | Python | mit | 886 | 0 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Delivery Costs',
'version': '1 | .0',
'category': 'Stock',
'description': """
Allows you to add delivery methods in sale orders and picking.
==============================================================
You can define your own carrier for prices. When creating
invoices from picking, the system is able to add and compute the shipping lin | e.
""",
'depends': ['sale_stock'],
'data': [
'security/ir.model.access.csv',
'views/delivery_view.xml',
'views/partner_view.xml',
'data/delivery_data.xml',
'views/report_shipping.xml',
'views/report_deliveryslip.xml'
],
'demo': ['data/delivery_demo.xml'],... |
Unofficial-Extend-Project-Mirror/openfoam-extend-Breeder-other-scripting-PyFoam | unittests/Basics/test_TemplateFile.py | Python | gpl-2.0 | 7,289 | 0.019207 | import unittest
from PyFoam.Basics.TemplateFile import TemplateFile,TemplateFileOldFormat,PyratempPreprocessor
from PyFoam.Error import FatalErrorPyFoamException
from tempfile import mktemp
from PyFoam.ThirdParty.six import PY3
import sys
theSuite=unittest.TestSuite()
template1="""$$ y = 3+x
This should be $x+y$"... | # Does not work with old nose
# with self.assertRaises(FatalErrorPyFoamException):
# p("$$ a ")
self.assertEqual(p("$$ a=2\n"),'$!setvar("a", "2")!$#!\n')
self.assertEqual(p("$$ a=2\n$$ | b=3"),'$!setvar("a", "2")!$#!\n$!setvar("b", "3")!$#!')
self.assertEqual(p(" $foo$ $bar$ ")," $foo$ $bar$ ")
self.assertEqual(p("$foo$ $bar$"),"$foo$ $bar$")
self.assertEqual(p("$foo$ $bar$\n"),"$foo$ $bar$\n")
theSuite.addTest(unittest.makeSuite(PyratempPreprocessorTest,"test"))
|
earies/jvpn | jvpn/netstats.py | Python | apache-2.0 | 1,247 | 0.020048 | """JVPN netstats libraries
"""
__author__ = '[email protected] (Ebben Aries)'
import socket
import struct
def GetNetstats(device):
device = device + ':'
for line in open('/proc/net/dev', 'r'):
data = filter(None, line.split(' '))
if data[0] == device:
return (data[1], data[2], data[9], data[10])
def Get... | ne.split()[7], 16)))
route_detail = '%s/%s:%d' % (prefix, netmask, metric)
routes.append(route_detail)
return routes
def GetIp(device):
ip = ''
for line in open('/proc/net/route', 'r'):
if line.startswith(device):
ip = socket.inet_ntoa(struct.pack('<L', int(line.split()[2] | , 16)))
break
return ip
def GetDefInterface(interface='eth0', gateway='0.0.0.0'):
for line in open('/proc/net/route', 'r'):
if line.split()[1] == '00000000' and line.split()[7] == '00000000':
interface = line.split()[0]
gateway = socket.inet_ntoa(struct.pack('<L', int(line.split()[2], 16)))
... |
danisuke0781/instant-press | languages/nl.py | Python | gpl-2.0 | 14,840 | 0.021972 | # coding: utf8
{
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" is een SQL-expressie zoals "field1=\'newvalue\'". U kunt de resultaten van een JOIN niet updaten of wissen',
'%Y-%m-%d': '%Y-%m-%d',
'%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S'... | t': 'Copyright',
'Create new article': 'Maak nieuw artikel',
'Curre | nt request': 'Huidige request',
'Current response': 'Huidige response',
'Current session': 'Huidige session',
'DB Model': 'DB Model',
'Database': 'Database',
'Delete:': 'Wis:',
'Description': 'Omschrijving',
'E-mail': 'E-mail',
'Edit': 'Verander',
'Edit This App': 'Pas deze App aan',
'Edit current record': 'P... |
FedoraScientific/salome-smesh | doc/salome/examples/filters_ex01.py | Python | lgpl-2.1 | 1,332 | 0.016517 | # Aspect ratio
# create mesh
from SMESH_mechanic import *
# get faces with aspect ratio > 1.5
filter = smesh.GetFilter(SMESH.FACE, SMESH.FT_AspectRatio, SMESH.FT_MoreThan, 1.5)
ids = mesh.GetIdsFromFilter(filter)
print "Number of faces with aspect ratio > 1.5:", len(ids)
# copy the faces with aspect ratio > 1.5 to a... | es with Aspect Ratio < 1.5;
# note that contents of a GroupOnFilter is dynamically updated as the mesh changes
crit = [ smesh.GetCriterion( SMESH.FACE, SMESH.FT_AspectRatio, '<', 1.5, BinaryOp=SMESH.FT_LogicalAND ),
smesh.GetCriterion( SMESH.FACE, SMESH.FT_ElemGeomType,'=', SMESH.Geom_TRIANGLE ) ]
filter = sme... | t )
triaGroup = mesh.GroupOnFilter( SMESH.FACE, "Tria AR < 1.5", filter )
print "Number of triangles with aspect ratio < 1.5:", triaGroup.Size()
|
kagel/foobnix | foobnix/gui/about/about.py | Python | gpl-3.0 | 1,313 | 0.008397 | # -*- coding: utf-8 -*-
'''
Created on Oct 2, 2010
@author: dimitry (zavlab1)
'''
from gi.repository import Gt | k
from gi.repository import Gdk
from foobnix.gui.service.path_service import get_foobnix_resourse_path_by_name
from foobnix.util.const import ICON_FOOBNIX
from foobnix.version import FOOBNIX_VERSION
class AboutWindow(Gtk.AboutDialog):
def __init__(self):
Gtk.AboutDialog.__init__(self)
self... | [email protected]>")
self.set_comments(_("Simple and Powerful player"))
self.set_website("http://www.foobnix.com")
self.set_authors(["Dmitry Kozhura (zavlab1) <[email protected]>", "Pietro Campagnano <fain182@gmailcom>", "Viktor Suprun <[email protected]>"])
self.set_translator_cre... |
simark/simulavr | regress/test_opcodes/test_SUB.py | Python | gpl-2.0 | 3,851 | 0.027266 | #! /usr/bin/env python
###############################################################################
#
# simulavr - A simulator for the Atmel AVR family of microcontrollers.
# Copyright (C) 2001, 2002 Theodore A. Roth
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of th... | 301 USA.
#
###############################################################################
#
# $Id: test_SUB.py,v 1.1 2004/07/31 00:59:11 rivetwa Exp $
#
"""Test the SUB opcode.
"""
import base_test
from registers import Reg, SREG
class SUB_TestFail(base_test.TestFail): pass
class base_SUB(base_test.opcode_test):
... | hout Carry. [Rd <- Rd - Rr]
opcode is '0001 10rd dddd rrrr' where r and d are registers (d is destination).
Only registers PC, Rd and SREG should be changed.
"""
def setup(self):
# Set SREG to zero
self.setup_regs[Reg.SREG] = 0
# Set the register values
self.setup_regs[self.Rd] = self.Vd
self.setup_regs... |
winksaville/craftr | craftr/defaults.py | Python | gpl-3.0 | 10,759 | 0.008458 | # The Craftr build system
# Copyright (C) 2016 Niklas Rosenstein
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ... | current
module's project directory.
"""
parent = session.module.project_dir
return path.norm(rel_path, parent)
def buildlocal(rel_path):
"""
Given a relative path, returns the path (still relative) to the build
directory for the current module. This is basically a shorthand for
prepending the module ... |
"""
if path.isabs(rel_path):
return rel_path
return path.canonical(path.join(session.module.ident, rel_path))
def relocate_files(files, outdir, suffix, replace_suffix=True, parent=None):
"""
Converts a list of filenames, relocating them to *outdir* and replacing
their existing suffix. If *suffix* is... |
poppogbr/genropy | packages/test15/webpages/tools/css3make.py | Python | lgpl-2.1 | 5,203 | 0.032866 | # -*- coding: UTF-8 -*-
#
"""css3make tester"""
class GnrCustomWebPage(object):
py_requires = "gnrcomponents/testhandler:TestHandlerBase"
dojo_theme = 'tundra'
def test_1_rounded(self, pane):
sl = pane.slotBar('k,*,test,*')
sl.k.verticalSlider(value='^.k',minimum=0,maximum='30',intermedi... | t_size='8px',
lbl_position='L',lbl_transform_rotate='-90',cell_border='1px dotted gray',
lbl_width='10px'
)
sl.x.verticalSlider(value='^.x',minimum=-30,maximum=30,intermediateChanges=True,height='100px',lbl='X')
sl.y.verticalSlider(... | mum=30,intermediateChanges=True,height='100px',lbl='Y')
sl.blur.verticalSlider(value='^.blur',minimum=-30,maximum=30,intermediateChanges=True,height='100px',lbl='Blurrone')
sl.inset.checkbox(value='^.inset',label='Inset')
sl.test1.div(margin='5px', display='inline-block', border='1px solid gray'... |
AustereCuriosity/astropy | astropy/utils/tests/test_data_info.py | Python | bsd-3-clause | 1,575 | 0.00127 | # -*- coding: utf-8 -*-
# TEST_UNICODE_LITERALS
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import absolute_import, division, print_function
import pytest
import numpy as np
from ...extern import six
from ..data_info import dtype_info_name
STRING_TYPE_NAMES = {(False, 'S'): 'str... | 64'),
('<f4', 'float32'),
('u8', 'uint64'),
('c16', 'complex128'),
('object', 'object'))
@pytest.mark.parametrize('input,output', DTYPE_TESTS)
def test_dtype_info_name(input, output):
"""
Test that dtype_info_name is giving the expected output
H... | 'b' boolean
'i' (signed) integer
'u' unsigned integer
'f' floating-point
'c' complex-floating point
'O' (Python) objects
'S', 'a' (byte-)string
'U' Unicode
'V' raw data (void)
"""
assert dtype_info_name(input) == output
|
morepj/numerical-mooc | working/HelloWorld.py | Python | mit | 44 | 0 | p | rint("Greetings Earth! We come in | peace.")
|
adsabs/adsabs-pyingest | pyingest/parsers/gcncirc.py | Python | mit | 4,888 | 0.000818 | from __future__ import print_function
from __future__ import absolute_import
import re
from pyingest.config.utils import u2asc
from .default import DefaultParser
from .author_names import AuthorNames
from .entity_convert import EntityConverter
head_dict = {'TITLE:': 'journal', 'NUMBER:': 'volume', 'SUBJECT:': 'title',... | tring)
auth_string = re.sub(r'on behalf of', ',', auth_string)
auth_string = re.sub(r'reports?', ',', auth_string)
auth_string = re.sub(r'\s?:', '', auth_string)
auth_string = re.sub(r',?\s+,', ',', auth_string)
auth_a | rray = [s.strip() for s in auth_string.split(',')]
auth_array = list([a for a in auth_array if len(a) > 3])
# auth_string = u'; '.join(auth_array)
auth_string = auth_delimiter.join(auth_array)
auth_mod = AuthorNames()
# self.data_dict['authors'] = auth_mod.parse(auth_string)
... |
rtb1c13/scripts | IR_lineshapes/lmcurvefit.py | Python | gpl-2.0 | 5,749 | 0.003131 | #!/usr/bin/env python
# Author: Richard Bradshaw, [email protected]
# Module to fit various curves to provided x/y data
# Current available curves: Linear, Gaussian, Lorentzian, Voigt
# Requirements: lmfit, numpy, matplotlib (as dependencies of lmfit)
from lmfit.models import LinearModel,GaussianModel,Lorent... | y of x and y values."""
if len(data) != 2:
raise FitError("""Your data is formatted incorrectly -
it should be a 2D array of all x-,
then all y-values""")
| self.xs = data[0]
self.ys = data[1]
def __str__(self):
"""Prints lmfit fit report for the current object"""
try:
return self.fit.fit_report()
except AttributeError:
return "No fit yet performed for this object."
def linear(self, **kwargs):
"""... |
cloudbase/neutron-virtualbox | neutron/db/migration/migrate_to_ml2.py | Python | apache-2.0 | 19,607 | 0.000102 | # Copyright (c) 2014 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | ts = metadata.tables['ml2_network_segments']
engine.execute(ml2_network_segments.insert(), ml2_segments)
def migrate_tunnels(self, engine, tunnel_type, vxlan_udp_port=None):
"""Override this method to perform plugin- | specific tunnel migration."""
pass
def migrate_vlan_allocations(self, engine):
engine.execute(("""
INSERT INTO ml2_vlan_allocations
SELECT physical_network, vlan_id, allocated
FROM %(source_table)s
WHERE allocated = TRUE
""") % {'source_tabl... |
904labs/ctTrakr | nlp/simple.py | Python | mit | 764 | 0.024869 | import nltk.data
from nltk.tokenize import word_tokenize, sent_tokenize
from util import errors, cleaning
def tokenize(**kwargs):
"""Tokenize text using nltk's tokenizer."""
if 'text' in kwargs.keys():
return word_tokenize(kwargs['text'])
raise errors.CustomAPIError('No text argument found.', status_code=400,... |
def sentence_split(**kwargs):
"""Split sentences using nltk."""
tokenizer = nltk.data.load('tokenizers/punkt/dutch.pickle')
if 'text' in kwargs.keys():
cleaner = cleaning.Clean()
cleaner.feed(kwargs['text'])
cleanedText = cleaner.get_data()
return tokenizer.tokenize(cleanedText)
raise errors.CustomAP... | de=400, payload={'arguments':kwargs.keys()}) |
abramhindle/UnnaturalCodeFork | python/testdata/launchpad/lib/lp/code/interfaces/tests/test_branch.py | Python | agpl-3.0 | 2,218 | 0 | # Copyright 2009-2011 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""Tests of the branch interface."" | "
__metaclass__ = type
from bzrlib.branch import format_registry as branch_format_registry
from bzrlib.bzrdir import BzrProber
from bzrlib.repository import format_registry as repo_format_registry
from lp.code.bzr import (
BranchFormat,
ControlFormat,
RepositoryFormat,
)
import lp.codehosting # For ... | sure the launchpad format list is up-to-date.
While ideally we would ensure that the lists of markers were the same,
early branch and repo formats did not use markers. (The branch/repo
was implied by the control dir format.)
"""
def test_control_format_complement(self):
self.bzrlib_is_sub... |
lbybee/Python-for-Econ | Chap_4/scraper_example.py | Python | gpl-2.0 | 1,393 | 0 | # This script gives an example of how to scrape a webpage
import requests
from BeautifulSoup import BeautifulSoup
url = "http://chicagofoodtruckfinder.com/weekly-schedule"
truck_data_list = []
soup = BeautifulSoup(requests.post(url).text)
table = soup.find("table").findAll("tr")
days = [d.text for d in table[0].find... | for t in trucks:
time_name = t["title"]
am_spt = time_name.split("AM")
pm_spt = time_name.split("PM")
if len(pm_spt) > 1 and len(am_spt) > 1:
name = pm_spt[1]
if len(pm_spt) > 1 and len(am_spt) == 1:
... | f len(pm_spt) == 1 and len(am_spt) > 1:
name = am_spt[2]
time = time_name.replace(name, "")
truck_data_list.append({"name": name,
"time": time,
"week_day": days[i],
... |
sostenibilidad-unam/posgrado | posgradmin/posgradmin/migrations/0035_auto_20190620_1343.py | Python | gpl-3.0 | 1,049 | 0.001907 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.20 on 2019-06-20 18:43
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations | .Migration):
dependencies = [
('posgradmin', '0034_auto_20190620_1333'),
]
operations = [
migrations.RemoveField(
model_name='asignatura',
name='clave',
),
migrations.AddField(
model_name='curso',
name='clave',
fie... | =True),
),
migrations.AddField(
model_name='curso',
name='entidad',
field=models.CharField(blank=True, choices=[(3, 3), (700, 700), (800, 800)], max_length=20, null=True),
),
migrations.AlterField(
model_name='curso',
name='sede... |
tivaliy/empire-of-code | find_sequence.py | Python | gpl-2.0 | 1,551 | 0.000645 | __author__ = 'Vitalii K'
from itertools import groupby
SEQ_LENGTH = 4
def is_in_matrix(m):
len_list = [[len(list(group)) for key, group in groupby(j)] for j in m]
if any(map(lambda x: [i for i in x if i >= SEQ_LENGTH], len_list)):
return True
return False
def get_diagonals(m):
d = []
f... |
[2, 3, 1, 2, 5, 1],
[1, 1, 1, 5, 1, 4],
[4, 6, 5, 1, 3, 1],
[1, 1, 9, 1, 2, 1]
]), "Diagonal"
print("All set? Click 'Check' to review your code and earn | rewards!")
|
igudym/twango | twango/template/default/src/apps/twango_dashboard/admin.py | Python | bsd-3-clause | 83 | 0.012048 | from django.contrib import ad | min
fro | m models import *
admin.site.register(Section) |
rgayon/plaso | tests/parsers/presets.py | Python | apache-2.0 | 4,926 | 0.003045 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for parser and parser plugin presets."""
from __future__ import unicode_literals
import unittest
from plaso.containers import artifacts
from plaso.parsers import presets
from tests import test_lib as shared_test_lib
class ParserPresetTest(shared_test_lib.Bas... | f):
"""Tests the GetPresetByName function."""
test_file_path = self._GetTestFilePath(['presets.yaml'])
self._SkipIfPathNotExists(test_file_path)
test_manager = presets.ParserPresetsManager()
test_manager.ReadFromFile(test_file_path)
test_preset = test_manager.GetPresetByName('linux')
self.... | (test_preset)
self.assertEqual(test_preset.name, 'linux')
self.assertEqual(test_preset.parsers, self._LINUX_PARSERS)
test_preset = test_manager.GetPresetByName('bogus')
self.assertIsNone(test_preset)
def testGetPresetsByOperatingSystem(self):
"""Tests the GetPresetsByOperatingSystem function.""... |
rodo/cotetra | cotetra/survey/api.py | Python | agpl-3.0 | 1,782 | 0 | # -*- coding: utf-8 -*- pylint: disable-msg=R0801
#
# Copyright (c) 2013 Rodolphe Quiédeville <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either ver... | ey(StationResource, 'station_to')
class Meta:
queryset = Journey.objects.all()
resource_name = 'journey'
throttle = BaseThrottle(throttle_at=100, timeframe=60)
class ConnectionResource(ModelResource):
"""
The connections
"""
station_from = fields.ForeignKey(StationResource... | ta:
queryset = Connection.objects.all()
resource_name = 'connection'
throttle = BaseThrottle(throttle_at=100, timeframe=60)
|
ZachOhara/OCSTA-Programming-Contest-2015 | python/TestPrintLines.py | Python | gpl-3.0 | 134 | 0.014925 | lines = int(inpu | t("How many lines of text? "))
lineText = input("What is the line of text? ")
for i in range(lines):
print(lineText | ) |
Queens-Applied-Sustainability/PyRTM | rtm/test/test_cache.py | Python | gpl-3.0 | 2,536 | 0.001577 | """
Copyright (c) 2012 Philip Schliehauf ([email protected]) and the
Queen's University Applied Sustainability Centre
This project is hosted on github; for up-to-date code and contacts:
https://github.com/Queens-Applied-Sustainability/PyRTM
This file is part of PyRTM.
PyRTM is free so... | sive_fn = | lambda c: 1
# self.config = {
# 'description': 'test',
# 'longitude': -75.3,
# 'latitude': 44.22,
# 'time': datetime(2012, 1, 1, 0, 0, 0)
# }
# self.cachedconfig = {
# 'description': 'cachedtest',
# 'longitude': -75.3,
# 'latitude': 44.22,
# 'time': datetime(2012, 1, 1, 0, 0, 0)
# }
# ... |
gouthambs/Flask-Blogging | test/utils.py | Python | mit | 948 | 0 | # http://stackoverflow.com/questions/1477294/generate-random-utf-8-string-in-python
import random
def get_random_unicode(length):
try:
get_char = unichr
except NameError:
| get_char = chr
# Update this to include code point ranges to be sampled
include_ranges = [
( | 0x0021, 0x0021),
(0x0023, 0x0026),
(0x0028, 0x007E),
(0x00A1, 0x00AC),
(0x00AE, 0x00FF),
(0x0100, 0x017F),
(0x0180, 0x024F),
(0x2C60, 0x2C7F),
(0x16A0, 0x16F0),
(0x0370, 0x0377),
(0x037A, 0x037E),
... |
donatello/minio-py | tests/unit/minio_test.py | Python | apache-2.0 | 3,851 | 0.000519 | # -*- coding: utf-8 -*-
# Minio Python Library for Amazon S3 Compatible Cloud Storage,
# (C) 2015, 2016, 2017 Minio, 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.ap... | 'https://bucket-name.s3-us-west-2.amazonaws.com/objectName')
@raises(TypeError)
def test_minio_requires_string(self):
Minio(10)
@raises(InvalidEndpointError)
def test_minio_requires_hostname(self):
Minio('http:// | ')
class UserAgentTests(TestCase):
def test_default_user_agent(self):
client = Minio('localhost')
eq_(client._user_agent, _DEFAULT_USER_AGENT)
def test_set_app_info(self):
client = Minio('localhost')
expected_user_agent = _DEFAULT_USER_AGENT + ' hello/2.0.6'
client.set... |
hal0x2328/neo-python | neo/Core/State/AssetState.py | Python | mit | 6,477 | 0.000926 | from .StateBase import StateBase
from neo.Core.Fixed8 import Fixed8
from neo.Core.IO.BinaryReader import BinaryReader
from neo.IO.MemoryStream import StreamManager
from neo.Core.AssetType import AssetType
from neo.Core.UInt160 import UInt160
from neo.Core.Cryptography.Crypto import Crypto
from neo.Core.Cryptography.ECC... | e)
writer.WriteUInt160(self.FeeAddress)
self.Owner.Serialize(writer)
writer.WriteUInt160(self.Admin)
writer.WriteUInt160(self.Issuer)
writer.WriteUInt32(self.Expiration)
writer.WriteBool(self.IsFrozen)
def GetName(self):
"""
Get the asset name based o... | pe == AssetType.GoverningToken:
return "NEO"
elif self.AssetType == AssetType.UtilityToken:
return "NEOGas"
if type(self.Name) is bytes:
return self.Name.decode('utf-8')
return self.Name
def ToJson(self):
"""
Convert object members to a d... |
quantumlib/OpenFermion | src/openfermion/measurements/qubit_partitioning.py | Python | apache-2.0 | 9,586 | 0.000104 | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distribu... | operators lies in at least one string.
Args:
num_qubits(int): number of qubits in string
max_word_size(int): maximum required word
Returns:
pauli_string(iterator of strings): iterator
over Pauli strings
"""
if max_word_si | ze > num_qubits:
raise ValueError('Number of qubits is too few')
if max_word_size <= 0:
raise ValueError('Word size too small')
qubit_list = list(range(num_qubits))
partitions = partition_iterator(qubit_list, max_word_size)
pauli_string = ['I' for temp in range(num_qubits)]
pauli_le... |
otsaloma/poor-maps | guides/foursquare.py | Python | gpl-3.0 | 4,437 | 0.001129 | # -*- coding: utf-8 -*-
# Copyright (C) 2014 Osmo Salomaa
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This pr... | from search result `item`."""
description = []
with poor.util.silent(Exception):
rating = float(item.venue.rating)
description.append("{:.1f}/10".format(rating))
with poor.util.silent(Exception):
description.append(item.venue.categories[0] | .name)
with poor.util.silent(Exception):
description.append(item.venue.location.address)
description = ", ".join(description)
with poor.util.silent(Exception):
description += "\n“{}”".format(item.tips[0].text)
return description
def parse_link(item):
"""Parse hyperlink from search r... |
narasimhan-v/avocado-misc-tests-1 | io/net/multicast.py | Python | gpl-2.0 | 5,757 | 0 | #!/usr/bin/env python
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that ... | 0:
self.log.info("Unable to delete m | ulticast route added for peer")
cmd = "echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts"
if process.system(cmd, shell=True, verbose=True,
ignore_status=True) != 0:
self.log.info("unable to unset all mulicast option")
cmd = "ip link set %s allmulticast... |
druss16/danslist | polls/urls.py | Python | mit | 400 | 0.02 | from django.conf.urls import url
from . import views
urlpatterns = [
# ex: /polls/
url(r'^$', views.index, name='index'),
# ex: /polls/5/
url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
# ex: /polls/5/results/
url(r'^(?P< | question_id>[0-9]+)/results/$', views.results, name='results'),
# ex: /polls/5/vote/
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='v | ote'),
]
|
thorwhalen/ut | util/context_managers.py | Python | mit | 908 | 0.001101 | """useful context managers"""
from contextlib import suppress
with suppress(ModuleNotFoundError):
from lag import *
import os
import contextlib
def clog(*args, condition=True, log_func=print, **kwargs):
if condition:
return log_func(*args, **kwargs)
@contextlib.contextmanager
def cd(newdir, verbos... | int("Called under cd", Path().absolute | ())
# _clog("Called after cd and same as before", Path().absolute())
|
bjornsturmberg/NumBAT | JOSAB_tutorial/simo-josab-IFSBS-1umcylwg-SiO2.py | Python | gpl-3.0 | 7,020 | 0.010684 | """
Script to evaluate intermodal forward Brillouin scattering in a cylindrical SiO2 waveguide
"""
# Import the necessary packages
import time
import datetime
import numpy as np
import sys
import copy
from matplotlib.ticker import AutoMinorLocator
import math
sys.path.append("../backend/")
import material... | EM_ival_pump, EM_ival_Stokes=EM_ival_Stokes, AC_ival=AC_ival)
# Mask negligible gain values to improve clarity of print out.
threshold = 1e-3
masked_PE = np.ma.masked_inside(SBS_gain_PE[EM_ival_pump,EM_ival_Stokes,:], 0, threshold)
masked_MB = np.ma.masked_inside(SBS_gain_MB[EM_ival_pump,EM_ival_Stokes,:], 0, thr... | Display these in terminal
print("\n Displaying results with negligible components masked out")
print("SBS_gain [1/(Wm)] PE contribution \n", masked_PE)
print("SBS_gain [1/(Wm)] MB contribution \n", masked_MB)
print("SBS_gain [1/(Wm)] total \n", masked)
# determining the location of the maximum gain
maxGainloc=6;... |
Alkalit/silk | silk/config.py | Python | mit | 1,268 | 0.000789 | from copy import copy
import silk.utils.six as six
from silk.singleton import Singleton
def default_permissions(user):
if user:
return user.is_staff
return False
class SilkyConfig(six.with_metaclass(Singleton, object)):
defaults = {
'SILKY_DYNAMIC_PROFILING': [],
'SILKY_IGNORE_... | False,
'SILKY_AUTHENTICATION': False,
'SILKY_AUTHORISATION': False,
'SILKY_PERMISSIONS': default_permissions,
'SILKY_MAX_REQUEST_BODY_SIZE': -1,
'SILKY_MAX_RESPONSE_BODY_SIZE': -1,
'SILKY_INTER | CEPT_PERCENT': 100,
'SILKY_INTERCEPT_FUNC': None,
'SILKY_PYTHON_PROFILER': False,
}
def _setup(self):
from django.conf import settings
options = {option: getattr(settings, option) for option in dir(settings) if option.startswith('SILKY')}
self.attrs = copy(self.defaults... |
SDoc/py-sdoc | sdoc/sdoc1/error.py | Python | mit | 147 | 0.006803 | class DataTypeError(RuntimeError):
"""
Generic exception cl | ass for SDoc1 language errors with data types and expressions.
| """
pass
|
yujikato/DIRAC | src/DIRAC/Core/Utilities/Devloader.py | Python | gpl-3.0 | 2,365 | 0.011839 | """ Here, we need some documentation...
"""
from __future__ import absolute_import
| from __future__ import division
from __future__ import print_fu | nction
import sys
import os
import types
import threading
import time
import six
from DIRAC import gLogger
from DIRAC.Core.Utilities.DIRACSingleton import DIRACSingleton
@six.add_metaclass(DIRACSingleton)
class Devloader(object):
def __init__(self):
self.__log = gLogger.getSubLogger("Devloader")
self.__rel... |
polypmer/obligarcy | obligarcy/migrations/0007_auto_20151010_2304.py | Python | gpl-3.0 | 696 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('obligarcy', '0006_auto_20151009_1947'),
]
operations = [
migrations.AlterField(
... | on',
name='user',
field=models.ForeignKey(to=settings.AUTH_USER_MODEL),
), |
migrations.DeleteModel(
name='User',
),
]
|
mkeller0815/py65 | py65/memory.py | Python | bsd-3-clause | 2,382 | 0.00084 | from collections import defaultdict
class ObservableMemory:
def __init__(self, subject=None, addrWidth=16):
self.physMask = 0xffff
if addrWidth > 16:
# even with 32-bit address space, model only 256k memory
self.physMask = 0x3ffff
if subject is None:
su... | ):
if isinstance(address, slice):
r = range(*address.indices(self.physMask + 1))
return [ self[n] for n in r ]
address &= self.physMask
callbacks = self._read_subscribers[address]
final_result = None
for callback in callbacks:
result = callba... | if result is not None:
final_result = result
if final_result is None:
return self._subject[address]
else:
return final_result
def __getattr__(self, attribute):
return getattr(self._subject, attribute)
def subscribe_to_write(self, address_... |
lafranceinsoumise/api-django | agir/payments/migrations/0014_auto_20190726_1503.py | Python | agpl-3.0 | 364 | 0 | # Generated by Django 2.2.3 on 2019-07-26 13:03
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("payments", "0013_auto_20 | 190724_1628")]
operations = [
migrations.AlterModelOptions(
name="payment",
| options={"get_latest_by": "created", "ordering": ("-created",)},
)
]
|
saydulk/django-wysiwyg | django_wysiwyg/templatetags/wysiwyg.py | Python | mit | 2,413 | 0.002072 | from django import template
from django.conf import settings
from django.template.loader import render_to_string
try:
from urlparse import urljoin
except ImportError:
from urllib.parse import urljoin
register = template.Library()
def get_settings():
"""Utility function to retrieve settings.py values wit... | ing(
"django_wysiwyg/%s/includes.html" % ctx['DJANGO_WYSIWYG_FLAVOR'],
ctx
)
@register.simple_tag
def wysiwyg_editor(field_id, editor_name=None, config=None):
"""
Turn the textarea #field_id into a rich editor. If you do not spe | cify the
JavaScript name of the editor, it will be derived from the field_id.
If you don't specify the editor_name then you'll have a JavaScript object
named "<field_id>_editor" in the global namespace. We give you control of
this in case you have a complex JS ctxironment.
"""
if not editor_na... |
FrodeSolheim/fs-uae-launcher | launcher/ui/config/CustomOptionsPage.py | Python | gpl-2.0 | 2,973 | 0.000336 | import fsui
from fsgamesys.context import fsgs
from launcher.i18n import gettext
from launcher.launcher_config import LauncherConfig
class CustomOptionsPage(fsui.Panel):
def __init__(self, parent):
fsui.Panel.__init__(self, parent)
self.layout = fsui.VerticalLayout()
label = fsui.MultiLin... | t(fsgs.config.values.keys()):
if key not in LauncherConfig.default_config:
update_config[key] = ""
# Then we overwrite with specific values
for line in text.split("\n"):
line = line.strip()
parts = line.split("=", 1)
if len(parts) == 2:
... | onfig:
# continue
value = parts[1].strip()
update_config[key] = value
# Finally, set everything at once
LauncherConfig.set_multiple(update_config.items())
def initial_text():
text = []
keys = fsgs.config.values.keys()
for key in sorted(ke... |
lukas/ml-class | examples/keras-smile/smile-server-1.py | Python | gpl-2.0 | 1,356 | 0 | import flask
import keras
import numpy as np
import os
from keras.model | s import load_model
from PIL import Image
from flask import Flask, request
from jinja2 import Template
app = Flask(__name__)
model = load_model('smile.h5')
model._make_predict_function()
def predict_image(image):
image = image.convert(mode="L")
image = image.resize((32, 32))
im = np.asarray(image)
i... | route("/predict", methods=["POST"])
def predict():
f = request.files['file']
image = Image.open(f.stream)
pred = predict_image(image)
template = Template("""
<html>
<body>
<p>Probability of Smiling: {{smile_prob}}</p>
<p>Probability of Not Smiling: {{n... |
frederick623/pb | deltaone/d1_sbl_recon.py | Python | apache-2.0 | 7,739 | 0.030236 | import re
import sqlite3
import csv
import ast
import os
import sys
import fnmatch
import datetime
import xlrd
import win32com.client
def question_marks(st):
question_marks = '?'
for i in range(0, len(st.split(','))-1):
question_marks = question_marks + ",?"
return question_marks
def xlsx_to_arr(xlsx_file, works... | FA-Share\\PB_DeltaOne\\SBL FA Deltaone Recon"
sblmap_file = files_lookup(pb_dir, "ClientDetails_????????.xlsx")
fasbl_file = files_lookup(pb_dir, "RepoSBLTrade_????????.xlsx")
os_file = files_lookup(sbl_dir, "OS_Trades_Extract_*.CSV")
pd_file = files_lookup(sbl_dir, "Pending_Trades_Extract_*.CSV")
print (sblmap_... | ir, "FA_G1_SBL_recon_"+trd_date+".xlsx")
sblmap_header, sblmap_arr = xlsx_to_arr(sblmap_file, row_start=1)
sblmap_header = sblmap_header.replace("ClientId", "ClientId1", 1)
fasbl_header, fasbl_arr = xlsx_to_arr(fasbl_file, row_start=1)
fasbl_arr = conv_xl_dt_arr(fasbl_arr, [3, 4])
os_header, os_arr = csv_to_arr(... |
jeremiah-c-leary/vhdl-style-guide | vsg/tests/ieee/test_rule_500.py | Python | gpl-3.0 | 2,648 | 0.003776 |
import os
import unittest
from vsg.rules import ieee
from vsg import vhdlFile
from vsg.tests import utils
sTestDir = os.path.dirname(__file__)
lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_500_test_input.vhd'))
lExpected_lower = []
lExpected_lower.append('')
utils.read_file(os.path.join(s... | (self):
oRule = ieee.rule_500()
oRule.fix(self.oFile)
lActual = self.oFile.get_lines()
self.assertEqual(lExpected_lower, lActual)
oRule.analyze(self.oFile)
self.assertEqual(oRule.violations | , [])
def test_fix_rule_500_upper(self):
oRule = ieee.rule_500()
oRule.case = 'upper'
oRule.fix(self.oFile)
lActual = self.oFile.get_lines()
self.assertEqual(lExpected_upper, lActual)
oRule.analyze(self.oFile)
self.assertEqual(oRule.violations, [])
|
fzuellich/urlmonitor | view.py | Python | gpl-3.0 | 4,690 | 0.002559 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from Tkinter import *
from ttk import *
class URLDialogView(object):
_LABEL_CONF = {'column': 0, 'padx': 5, 'pady': 5, 'sticky': W}
_ENTRY_CONF = {'padx': 5, 'pady': 5, 'sticky': E+W}
def __init__(self, parent, controller, data=N... | """Create all the widgets."""
# frame to pack everything
frame = Frame(self.window, padding=10)
frame.pack()
# define labels
Label(frame, text='URL', anchor=W).gr | id(self._LABEL_CONF)
Label(frame, text='Label').grid(self._LABEL_CONF)
Label(frame, text='User').grid(self._LABEL_CONF)
Label(frame, text='Password').grid(self._LABEL_CONF)
# entries
url = Entry(frame, width=75, textvariable=self.url_var)
url.grid(... |
chrism0dwk/PyTado | setup.py | Python | gpl-3.0 | 1,442 | 0.001387 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
here = lambda *a: os.path.join(os.path.dirname(__file__), *a)
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
... |
platforms=["any"],
packages=find_packages(),
classifiers=[
'Development Status :: 3 - Alpha',
'Topic :: Home Automation',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
'Nat | ural Language :: English',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.5'
],
entry_points={
'console_scripts': [
'pytado = pytado.__main__:main'
]
},
)
|
stangls/omim | tools/run_desktop_tests.py | Python | apache-2.0 | 9,109 | 0.007355 | #!/usr/bin/env python
"""
This script is mainly for running autotests on the build server, however, it
can also be used by engineers to run the tests locally on their machines.
It takes as optional parameters the path to the folder containing the test
executables (which must have names ending in _tests), and a list... | = filter(not_on_disk, self.runlist)
# now let's move the tests that need a server either to the beginning or the end of the tests_to_run list
te | sts_with_server = list(TESTS_REQUIRING_SERVER)
for test in TESTS_REQUIRING_SERVER:
if test in tests_to_run:
tests_to_run.remove(test)
else:
tests_with_server.remove(test)
return {TO_RUN:tests_to_run, SKIP:local_skiplist, NOT_FOUND:not_found, WITH_... |
Laurawly/tvm-1 | python/tvm/relay/backend/contrib/ethosu/te/identity.py | Python | apache-2.0 | 2,862 | 0.001048 | # 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
# re | garding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# | "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT ... |
nasi/MyPy | MyPy/__init__.py | Python | bsd-3-clause | 2,276 | 0.010984 | import time
import datetime
from MyPy.core.exceptions import (
Warning, Error, InterfaceError, DatabaseError, DataError, OperationalError,
IntegrityError, InternalError, ProgrammingError, NotSupportedError
)
from MyPy.constants import fieldtypes
apilevel = '2.0'
threadsafety = 1
paramstyle = 'format'
def Co... | :
def __init__(self, *values):
self.values = values
def __cmp__(self, other):
if other in self.values:
return 0
if other < self.values:
return 1
else:
return -1
STRING = DBAPITypeObject(fieldtypes.FIELD_TYPE_ENUM, fieldtype... | fieldtypes.FIELD_TYPE_MEDIUM_BLOB, fieldtypes.FIELD_TYPE_TINY_BLOB)
NUMBER = DBAPITypeObject(fieldtypes.FIELD_TYPE_DECIMAL, fieldtypes.FIELD_TYPE_DOUBLE,
fieldtypes.FIELD_TYPE_FLOAT, fieldtypes.FIELD_TYPE_INT24,
fieldtypes.FIELD_TYPE_LONG, fieldtypes.FIEL... |
lmazuel/azure-sdk-for-python | azure-mgmt-consumption/azure/mgmt/consumption/models/marketplace.py | Python | mit | 7,474 | 0.000803 | # 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 ... | '},
'offer_name': {'key': 'properties.offerName', 'type': 'str'},
'resource_group': {'key': 'properties.resourceGroup', 'type': 'str'},
'order_number': {'key': 'properties.orderNumber', 'type': 'str'},
'instance_name': {'key': 'properties.instanceName', 'type': 'str'},
'instance_... | erties.currency', 'type': 'str'},
'consumed_quantity': {'key': 'properties.consumedQuantity', 'type': 'decimal'},
'unit_of_measure': {'key': 'properties.unitOfMeasure', 'type': 'str'},
'pretax_cost': {'key': 'properties.pretaxCost', 'type': 'decimal'},
'is_estimated': {'key': 'properties... |
shownotes/snotes20-restapi | statistic/admin.py | Python | agpl-3.0 | 91 | 0.010989 | from django.contrib import admin
# Register | your models here.
from statistic | import models |
Orav/kbengine | kbe/src/lib/python/Lib/unittest/test/testmock/__main__.py | Python | lgpl-3.0 | 641 | 0.00156 | import os
import unittest
def load_tests(loader, standard_tests, pattern):
# top level directory cached on loader instance
this_dir = os.path.dirname(__file__)
pattern = pattern or " | test*.py"
# We are inside unittest.test.testmock, so the top-level is three notches up
top_level_dir = os.path.dirname(os.path.dirname(os.path.dirname(this_dir)))
package_tests = loader.discover(start_dir=this_dir, pattern=pattern,
| top_level_dir=top_level_dir)
standard_tests.addTests(package_tests)
return standard_tests
if __name__ == '__main__':
unittest.main()
|
VirusTotal/content | Packs/CofenseTriage/Scripts/CofenseTriageThreatEnrichment/CofenseTriageThreatEnrichment.py | Python | mit | 1,197 | 0.002506 | from CommonServerPython import *
''' | STANDALONE FUNCTION '''
def get_threat_indicator_list(args: Dict[str, Any]) -> list:
"""
Executes cofense-threat-indicator-list command for given arguments. |
:type args: ``Dict[str, Any]``
:param args: The script arguments provided by the user.
:return: List of responses.
:rtype: ``list``
"""
# Fetch threat indicators based on threat value provided in the argument.
# cofense-threat-indicator-list command will enrich the information based on v... |
jeffames-cs/nnot | pyfann/libfann.py | Python | mit | 29,340 | 0.00426 | # This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.7
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info
if version_info >= (2, 6, 0):
def swig_import_helper():
from os.path imp... | EAR = _libfann.LINEAR
_libfann.THRESHOLD_swigconstant(_libfann)
THRESHOLD = _libfann.THRESHOLD
_libfann.THRESHOLD_SYMMETRIC_swigconstant(_libfann)
THRESHOLD_SYMMETRIC = _libfann.THRESHOLD_SYMMETRIC
_libfann.SIGMOID_swigconstant(_libfa | nn)
SIGMOID = _libfann.SIGMOID
_libfann.SIGMOID_STEPWISE_swigconstant(_libfann)
SIGMOID_STEPWISE = _libfann.SIGMOID_STEPWISE
_libfann.SIGMOID_SYMMETRIC_swigconstant(_libfann)
SIGMOID_SYMMETRIC = _libfann.SIGMOID_SYMMETRIC
_libfann.SIGMOID_SYMMETRIC_STEPWISE_swigconstant(_libfann)
SIGMOID_SYMMETRIC_STEPWISE = _libfan... |
azaghal/ansible | test/lib/ansible_test/_internal/coverage/analyze/targets/expand.py | Python | gpl-3.0 | 1,272 | 0.001572 | """Expand target names in an aggregated coverage file."""
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from .... import types as t
from ....io import (
SortedSetEncoder,
write_json_file,
)
from . import (
CoverageAnalyzeTargetsConfig,
expand_indexes,
for... | targets_expand(args): # type: (CoverageAnalyzeTargetsExpandConfig) -> None
"""Expand target names in an aggregated coverage file."""
covered_targets, covered_path_arcs, covered_path_lines = read_report(args.input_file)
report = dict(
| arcs=expand_indexes(covered_path_arcs, covered_targets, format_arc),
lines=expand_indexes(covered_path_lines, covered_targets, str),
)
if not args.explain:
write_json_file(args.output_file, report, encoder=SortedSetEncoder)
|
btouchard/piserver | src/piserver.py | Python | gpl-3.0 | 320 | 0.009404 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import os, locale, sys
from core import controller
locale.setlocale(locale.LC_ALL, 'fr_FR.UTF-8')
debug = False
if len(sys.argv) > 1: debug = sys.argv[1] == '-d'
# Initialisation du controller principale
ctrl | = controller.Cont | roller(debug)
# démarrage du serveur
ctrl.run() |
dios-game/dios-cocos | src/oslibs/cocos/cocos-src/tools/cocos2d-console/plugins/project_compile/build_android.py | Python | mit | 28,191 | 0.003689 | #!/usr/bin/python
# build_native.py
# Build native codes
import sys
import os, os.path
import shutil
from optparse import OptionParser
import cocos
from MultiLanguage import MultiLanguage
import cocos_project
import json
import re
from xml.dom import minidom
import project_compile
BUILD_CFIG_FILE="build-cfg.json"
... | d_root = app_android_root
self._no_res = no_res
self._project = proj_obj
self.use_studio = use_studio
# check environment variable
if self.use_studio:
| self.ant_root = None
self.sign_prop_file = os.path.join(self.app_android_root, 'app', "gradle.properties")
else:
self.ant_root = cocos.check_environment_variable('ANT_ROOT')
self.sign_prop_file = os.path.join(self.app_android_root, "ant.properties")
self.sdk... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.