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 |
|---|---|---|---|---|---|---|---|---|
policycompass/policycompass-services | apps/metricsmanager/signals.py | Python | agpl-3.0 | 1,207 | 0.002486 | """
This creates Django signals that automatically update the elastic search Index
When an item is created, a signal is thrown that runs the create / upd | ate index API of the Search Manager
When an item is deleted, a signal is thrown that executes the delete index API of the Search Manager
This way the Policy compass database and Elastic search index remains synced.
"""
from django.db.models.signals i | mport post_save, post_delete
from django.dispatch import receiver
from .models import Metric
from apps.searchmanager.signalhandlers import search_index_update, search_index_delete
from apps.datasetmanager import internal_api
@receiver(post_save, sender=Metric)
def update_document_on_search_service(sender, **kwargs):
... |
ktan2020/legacy-automation | win/Lib/site-packages/wx-3.0-msw/wx/lib/masked/ipaddrctrl.py | Python | mit | 8,362 | 0.013155 | #----------------------------------------------------------------------------
# Name: masked.ipaddrctrl.py
# Authors: Will Sadkin
# Email: wsadkin@nameconnector.com
# Created: 02/11/2003
# Copyright: (c) 2003 by Will Sadkin, 2003
# RCS-ID: $Id$
# License: wxWidgets license
... | o take when the '.' character is typed in the
control. | By default, the current field is right-justified, and the
cursor is placed in the next field.
"""
## dbg('IpAddrCtrl::OnDot', indent=1)
pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode())
oldvalue = self.GetValue()
edit_start, edit_end, slice = self... |
ekivemark/bofhirdev | accounts/admin.py | Python | gpl-2.0 | 4,321 | 0.000694 | from django import forms
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
# Register your models here.
from accounts.models import (User,
ValidSMSCod... | eating a user.
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('user', 'email', 'password1', 'password2')}
),
)
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ()
# class ApplicationAdmin(admin.ModelAdmin):
# """
# T... | n module
# """
# # DONE: Add Admin view for applications
# list_display = ('name', 'user')
# admin.site.register(Account)
admin.site.register(User, UserAdmin)
# admin.site.register(Application, ApplicationAdmin)
# admin.site.register(ApplicationKey)
admin.site.register(ValidSMSCode)
admin.site.register(Cr... |
khrapovs/multivol | setup.py | Python | mit | 1,004 | 0 | #!/usr/bin/env python
from setuptools import setup, find_packages
with open('README.rst') as file:
long_description = file.read()
setup(name='multivol',
version='1.0',
description=('Multivariate (co)variance'),
long_description=long_description,
author='Stanislav Khrapov',
license=... | on :: 3. | 3',
'Programming Language :: Python :: 3.4',
],
)
|
dl1ksv/gnuradio | gr-utils/modtool/core/rm.py | Python | gpl-3.0 | 9,217 | 0.001844 | #
# Copyright 2013, 2018-2020 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
""" Remove blocks module """
import os
import re
import sys
import glob
import logging
from ..tools import remove_pattern_from_file, CMakeFileEditor, CPPFileEditor, get_bl... | e + '(m);')
ed.write()
if not self.skip_subdirs['lib']:
self._run_subdir('lib', ('*.cc', '*.h'), ('add_library', 'list'),
cmakeedit_func=_remove_cc_test_case)
if not self.skip_subdirs['include']:
incl_files_de | leted = self._run_subdir(
self.info['includedir'], ('*.h',), ('install',))
if not self.skip_subdirs['grc']:
self._run_subdir('grc', ('*.yml',), ('install',))
def _run_subdir(self, path, globs, makefile_vars, cmakeedit_func=None):
""" Delete all files that match a certain... |
Lilykos/invenio | invenio/testsuite/test_utils_pagination.py | Python | gpl-2.0 | 2,174 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2013 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
# License, or (at your option) any later... | assertTrue(pagination.has_next)
self.assertEqual(list(pagination.iter_pages()), [1, 2, 3, None, 10])
def test_last_page(self):
page = 10
per_page = 10
total_count = 98
pagination = Pagination(page, per_page, total_count)
self.assertTrue(pagination.has_prev)
s... | otal_count = 98
pagination = Pagination(page, per_page, total_count)
self.assertTrue(pagination.has_prev)
self.assertTrue(pagination.has_next)
self.assertEqual(list(pagination.iter_pages()),
[1, None, 4, 5, 6, 7, None, 10])
TEST_SUITE = make_test_suite(TestPagi... |
sbyount/pynet_test | netmiko_test.py | Python | apache-2.0 | 377 | 0.007958 | #!usr/bin | /env python
from netmiko import ConnectHandler
from getpass import getpass
#passowrd = getpass()
pynet1 = {
'device_type': 'cisco_ios',
'ip': '184.105.247.70',
'username': 'pyclass',
'password': '88newclass'
}
pynet_rtr1 = ConnectHandler(**pynet1) # Pass all args from | the dictionary
outp = pynet_rtr1.send_command('sh ip int br')
print outp
|
jawilson/home-assistant | homeassistant/helpers/debounce.py | Python | apache-2.0 | 3,910 | 0.000512 | """Debounce helper."""
from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable
from logging import Logger
from typing import Any
from homeassistant.core import HassJob, HomeAssistant, callback
class Debouncer:
"""Class to rate limit calls to a specific command."""
... | rt if timer got set while we're waiting for the lock.
| if self._timer_task:
return # type: ignore
try:
task = self.hass.async_run_hass_job(self._job)
if task:
await task
except Exception: # pylint: disable=broad-except
self.logger.exception("Unexpected... |
briancline/softlayer-python | SoftLayer/CLI/vlan/detail.py | Python | mit | 3,145 | 0 | """Get details about a VLAN."""
# :license: MIT, see LICENSE for more details.
import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import formatting
from SoftLayer.CLI import helpers
import click
@click.command()
@click.argument('identifier')
@click.option('--no-vs',
is_flag=Tru... | able.add_row(['primary router',
vlan['primaryRouter']['fullyQualifiedDomainName']])
table.add_row(['firewall',
'Yes' if vlan['firewallInterfaces'] else 'No'])
subnets = []
for subnet in vlan['subnets']:
subnet_table = formatting.KeyValueTable(['Name', 'Value'])
... | = 'r'
subnet_table.align['Value'] = 'l'
subnet_table.add_row(['id', subnet['id']])
subnet_table.add_row(['identifier', subnet['networkIdentifier']])
subnet_table.add_row(['netmask', subnet['netmask']])
subnet_table.add_row(['gateway', subnet.get('gateway', '-')])
subnet_t... |
knagra/farnsworth | managers/migrations/0001_initial.py | Python | bsd-2-clause | 6,574 | 0.00578 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('base', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Announce... | , max_length=255)),
('enabled', models.BooleanField(default=True, help_text='Whether this type of request i | s currently accepted. Toggle this to off to temporarily disable accepting this type of request.')),
('glyphicon', models.CharField(help_text='Glyphicon for this request type (e.g., cutlery). Check Bootstrap documentation for more info.', max_length=100, null=True, blank=True)),
('manage... |
bundgus/python-playground | matplotlib-playground/examples/pylab_examples/demo_agg_filter.py | Python | mit | 9,321 | 0.000858 | import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
import matplotlib.mlab as mlab
def smooth1d(x, window_len):
# copied from http://www.scipy.org/Cookbook/SignalSmooth
s = np.r_[2*x[0] - x[window_len:1:-1], x, 2*x[-1] - x[-1:-window_len:-1]]
w = np.hanning(window_len)
y = ... | lter(self._filter)
| renderer.stop_rasterizing()
import matplotlib.transforms as mtransforms
def filtered_text(ax):
# mostly copied from contour_demo.py
# prepare image
delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = mlab.bivariate_normal(X, ... |
vmahuli/contrail-controller | src/api-lib/tools/install_venv_common.py | Python | apache-2.0 | 6,620 | 0.000755 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 OpenStack Foundation
# Copyright 2013 IBM Corp.
#
# 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.a... | self):
if sys.version_info < (2, 6):
self.die("Need Python Version >= 2.6")
def run_command_with_code(self, cmd, redirect_output=True,
check_exit_code=True):
"""Runs a command in an out-of-process shell.
Returns the output of that command. Working ... | _output:
stdout = subprocess.PIPE
else:
stdout = None
proc = subprocess.Popen(cmd, cwd=self.root, stdout=stdout)
output = proc.communicate()[0]
if check_exit_code and proc.returncode != 0:
self.die('Command "%s" failed.\n%s', ' '.join(cmd), output)
... |
Galiaf47/lib3d | convert_obj_three.py | Python | gpl-2.0 | 48,258 | 0.006113 | """Convert Wavefront OBJ / MTL files into Three.js (JSON model version, to be used with ascii / binary loader)
-------------------------
How to use this converter
-------------------------
python convert_obj_three.py -i infile.obj -o outfile.js [-m "morphfiles*.obj"] [-c "morphcolors*.obj"] [-a center|centerxz|top|bo... | en(vertices)>0:
minx = maxx = vertices[0][0]
miny = maxy = vertices[0][1]
minz = maxz = vertices[0][2]
for v in vertices[1:]:
| if v[0]<minx:
minx = v[0]
elif v[0]>maxx:
maxx = v[0]
if v[1]<miny:
miny = v[1]
elif v[1]>maxy:
maxy = v[1]
if v[2]<minz:
minz = v[2]
elif v[2]>maxz:
maxz = ... |
partofthething/home-assistant | homeassistant/components/airvisual/__init__.py | Python | apache-2.0 | 13,229 | 0.001814 | """The airvisual component."""
import asyncio
from datetime import timedelta
from math import ceil
from pyairvisual import CloudAPI, NodeSamba
from pyairvisual.errors import (
AirVisualError,
InvalidKeyError,
KeyExpiredError,
NodeProError,
)
from homeassistant.config_entries import SOURCE_REAUTH
from ... | _COORDS,
INTEGRATION_TYPE_GEOGRAPHY_NAME,
INTEGRATION_TYPE_NODE_PRO,
LOGGER,
)
PLATFORMS = ["air_quality", "sensor"]
DATA_LISTENER = "listener"
DEFAULT_ATTRIBUTION = "Data provided by Ai | rVisual"
DEFAULT_NODE_PRO_UPDATE_INTERVAL = timedelta(minutes=1)
CONFIG_SCHEMA = cv.deprecated(DOMAIN)
@callback
def async_get_geography_id(geography_dict):
"""Generate a unique ID from a geography dict."""
if not geography_dict:
return
if CONF_CITY in geography_dict:
return ", ".join(
... |
allenwoods/parasys | debug/__init__.py | Python | mit | 306 | 0 | #! /usr/bin/ | env python
# -*- coding: utf-8 -*-
"""
@file __init__.py.py
@author Allen Woods
@date 2016-08-02
@version 16-8-2 上午8:50 ???
Some other Description
"""
def func():
pass
class Main(object):
def __init__(self):
pass
if __name__ == '__main__ | ':
pass
|
andrius-preimantas/odoo | addons/website/models/website.py | Python | agpl-3.0 | 33,629 | 0.003717 | # -*- coding: utf-8 -*-
import cStringIO
import contextlib
import datetime
import hashlib
import inspect
import itertools
import logging
import math
import mimetypes
import unicodedata
import os
import re
import urlparse
from PIL import Ima | ge
from sys import maxint
import werkzeug
import werkzeug.exceptions
import werkzeug.utils
import werkzeug.wrappers
# optional python-slugify import (https://github.com/un33k/python-slugify)
try:
| import slugify as slugify_lib
except ImportError:
slugify_lib = None
import openerp
from openerp.osv import orm, osv, fields
from openerp.tools import html_escape as escape
from openerp.tools import ustr as ustr
from openerp.tools.safe_eval import safe_eval
from openerp.addons.web.http import request
logger = log... |
skoobe/riofs | tests/test_amazon.py | Python | gpl-3.0 | 1,249 | 0.001601 | import os
import sys
import shutil
import unittest
import tempfile
import time
sys.path.append(os.path.join(os.path.dirname(__file__), "..", "..", "ms3"))
from ms3.testing import MS3Server
from s3ffs_server import s3ffsServer, wait_until
class AmazonTestCase(unittest.TestCase):
def setUp(self):
self.lo... | raise
def tearDown(self):
if self.s3ffs:
self.s3ffs.stop()
shutil.rmtree(self.local, True)
def test_mounted(self):
self.assertTrue(os.path.ismount(self.local))
def test_single_file(self):
content = "Hello, world!"
path | = os.path.join(self.local, "file.txt")
with open(path, "w") as f:
f.write(content)
wait_until(os.path.exists, path)
self.assertTrue(open(path).read(), content)
if __name__ == "__main__":
unittest.main()
|
eriol/pywt | pywt/_dwt.py | Python | mit | 9,891 | 0.000303 | import numpy as np
from ._extensions._pywt import Wavelet, Modes, _check_dtype
from ._extensions._dwt import (dwt_single, dwt_axis, idwt_single, idwt_axis,
upcoef as _upcoef, downcoef as _downcoef,
dwt_max_level as _dwt_max_level,
... | : str, optional (default: 'symmetric')
Signal extension mode, see Modes
axis: int, optional
Axis over which to compute the inverse DWT. If not given, the
last axis is used.
Returns
---- | ---
rec: array_like
Single level reconstruction of signal from given coefficients.
"""
# TODO: Lots of possible allocations to eliminate (zeros_like, asarray(rec))
# accept array_like input; make a copy to ensure a contiguous array
if cA is None and cD is None:
raise ValueError("At... |
ryfeus/lambda-packs | Shapely_numpy/source/numpy/distutils/__config__.py | Python | mit | 1,319 | 0.015921 | # This file is generated by /tmp/pip-kUGBJh-build/-c
# It contains system_info results at the time of building this package.
__all__ = ["get_info","show"]
|
lapack_opt_info={'libraries': ['openblas', 'openblas'], 'library_dirs': ['/usr/local/lib'], 'language': 'c', 'define_macros': [('HAVE_CBLAS', None)]}
blas_opt_info={'libraries': ['openblas', 'openblas'], 'library_dirs': ['/usr/local/lib'], 'language': 'c', 'define_macros': [('HAVE_CBLAS', None)]}
blis_info={}
openblas... | guage': 'c', 'define_macros': [('HAVE_CBLAS', None)]}
openblas_lapack_info={'libraries': ['openblas', 'openblas'], 'library_dirs': ['/usr/local/lib'], 'language': 'c', 'define_macros': [('HAVE_CBLAS', None)]}
lapack_mkl_info={}
blas_mkl_info={}
def get_info(name):
g = globals()
return g.get(name, g.get(name + ... |
kernsuite-debian/lofar | CEP/GSM/bremen/recreate_tables.py | Python | gpl-3.0 | 8,597 | 0.001745 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Tool to recreate all tables/procedures in the database.
"""
import argparse
import copy
import re
from os import path
from src.sqllist import re_sub
try:
import monetdb.sql as db
try:
import monetdb.exceptions as me
except ImportError:
# Ol... | cute(
"select count(*) from pg_tables where tablename ='%s';"
% tab_name)
data = cur.fetchone()
return data[0] == 1
def drop_table(self, tab_name):
"""
Drop table if it exists.
"""
if self.get_table_exists(tab_name):
... | able %s;" % tab_name)
else:
self.conn.execute("drop table %s cascade;" % tab_name)
self.conn.execute(
"drop sequence if exists seq_%s cascade;" % tab_name)
print('Table %s dropped' % tab_name)
# For MonetDB-PostgreSQL convertion.
PG_SUBST... |
iocanto/bug-python-libraries | sample.py | Python | gpl-3.0 | 1,158 | 0.003454 | '''
*******************************************************************************
* sample.py 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... | e hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public Licen | se
* along with sample.py. If not, see <http://www.gnu.org/licenses/>.
********************************************************************************
Created on Jan 13, 2010
@author: iocanto
'''
import BUGBaseControl
import InputEventProvider
if __name__ == "__main__":
print "STARTING BugBaseControl TEST"... |
harveywwu/vnpy | vnpy/trader/gateway/tkproGateway/TradeApi/trade_api.py | Python | mit | 19,713 | 0.008573 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import json
from builtins import *
import pandas as pd
from . import utils
class EntrustOrder(object):
def __init__(self, security, action, price, size):
... | trategy_selected = r
return (r, msg)
else:
| return (False, "-1,no strategy_id was specified")
def confirm_internal_order(self, task_id, confirmed):
"""
return (result, message)
if result is None, message contains error information
"""
r, msg = self._check_session()
if not r: return (None, msg)
... |
clones/django-profiles | profiles/urls.py | Python | bsd-3-clause | 919 | 0 | """
URLConf for Django user profile management.
Recommended usage is to use a call to ``include()`` in your project's
root URLConf to include this URLConf for any URL beginning with
'/profiles/'.
"""
from django.conf.urls.defaults import *
from profiles import views
urlpatterns = patterns('',
... | name='profiles_profile_detail'),
url(r'^$',
| views.profile_list,
name='profiles_profile_list'),
)
|
jimporter/doppel | doppel/__init__.py | Python | bsd-3-clause | 1,483 | 0 | import errno
import os
import shutil
def mkdir(path, mode=0o777, exist_ok=False):
try:
os.mkdir(path, mode)
except OSError as e:
if not exist_ok or e.errno != errno.EEXIST or not os.path.isdir(path):
raise
def makedirs(path, mode=0o777, exist_ok=False):
try:
os.makedi... | or e.errno | != errno.ENOENT:
raise
def copy(src, dst, recursive=False, symlink='relative', mode=None):
if symlink != 'never' and os.path.islink(src):
link = os.readlink(src)
if symlink == 'always' or not os.path.isabs(link):
remove(dst, nonexist_ok=True)
os.symlink(link, ds... |
gencer/python-phonenumbers | python/tests/testdata/region_882.py | Python | apache-2.0 | 527 | 0.011385 | """Auto-generated file, do not edit by hand. 882 m | etadata"""
from phonenumbers.phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_882 = PhoneMetadata(id='001', country_code=882, international_prefix=None,
general_desc=PhoneNumberDesc(national_number_pattern='\\d{9}', possible_length=(9,)),
mobile=PhoneNumber | Desc(national_number_pattern='\\d{9}', example_number='123456789', possible_length=(9,)),
number_format=[NumberFormat(pattern='(\\d)(\\d{4})(\\d{4})', format='\\1 \\2 \\3')])
|
noironetworks/group-based-policy | gbpservice/neutron/tests/unit/nfp/orchestrator/mock_dicts.py | Python | apache-2.0 | 29,927 | 0 | # 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
#
# U | nless 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 limitations
# under the Lice... |
sklam/numba | numba/tests/doc_examples/test_literally_usage.py | Python | bsd-2-clause | 1,625 | 0 | # "magictoken" is used for markers as beginning and ending of example text.
import unittest
from numba.tests.support import captured_stdout
class DocsLiterallyUsageTest(unittest.TestCase):
def test_literally_usage(self):
with captured_stdout():
# magictoken.ex_literally_usage.begin
... | ))
# should print "square" and "9"
print(test_power(3, 2))
# should print "cubic" and "27"
print(test_power(3, 3))
# should print "generic" and "81"
print(test_power(3, 4))
# magictoken.ex_literally_usage.end
assert test... | st_power(3, 3) == 3 ** 3
assert test_power(3, 4) == 3 ** 4
if __name__ == '__main__':
unittest.main()
|
nkgilley/home-assistant | tests/components/google_translate/__init__.py | Python | apache-2.0 | 50 | 0 | """Tests for the Google Tr | anslate integration."""
| |
mfherbst/spack | var/spack/repos/builtin/packages/nwchem/package.py | Python | lgpl-2.1 | 9,995 | 0.002401 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | 'LAPACK_LIB=%s' % lapack.ld_flags,
'USE_SCALAPACK=y',
'SCALAPACK=%s' % scalapack.ld_flags,
'NWCHEM_MODULES=all python',
'NWCHEM_LONG_PATHS=Y' # by default NWCHEM_TOP is 64 char max
])
# TODO: query if blas/lapack/scalapack uses 64bit Ints
# A ... | in_alg = True
if use_32_bit_lin_alg:
args.extend([
'USE_64TO32=y',
'BLAS_SIZE=4',
'LAPACK_SIZE=4',
'SCALAPACK_SIZE=4'
])
else:
args.extend([
'BLAS_SIZE=8',
'LAPACK_SIZE=8'... |
fnp/prawokultury | shop/models.py | Python | agpl-3.0 | 4,642 | 0.004094 | # -*- coding: utf-8 -*-
# This file is part of PrawoKultury, licensed under GNU Affero GPLv3 or later.
# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
#
from datetime import datetime
from django.core.mail import send_mail, mail_managers
from django.conf import settings
from django.contrib.sit... | raiser for a particular book. """
entry = models.OneToOneField(Entry, models.CASCADE) # filter publications!
price = models.DecimalField(_('price'), decimal_places=2, max_digits=6)
cost_const = models.DecimalField(decimal_place | s=2, max_digits=6)
cost_per_item = models.DecimalField(decimal_places=2, max_digits=6, default=0)
class Meta:
verbose_name = _('offer')
verbose_name_plural = _('offers')
ordering = ['entry']
def __unicode__(self):
return unicode(self.entry)
def get_absolute_url(self):
... |
OpenSPA/dvbapp | lib/python/Components/Timezones.py | Python | gpl-2.0 | 1,411 | 0.041106 | import xml.etree.cElementTree
from os import environ, unlink, symlink, path
from Tools.Directories import SCOPE_SKIN, resolveFilename
import time
from Tools.StbHardware import setRTCoffset
class Timezones:
def __init__(self):
self.timezones = []
self.readTimezonesFromFile()
def readTimezonesFromFile(self):
t... | l("zone"):
self.timezones.append((zone.get('name',""), zone.get('zone',"")))
except:
pass
if len(self.timezones) == 0:
self.timezones = [("UTC", "UTC")]
def activateTimezone(self, index):
if len(self.timezones) <= index:
return
environ['TZ'] = self.timezones[index][1]
try:
un | link("/etc/localtime")
except OSError:
pass
try:
symlink("/usr/share/zoneinfo/%s" %(self.timezones[index][1]), "/etc/localtime")
except OSError:
pass
try:
time.tzset()
except:
from enigma import e_tzset
e_tzset()
if path.exists("/proc/stb/fp/rtc_offset"):
setRTCoffset()
def getTimezo... |
devinbalkind/eden | tests/dbmigration/old_models/db.py | Python | mit | 749 | 0 | if not request.env.web2py_runtime_gae:
db = DAL("sqlite://storage.sqlite")
else:
db = DAL("google:datastore")
session.connect(request, response, db=db)
# Test for removing a table, this table is removed in the next revision
db.define_table("removing",
Field("name")
)
db.def... | Field("renamed")
)
# Test for adding and deleting a field
db.define_table("edit",
Field("name", "integer",
default="2")
)
# END =========================================================================
| |
faribas/RMG-Py | rmgpy/statmech/rotationTest.py | Python | mit | 34,218 | 0.007248 | #!/usr/bin/env python
# encoding: utf-8
################################################################################
#
# RMG - Reaction Mechanism Generator
#
# Copyright (c) 2002-2009 Prof. William H. Green (whgreen@mit.edu) and the
# RMG Team (rmg_dev@mit.edu)
#
# Permission is hereby granted, free of cha... | self.mode.quantum = False
Elist = numpy.arange(0, 2000*11.96, 1.0*11.96)
densStates = self.mode.getDensityOfStates(Elist)
| sumStates = self.mode.getSumOfStates(Elist)
for n in range(1, len(Elist)):
self.assertAlmostEqual(numpy.sum(densStates[0:n]) / sumStates[n], 1.0, 3)
def test_getSumOfStates_quantum(self):
"""
Test the LinearRotor.getSumOfStates() method using a quantum rotor.
"""
... |
kadamski/func | func/overlord/func_command.py | Python | gpl-2.0 | 2,133 | 0.007501 | #!/usr/bin/python
## func command line interface & client lib
##
## Copyright 2007,2008 Red Hat, Inc
## +AUTHORS
##
## This software may be freely redistributed under the terms of the GNU
## general public license.
##
## You should have received a copy of the GNU General Public License
## along with this program; if n... | goo to try to guess if arg[1] is hostnamegoo or
# a command name
def _isGlob(self, str):
if str.find("*") or str.find("?") or str.find("[") or str.find("]"):
return True
return False
def handleArguments(self, args):
if len(args) < 2:
sys.stde | rr.write("see the func manpage for usage\n")
sys.exit(411)
minion_string = args[0]
# try to be clever about this for now
if client.is_minion(minion_string) or self._isGlob(minion_string):
self.server_spec = minion_string
args.pop(0)
# if it doesn't loo... |
reTXT/thrift | lib/py/src/protocol/TBinaryProtocol.py | Python | apache-2.0 | 7,772 | 0.009779 | #
# 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 un | der 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 di... |
Bforartists/scons | scons-local/SCons/Tool/f03.py | Python | mit | 1,990 | 0.002513 | """engine.SCons.Tool.f03
Tool-specific initialization for the generic Posix f03 Fortran compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001 - 2014 The SCons Foundation
#
# Permis... | a copy of this softwar | e and associated documentation files (the
# "Software"), to deal in the Software without 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 ... |
redsk/neo_merger | neo_merger.py | Python | gpl-2.0 | 10,267 | 0.007013 | import sys
class MergeKBs():
def __init__(self, WNnodesFilename, WNedgesFilename, CNnodesFilename, CNedgesFilename, matchedNodesFilename, matchedEdgesFilename, matchKBs):
self.WNnodesFilename = WNnodesFilename
self.WNedgesFilename = WNedgesFilename
self.CNnodesFilename = CNnodesFilename
... | pend('s')
for r in self.WNrelsList:
r['KB'] = "W"
for r in self.CNrelsList:
r['KB'] = "C"
def getDictFromListOfNodes(self, l):
d = {}
for e in l:
d[ e['id:ID'] ] = e
return d
def writeCSV(self, filename, ItemsLists, ItemFields, Item... | , matchedTypes = self.matchHeaders(ItemFields, ItemsTypes)
with open(filename, 'w') as of:
header = '\t'.join(matchedFields)
of.write(header + '\n')
for l in ItemsLists:
for i in l:
line = ''
for idx, f in enumerate(ma... |
mick-d/nipype | nipype/interfaces/afni/tests/test_auto_TCorrelate.py | Python | bsd-3-clause | 1,367 | 0.02414 | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..preprocess import TCorrelate
def test_T | Correlate_inputs():
input_map = dict(args=d | ict(argstr='%s',
),
environ=dict(nohash=True,
usedefault=True,
),
ignore_exception=dict(nohash=True,
usedefault=True,
),
num_threads=dict(nohash=True,
usedefault=True,
),
out_file=dict(argstr='-prefix %s',
name_source='xset',
name_template='%s_tcorr',
),
outpu... |
sfu-rcg/ampush | amlib/conf.py | Python | mit | 1,274 | 0 | import os
from ConfigParser import ConfigParser
from amlib import argp
tmp_conf = ConfigParser()
tmp_path = os.path.dirname(os.path.abspath(__file__)) # /base/lib/here
tmp_path = tmp_path.split('/')
conf_path = '/'.join(tmp_path[0:-1]) # /base/lib
tmp_conf.read(conf_path+'/ampush.conf')
c = {}
c.update(tmp_conf.ite... | ct alternate flat file automount maps: default o | r user-specified
# set passed via --source?
if argp.a['source'] is not None:
try:
ff_map_dir_conf_key = 'flat_file_map_dir_' + argp.a['source']
c['flat_file_map_dir'] = c[ff_map_dir_conf_key]
except KeyError:
log_msg = 'Terminating. No such parameter in ampush.conf: ' + \
... |
mariocesar/namegenerator | codenamegenerator/__main__.py | Python | mit | 1,218 | 0.001642 | import argparse
from . import dictionary_sample, generate_codenames
def main():
parser = argparse.ArgumentParser(
prog="codenamegenerator", description="Code name generator"
)
parser.add_argument("num", type=int, default=1)
parser.add_argument("-c", "--capitalize", action="store_true", d | efault=False)
parser.add_argument("-t", "--title", action="store_true", default=False)
parser.add_argum | ent("-s", "--slugify", action="store_true", default=False)
parser.add_argument("--prefix", help="Prefix dictionary", default="adjectives")
parser.add_argument(
"--suffix",
help="Suffix dictionary",
default="mobi_notable_scientists_and_hackers",
)
args = parser.parse_args()
... |
robbiet480/home-assistant | homeassistant/components/plugwise/climate.py | Python | apache-2.0 | 9,147 | 0.000219 | """Plugwise Climate component for Home Assistant."""
import logging
from Plugwise_Smile.Smile import Smile
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import (
CURRENT_HVAC_COOL,
CURRENT_HVAC_HEAT,
CURRENT_HVAC_IDLE,
HVAC_MODE_AUTO,
HVAC_... | active hvac state."""
return self._hvac_mode
@property
def target_temperature(self):
"""Return the target_temperature."""
return self._setpoint
@property
def preset_mode(self):
"""Return the active preset."""
if self._presets:
return self._preset_mod... | n None
@property
def current_temperature(self):
"""Return the current room temperature."""
return self._temperature
@property
def min_temp(self):
"""Return the minimal temperature possible to set."""
return self._min_temp
@property
def max_temp(self):
"... |
jasonwbw/jason_putils | putils/io/file_iter.py | Python | apache-2.0 | 1,029 | 0.003887 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
This is a tool for file iterate
@Author : Jasonwbw@yahoo.com
'''
import numpy
from itertools import izip
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
def to_unicode(text, encoding='utf8', errors='strict'):
"""Convert a string (bytestr... |
"""Simple format: one sentence = one line; words already preprocessed and separated by whitespace."""
def __init__(self, source):
"""
`source` can be either a string or a file object.
Example:
sentences = LineSentence('myfile.txt')
"""
self.source = ... | line in fin:
yield to_unicode(line) |
dimagi/rapidsms-contrib-apps-dev | scheduler/views.py | Python | bsd-3-clause | 1,431 | 0.004892 | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from django.utils.translation import ugettext as _
from django.contrib.auth.decorators import login_required
from rapidsms.utils.pagination im... | hod == 'POST':
form = ScheduleForm(request.POST, instance= | schedule)
if form.is_valid():
form.save()
context['status'] = _("Schedule '%(name)s' successfully updated" % \
{'name':schedule.callback} )
else:
context['errors'] = form.errors
else:
form = ScheduleForm(instance=schedule)
... |
jeffthemaximum/jeffPD | config.py | Python | mit | 1,272 | 0.002358 | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
MAIL_SERVER = 'smtp.googlemail.com'
MAIL_PORT = 587
MAIL_USE_TLS = True
MAIL_USERNAME = 'frey.maxim@gmail.com'
... | 5432/d8hosmtv1eijgp'
class TestingConfig(Config):
TESTING = True
SQLALCHEMY_DATABASE_URI = 'postgres://uaaalnaflmsjnp:pLyQ5JRVbro0WCgXuMVorfqSjY@ec2-54-227-255-240.compute-1.amazonaws.com:5432/d8hosmtv1eijgp'
class ProductionConfig(Config):
SQ | LALCHEMY_DATABASE_URI = 'postgres://uaaalnaflmsjnp:pLyQ5JRVbro0WCgXuMVorfqSjY@ec2-54-227-255-240.compute-1.amazonaws.com:5432/d8hosmtv1eijgp'
config = {
'development': DevelopmentConfig,
'testing': TestingConfig,
'production': ProductionConfig,
'default': DevelopmentConfig
}
|
benosment/generators | generators-for-system-programmers/retuple.py | Python | gpl-2.0 | 417 | 0.01199 | # retuple.py
#
# Read a sequence of log lines and parse them into a sequence of tuples
loglines = open("access-log")
import re
log | pats = r'(\S+) (\S+) (\S+) \[(.*?)\] ' \
r'"(\S+) (\S+) (\S+)" (\S+) (\S+)'
logpat = re.compile(logpats)
groups = (logpat.match(line) for line in loglines)
tuples = (g.groups() f | or g in groups if g)
if __name__ == '__main__':
for t in tuples:
print t
|
box/box-python-sdk | test/functional/test_token_refresh.py | Python | apache-2.0 | 767 | 0.001304 | import pytest
from boxsdk.exception import BoxOAuthException
def test_expired_access_token_is_refreshed(box_oauth, box_client, mock_box):
# pylint:disable=protected-access
mock_box.oauth.expire_token(box_oa | uth._access_token)
# pylint:enable=protected-access
box_client.folder('0').get()
assert len(mock_box.requests) == 6 # GET /authorize, POST /authorize, /token, get_info, refresh /token, get_info
def test_expired_refresh_token_raises(box_oauth, box_client, mock_box):
# pylint:disable=protected-access
... | ytest.raises(BoxOAuthException):
box_client.folder('0').get()
|
mava-ar/sgk | src/dj_auth/signals.py | Python | apache-2.0 | 408 | 0 | from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
from django.db.models.signals import post_save
from django.dispatch impor | t receiver
@receiver(post_save, sender=User)
def create_auth_token(sender, instance=None, created=False, **kwargs):
"""
Cr | eates a token whenever a User is created
"""
if created:
Token.objects.create(user=instance)
|
hsadler/con-science-twitter-bot | models/error_log.py | Python | mit | 1,068 | 0.0103 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Error Log model
import logging
logger = logging.getLogger('con_science_bot')
hdlr = logging.FileHandler('logs/error.log')
formatter = logging.Formatter('\n%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.IN... | except:
error_message = 'i am a test error message'
error = cls.log_e | xception(error_message)
|
realms-team/solmanager | libs/smartmeshsdk-REL-1.3.0.1/external_libs/cryptopy/crypto/passwords/__init__.py | Python | bsd-3-clause | 179 | 0.005587 | """ CryptoPy - a pure python cryptographic libraries
crypto.passwords package
Copyright (c) 2002 by P | aul A. Lambert
Read LICENS | E.txt for license information.
"""
|
superstack/nova | nova/tests/test_api.py | Python | apache-2.0 | 17,953 | 0.00039 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compli... | ction(
self.app, '%s:8773' % (self.host), False)
# pylint: disable=E1103
self.ec2.new_http_connection(host, is_secure).AndReturn(self.http)
return self.http
def test_return_valid_isoformat(self):
"""
Ensure that the ec2 api returns datetime in xs:dateTime... | ently isn't datetime.isoformat())
NOTE(ken-pepple): https://bugs.launchpad.net/nova/+bug/721297
"""
conv = apirequest._database_to_isoformat
# sqlite database representation with microseconds
time_to_convert = datetime.datetime.strptime(
"2011-02-2... |
goblinhack/MundusMeus | python/things/snow_deco.py | Python | lgpl-3.0 | 875 | 0.001143 | import tp
import mm
def th | ing_init(t):
return
def snow_deco1_init(name, short_name, tiles=[]):
x = tp.Tp(name)
x.set_short_name(short_name)
x.set_z_depth(mm.Z_DEPTH_SNOW)
x.set_is_snow_deco(True)
if tile | s is not None:
for t in tiles:
x.set_tile(t, delay_ms=50)
else:
x.set_tile(tile=name, delay_ms=50)
x.thing_init = thing_init
return x
def init():
snow_deco1_init(name="snow_deco",
short_name="Snow",
tiles=[
... |
ukBaz/ble_beacon | examples/workshop3.py | Python | gpl-2.0 | 635 | 0 | from scanner import protocols, hci_socket
import base64
for pkt in hci_socket.run():
ad = protocols.AdvertEventHandler(pkt)
if ad.eddystone_uid:
print(f'\nBeacon instance id: {ad.eddystone_uid.instance_id}'
f' @ ({ad.address[-5:]})')
if ad.eddystone_uid.instance_id == 0xbb:
... | dystone_uid.data_in[1:11]
h | idden_word = base64.b85decode(namespace_bytes).decode("utf-8")
print(f'Namespace Value:\t{ad.eddystone_uid.namespace_id}')
print(f'Namespace Bytes:\t{namespace_bytes}')
print(f'Hidden word: \t{hidden_word}')
|
assem-ch/snowball | python/stemwords.py | Python | bsd-3-clause | 3,277 | 0.001526 | import sys
import re
import codecs
import snowballstemmer
def usage():
print('''usage: %s [-l <language>] [-i <input file>] [-o <output file>] [-c <character encoding>] [-p[2]] [-h]
The input file consists of a list of words to be stemmed, one per
line. Words should be in lower case, but (for English) A-Z letters... | input == '' or output == '':
usage()
else:
stemming(language, input, output, encoding, pretty)
def stemming(lang, input, output, encoding, pretty):
stemmer = snowballstemmer.stemmer(lang)
outfile = codecs.open(output, "w", encoding)
for original in codecs.open(input, "r", ... | ers to lowercase, to match C behavior
original = ''.join((lower_(c) if 'A' <= c <= 'Z' else c for c in original))
stemmed = stemmer.stemWord(original)
if pretty == 0:
if stemmed != "":
outfile.write(stemmed)
elif pretty == 1:
outfile.write(original... |
sharescience/ardupilot | Tools/scripts/build_binaries.py | Python | gpl-3.0 | 26,405 | 0.000227 | #!/usr/bin/env python
"""
script to build the latest binaries for each vehicle type, ready to upload
Peter Barker, August 2017
based on build_binaries.sh by Andrew Tridgell, March 2013
"""
from __future__ import print_function
import datetime
import optparse
import os
import re
import shutil
import time
import subpr... | errno != 2:
raise
# see if there's a hwdef.dat for this board:
if os.path.exists(os.path.join(self.basedir,
'libraries',
'AP_HAL_ChibiOS',
'hwdef',
... | board)):
self.progress("ChibiOS build: %s" % (board,))
return False
self.progress("Skipping unsupported board %s" % (board,))
return True
def skip_frame(self, board, frame):
'''returns true if this board/frame combination should not be built'''
if fr... |
cordis/pyschema | pyschema/nodes.py | Python | mit | 2,017 | 0 | from decimal import Decimal as DecimalDecoder
try:
from bson import ObjectId as ObjectIdEncoder
except ImportError:
def ObjectIdEncoder(*args):
raise ImportWarning('`bson` module not found')
from pyschema.bases import BaseNode
__all__ = [
'Node',
'Str',
'Unicode',
'Int',
'Bool',
... | ult_encode = str
class ObjectId(Node):
default_decode = str
default_encode = ObjectIdEncoder
class Builder(Node):
default_decode = dict
def __init__(self, schema_cls, key=None):
super(Builder, self).__init__(key=key)
self. | schema_cls = schema_cls
class Registry(Node):
def __init__(self, args_getter, registry, key=None):
super(Registry, self).__init__(key=key)
self.args_getter = args_getter
self.registry = registry
class List(Node):
default_decode = list
default_encode = list
def __init__(self,... |
bussiere/pypyjs | website/demo/home/rfk/repos/pypy/lib_pypy/_ctypes/basics.py | Python | mit | 7,084 | 0.005788 |
import _rawffi
import _ffi
import sys
try: from __pypy__ import builtinify
except ImportError: builtinify = lambda f: f
keepalive_key = str # XXX fix this when provided with test
def ensure_objects(where):
try:
ensure = where._ensure_objects
except AttributeError:
return None
return ensu... | #
assert False, 'unknown shape %s' % (shape,)
_shape_to_ffi_type.typemap = {
'c' : _ffi.types.char,
'b' : _ffi.types.sbyte,
'B' : _ffi.types.ubyte,
'h' : _ffi.types.sshort,
'u' : _ffi.types.unichar,
'H' : _ffi.types.ushort,
'i' : _ffi.types.sint,
'I' : _ffi.types.uint,
'l' : ... | 'f' : _ffi.types.float,
'd' : _ffi.types.double,
's' : _ffi.types.void_p,
'P' : _ffi.types.void_p,
'z' : _ffi.types.void_p,
'O' : _ffi.types.void_p,
'Z' : _ffi.types.void_p,
'X' : _ffi.types.void_p,
'v' : _ffi.types.sshort,
'?' : _ffi.types.ubyte,
}
# called from primitive.py, ... |
ibmsoe/ImpalaPPC | tests/custom_cluster/test_spilling.py | Python | apache-2.0 | 3,129 | 0.008949 | # Copyright (c) 2014 Cloudera, 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 o... | d_catalog_i | n_background=false"'])
super(CustomClusterTestSuite, cls).setup_class()
def setup_method(self, method):
# We don't need CustomClusterTestSuite.setup_method() or teardown_method() here
# since we're not doing per-test method restart of Impala.
pass
def teardown_method(self, method):
pass
@cl... |
tatarbrot/foraging | hive_com.py | Python | gpl-3.0 | 687 | 0.004367 | #!/usr/bin/env python
from hive import *
from bee import *
from random import random as rand
import numpy as np
class HiveCom(Hive):
def __init__(self, x, y, n_bees, grid_size, grid):
self.directions = []
Hive.__init__( | self, x, y, n_bees, grid_size, grid)
def assign_settings(self, b | ee):
Hive.assign_settings(self, bee)
# direction
if len(self.directions) == 0:
new_angle = bee.compute_angle()
else:
new_angle = self.directions.pop()
bee.angle = new_angle
def load_settings_from(self, bee):
self.directions.append(bee.me... |
MayankGo/ec2-api | ec2api/config.py | Python | apache-2.0 | 2,017 | 0 | # Copyright 2014
# The Cloudscaling Group, 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... | S OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from oslo_config import cfg
from oslo_db import options
from oslo_log import log
from ec2api import pa | ths
from ec2api import version
CONF = cfg.CONF
_DEFAULT_SQL_CONNECTION = 'sqlite:///' + paths.state_path_def('ec2api.sqlite')
_DEFAULT_LOG_LEVELS = ['amqp=WARN', 'amqplib=WARN', 'boto=WARN',
'qpid=WARN', 'sqlalchemy=WARN', 'suds=INFO',
'oslo.messaging=INFO', 'iso8601=WA... |
leapcode/soledad | src/leap/soledad/server/launcher.py | Python | gpl-3.0 | 1,831 | 0 | # -*- coding: utf-8 -*-
# launcher.py
# Copyright (C) 2017 LEAP
#
# 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.
#
# Th... | f parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--version', action='store_true',
help='Print the program versi | on.')
return parser.parse_args()
def here(module=None):
if STANDALONE:
# we are running in a |PyInstaller| bundle
return sys._MEIPASS
else:
if module:
return os.path.dirname(module.__file__)
else:
return os.path.dirname(__file__)
def run_server():
... |
davebridges/ExperimentDB | experimentdb/__init__.py | Python | bsd-3-clause | 2,496 | 0.003205 | """The experimentDB is a web-based application for the storage, organization and communication of experimental data with a focus on molecular biology and biochemical data. This application also stores data regarding reagents, including antibodies, constructs and other biomolecules as well as tracks the distribution of ... | common relevant information.
External
--------
The idea is to attribute particular models with references regarding external contacts or vendors or to link in specific references important to the experiments or projects.
D | atasets
--------
The datasets app contains data and views for some external databases. This may include external databases accessed directly or with a mirrored internal database. This module is fairly research-interest specific and will likely be removed eventually.
"""
|
guyinatuxedo/escape | buf_ovf/b4_64/exploit.py | Python | gpl-3.0 | 1,016 | 0.01378 | #Import the pwntools library.
from pwn import *
#The process is like an actualy command you run, so you will have to adjust the path if your exploit isn't in the same directory as the challenge.
target = process("./b4_64")
#Just receive the first line, which for our purposes isn't important.
target.recvline()
#Store... | o prevent conversion issues
address = target.recvline().strip("\n")
#Convert the string to a hexidecimal
address = int(address, 16)
#Pack the hexidecimal in little endian for 32 bit systems
address = p64(address)
print address
#Store the shellcode in a variable
shellcode = "\x31\xc0\x48\xbb\xd1\x9d\x96\x91\xd0\x8c\x9... | #Send the payload
target.sendline(payload)
#Drop into interactive mode so you can use the shell
target.interactive()
|
openstack/zaqar | zaqar/tests/unit/transport/wsgi/v1_1/test_messages.py | Python | apache-2.0 | 25,080 | 0 | # Copyright (c) 2013 Rackspace, 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... | r m in sample_messages])
# Test GET on the message resource directly
# NOTE(cpp-cabrera): force the passing of time to age a message
timeu | tils_utcnow = 'oslo_utils.timeutils.utcnow'
now = timeutils.utcnow() + datetime.timedelta(seconds=10)
with mock.patch(timeutils_utcnow) as mock_utcnow:
mock_utcnow.return_value = now
for msg_id in msg_ids:
message_uri = self.messages_path + '/' + msg_id
... |
grehujt/leetcode | 17. Letter Combinations of a Phone Number/solution.py | Python | mit | 707 | 0.004243 | class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
def fill(n):
if n == l:
result.append(''.join(combination))
return
for cs in ds[digits[n]]:
| for c in cs:
combination[n] = c
fill(n+1)
ds = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
l = len(digits)
if l < 1:
re | turn []
combination = ['x'] * l
result = []
fill(0)
return result
print Solution().letterCombinations('238')
|
wilsonkichoi/zipline | zipline/data/minute_bars.py | Python | apache-2.0 | 33,297 | 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 writ... | market_opens,
market_closes,
ohlc_ratio):
self.first_trading_day = first_trading_day
self.market_opens = market_opens
self.market_closes = market_closes
self.ohlc_ratio = ohlc_ratio
def write(self, rootdir):
"""
Write the metadat... | : string
'YYYY-MM-DD' formatted representation of the first trading day
available in the dataset.
minute_index : list of integers
nanosecond integer representation of the minutes, the enumeration
of which corresponds to the values in each bcolz carray.
... |
veltzer/demos-python | src/examples/short/keyring/get.py | Python | gpl-3.0 | 253 | 0 | #!/usr/bin/env python
"""
A basic example of how to get a pa | ssword from the default
keyring of you environment.
"""
import keyring
password = keyring.get_password(u"dummyapp", u"mark.v | eltzer@gmail.com")
print("your password is [{}]".format(password))
|
polyaxon/polyaxon | core/tests/test_polypod/test_resolvers/test_core_resolver.py | Python | apache-2.0 | 9,111 | 0.000439 | #!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, 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 ... |
assert resolver.a | rtifacts_store == connection1
assert [s.schema for s in resolver.secrets] == [secret1.schema, secret2.schema]
assert resolver.polyaxon_sidecar == get_default_sidecar_container()
assert resolver.polyaxon_init == get_default_init_container()
# Add run spec to resolve connections
c... |
socialwifi/dila | dila/data/base_strings.py | Python | bsd-3-clause | 2,698 | 0.002224 | import sqlalchemy
import sqlalchemy.dialects.postgresql as postgres_dialect
from sqlalchemy import orm
from dila.application import structures
from dila.data import engine
from dila.data import resources
class BaseString(engine.Base):
__tablename__ = 'base_string'
id = sqlalchemy.Column(postgres_dialect.UUID... | :
return None
def add_or_update_base_string(resource_pk, base_string, *, comment, context, plural=''):
try:
base_string = BaseString.query.filter(
BaseString.resource_pk == resource_pk,
BaseString.base_string == base_string,
BaseString.context == (co | ntext or ''),
).one()
except sqlalchemy.orm.exc.NoResultFound:
base_string = BaseString(resource_pk=resource_pk, base_string=base_string, comment=comment, context=context,
plural=plural)
engine.session.add(base_string)
else:
base_string.comment = ... |
Datera/cinder | cinder/tests/unit/volume/drivers/netapp/dataontap/client/test_api.py | Python | apache-2.0 | 23,756 | 0.000042 | # Copyright (c) 2014 Ben Swartzlander. All rights reserved.
# Copyright (c) 2014 Navneet Singh. All rights reserved.
# Copyright (c) 2014 Clinton Knight. All rights reserved.
# Copyright (c) 2014 Alex Meade. All rights reserved.
# Copyright (c) 2014 Bob Callaway. All rights reserved.
#
# Licensed under the Apac... | R)
mock_invoke.assert_called_with(zapi_fakes.FAKE_XML_STR)
def test__build_opener_not_implemented_error(self):
"""Tests whether certificate style authorization raises Exception"""
self.root._auth_style = 'not_basic_auth'
self.assertRaises(NotImplementedError, self.root._build_open... | """Tests whether build opener works with valid parameters"""
self.root._auth_style = 'basic_auth'
mock_invoke = self.mock_object(urllib.request, 'build_opener')
self.root._build_opener()
self.assertTrue(mock_invoke.called)
@ddt.data(None, zapi_fakes.FAKE_XML_STR)
def test... |
projectcalico/calico-nova | nova/tests/unit/api/openstack/compute/contrib/test_server_groups.py | Python | apache-2.0 | 14,004 | 0.001428 | # Copyright (c) 2014 Cisco Systems, 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 r... |
def server_group_template(**kwargs):
sgroup = kwargs.cop | y()
sgroup.setdefault('name', 'test')
return sgroup
def server_group_resp_template(**kwargs):
sgroup = kwargs.copy()
sgroup.setdefault('name', 'test')
sgroup.setdefault('policies', [])
sgroup.setdefault('members', [])
return sgroup
def server_group_db(sg):
attrs = sg.copy()
if 'i... |
yarikoptic/pystatsmodels | statsmodels/tsa/tsatools.py | Python | bsd-3-clause | 17,721 | 0.005135 | import numpy as np
import numpy.lib.recfunctions as nprf
from statsmodels.tools.tools import add_constant
def add_tre | nd(X, trend="c", prepend=False):
"""
Adds a trend and/or constant to an array.
Parameters
----------
X : array-like
Original array of data.
trend : str {"c","t","ct","ctt"}
"c" add constant only
"t" add trend only
"ct" add constant and linear trend
"ctt" ... | Returns columns as ["ctt","ct","c"] whenever applicable. There is currently
no checking for an existing constant or trend.
See also
--------
statsmodels.add_constant
"""
#TODO: could be generalized for trend of aribitrary order
trend = trend.lower()
if trend == "c": # handles struc... |
logston/django_openS3 | setup.py | Python | mit | 2,012 | 0 | #! /usr/bin/env python
import os
import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
import django_openS3
with open(os.path.join(os.path.dirname(__file__), "README.rst")) as file:
README = file.read()
with open(os.path.join(os.path.dirname(__file__), 'LICENSE')) as ... | :: Python :: 3.4",
"Programming Language :: Python :: 3 :: Only",
"Topic :: Internet",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Utilities",
]
setup(name='django_openS3',
version=django_openS3.__version__,
author=django_openS3.__author__,
author_email=django_openS3.__email__,
... | S3.__email__,
url='http://github.com/logston/django_openS3',
description='An openS3 wrapper for use with Django',
long_description=README,
license=LICENSE,
classifiers=CLASSIFIERS,
packages=['django_openS3'],
include_package_data=True,
package_data={'': ['LICENSE', 'READM... |
anderson1008/NOCulator | hring/src/Script/eval_batch.py | Python | mit | 2,292 | 0.02007 | #!/usr/bin/python
import sys
import os
import re
import fnmatch
import string
import compute
import get
dir_canpc = "/home/anderson/Desktop/results/homo_mem/"
dir_alone = dir_canpc + "baseline/4x4_insn100K/"
dir_share = dir_canpc + "mshr/"
sum_ws = 0
sum_hs = 0
sum_uf = 0
eff_count = 0
ipc_alone = ... | eff_count = eff_count + 1
sum_ws = sum_ws + w | s
sum_hs = sum_hs + hs
sum_uf = sum_uf + uf
#print "Weighted Speedup = " + str("%.3f" % ws)
#print "Harmonic Speedup = " + str("%.3f" % hs)
#print "Unfairness = " + str("%.3f" % uf)
avg_ws = sum_ws / eff_count
avg_hs = sum_hs / eff_count
avg_uf = sum_uf / eff_count
print "Weighted Speedup = " + ... |
videetssinghai/Blog-Rest-Api | posts/api/permissions.py | Python | mit | 196 | 0.010204 | from rest_framework.permissions import BasePermission
class IsOwnerOrReadOnly(BasePermission):
d | ef has_ | object_permission(self, request, view, obj):
return obj.user == request.user |
Eagles2F/sync-engine | tests/security/test_smtp_ssl.py | Python | agpl-3.0 | 3,497 | 0.000286 | import ssl
import json
import smtpd
import asyncore
import datetime
import pytest
import gevent
from tests.util.base import default_account
from tests.api.base import api_client, new_api_client
from tests.api | _legacy.base import api_client as api_legacy_client
__all__ = ['api_client', 'api_legacy_cl | ient', 'default_account']
SELF_SIGNED_CERTFILE = 'tests/data/self_signed_cert.pem'
SELF_SIGNED_KEYFILE = 'tests/data/self_signed_cert.key'
from inbox.sendmail.smtp.postel import SMTP_OVER_SSL_TEST_PORT
SMTP_SERVER_HOST = 'localhost'
SMTP_SERVER_PORT = SMTP_OVER_SSL_TEST_PORT
class BadCertSMTPServer(smtpd.Debugging... |
teythoon/Insekta | insekta/scenario/management/commands/vmd.py | Python | mit | 2,945 | 0.001698 | from __future__ import print_function
import time
import signal
from datetime import datetime
from django.core.management.base import NoArgsCommand
from django.conf import settings
from insekta.common.virt import connections
from insekta.scenario.models import ScenarioRun, RunTaskQueue, ScenarioError
from insekta.vm.... | NARIO_EXPIRE_TIME)
for scenario_run in expired_runs:
try:
scenario_run.vm.destroy()
except VirtualMachineError:
| # We have an inconsistent state. See comment above.
pass
current_time = time.time()
time_passed = current_time - last_call
if time_passed < MIN_SLEEP:
time.sleep(MIN_SLEEP - time_passed)
last_call = current_time
connections.... |
deuscoin-org/deuscoin-core | qa/rpc-tests/test_framework/bignum.py | Python | mit | 1,997 | 0.006009 | #
#
# bignum.py
#
# This file is copied from python-deuscoinlib.
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
"""Bignum routines"""
from __future__ import absolute_import, division, print_function, unicode_literals
im... | size
r = r[::-1] # reverse string, converting BE->LE
return r
def bn2vch(v):
return bytes(mpi2vch(bn2mpi(v)))
def vch2mpi(s):
r = struct.pack(b">I", len(s)) # size
r + | = s[::-1] # reverse string, converting LE->BE
return r
def vch2bn(s):
return mpi2bn(vch2mpi(s))
|
Sigmapoint/notos | src/notos/policies.py | Python | mit | 4,467 | 0.005373 | '''
Created on 25-07-2013
@author: kamil
'''
import logging
import datetime
from django.contrib.contenttypes.models import ContentType
from django.utils.timezone import utc
from models import ScheduledPush
class BasePushPolicy:
ALLOWED_METHODS = ["POST", "PUT", "PATCH", "DELETE"]
MAX_RETRIES = 5
... | for_concrete_model=False
)
app_label = ct.app_label
classname = self.view.queryset.model.__name__
entity_id = u".".join([app_label, classname])
else:
entity_id = None
| return entity_id
def get_has_many(self, reg_id):
try:
obj = self.view.object
except AttributeError:
obj = None
try:
qs = self.view.qs
except AttributeError:
qs = None
if obj:
return False
elif qs:
... |
russelmahmud/mess-account | core/utils.py | Python | bsd-3-clause | 581 | 0.006885 | from datetime import date, timedelta, datetime
import time
def | get_first_day(dt, d_years=0, d_months=0):
# d_years, d_months are "deltas" to apply to dt
y, m = dt.year + d_years, dt.month + d_months
a, m = divmod(m-1, 12)
return date(y+a, m+1, 1)
def get_last_day(dt):
return get_first_day(dt, 0, 1) + timedelta(-1)
def str_to_date(value):
"""
Conver... | return value
if value.__class__.__name__ in ['date']:
return value
return datetime.strptime(value, "%Y-%m-%d").date()
|
jsvine/markovify | test/test_basic.py | Python | mit | 7,758 | 0.001676 | import unittest
import markovify
import os
import operator
def get_sorted(chain_json):
return sorted(chain_json, key=operator.itemgetter(0))
class MarkovifyTestBase(unittest.TestCase):
__test__ = False
def test_text_too_small(self):
text = "Example phrase. This is another example sentence."
... | sent = self.sherlock_model.make_short_sentence(100, min_chars=50)
assert len(sent) <= 100
assert len(sent) >= 50
def test_dont_test_output(self):
text_model = self.sherlock_model
sent = text_model.make_sentence(test_output=False)
assert sent is not None
def t... | xt_model = self.sherlock_model
sent = text_model.make_sentence(min_words=5)
assert len(sent.split(" ")) >= 5
def test_newline_text(self):
with open(
os.path.join(os.path.dirname(__file__), "texts/senate-bills.txt")
) as f:
model = markovify.NewlineText(f.read... |
chipaca/snapcraft | tests/unit/plugins/v1/test_maven.py | Python | gpl-3.0 | 23,004 | 0.001435 | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2016-2018-2020 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distribute... | ("11", "core18"),
]
@pytest.fixture(params=_BASE_JAVA_COMBINATIONS)
def maven_plugin(tmp_work_path, request):
"""Return an instance of MavenPlugin setup with different bases and java versions."""
java_version, base = request.param
cl | ass Options:
maven_options = []
maven_targets = [""]
maven_version = maven._DEFAULT_MAVEN_VERSION
maven_version_checksum = maven._DEFAULT_MAVEN_CHECKSUM
maven_openjdk_version = java_version
project = Project()
project._snap_meta = Snap(name="test-snap", base=base, confin... |
LighthouseHPC/lighthouse | sandbox/scripts/anamod2arff.py | Python | mit | 18,296 | 0.013172 | #!/usr/bin/env python
'''
Created on Feb 17, 2015
@author: norris
'''
import re, sys, os, argparse, glob, time, datetime, socket, random
from solvers import *
solveropts = getsolvers()
def readFeatures(dirname='anamod_features'):
files=glob.glob(dirname + '/*.anamod')
featuresre= re.compile(r'========([^=]+)=... | ictstr += " '" + nameval[0] + "' : " + val + ','
tmpdictstr.rstrip(',')
tmpdictstr += '}'
features[matrixname] = eval(tmpdictstr.replace('****',"'?'").replace('-nan',"'?'").replace('inf',"float('Inf')"))
#print feature_times
return | features, feature_times
def readFeaturesTrilinos(path='tpetra_properties/12procs_results.csv'):
fd = open(path,'r')
lines = fd.readlines()
fd.close()
features = dict()
# features dictionary is indexed by matrix name
# each value is a dictionary with keys corresponding to feature name and
#... |
vtemian/uni-west | second_year/os/exams/round2/scheduler/parsers/base.py | Python | apache-2.0 | 207 | 0 | from abc | import ABCMeta, abstractmethod
class Parser(object):
__meta__ = ABCMeta
def __init__(self, source):
self.source = source
@abstractmethod
| def schedule(self):
pass
|
bendemott/solr-zkutil | solrzkutil/__init__.py | Python | mit | 38,530 | 0.00654 | #!/usr/bin/python
from __future__ import print_function
from __future__ import unicode_literals
import os
import sys
import time
import argparse
from datetime import datetime, timedelta, tzinfo
from textwrap import dedent
import json
from random import choice
import webbrowser
import itertools
import log... | te.
WATCH_COUNTER = 0
ZK_ADMIN_CMDS = {
'conf': {
'help': 'Print details about serving configuration.',
'example': '',
'version': '3.3.0',
},
'cons': {
'help': ('List full connection/session details for all clients connected to | this server. '
'Includes information on numbers of packets received/sent, session id, operation '
'latencies, last operation performed, etc...'),
'example': '',
'version': '3.3.0',
},
'crst':{
'help': 'Reset connection/session statistics for all connections... |
Letractively/spiff | src/FooLib/OptionParser.py | Python | gpl-2.0 | 2,493 | 0.005616 | # Copyright (C) 2007 Samuel Abels, http://debain.org
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOU... | to parse the options.
short = ''.join([option[1] or '' for option in options])
lon | g = [option[0] for option in options]
try:
opts, args = getopt(argv[1:], short, long)
except:
raise Exception("Invalid arguments")
# Copy the default options into a hash.
option_hash = {}
for option in options:
long = option[0].replace('=', '')
op... |
vikkyrk/incubator-beam | sdks/python/apache_beam/runners/dataflow/internal/dependency_test.py | Python | apache-2.0 | 16,889 | 0.00521 | #
# 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 us... | gleCloudOptions).staging_location = staging_dir
self.update_options(options)
options.view | _as(SetupOptions).setup_file = os.path.join(
source_dir, 'setup.py')
self.assertEqual(
[dependency.WORKFLOW_TARBALL_FILE],
dependency.stage_job_resources(
options,
# We replace the build setup command because a realistic one would
# require the setuptools... |
ahmedaljazzar/edx-platform | common/djangoapps/third_party_auth/migrations/0021_sso_id_verification.py | Python | agpl-3.0 | 1,186 | 0.00253 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-04-11 15:33
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('third_party_auth', '0020_cleanup_slug_fields'),
]
operations = [
migration... | providerconfig',
name='enable_sso_id_verification',
field=models.BooleanField(default=False, help_text=b'Use the presence of a profile from a trusted third party as proof of identity verification.'),
),
migrations.AddField(
model_name='oauth2providerconfig',
... | me='enable_sso_id_verification',
field=models.BooleanField(default=False, help_text=b'Use the presence of a profile from a trusted third party as proof of identity verification.'),
),
migrations.AddField(
model_name='samlproviderconfig',
name='enable_sso_id_verificati... |
formalmethods/intrepyd | intrepyd/iec611312py/stmtbuilder.py | Python | bsd-3-clause | 8,639 | 0.002199 | """
Copyright (C) 2018 Roberto Bruttomesso <roberto.bruttomesso@gmail.com>
This file is distributed under the terms of the 3-clause BSD License.
A copy of the license can be found in the root directory or at
https://opensource.org/licenses/BSD-3-Clause.
Author: Roberto Bruttomesso <roberto.bruttomesso@gmail.com>
Da... | lExpression(self, ctx):
return ctx.getChild(0).accept(self)
def | visitParBoolExpression(self, ctx):
return ctx.subexpr.accept(self)
def visitParTermExpression(self, ctx):
return ctx.subexpr.accept(self)
def visitSimple_var(self, ctx):
var = ctx.getChild(0).getText()
if not var in self._name2var:
raise RuntimeError('Undeclared... |
wangtaoking1/found_website | 项目代码/classification.py | Python | gpl-2.0 | 6,580 | 0.037633 | # -*- coding: utf-8 -*-
#search函数,参数为输入文件,输出文件,关键词。关键词与输入文件的每六行进行匹配(六行为一条微博),如果出现该关键词,则把该微博输出到输出文件中
def search(input_file,output_file,key):
line = input_file.readline()
if line == "\n":
line = input_file.readline()
while line: #如果文件没有结束,继续读取
lines = ""
lines += line
... | ile=open("data/weibo.txt","r") |
cellphone=open("data/allClasses/cellphone.txt","a")
search(inputFile,cellphone,"iphone")
inputFile.close()
cellphone.close()
inputFile=open("data/weibo.txt","r")
key=open("data/allClasses/key.txt","w")
key.write(s)
search(inputFile,key,"钥匙") #匹配关键词“钥匙”
inputFile.close()
key.clo... |
TwilioDevEd/api-snippets | rest/incoming-phone-numbers/list-post-example-1/list-post-example-1.7.x.py | Python | mit | 660 | 0 | # Download the Python helper library from twilio.com/docs/python/install
import os
from twilio.rest import Client
# Your Account Sid | and Auth Token from twilio.com/user/account
# To set up environmental variables, see http://twil.io/secu | re
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account_sid, auth_token)
number = client.incoming_phone_numbers \
.create(friendly_name="My Company Line",
voice_url="http://demo.twilio.com/docs/voice.xml",
... |
curtisalexander/csvsubquery | csvsubquery.py | Python | mit | 1,220 | 0.006557 | #!/usr/bin/env python
import csv
import click # pip install click -- assumes version 5.x
@click.command()
@click.option('--incsv', type=click.File(mode='rU', lazy=True), help='input csv (the larger of the csv files)')
@click.option('--subcsv', type=click.File(mode='rU', lazy=True), help='subquery csv (the smaller ... | key variable to be used for the subquery - only supports a single key')
def subquery(incsv, subcsv, outcsv, key):
"""Perform a subquery using CSV files with a common key.
\b
Example:
csvsubquery.py -- | incsv /dir/to/infile.csv --subcsv /dir/to/subfile.csv --outcsv /dir/to/outfile.csv --key keyvar
"""
sub_reader = csv.DictReader(subcsv)
key_subset = {row[key] for row in sub_reader}
in_reader = csv.DictReader(incsv)
header = next(in_reader)
out_writer = csv.DictWriter(outcsv, header, extrasacti... |
nburn42/tensorflow | tensorflow/python/ops/linalg/linear_operator_test_util.py | Python | apache-2.0 | 28,767 | 0.005597 | # 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... |
dtypes.float32: 1e-6,
dtypes.float64: 1e-12,
dtypes.complex64: 1e-6,
dtypes.complex128: 1e-12
}
_rtol = {
dtypes.float16: 1e-3,
dtypes.float32: 1e-6,
dtypes.float64: 1e-12,
dtypes.complex64: 1e-6,
dtypes.complex128: 1e-12
}
def assertAC(self, x, y):
""... | nce."""
dtype = dtypes.as_dtype(x.dtype)
atol = self._atol[dtype]
rtol = self._rtol[dtype]
self.assertAllClose(x, y, atol=atol, rtol=rtol)
@property
def _adjoint_options(self):
return [False, True]
@property
def _adjoint_arg_options(self):
return [False, True]
@property
def _dtype... |
lyndsysimon/django-changelog | tests/test_settings.py | Python | gpl-3.0 | 2,637 | 0.001517 | import os
# Build paths inside t | he project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'fake-key'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.co | ntenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'tests',
'changelog',
]
ROOT_URLCONF = 'tests.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTI... |
tdruez/django-registration | registration/runtests.py | Python | bsd-3-clause | 2,003 | 0 | """
A standalone test runner script, configuring the minimum settings
required for tests to execute.
Re-use at your own risk: many Django applications will require
different settings and/or templates to run their tests.
"""
import os
import sys
# Make sure the app is (at least temporarily) on the import path.
APP_... | sts():
# Making Django run this way is a two-step process. First, call
# settings.configure() to give Django settings to work with:
fro | m django.conf import settings
settings.configure(**SETTINGS_DICT)
# Then, call django.setup() to initialize the application cache
# and other bits:
import django
if hasattr(django, 'setup'):
django.setup()
# Now we instantiate a test runner...
from django.test.utils import get_runn... |
michael-okeefe/soep-sandbox | src/python2/dump_source.py | Python | mit | 815 | 0.006135 | # Import the JModelica.org Python packages
import pymodelica
from pymodelica.compiler_wrappers import ModelicaCompiler
# Create a compiler and compiler target object
mc = ModelicaCom | piler()
# Build trees as if for an FMU or Model Exchange v 1.0
#target = mc.create_target_object("me", "1.0")
source = mc.parse_model("CauerLowPassAnalog.mo")
indent_a | mount = 2
def dump(src, fid, indent=0):
ind = " " * (indent_amount * indent)
try:
fid.write(ind + src.getNodeName() + "\n")
except:
fid.write(ind + "exception: " + str(src) + "\n")
try:
for idx in range(src.numChild):
dump(src.children[idx], fid, indent+1)
except... |
ktkirk/HSSI | IoT/iot_lcd.py | Python | bsd-2-clause | 1,768 | 0.005656 | #!/usr/bin/env python
from __future__ import print_function
import time
import pyupm_grove as grove
import pyupm_i2clcd as lcd
import pyupm_th02 as th02
import pyupm_guvas12d as upmUV
import pyupm_grovemoisture as upmMoisture
from phant import Phant
import requests
from iot_utils import *
__author__ = 'KT Kirk'
# Ini... | ject using AIO pin 0
i2c_th = th02.TH02()
#
p = Phant(keys["publicKey"],
'device', 'temp', 'humidity', 'light', "uv", "moisture",
private_key=keys["privateKey"])
device = open("/factory/serial_nu | mber").read().strip('\n')
while(True):
temp = i2c_th.getTemperature()
humid = i2c_th.getHumidity()
lux_val = light.value()
uv_val = uv.value(GUVAS12D_AREF, SAMPLES_PER_QUERY)
moisture_val = moisture.value()
myLcd.setCursor(1, 0)
try:
p.log(device, temp, humid, lux_val, uv_val, mois... |
metacloud/molecule | test/unit/command/test_syntax.py | Python | mit | 1,887 | 0 | # Copyright (c) 2015-2018 Cisco Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge... | # DEALINGS IN THE SOFTWARE.
import pytest
from molecule.command import syntax
@pytest.fixture
def _patched_ansible_syntax(mocker):
return mocker.patch('molecule.provisioner.ansible.Ansible.syntax')
# NOTE(retr0h): The use of the `patched_config_validate` fixture, disables
# config.Config._validate from execu... | hus preventing odd side-effects
# throughout patched.assert_called unit tests.
def test_execute(mocker, patched_logger_info, _patched_ansible_syntax,
patched_config_validate, config_instance):
s = syntax.Syntax(config_instance)
s.execute()
x = [
mocker.call("Scenario: 'default'"),
... |
correctiv/correctiv-justizgelder | correctiv_justizgelder/views.py | Python | mit | 1,160 | 0 | from django.views.generic import ListView, DetailView
from .forms import OrganisationSearchForm
from .models import Organisation
class OrganisationSearchView(ListView):
template_name = 'justizgelder/search.html'
paginate_by = 25
def get_queryset(self):
self.form = OrganisationSearchForm(self.req... | ionSearchView,
self).get_context_data(**kwargs)
context['aggregates'] = self.aggregates
context['query'] = self.request.GET.get('q')
context['form'] = self.form
context['base_template'] = 'justizgelder/search_base.html'
if self.request.GET.get('embed'):
... | e_name = 'justizgelder/organisation_detail.html'
model = Organisation
def get_context_data(self, **kwargs):
context = super(OrganisationDetail, self).get_context_data(**kwargs)
return context
|
stencila/hub | manager/accounts/api/serializers_account_image.py | Python | apache-2.0 | 740 | 0.001351 | from rest_framework import serializers
from accounts.models import Account
class AccountImageSerializer(serializers.Serializer):
"""
A serializer for account images.
The main purpose of this class is to provide a subschema
for the type of the account.image in | responses.
"""
small = serializers.CharField()
medium = serializers.CharField()
large = serializers.CharField()
@staticmethod
def create(request, account: Account):
"""Get the URLs of alternative image sizes for the account."""
return dict(
[
(size,... | ccount.image, size)),)
for size in ("small", "medium", "large")
]
)
|
ChessCorp/docker-ascii-map | tests/raster_test.py | Python | mit | 3,352 | 0.00179 | import unittest
from docker_ascii_map.raster import Raster, Boundary, RasterCell
class RasterTests(unittest.TestCase):
def test_empty_raster(self):
raster = Raster()
self.assertEqual('', str(raster))
self.assertEqual((0, 0), raster.size())
self.assertEqual(RasterCell(), raster.get... | , str(r)
)
def test_line_overlap(self):
r = Raster()
r.draw_line(0, 3, 6, 2)
r.draw_line(0, 3, 6, 0)
self.assertEqual(
' +--\n'
' |\n'
' +--\n'
| '---+\n'
, str(r)
)
def test_color_disabled(self):
r = Raster()
r.write(0, 0, 'Red', color='red')
r.write(0, 1, 'Green', color='green')
self.assertEqual(
'Red\n'
'Green\n'
, str(r)
)
def test_color_enab... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.