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 |
|---|---|---|---|---|---|---|---|---|
rdo-management/tuskar | tuskar/tests/templates/test_namespace.py | Python | apache-2.0 | 1,765 | 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
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Li... | self.assertTrue(namespace.matches_template_namespace('test-ns', value))
self.assertFalse(namespace.matches_template_namespace('fake', value))
def test_apply_resource_alias_namespace(self):
namespaced = namespace.apply_resource_alias_namespace('compute')
self.assertEqual(namespaced, 'Tus... | ual(stripped, 'controller')
|
QualiSystems/OpenStack-Shell | package/tests/test_cp/test_openstack/test_domain/test_services/test_nova/test_nova_instance_service.py | Python | isc | 27,295 | 0.005166 | from unittest import TestCase
from mock import Mock
from cloudshell.cp.openstack.domain.services.nova.nova_instance_service import NovaInstanceService
import cloudshell.cp.openstack.domain.services.nova.nova_instance_service as test_nova_instance_service
from cloudshell.cp.openstack.common.driver_helper import Cloudsh... | deploy_req_model=Mock(),
cancellation_context=Mock(),
logger=self.mock_logger)
self.assertEqual(result, None)
def test_instance_create_success(self):... | mock_client2 = Mock()
test_nova_instance_service.novaclient.Client = Mock(return_value=mock_client2)
# mock_client.Client = Mock(return_vaule=mock_client2)
mock_image = Mock()
mock_flavor = Mock()
mock_client2.images.find = Mock(return_value=mock_image)
mock_client2.f... |
Alignak-monitoring/alignak | tests/test_macros_resolver.py | Python | agpl-3.0 | 51,044 | 0.005924 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2018: Alignak team, see AUTHORS.txt file for contributors
#
# This file is part of Alignak.
#
# Alignak is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free So... | f test_args_macro(self):
"""
Test ARGn macros
:return:
"""
print("Initial test macros: %d - %s" % (len(self._scheduler.pushed_conf.__class__.macros),
self._scheduler.pushed_conf.__class__.macros))
print(" - : %s" % (self._sc... | nt(" - : %s" % (self._scheduler.pushed_conf.properties['$USER1$']))
print(" - : %s" % (getattr(self._scheduler.pushed_conf, '$USER1$', None)))
for key in self._scheduler.pushed_conf.__class__.macros:
key = self._scheduler.pushed_conf.__class__.macros[key]
if key:
... |
nachiketmistry/splunk-app-pstack | bin/paginatefields.py | Python | mit | 391 | 0.015345 | # | Version 4.0
i | mport csv
import sys
count = 10
offset = 0
if len(sys.argv) >= 3:
count = int(sys.argv[1])
offset = int(sys.argv[2]) - 1
start = offset*count
start = 1 if start==0 else start
end = start + count
r = csv.reader(sys.stdin)
rows = []
i = 0
for l in r:
rows.append(l[:1] + l[start:end])
i = i + 1
if... |
OpenClovis/ncclient | ncclient/transport/session.py | Python | apache-2.0 | 9,854 | 0.003146 | # Copyright 2009 Shikhar Bhushan
# Copyright 2014 Leonidas Poulopoulos
#
# 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... | ass:`SessionListener`
| """
logger.debug('installing listener %r' % listener)
if not isinstance(listener, SessionListener):
raise SessionError("Listener must be a SessionListener type")
with self._lock:
self._listeners.add(listener)
def remove_listener(self, listener):
"""Unreg... |
DataDog/integrations-extras | portworx/datadog_checks/portworx/__init__.py | Python | bsd-3-clause | 115 | 0 | from .__about__ import __version__
from .portworx import PortworxCheck
|
__all__ = [' | __version__', 'PortworxCheck']
|
alexrudy/Zeeko | zeeko/handlers/setup_package.py | Python | bsd-3-clause | 1,501 | 0.016656 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
from zeeko._build_helpers import get_utils_extension_args, get_zmq_extension_args, _generate_cython_extensions, pxd, get_package_data
from astropy_helpers import setup_helpers
utilities = [pxd("..utils.rc"),
pxd("..utils.msg"),
... | rgs())
extension_args.update(get_zmq_extension_args())
extension_args['include_dirs'].append('numpy')
package_name = __name__.split(".")[:-1]
extensions = [e for e in _generate_cython_extensions(extension_args, os.pat | h.dirname(__file__), package_name)]
for extension in extensions:
name = extension.name.split(".")[-1]
if name in dependencies:
extension.depends.extend(dependencies[name])
return extensions |
jplusplus/broken-promises | Scripts/collect_articles.py | Python | gpl-3.0 | 3,847 | 0.011178 | #!/usr/bin/env python
# Encoding: utf-8
# -----------------------------------------------------------------------------
# Project : Broken Promises
# -----------------------------------------------------------------------------
# Author : Edouard Richard <edou4rd@gmail.com>
# ----------... | OUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Broken Promises. If not, see <http://www.gnu.org/lice... | til import dumps
import optparse
import brokenpromises.channels
import sys
import reporter
reporter.REPORTER.register(reporter.StderrReporter())
debug, trace, info, warning, error, fatal = reporter.bind("script_collect_articles")
oparser = optparse.OptionParser(usage ="\n./%prog [options] year \n./%prog [... |
ajaniv/softwarebook | cpython/contract/core/api.py | Python | gpl-2.0 | 1,699 | 0.006474 | #/usr/bin/env python
# -#- coding: utf-8 -#-
#
# contract/core/api.py - functions which simplify contract package feature access
#
# This file is part of OndALear collection of open source components
#
# This so | ftware is provided 'as-is', without an | y express or implied
# warranty. In no event will the authors be held liable for any damages
# arising from the use of this software.
#
# Copyright (C) 2008 Amnon Janiv <amnon.janiv@ondalear.com>
#
# Initial version: 2008-02-01
# Author: Amnon Janiv <amnon.janiv@ondalear.com>
"""
.. module:: contract.core.api
:sy... |
lukashermann/pytorch-rl | core/models/a3c_mlp_con.py | Python | mit | 4,501 | 0.005776 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from utils.init_weights import init_weights, normalized_columns_initializer
from core.mo... | ims[0] * self.input_dims[1], self.hidden_dim) # NOTE: for pkg="gym"
self.rl1_v = nn.ReLU()
self.fc2_v = nn.Linear(self.hidden_dim, self.hidden_dim)
self.rl2_v = nn.ReLU()
self.fc3_v = nn.Linear(self.hidden_dim, self.hidden_dim)
self.rl3_v = nn.ReLU()
self.fc4_v = nn.Linea... | l4_v = nn.ReLU()
# lstm
if self.enable_lstm:
self.lstm = nn.LSTMCell(self.hidden_dim, self.hidden_dim)
self.lstm_v = nn.LSTMCell(self.hidden_dim, self.hidden_dim)
# 1. policy output
self.policy_5 = nn.Linear(self.hidden_dim, self.output_dims)
self.po... |
dluschan/olymp | lomonosov/num16.py | Python | mit | 550 | 0.005455 | n = int(input())
s = i | nput()
letterlist = ['x', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']
letter = {}
for l in letterlist:
letter[l] = 0
for i in range(n):
if s[i:i+1] in letterlist:
letter[s[i:i+1]] += 1
if letter['x'] > 0 and letter['0'] > 0:
letter['0'] -= 1
del letter['x']... | list:
res += l*letter[l]
print(res)
else:
print('No')
|
ReanGD/web-home-manage | backend/torrents/apps.py | Python | apache-2.0 | 91 | 0 | from django.apps i | mport AppConfig
class TorrentsConfig(AppConfig):
name = 'torre | nts'
|
pivot-libre/tideman | tests/parse_ballot.py | Python | apache-2.0 | 2,798 | 0.006076 | import sys
import json
def make_column_to_candidate_dict(header_row):
my_dict = {}
for colIndex, candidate in enumerate(header_row):
my_dict[colIndex] = candidate.strip()
return my_dict
def return_candidates_in_order(row, col_to_candidate_dict):
ballot = []
for i in range(0,len(row)):
... | ndidate + '")')
candidate_list += ',\n'.join(candidates)
candidate_list += '\n )'
candidate_lists.append(candidate_list)
php += ',\n'.join(candidate_lists | )
php += '\n )'
return php
def get_ballot_arrays(filename):
ballots = []
header = True
ids = False
with open(filename, 'r') as csv:
for line in csv.readlines():
row = split_line(line)
if header:
header = False
ids = Tru... |
anhstudios/swganh | data/scripts/templates/object/static/structure/tatooine/shared_pillar_pristine_small_style_01.py | Python | mit | 469 | 0.046908 | #### NOTICE: THIS FILE | IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Static()
result.template = "object/static/structure/tatooine/shared_pillar_pristine_small_style_01.iff"
result.attribute_template_id = -... | lt |
qytz/qytz-notes | source/tech/PyGObject-Tutorial/examples/button_example.py | Python | mit | 1,105 | 0.00362 | #!/usr/bin/eny python
#coding:utf-8
from gi.repository import Gtk
class ButtonWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title='Button Demo')
self.set_border_width(10)
hbox = Gtk.Box(spacing=6)
self.add(hbox)
button = Gtk.Button('Click Me')
... | ton, True, True, 0)
def on_click_me_clicked(self, button):
print '"click me" button was clicked'
def on_open_clicked(self, button):
print '"open" button was clicked'
def on_close_clicked(self, button):
print 'Closing application'
Gtk.main_quit() |
wind = ButtonWindow()
wind.connect('delete-event', Gtk.main_quit)
wind.show_all()
Gtk.main()
|
andrebellafronte/stoq | stoqlib/gui/test/test_stocktransferwizard.py | Python | gpl-2.0 | 2,810 | 0.004982 | # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
##
## Copyright (C) 2012 Async Open Source <http://www.async.com.br>
## All rights reserved
##
## 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 Foundati... | .emit'
with mock.patch(module) as emit:
with mock.patch.object(self.store, 'commit'):
self.click(wizard.next_button)
self.assertEquals(emit.call_count, 1)
args, kwargs = emit.call_args |
self.assertTrue(isinstance(args[0], TransferOrder))
yesno.assert_called_once_with(
_('Would you like to print a receipt for this transfer?'),
gtk.RESPONSE_YES, 'Print receipt', "Don't print")
self.assertEquals(print_report.call_count, 1)
|
2ndy/RaspIM | usr/lib/python2.6/lib2to3/fixes/fix_itertools_imports.py | Python | gpl-2.0 | 1,840 | 0.000543 | """ Fixer for imports of itertools.(imap|ifilter|izip|ifilterfalse) """
# Local imports
from lib2to3 import fixer_base
from lib2to3.fixer_util import BlankLine, syms, token
class FixItertoolsImports(fixer_base.BaseFix):
PATTERN = """
import_from< 'from' 'itertools' 'import' imports=any >
... | u'ifilter'):
child.value = None
child.remove() |
elif member_name == u'ifilterfalse':
node.changed()
name_node.value = u'filterfalse'
# Make sure the import statement is still sane
children = imports.children[:] or [imports]
remove_comma = True
for child in children:
if remove_c... |
brotherjack/RoodeStem | tests/test_voting_systems.py | Python | mit | 709 | 0.008463 | '''
Created on Jun 29, 2016
@author: Thomas Adriaan Hellinger
'''
import pytest
from roodestem.voting_systems.voting_system import Result
class TestResult:
def test_null_re | sult_not_tolerated(self):
with pytest.raises(TypeError):
Result()
| def test_passed_multiple_winners(self):
res = Result(winner=['a', 'b', 'c'], tied=['b','c'])
assert res == Result(tied=['a', 'b', 'c'])
def test_passed_all_losers(self):
res = Result(loser=['a', 'b', 'c'])
assert res == Result(tied=['a', 'b', 'c'])
def test_passed_al... |
KDD-OpenSource/fexum | users/views.py | Python | mit | 1,286 | 0.001555 | from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.status import HTTP_204_NO_CONTENT
from users.serializers import UserSerializer
from rest_framework.permissions import AllowAny
from django.contrib.auth import login, logout
from rest_framework.authentication import... | user)
return Response(status=HTTP_204_NO_CONTENT)
class AuthLogoutView(APIView):
def delete(sel | f, request):
logout(request)
return Response(status=HTTP_204_NO_CONTENT)
class UserRegisterView(APIView):
permission_classes = (AllowAny,)
authentication_classes = () # TODO: Remove
def post(self, request):
serializer = UserSerializer(data=request.data)
serializer.is_valid... |
butla/experiments | aiohttp_redis_producer_consumer/txodds_code_test/url_extractor.py | Python | mit | 2,896 | 0.003108 | """
The consumer's code.
It takes HTML from the queue and outputs the URIs found in it.
"""
import asyncio
import json
import logging
from typing import List
from urllib.parse import urljoin
import aiored | is
from bs4 import BeautifulSoup
from . import app_cli, redis_queue
_log = logging.getLogger('url_extractor')
def _scrape_urls(html: str, base_url: str) -> List[str]:
"""Gets all valid links from a site and returns them as URIs (some links may be relative.
If the URIs scraped here would go back into the s... | o have more URIs scraped from their
HTML, we would need to filter out all those who are not HTTP or HTTPS.
Also, assuming that many consumers and many producers would be running at the same time,
connected to one Redis instance, we would need to cache normalized versions or visited URIs
without fragment... |
isubuz/zahlen | algorithms/sorting/radix_sort.py | Python | mit | 805 | 0 | from math import log
def sort(a_list, base):
"""Sort the input list with the specified base, using Radix sort.
This implementation assumes that the input list does not contain negative
numbers. This algorithm is inspired from the | Wikipedia implmentation of
Radix sort.
"""
passes = int(log(max(a_list), base) + 1)
items = a_list[:]
for digit_index in xrange(passes):
buckets = [[] for _ in xrange(base)] # Buckets for sorted sublists.
for item in items:
digit = _get_digit(item, base, digit_index)
... | blists in buckets:
items.extend(sublists)
return items
def _get_digit(number, base, digit_index):
return (number // base ** digit_index) % base
|
bnsgeyer/Copter3_4 | Tools/autotest/sim_vehicle.py | Python | gpl-3.0 | 32,299 | 0.002848 | #!/usr/bin/env python
"""
Framework to start a simulated vehicle and connect it to MAVProxy.
Peter Barker, April 2016
based on sim_vehicle.sh by Andrew Tridgell, October 2011
"""
from __future__ import print_function
import atexit
import getpass
import optparse
import os
import os.path
import re
import signal
import... | thub.com/kata198/cygwin-ps-misc/blob/master/pidof
"""
pipe = subprocess.Popen("ps -ea | grep " + proc_name, shell=True, stdout=subprocess.PIPE)
output_lines = pipe.stdout.read().replace("\r", "").split("\n")
ret = pipe.wait()
pids = []
if ret != 0:
# No results
return []
for ... | or item in line.split(' ') if item]
cmd = line_split[-1].split('/')[-1]
if cmd == proc_name:
try:
pid = int(line_split[0].strip())
except:
pid = int(line_split[1].strip())
if pid not in pids:
pids.append(pid)
return ... |
hansika/pyquora | scrape_quora/pyquora.py | Python | apache-2.0 | 3,445 | 0.004354 | import urllib2
from lxml import etree
####################################################################
# API
####################################################################
class Scrape_Quora:
regexpNS = "http://exslt.org/regular-expressions"
@staticmethod
def get_name(user_name):
url =... | uestions(user_name):
url = 'https://www.quora.com/profile/' + user_name
response = urllib2.urlopen(url)
htmlparser = etree.HTMLParser()
tree = etree.parse(response, htmlparser)
no_of_questions = tree.xpath('//*[re:test(@id, "ld_[a-z]+_\\d+", g)]/li/a[text()="Questions"]/span/text... | 're':Scrape_Quora.regexpNS})[0]
return no_of_questions
@staticmethod
def get_no_of_answers(user_name):
url = 'https://www.quora.com/profile/' + user_name
response = urllib2.urlopen(url)
htmlparser = etree.HTMLParser()
tree = etree.parse(response, htmlparser)
no_o... |
FCP-INDI/C-PAC | CPAC/group_analysis/__init__.py | Python | bsd-3-clause | 158 | 0.006329 | from .group_analysis import create_fsl_flame_wf, \
| get_operation
__all__ = ['create_fsl_flame_wf', \
'get_oper | ation']
|
mastizada/kuma | kuma/wiki/migrations/0041_auto__del_firefoxversion__del_unique_firefoxversion_item_id_document__.py | Python | mpl-2.0 | 21,931 | 0.007387 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Removing unique constraint on 'OperatingSystem', fields ['item_id', 'document']
db.delete_unique('wiki_ope... | ('item_id', self.gf('django.db.models.fields.IntegerField')()),
('document', self.gf('django.db.models.fields.related.ForeignKey')(related_name='operating_system_set', to=orm['wiki.Document'])),
('id', self.gf('django.db.models.fields.Auto | Field')(primary_key=True)),
))
db.send_create_signal('wiki', ['OperatingSystem'])
# Adding unique constraint on 'OperatingSystem', fields ['item_id', 'document']
db.create_unique('wiki_operatingsystem', ['item_id', 'document_id'])
# Adding field 'Revision.significance'
... |
cloudbase/cinder | cinder/tests/unit/volume/drivers/emc/vnx/test_client.py | Python | apache-2.0 | 17,512 | 0 | # Copyright (c) 2016 EMC Corporation, 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 ap... | elf, client, mocked):
client.create_lun(pool='pool1', name='lun3', size=1, provision=None,
tier=None, cg_id=None, ignore_thresholds=False)
client.vnx.get_lun.assert_called_once_with(name='lun3')
@res_mock.patch_client
def test_create_lun_in_cg(self, client, mocked):
... | tier=None, cg_id='cg1', ignore_thresholds=False)
@res_mock.patch_client
def test_create_lun_compression(self, client, mocked):
client.create_lun(pool='pool1', name='lun2', size=1,
provision=storops.VNXProvisionEnum.COMPRESSED,
tier=None, cg... |
AntoineToubhans/trellearn | main.py | Python | mit | 389 | 0.002571 | #!/usr/ | bin/env python
import sys
import src.json_importing as I
import src.data_training as T
import src.data_cross_validation as V
import src.extract_feature_multilabel as EML
if __name__ == '__main__':
print('Hello, I am Trellearn')
jsonFileName = sys.argv[1]
cards = I.parseJS | ON(jsonFileName)
X, Y, cv, mlb = EML.extract(cards)
V.validateML(X, Y)
exit(0)
|
Alberto-Beralix/Beralix | i386-squashfs-root/usr/lib/pymodules/python2.7/gwibber/lib/gtk/widgets.py | Python | gpl-3.0 | 46 | 0.021739 | /usr/sha | re/pyshared/gwibber/lib/gtk/widgets.p | y |
ajose1024/Code_Igniter_Extended | user_guide_src/cilexer/cilexer/cilexer.py | Python | mit | 2,222 | 0.00495 | # CodeIgniter
# http://codeigniter.com
#
# An open source application development framework for PHP
#
# This content is released under the MIT License (MIT)
#
# Copyright (c) 2014 - 2015, British Columbia Institute of Technology
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of thi... | es of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVID | ED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONT... |
limdauto/django-social-auth | social_auth/backends/contrib/rdio.py | Python | bsd-3-clause | 4,358 | 0.000918 | import urllib.request, urllib.parse, urllib.error
from oauth2 import Request as OAuthRequest, SignatureMethod_HMAC_SHA1
try:
import json as simplejson
except ImportError:
try:
import simplejson
except ImportError:
from django.utils import simplejson
from social_auth.backends import Consum... | E = 'RDIO2_PERMISSIONS'
EXTRA_PARAMS_VAR_NAME = 'RDIO2_EXTRA_PARAMS'
def user_data(self, access_token, *args, **kwargs):
params = {
'method': 'currentUser',
'extras': 'username,displayName,streamRegion',
'access_token': access_token,
}
response = dsa | _urlopen(self.RDIO_API_BASE, urllib.parse.urlencode(params))
try:
return simplejson.load(response)['result']
except ValueError:
return None
# Backend definition
BACKENDS = {
'rdio-oauth1': RdioOAuth1,
'rdio-oauth2': RdioOAuth2
}
|
dmilith/SublimeText3-dmilith | Packages/lsp_utils/st3/lsp_utils/_util/weak_method.py | Python | mit | 1,266 | 0.004739 | from LSP.plugin.core.typing import Any, Callable
from types import MethodType
import weakref
__all__ = ['weak_method']
# An implementation of weak method borrowed from sublime_lib [1]
#
# We need it to be able to weak reference bound methods as `weakref.WeakMethod` is not avail | able in
# 3.3 runtime.
#
# The reason this is necessary is explained in the documentation of `weakref.WeakMethod`:
# > A custom ref subclass which simulates a weak reference to a bound method (i.e., a method defined
# > on a class and looked up on an instance). Since a bound method is ephemeral, a standard weak
# > ref... | keep hold of it.
#
# [1] https://github.com/SublimeText/sublime_lib/blob/master/st3/sublime_lib/_util/weak_method.py
def weak_method(method: Callable) -> Callable:
assert isinstance(method, MethodType)
self_ref = weakref.ref(method.__self__)
function_ref = weakref.ref(method.__func__)
def wrapped(*arg... |
enthought/etsproxy | enthought/util/math.py | Python | bsd-3-clause | 1,984 | 0.003528 | #------------------------------------------------------------------------------
# Copyright (c) 2005, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditions describe... | xt
# Thanks for using Enthought open source!
#
# Author: Enthought, Inc.
# Description: <Enthought util package component>
#------------------------------------------------------------------------------
""" A placeholder for math functional | ity that is not implemented in SciPy.
"""
import warnings
warnings.warn("Module is deprecated.", DeprecationWarning)
import numpy
def is_monotonic(array):
""" Does the array increase monotonically?
>>> is_monotonic(array((1, 2, 3, 4)))
True
>>> is_monotonic(array((1, 2, 3, 0, 5)))
False
This ... |
idaholab/civet | ci/recipe/recipe_to_bash.py | Python | apache-2.0 | 6,708 | 0.00641 | #!/usr/bin/env python
# Copyright 2016 Battelle Energy Alliance, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | ", action= | "store_true")
parsed = parser.parse_args(args)
dirname = os.path.dirname(os.path.realpath(__file__))
parent_dir = os.path.dirname(dirname)
# RecipeReader takes a relative path from the base repo directory
real_path = os.path.realpath(parsed.recipe)
rel_path = os.path.relpath(real_path, parent_di... |
llvm-mirror/lldb | packages/Python/lldbsuite/test/functionalities/multiword-commands/TestMultiWordCommands.py | Python | apache-2.0 | 1,161 | 0.002584 | """
Test multiword commands ('platform' in this case).
"""
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
class MultiwordCommandsTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
@no_debug_info_test
def test_ambiguous_subcommand(self):
self.e... | mpty_subcommand(self):
self.expect("platform \"\"", error=True, substrs=["Need to specify a non-empty subcommand."])
@no_debug_info_test
def test_help(self):
# <multiword> help brings up help.
self.expect("platform help",
substrs=["Commands to manage and create platf... | "The following subcommands are supported:",
"connect",
"Select the current platform"])
|
openweave/openweave-core | src/test-apps/happy/bin/weave-ping.py | Python | apache-2.0 | 2,876 | 0.001043 | #!/usr/bin/env python3
#
# Copyright (c) 2015-2017 Nest Labs, 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/lic... | if o in ("-c", "--count"):
options["count"] = a
elif o | in ("-i", "--interval"):
options["interval"] = a
elif o in ("-p", "--tap"):
options["tap"] = a
elif o in ("-C", "--case"):
options["case"] = True
elif o in ("-E", "--case_cert_path"):
options["case_cert_path"] = a
elif o in ("-T", "--ca... |
Awesomeomics/webserver | guava/settings.py | Python | mit | 210 | 0.009524 | #!/usr/bin/env python
# -* | - coding: utf-8 -*-
debug = True
REDIS_HOST = 'localhost'
REDIS_PORT = 6379
REDIS_DB = 0
REDIS_PASSWORD = '820AEC1BFC5D2C71E06CBF947A3A6191'
GUAVA_API_URL = 'http://localhost:5 | 000' |
huangshenno1/algo | ml/iris/ada_MO/weakclassifier.py | Python | mit | 425 | 0.030588 | from sklearn | .tree import DecisionTreeClassifier
# weak classifier
# decision tree (max depth = 2) using scikit-learn
class WeakClassifier:
# initialize
def __init__(self):
self.clf = DecisionTreeClassifier(max_depth = 2)
# train on dataset (X, | y) with distribution weight w
def fit(self, X, y, w):
self.clf.fit(X, y, sample_weight = w)
# predict
def predict(self, X):
return self.clf.predict(X)
|
sbarratt/flask-prometheus | flask_prometheus/__init__.py | Python | bsd-3-clause | 1,126 | 0.008881 |
import time
from prometheus_client import Counter, Histogram
from prometheus_client import start_http_server
from flask import request
FLASK_REQUEST_LATENCY = Histogram('flask_request_latency_seconds', 'Flask Request Latency',
['method', 'endpoint'])
FLASK_REQUEST_COUNT = Counter('flask_request_count', ... | uest.path, response.status_code).inc()
return respons | e
def monitor(app, port=8000, addr=''):
app.before_request(before_request)
app.after_request(after_request)
start_http_server(port, addr)
if __name__ == '__main__':
from flask import Flask
app = Flask(__name__)
monitor(app, port=8000)
@app.route('/')
def index():
... |
iulian787/spack | var/spack/repos/builtin/packages/r-rrcov/package.py | Python | lgpl-2.1 | 932 | 0.002146 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RRrcov(RPackage):
"""rrcov: Scalable Robust Estimators with High Breakdown Point"""
h... | depends_on('r-robustbase@0.92.1:', type=('build', | 'run'))
depends_on('r-mvtnorm', type=('build', 'run'))
depends_on('r-lattice', type=('build', 'run'))
depends_on('r-cluster', type=('build', 'run'))
depends_on('r-pcapp', type=('build', 'run'))
|
ericholscher/django | tests/expressions_regress/models.py | Python | bsd-3-clause | 766 | 0.001305 | from __fu | ture__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible
"""
Model for testing arithmetic expressions.
"""
from django.db import models
@python_2_unicode_compatible
class Number(models.Model):
integer = models.Bi | gIntegerField(db_column='the_integer')
float = models.FloatField(null=True, db_column='the_float')
def __str__(self):
return '%i, %.3f' % (self.integer, self.float)
class Experiment(models.Model):
name = models.CharField(max_length=24)
assigned = models.DateField()
completed = models.DateF... |
janiheikkinen/irods | tests/pydevtest/configuration.py | Python | bsd-3-clause | 802 | 0 | import socket
import os
RUN_IN_TOPOLOGY = False
TOPOLOGY_FROM_RESOURCE_SERVER = False
HOSTNAME_1 = HOSTNAME_2 = HOSTNAME_3 = socket.gethostname()
USE_SSL = False
ICAT_HOSTNAME = socket.gethostname()
PREEXISTING_ADMIN_PASSWORD = 'rods'
# TODO: allow for arbitrary number of remote zones
class FEDERATION(object):
... | 'dev'
REMOTE_ZONE = 'buntest'
REMOTE_HOST = 'bunte | st'
REMOTE_RESOURCE = 'demoResc'
REMOTE_VAULT = '/var/lib/irods/iRODS/Vault'
TEST_FILE_SIZE = 4*1024*1024
LARGE_FILE_SIZE = 64*1024*1024
TEST_FILE_COUNT = 300
MAX_THREADS = 16
|
frederick623/pb | fa_collateral_upload/HTI_Loan_Collateral_Automation.py | Python | apache-2.0 | 25,027 | 0.010349 | # 20170226 Add more additional info
import acm
import ael
import HTI_Util
import HTI_FeedTrade_EDD_Util
import fnmatch
import datetime
import os
import sys
import csv
import re
import sqlite3
import math
import glob
import win32com.client
import traceback
ael_variables = [['asofdate', 'Date', 'string', [str(ael.date_t... | Market', None, 1],
['pb_trd_file', 'PB | Trade File', 'string', None, '\\\\P7fs0003\\nd\\3033-Horizon-FA-Share\\PB_DeltaOne\\FA_Trade_Import\\pb_to_fa_YYYYMMDD.csv', 1, 0, 'PB Trade File', None, 1],
['loan_xls_template', 'Loan Template', 'string', None, 'S:\\Prime Brokerage (PB)\\Tools\\Stock Loan Collateral\\template\\ExcelUpload - Cash Entr... |
DigitalGlobe/gbdxtools | examples/basic_workflow_client.py | Python | mit | 211 | 0.009479 | from gbdxtools import Interface |
gbdx = None
def go():
print(gbdx.task_registry.list())
print(gbdx.task_registry.get_definition('HelloGBDX'))
| if __name__ == "__main__":
gbdx = Interface()
go()
|
nordicdyno/cfbackup | cfbackup/core.py | Python | bsd-2-clause | 6,025 | 0.001494 | """This module provides the main functionality of cfbackup
"""
from __future__ import print_function
import sys
import argparse
import json
import CloudFlare
# https://api.cloudflare.com/#dns-records-for-a-zone-list-dns-records
class CF_DNS_Records(object):
"""
commands for zones manipulation
"""
def ... | ds_by_type = {}
types = {}
for rec in records:
if not records_by_type.get(rec["type"]):
types[rec["type"]] = 0
records_by_type[rec["type"]] = []
types[rec["type"]] += 1
records_by_type[rec["type"]].append(rec)
for t in sorted(l... | e"]))
print("Name: {}".format(rec["name"]))
print("Content: {}".format(rec["content"]))
print("TTL: {}{}".format(
rec["ttl"],
" (auto)" if str(rec["ttl"]) == "1" else "",
))
print("Proxied:... |
kidmillions/Stino | stino/st_base.py | Python | mit | 1,584 | 0.000631 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
#
# Documents
#
"""
Documents
"""
from __future__ import absolute_import
from __future__ import print_function |
from __future__ import division
from __future__ import unicode_literals
import os
import inspect
from . import pyarduino
thi | s_file_path = os.path.abspath(inspect.getfile(inspect.currentframe()))
def get_plugin_path():
this_folder_path = os.path.dirname(this_file_path)
plugin_path = os.path.dirname(this_folder_path)
return plugin_path
def get_packages_path():
plugin_path = get_plugin_path()
packages_path = os.path.dir... |
kuangliu/pytorch-cifar | models/mobilenetv2.py | Python | mit | 3,092 | 0.003558 | '''MobileNetV2 in PyTorch.
See the paper "Inverted Residuals and Linear Bottlenecks:
Mobile Networks for Classification, Detection and Segmentation" for more details.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class Block(nn.Module):
'''e | xpand + depthwise + pointwise'''
def __init__(self, in_planes, out_planes, expansion, stride):
super(Block, self).__init__()
self.stride = stride
planes = expansion * in_planes
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, stride=1, padding=0, bias=False)
self.bn1... | BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, groups=planes, bias=False)
self.bn2 = nn.BatchNorm2d(planes)
self.conv3 = nn.Conv2d(planes, out_planes, kernel_size=1, stride=1, padding=0, bias=False)
self.bn3 = nn.BatchNorm2d(out_planes... |
RIFTIO/rift.ware-descriptor-packages | 4.3/src/nsd/haproxy_waf_http_ns/scripts/waf_config.py | Python | apache-2.0 | 9,663 | 0.003415 | #!/usr/bin/env python3
############################################################################
# Copyright 2017 RIFT.IO Inc #
# #
# Licensed under the Apache License, Version 2.0 (the "License");... | logging.basicConfig(filename=log_file, level=logging.DEBUG)
logger = logging.getLogger()
ch = logging.StreamHandler()
if args.verbose:
| ch.setLevel(logging.DEBUG)
else:
ch.setLevel(logging.INFO)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)
except Exce... |
dangoldin/poor-mans-data-pipeline | setup.py | Python | mit | 491 | 0.04277 | # Mostly from http://peterdowns.com/posts/first-time-with-pypi.html
from di | stutils.core import setup
setup(
name = 'pmdp',
packages = ['pmdp'],
version = '0.3',
description = 'A poor man\'s data pipeline',
author = 'Dan Goldin',
author_email = 'dangoldin@gmail.com',
url = 'https://github.com/dangoldin/poor-mans-data-pipeline',
download_url = 'https://github.com/dangoldin/poor-... | data-pipeline'],
classifiers = [],
)
|
lawphill/PhillipsPearl_Corpora | Spanish/scripts/dict_convert.py | Python | mit | 8,349 | 0.010189 | # -*- coding: utf-8 -*-
import os
import glob
import sys
import re
# Display debug information, print to statistics file
verbose = 0
obstruents = {'b':'B', 'd':'D', 'g':'G'}
nasals = ['m', 'n', 'N']
# Vocales
vowels = ['a', 'e', 'i', 'o', 'u']
# Semivocales
semivowels = ['%', '#', '@', '$', '&', '!', '*', '+', '-', ... | honemesPerWord = []
def interVocalicRules(sent):
newSent = sent
# Create all the dipthongs that occur between words
newSent = newSent.replace('a i', '- ')
newSent = newSent.replace('a u', '+ ')
# Do I in | dicate vowel lengthening?
# newSent = newSent.replace('a a', 'aa ')
newSent = newSent.replace('e i', '* ')
# newSent = newSent.replace('e e', 'ee ')
newSent = newSent.replace('i a', '% ')
newSent = newSent.replace('i e', '# ')
newSent = newSent.replace('i o', '@ ')
# newSent = newSent.replace('... |
kfoss/try41 | dockerfiles/redwood/visual.py | Python | apache-2.0 | 2,481 | 0.008061 | #!/usr/bin/env python
#
# Copyright (c) 2013 In-Q-Tel, Inc/Lab41, All Rights Reserved.
#
# Licensed 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 applicabl | e 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 License.
"""
Created on 19 October 2013
@a... |
iwm911/plaso | plaso/parsers/winreg_plugins/outlook.py | Python | apache-2.0 | 2,761 | 0.010503 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2013 The Plaso Project Authors.
# Please see the AUTHORS file for details on individual 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 L... | alue.name:
continue
# Ignore any value that is empty or that does not contain an integer.
if not value.data or not value.DataIsInteger():
continue
# TODO: change this 32-bit integer into something meaningful, for now
# the value name is the most interesting part.
text_dic... | itten_timestamp
else:
timestamp = 0
yield event.WinRegistryEvent(
key.path, text_dict, timestamp=timestamp,
source_append=': {0:s}'.format(self.DESCRIPTION))
value_index += 1
|
DylannCordel/django-filer | filer/fields/folder.py | Python | bsd-3-clause | 4,982 | 0.001004 | # -*- coding: utf-8 -*-
import warnings
from django import forms
from django.contrib.admin.sites import site
from django.contrib.admin.widgets import ForeignKeyRawIdWidget
from django.contrib.staticfiles.templatetags.staticfiles import static
from django.core.urlresolvers import reverse
from django.db import models
f... | ices_to', None)
self.to_field_name = to_field_name
self.max_value = None
self.min_value = None
kwargs.pop('widget', None)
| forms.Field.__init__(self, widget=self.widget(rel, site), *args, **kwargs)
def widget_attrs(self, widget):
widget.required = self.required
return {}
class FilerFolderField(models.ForeignKey):
default_form_class = AdminFolderFormField
default_model_class = Folder
def __init__(sel... |
akmcinto/TodoApp | ToDoApp/polls/views.py | Python | apache-2.0 | 1,788 | 0.003356 | """
Copyright 2016 Andrea McIntosh
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... | .DetailView):
model = Question
template_name = 'polls/results.html'
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except:
return render(request, 'polls/detail.html', {
... | )
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
|
carefree0910/MachineLearning | _Dist/NeuralNetworks/i_CNN/CNN.py | Python | mit | 3,860 | 0.00544 | import os
import sys
root_path = os.path.abspath("../../../")
if root_path not in sys.path:
sys.path.append(root_path)
import numpy as np
import tensorflow as tf
from _Dist.NeuralNetworks.Base import Generator4d
from _Dist.NeuralNetworks.h_RNN.RNN import Basic3d
from _Dist.NeuralNetworks.NNUtil import Activations... | ght, self.width = kwargs.pop("height", None), kwargs.pop("width", None)
super(CNN, self).__init__(*args, **kwargs)
self._name_appendix = "CNN"
self._generator_base = Generator4d
self.conv_activations = None
self.n_filters = self.filter_sizes = self.poolings = None
def init... | tions", "relu")
def init_model_structure_settings(self):
super(CNN, self).init_model_structure_settings()
self.n_filters = self.model_structure_settings.get("n_filters", [32, 32])
self.filter_sizes = self.model_structure_settings.get("filter_sizes", [(3, 3), (3, 3)])
self.poolings =... |
ukch/gae_simple_blog | settings.py | Python | bsd-3-clause | 2,108 | 0.000949 | # Initialize App Engine and import the default settings (DB backend, etc.).
# If you want to use a different backend you have to remove all occurences
# of "djangoappengine" from this file.
from djangoappengine.settings_base import *
from private_settings import SECRET_KEY
import os
# Activate django-dbindexer for th... | ED_APPS = (
# 'django.contrib.admin',
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.staticfiles',
'django.contrib.markup',
'djangotoolbox',
'autoload',
'dbindexer',
"simpleblog.content",
# djangoappengine should come last, so... | re.AutoloadMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
]
if not DEBUG:
# Put the stats middleware after autoload
MIDDLEWARE_CLASSES.insert(
1, 'google.appengine.... |
choffmeister/transcode | lib/ffmpeg.py | Python | mit | 1,356 | 0.030236 | import utils
import re
import subprocess
#regexes
duration_regex = re.compile('Duration:\s*(?P<time>\d{2}:\d{2}:\d{2}.\d{2})')
stream_regex = re.compile('Stream #(?P<stream_id>\d+:\d+)(\((?P<language>\w+)\))?: (?P<type>\w+): (?P<format>[\w\d]+)')
crop_regex = re.compile('crop=(?P<width>\d+):(?P<height>\d+):(?P<x>\ | d+):(?P<y>\d+)')
# detect crop settings
def detect_crop(src):
proc = subprocess.Popen(['ffmpeg', '-i', src, '-t', str(100), '-filter:v', 'cropdetect', '-f', 'null', '-'], stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()
crops = crop_rege | x.findall(stderr)
return max(set(crops), key=crops.count)
# detect duration
def detect_duration(src):
proc = subprocess.Popen(['ffmpeg', '-i', src], stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()
match = duration_regex.search(stderr)
duration_str = match.group('time')
duration_secs = utils.ti... |
imait/HtmlDocument | for_python2.x/htmldocument.py | Python | mit | 46,242 | 0.00093 | # -*- coding: utf-8-unix; mode: python -*-
"""Module to assist to make HTML.
This module provides class that assist to make HTML.
Author: 2011 IMAI Toshiyuki
Copyright (c) 2011 IMAI Toshiyuki
This software is released under the MIT License.
http://opensource.org/licenses/mit-license.php
Class:
HTML -- Assist t... | element.
end_ol() -- Crea | te end tag of ol element.
ul(content, [attrs]) -- Create ul element.
start_ul([attrs]) -- Create start tag of ul element.
end_ul() -- Create end tag of ul element.
li(content, [attrs]) -- Create li element.
dl(content, [attrs]) -- Create dl element.
start_dl([attrs]) -- C... |
maurobaraldi/quokka | quokka/utils/__init__.py | Python | mit | 714 | 0 | # -*- coding: utf-8 -*-
import logging
from speaklater import make_lazy_string
from quokka.modules.accounts.models import User
logger = logging.getLogger()
def lazy_str_setting(key, default=None):
from flask import | current_app
return make_lazy_string(
lambda: current_app.config.get(key, default)
)
def get_current_user():
from flask.ext.security im | port current_user
try:
if not current_user.is_authenticated():
return None
except RuntimeError:
# Flask-Testing will fail
pass
try:
return User.objects.get(id=current_user.id)
except Exception as e:
logger.warning("No user found: %s" % e.message)
... |
cloudnsru/PyCloudNS | PyCloudNS/records.py | Python | mit | 967 | 0 | from .req import Req
class Records(Req):
def __init__(self, url, email, secret):
super().__init__(url=url, email=email, secret=secret)
def get(self, zone_id, layer='default'):
return self.do_get("/zones/{}/{}/records".format(zone_id, layer))
def create(self, zone, layer, name, ttl, rtype... | name,
'ttl': ttl,
'record_type': rtype,
'value': data,
'priority': priority
}
return self.do_post(url, data=data)
def delete(self, zone, layer, record_id):
url = "/zones/{}/{}/records/{}".format(zone, layer, recor | d_id)
return self.do_delete(url)
def update(self, zone, layer, record_id, **params):
url = "/zones/{}/{}/records/{}".format(zone, layer, record_id)
return self.do_put(url, data=params)
|
MoonRaker/cons2-python | cons2/crop.py | Python | gpl-3.0 | 6,619 | 0.009216 | # crop.py
# Derek Groenendyk
# 2/15/2017
# reads input data from Excel workbook
from collections import OrderedDict
import logging
import numpy as np
import os
import sys
from cons2.cu import CONSUMPTIVE_USE
# from utils import excel
logger = logging.getLogger('crop')
logger.setLevel(logging.DEBUG)
class CROP(obje... | 'scs_crop_coef.csv'),'r')
except TypeError:
logger_fn.critical('scs_crop_coef.csv file not found.')
rai | se
else:
lines = infile.readlines()
infile.close()
if self.crop_type == 'PERENNIAL':
end = 26
else:
end = 22
for line in lines:
sline = line.split(',')
sline[-1] = sline[-1][:-1]
# print(sline[0],self.s... |
daviddrysdale/python-phonenumbers | python/phonenumbers/shortdata/region_BS.py | Python | apache-2.0 | 677 | 0.008863 | """Auto-generated file, do not edit by hand. BS metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_BS = PhoneMetadata(id='BS', country_code=None, international_prefix=None,
general_desc=PhoneNumberDesc(national_number_pattern='9\\d\\d', possible_length=(3,)),
to... | nal_number_pattern='9(?:1[19]|88)', example_number='911', possible_length=(3,)),
emergency=PhoneNu | mberDesc(national_number_pattern='91[19]', example_number='911', possible_length=(3,)),
short_code=PhoneNumberDesc(national_number_pattern='9(?:1[19]|88)', example_number='911', possible_length=(3,)),
short_data=True)
|
chiffa/numpy | numpy/lib/nanfunctions.py | Python | bsd-3-clause | 46,492 | 0.000022 | """
Functions that ignore NaN.
Functions
---------
- `nanmin` -- minimum non-NaN value
- `nanmax` -- maximum non-NaN value
- `nanargmin` -- index of minimum non-NaN value
- `nanargmax` -- index of maximum non-NaN value
- `nansum` -- sum of non-NaN values
- `nanprod` -- product of non-NaN values
- `nanmean` -- mean of... | t as the value of the out argument in some
operations.
Parameters
----------
a : array-like
Input array.
val : float
NaN values are set to val before doing the operation.
Returns
-------
y : ndarray
If `a` is of inexact type, return a copy of `a` with the NaNs
... | ne}
If `a` is of inexact type, return a boolean mask marking locations of
NaNs, otherwise return None.
"""
is_new = not isinstance(a, np.ndarray)
if is_new:
a = np.array(a)
if not issubclass(a.dtype.type, np.inexact):
return a, None
if not is_new:
# need copy... |
chheplo/jaikuengine | common/models.py | Python | apache-2.0 | 22,503 | 0.016531 | # Copyright 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | key_name = self.key_from(**kw)
super(CachingModel, self).__init__(
parent, key_name=key_name, _app=_app, **kw)
if not key_name:
key_name = self.key_from(**kw)
self._cache_keyname__ = (key_name, parent)
@classmethod
def key_from(cls, **kw):
if hasattr(cls, ' | key_template'):
try:
return cls.key_template % kw
except KeyError:
logging.warn('Automatic key_name generation failed: %s <- %s',
cls.key_template,
kw)
return None
def _remove_from_cache(self):
clsname = self.__class__.__name__
if Ca... |
DoubleNegativeVisualEffects/gaffer | python/GafferUI/OpDialogue.py | Python | bsd-3-clause | 4,512 | 0.038121 | ##########################################################################
#
# Copyright (c) 2011-2012, Image Engine Design Inc. All rights reserved.
# Copyright (c) 2011-2012, John Haddon. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted ... | RTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTER... | LITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
from __future__ import with_statement
import IECore
import Gaffer
import Gaffer... |
hroncok/freeipa | ipapython/ipa_log_manager.py | Python | gpl-3.0 | 8,302 | 0.004095 | # Authors: John Dennis <jdennis@redhat.com>
#
# Copyright (C) 2011 Red Hat
# see file 'COPYING' for use and warranty information
#
# 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... | copy
from log_manager import LogManager, parse_log_level
#-------------------------------------------------------------------------------
# Our root logger, all loggers will be descendents of this.
IPA_ROOT_LOGGER_NAME = 'ipa'
# Format string for time.strftime() to produc | e a ISO 8601 date time
# formatted string in the UTC time zone.
ISO8601_UTC_DATETIME_FMT = '%Y-%m-%dT%H:%M:%SZ'
# Logging format string for use with logging stderr handlers
LOGGING_FORMAT_STDERR = 'ipa: %(levelname)s: %(message)s'
# Logging format string for use with logging stdout handlers
LOGGING_FORMAT_STDOUT = '[... |
alanjw/GreenOpenERP-Win-X86 | python/Lib/test/test_cfgparser.py | Python | agpl-3.0 | 28,482 | 0.000632 | import ConfigParser
import StringIO
import os
import unittest
import UserDict
from test import test_support
class SortedDict(UserDict.UserDict):
def items(self):
result = self.data.items()
result.sort()
return result
def keys(self):
result = self.data.keys()
... | tEqual(
cf.get("DEFAULT", "Foo"), "Bar",
"could not locate option, expecting case-insensitive defaults")
def test_parse_errors(self):
self.newconfig()
self.parse_error(ConfigParser.ParsingError,
"[Foo]\n extra-spaces: splat\n")
self.... |
self.parse_error(ConfigParser.ParsingError,
"[Foo]\n:value-without-option-name\n")
self.parse_error(ConfigParser.ParsingError,
"[Foo]\n=value-without-option-name\n")
self.parse_error(ConfigParser.MissingSectionHeaderError,
... |
burnpanck/chaco | examples/demo/shell/scatter.py | Python | bsd-3-clause | 533 | 0 | """This ex | ample shows how to create a scatter plot using the `shell` package.
"""
# Major library imports
from numpy import linspace, random, pi
# Enthought library imports
from chaco.shell import plot, hold, title, show
# Create some data
x = linspace(-2*pi, 2*pi, 100)
y1 = random.random(100)
y2 = random.random(100)
# Crea... | line
show()
|
luanjunyi/cortana | feat/bow/tokenize.py | Python | mit | 834 | 0.020384 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 05 17:10:34 2014
@author: Ning
"""
from util import *
from util.log import _logger
from feat.terms.term_categorize import term_category
import codecs
def parse(sentence):
for term in sentence.split():
yield term_category(term)
def tokenize():
r... | der(conv.redirect("data|test.dat"))
with codecs.open("test.tokenized.dat",'w',encoding='utf-8') as fl:
for row in rows:
fl.write("%s\t%s\n" % (' '.join(list(parse(row[0]))) , row[1]) )
if __name__ == "__main__": |
tokenize() |
eaton-lab/toytree | toytree/utils.py | Python | bsd-3-clause | 22,118 | 0.003979 | #!/usr/bin/env python
from __future__ import print_function, division, absolute_import
import re
import os
from copy import deepcopy
import numpy as np
import toytree
import toyplot
#######################################################
# Exception Classes
#######################################################
c... | Add annotations as a new | mark on top of an existing toytree mark.
"""
def __init__(self, tree, axes, mark):
self.tree = tree
self.axes = axes
self.mark = mark
def draw_clade_box(
self,
names=None,
regex=None,
wildcard=None,
yspace=None,
xspace=None,
... |
Micronaet/micronaet-xmlrpc | xmlrpc_operation_invoice/__openerp__.py | Python | agpl-3.0 | 1,553 | 0.001288 | ###############################################################################
#
# Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the ... | . - Nicola Riolini',
'website': 'http://www.micronaet.it',
'license': 'AGPL-3',
'depends': [
'base',
'xmlrpc_base',
'account',
],
'init_xml': [],
'demo': [],
'data': [
'security/xml_groups.xml',
#'oper | ation_view.xml',
'invoice_view.xml',
'data/operation.xml',
],
'active': False,
'installable': True,
'auto_install': False,
}
|
datamade/yournextmp-popit | candidates/feeds.py | Python | agpl-3.0 | 1,820 | 0.001099 | import re
from django.contrib.sites.models import Site
from django.contrib.syndication.views import Feed
from django.core.urlresolvers import reverse
from django.utils.feedgenerator import Atom1Feed
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
from .models import Logge... | m = lock_re.search(item.source)
if m:
return reverse('constituency', kwargs={
'post_id': m.group(2),
'ignored_slug': slugify(m.group(1))
})
else:
if item.person_id:
return reverse('person-view', args=[item.person_id]... | else:
return '/'
|
openslack/openslack-crawler | crawler/schedulers/kafka/scheduler.py | Python | apache-2.0 | 6,484 | 0.000617 | import json
import random
import time
import urllib
import re
from scrapy.utils.misc import load_object
from scrapy.http import Request
from scrapy.conf import settings
import redis
from crawler.schedulers.redis.dupefilter import RFPDupeFilter
from crawler.schedulers.redis.queue import RedisPriorityQueue
try:
im... | edisPriorityQueue(self.redis_conn,
self.spider.name + ":queue")
@classmethod
def from_settings(cls, settings):
server = redis.Redis(host=settings.get('REDIS_HOST'),
| port=settings.get('REDIS_PORT'))
persist = settings.get('SCHEDULER_PERSIST', True)
timeout = settings.get('DUPEFILTER_TIMEOUT', 600)
retries = settings.get('SCHEDULER_ITEM_RETRIES', 3)
return cls(server, persist, timeout, retries)
@classmethod
def from_crawler(cls, cr... |
jcrudy/sklearntools | sklearntools/test/test_kfold.py | Python | bsd-3-clause | 809 | 0.003708 | from sklearntools.kfold import ThresholdHybridCV
import numpy as np
from six.moves import reduce
from operator import __add__
from numpy.testing.utils import assert_array_equal
from nose.tools import assert_equal
def test_hybrid_cv():
X = np.random.normal(size=(100,10))
y = np.random.normal(size=100)
cv =... | run the test in this file.'
module_name = sys.modules[__name__].__file__
result = nose.run(argv=[sys.argv[0],
module_nam | e,
'-s', '-v']) |
mitsuhiko/sentry | src/sentry/utils/email.py | Python | bsd-3-clause | 15,463 | 0.000776 | """
sentry.utils.email
~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import logging
import os
import subprocess
import tempfile
import time
from email.utils import parseaddr
from fu... | 0020201195627.33539.96671@nightshade.la.mastaler.com>
Optional idstring if given is a string used to strengthen the
uniqueness of the message id. Optional domain if given provides the
portion of the message id after the '@'. It defaults to the locally
defined hostname.
"""
timeval = time.time(... | os.getpid()
randint = randrange(100000)
msgid = '<%s.%s.%s@%s>' % (utcdate, pid, randint, domain)
return msgid
# cache the domain_from_email calculation
# This is just a tuple of (email, email-domain)
_from_email_domain_cache = (None, None)
def get_from_email_domain():
global _from_email_domain_cac... |
hutcho66/imagerecognition | softmax_scripts/plot_softmax_results.py | Python | mit | 636 | 0.003145 | #!/usr/bin/env python
"""plot_softmax_results.py: Plot results of mnist softmax tests."""
from helper_scripts.mnist_read_log import plot_results
import matplotlib.pyplot as plt
# Produce cross entropy and accuracy plots for softmax models.
# Requires the training data for each of the models.
files = [r"""../mnist_s... | oss_entropy_1']
ylabels = ['Validation Accuracy', 'Cross Entropy (Validation Set)']
legend = [r'$\alpha=0.1, keep\_prob= | 0.9$']
plot_results(files, scalar_names, ylabels, legend, 'Softmax Models')
plt.show() |
levental/visualizer | docs/conf.py | Python | bsd-3-clause | 7,793 | 0.001155 | # -*- coding: utf-8 -*-
#
# mfp documentation build configuration file, created by
# sphinx-quickstart.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a def... | title.
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None
# The name of a | n image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin... |
decarboxy/py_protein_utils | scripts/best_models.py | Python | mit | 1,426 | 0.018934 | #!/usr/bin/env python2.5
from optparse import OptionParser
from rosettautil.rosetta import rosettaScore
usage = "%prog [options] --term=scoreterm silent files"
parser=OptionParser(usage)
parser.add_option("--term",dest="term",help="score term to use")
(options,args) = parser.parse_args()
if len(args) < 1:
parser... | r(options.term)
for tag,score in score_gen:
split_tag = tag.split("_")
model_id = "_".join(split_tag[0:len(split_tag)-1])
#file = scores.get_file_from_tag(tag)
try:
(current_file,current_best_tag,current_best_score) = best_models[model_id]
except KeyError:
| best_models[model_id] = (silent_file,tag,score)
continue
if score < current_best_score:
#print "changed"
best_models[model_id] = (silent_file,tag,score)
#print best_models
#print silent_file
#print file,score , current_best_score
pri... |
geneontology/go-site | scripts/sanity-check-users-and-groups.py | Python | bsd-3-clause | 7,704 | 0.007269 | ####
#### Give a report on the "sanity" of the users and groups YAML
#### metadata files.
####
#### Example usage to analyze the usual suspects:
#### python3 sanity-check-users-and-groups.py --help
#### Get report of current problems:
#### python3 ./scripts/sanity-check-users-and-groups.py | --users m | etadata/users.yaml --groups metadata/groups.yaml
#### Attempt to repair file (note that we go through json2yaml as libyaml output does not seem compatible with kwalify):
#### python3 ./scripts/sanity-check-users-and-groups.py --users metadata/users.yaml --groups metadata/groups.yaml --repair --output /tmp/output.json ... |
Olamyy/Norman | Norman/api/base.py | Python | bsd-3-clause | 846 | 0.002364 | import requests
from Norman.errors import HttpMethodError
class BaseAPI(object):
"""
"""
_content_type = "application/json"
def __init__(self):
pass
def _json_parser(self, json_response):
response = json_response | .js | on()
return response
def exec_request(self, method, url, data=None):
method_map = {
'GET': requests.get,
'POST': requests.post,
'PUT': requests.put,
'DELETE': requests.delete
}
payload = data if data else data
request = method... |
apanda/modeling | mcnet/components/erroneous_aclfull_proxy.py | Python | bsd-3-clause | 10,082 | 0.019242 | from . import NetworkObject
import z3
class ErroneousAclWebProxy (NetworkObject):
"""A caching web proxy which enforces ACLs erroneously.
The idea here was to present something that is deliberately not path independent"""
def _init (self, node, network, context):
super(ErroneousAclWebProxy, self... | )), \
| self.ctx.etime(self.proxy, p2, self.ctx.recv_event) > \
self.ctime(self.ctx.packet.dest(p2), self.ctx.packet.body(p2)), \
self.ctx.etime(self.proxy, p, self.ctx.send_event) > \
self.ctx.etime(s... |
karuppiah7890/Mail-for-Good | utility/generateEmailCsv.py | Python | bsd-3-clause | 664 | 0.004518 | import sys
import random, string
import os
numberOfEmailsToGenerate = sys.argv[1]
try:
int(numberOfEmailsToGenerate)
print('Generating a CSV with ' + numberOfEmailsToGenerate + ' random emails')
print('This make take some time if the CSV i | s large ...')
except:
sys.exit('Please pass a number as the first arg')
numberOfEmailsToGenerate = int(numberOfEmailsToGenerate)
# Delete ./generated.csv, then create it
os.system('touch ./generated.csv')
for x in range(0, numberOf | EmailsToGenerate):
randomString = ''.join(random.choice(string.lowercase) for i in range(20))
os.system('echo ' + randomString + '@email.com' ' >> ./generated.csv')
|
kustodian/ansible | lib/ansible/module_utils/network/common/utils.py | Python | gpl-3.0 | 21,313 | 0.001314 | # This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete wo... | else:
fallback_args = item
try:
value[name] = fallback_strategy(*fa | llback_args, **fallback_kwargs)
except basic.AnsibleFallbackNotFound:
continue
if attr.get('required') and value.get(name) is None:
self._module.fail_json(msg='missing required attribute %s' % name)
if 'choices' in attr:
... |
djkonro/client-python | kubernetes/test/test_v1beta1_storage_class.py | Python | apache-2.0 | 891 | 0.003367 | # coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.7.4
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
im... | ttest
import kubernetes.client
from kubernetes.client.rest import ApiException
from kubernetes.client.models.v1beta1_storage_class import V1beta1StorageClass
class TestV1beta1StorageClass(unittest.TestCase):
""" V1beta1Storag | eClass unit test stubs """
def setUp(self):
pass
def tearDown(self):
pass
def testV1beta1StorageClass(self):
"""
Test V1beta1StorageClass
"""
model = kubernetes.client.models.v1beta1_storage_class.V1beta1StorageClass()
if __name__ == '__main__':
unitt... |
FCP-INDI/nipype | nipype/interfaces/slicer/filtering/tests/test_auto_HistogramMatching.py | Python | bsd-3-clause | 1,372 | 0.019679 | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from .....testing import assert_equal
from ..histogrammatching import HistogramMatching
def test_HistogramMatching_inputs():
input_map = dict(args=dict(argstr='%s',
),
environ=dict(nohash=True,
usedefault=True,
),
ignore_exception=dict(noha... | old ',
),
)
inputs = HistogramMatching.input_spec()
for key, metadata in list(input_map.items()):
for metakey, value in list(metadata.items()):
yield assert_equal, getattr(inputs.traits()[key], metakey), value
def tes | t_HistogramMatching_outputs():
output_map = dict(outputVolume=dict(position=-1,
),
)
outputs = HistogramMatching.output_spec()
for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()):
yield assert_equal, getattr(outputs.traits()[key], metakey)... |
ecederstrand/exchangelib | exchangelib/services/get_folder.py | Python | bsd-2-clause | 2,503 | 0.004395 | from ..errors import ErrorFolderNotFound, ErrorInvalidOperation, ErrorNoPublicFolderReplicaAvailable
from ..util import MNS, create_element
from .common import EWSAccountService, folder_ids_element, parse_folder_elem, shape_element
class GetFolder(EWSAccountService):
"""MSDN: https://docs.microsoft.com/en-us/exch... | N_RESPONSE = EWSAccountService.ERRORS_TO_CATCH_IN_RESPONSE + (
Er | rorFolderNotFound,
ErrorNoPublicFolderReplicaAvailable,
ErrorInvalidOperation,
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.folders = [] # A hack to communicate parsing args to _elems_to_objs()
def call(self, folders, additional_fields, sha... |
jkonecki/autorest | AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/bar.py | Python | mit | 1,021 | 0.000979 | # 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 ... |
The URIs that are used to perform a retrieval of a public blob, queue or
table object.
:param recursive_point: Recursive Endpoints
:type recursive_point: :class:`Endpoints
<fixtures.acceptancetestsstoragemanagementclient.models.Endpoints>`
"""
_attribute_map = {
're | cursive_point': {'key': 'RecursivePoint', 'type': 'Endpoints'},
}
def __init__(self, recursive_point=None, **kwargs):
self.recursive_point = recursive_point
|
sam-m888/gprime | gprime/app/forms/nameform.py | Python | gpl-2.0 | 2,701 | 0.00074 | #
# gPrime - a web-based genealogy program
#
# Copyright (c) 2015 Gramps Development Team
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option)... | from .forms import Form
class NameForm(Form):
"""
A form for listing, viewing, and editing user settings.
"""
table = "Person"
def __init__(self, handler, instance, handle, row):
super().__init__(handler, instance)
self.tview = self._("Na | me")
self.view = "Name"
self.row = row
self.handle = handle
if int(row) == 1:
self.path = "primary_name"
else:
self.path = "alternate_name.%s" % (int(self.row) - 2)
self.edit_fields = []
if int(row) == 1:
for field in [
... |
mozilla/peekaboo | peekaboo/main/views.py | Python | mpl-2.0 | 17,096 | 0 | import calendar
import os
import subprocess
import tempfile
import shutil
import stat
import datetime
import time
import csv
from collections import defaultdict
from io import StringIO
import pytz
from pyquery import PyQuery as pq
from django import http
from django.core.cache import cache
from django.utils.timezone im... | ):
row = make_row(visitor)
assert row not in data['created']
| data['modified'].append(row)
first = visitor.modified
if first:
data['latest'] = calendar.timegm(first.utctimetuple())
# from time import sleep
# sleep(1)
# from pprint import pprint
# pprint(data)
return data
@json_view
@csrf_exempt
@non_mortals_required
def log_entr... |
stvstnfrd/edx-platform | lms/djangoapps/course_home_api/progress/v1/serializers.py | Python | agpl-3.0 | 3,620 | 0.000276 | """
Progress Tab Serializers
"""
from rest_framework import serializers
from rest_framework.reverse import reverse
class GradedTotalSerializer(serializers.Serializer):
earned = serializers.FloatField()
possible = serializers.FloatField()
class SubsectionSerializer(serializers.Serializer):
display_name =... | uest = self.context['request']
return request.build_absolute_uri(relative_path)
class VerificationDataSerializer(serializers.Serializer):
"""
Serializer for verification data object
"""
link = serializers. | URLField()
status = serializers.CharField()
status_date = serializers.DateTimeField()
class ProgressTabSerializer(serializers.Serializer):
"""
Serializer for progress tab
"""
certificate_data = CertificateDataSerializer()
credit_course_requirements = CreditCourseRequirementsSerializer()
... |
mobarski/sandbox | parallel/p7ex4.py | Python | mit | 2,120 | 0.032075 | ## p7.py - parallel processing microframework
## (c) 2017 by mobarski (at) gmail (dot) com
## licence: MIT
## version: ex4 (simple fan-in of subprocess outputs)
from __future__ import print_function
# CONFIG ###################################################################################
HEAD_LEN_IN = 2
HEAD_LEN_... | in range(N):
ctx[i]['proc'].stdin.close()
break
def pump_output():
done = set()
while True:
for i in range(N):
if i in done: continue
p = ctx[i]['proc']
head = p.stdout.read(HEAD_LEN_OUT)
OUT.write(head)
ctx[i]['head_cnt_out'] += 1
if len(head)<HEAD_LEN_OUT: # End Of File
done.add(i)
... | time()
ctx[i]['run_time'] = ctx[i]['t_stop'] - ctx[i]['t_start']
continue
tail = p.stdout.readline()
OUT.write(tail)
if len(done)==N:
return
# RUN DATA PUMPS
input_pump = threading.Thread(target=pump_input)
output_pump = threading.Thread(target=pump_output)
input_pump.start()
output_pump.start()
i... |
hziling/template | template.py | Python | mit | 11,977 | 0.002004 | # -*- coding: utf-8 -*-
"""
flango.template
~~~~~~~~~~~~~~
template module provide a simple template system that compiles
templates to Python code which like django and tornado template
modules.
Usage
-----
Well, you can view the tests file directly for the usage under tests.
Bas... | 1, 2, 3]) }}').render()
'3'
>>> templ | ate.Template('{{ [1, 2, 3].index(2) }}').render()
'1'
and complex function like lambda expression maybe works::
>>> template.Template('{{ list(map(lambda x: x * 2, [1, 2, 3])) }}').render()
'[2, 4, 6]'
and lastly, inheritance of template, extends and include::
... |
rdegges/django-sslify | sslify/middleware.py | Python | unlicense | 2,315 | 0.001296 | """Django middlewares."""
try:
# Python 2.x
from urlparse import urlsplit, urlunsplit
except ImportError:
# Python 3.x
from urllib.parse import urlsplit
from urllib.parse import urlunsplit
from django.conf import settings
from django.http import HttpResponsePermanentRedirect
try:
# Django 1.... | url_split = urlsplit(url)
scheme = 'https' if url_split.scheme == 'http' else url_split.scheme
ssl_port = getattr(settings, 'SSLIFY_PORT', 443)
url_secure_split = (scheme, "%s: | %d" % (url_split.hostname or '', ssl_port)) + url_split[2:]
secure_url = urlunsplit(url_secure_split)
return HttpResponsePermanentRedirect(secure_url)
|
dopuskh3/confluence-publisher | conf_publisher/page_dumper.py | Python | mit | 1,397 | 0.003579 | import argparse
import codecs
import sys
from .auth import parse_authentication
from .confluence_api import create_confluence_api
from .confluence import ConfluencePageManager
from .constants import DEFAULT_CONFLUENCE_API_VERSION
def main():
parser = argparse.ArgumentParser(description='Dumps Confluence page in ... | assword string')
auth_group.add_argument('-U', '--user', type=str, help='Username (prompt password)')
parser.add_argument('-o', '--output', type=str, help='Output file|stdout|stderr', default='stdout')
| args = parser.parse_args()
auth = parse_authentication(args.auth, args.user)
confluence_api = create_confluence_api(DEFAULT_CONFLUENCE_API_VERSION, args.url, auth)
page_manager = ConfluencePageManager(confluence_api)
page = page_manager.load(args.page_id)
if args.output.lower() == 'stdout':
... |
kerckasha/ACE3 | tools/search_privates.py | Python | gpl-2.0 | 4,384 | 0.021908 | #!/usr/bin/env python3
import fnmatch
import os
import re
import ntpath
import sys
import argparse
def get_private_declare(content):
priv_declared = []
srch = re.compile('private.*')
priv_srch_declared = srch.findall(content)
priv_srch_declared = sorted(set(priv_srch_declared))
priv_dec... | h = re.compile('params \[.*\]|PARAMS_[0-9].*|EXPLODE_[0-9]_PVT.*|DEFAULT_PARAM.*|KEY_PARAM.*|IGNORE_PRIVATE_WARNING.*')
priv_srch_declared = srch.findall(content)
priv_srch_declared = sorted(set(priv_srch_declared))
priv_dec_str = ''.join(priv_srch_declared)
srch = re.compile('(?<![_a-zA-Z0-9]... | riv_declared += priv_split;
srch = re.compile('(?i)[\s]*local[\s]+(_[\w\d]*)[\s]*=.*')
priv_local = srch.findall(content)
priv_local_declared = sorted(set(priv_local))
priv_declared += priv_local_declared;
return priv_declared
def check_privates(filepath):
bad_count_file... |
helfertool/helfertool | src/registration/models/helpershift.py | Python | agpl-3.0 | 1,614 | 0.002478 | from django.db import models
from django.utils.translation import ugettext_lazy as _
class HelperShift(models.Model):
"""
n-m relation between helper and shift.
This model then can be used by other apps to "attach" more data with OneToOne fields and signals.
The fields `present` and `manual_presence... | n_delete=models.CASCADE,
)
shift = models.ForeignKey(
'Shift',
on_delete=models.CASCADE,
)
timestamp = models.DateTimeField(
auto_now_add=True,
verbose_name=_("Registration time for this shift")
)
present = models.BooleanField(
default=False,
ve... | alse,
editable=False,
verbose_name=_("Presence was manually set"),
)
def __str__(self):
return "{} - {} - {}".format(self.helper.event, self.helper, self.shift)
|
ciarand/exhausting-search-homework | test/test_euclidean_mst.py | Python | isc | 2,000 | 0.0055 | """ Tests the implementation of the solution to the Euclidean Minimum Spanning
Tree (EMST) problem """
import pytest
from exhaustive_search.point import Point
from exhaustive_search.euclidean_mst import solve, edist
def compare_solutions(actual, expected):
assert len(actual) == len(expected), "expected %d to equ... | actual = solve([one, two])
compare_solutions(actual, [(one, two)])
def test_triangle():
""" Given a list of points L:
L = [Point(0, 0), Point(3, 0), Point(0, 6)]
The solution is:
[(Point(0, 0), Point(3, 0)), (Point(3, 0), Point(6, 0))]
"""
graph = [Point(0, 0), Point(3, 0), Poin... | 0), Point(6, 0))])
for result in actual:
left, right = result
if left == Point(0, 0) or left == Point(6, 0):
assert right == Point(3, 0), \
"expected right (%s) to == %s (left is %s)" % (right, Point(3, 0), left)
else:
assert right == Point(0, 0) or ... |
sunqm/pyscf | pyscf/agf2/test/test_c_agf2.py | Python | apache-2.0 | 4,413 | 0.004759 | # Copyright 2014-2020 The PySCF Developers. 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 appl... | f.assertAlmostEqual(np.max(np.absolute(vv1-vv2)), 0.0, 10)
self.assertAlmostEqual(np.max(np.absolute(vev1-vev2)), 0.0, 10)
def test_c_dfragf2(self):
qxi = np.random.random((self.naux, self.nmo*self.nocc)) / self.naux
qja = np.random.random((self.naux, self.nocc*self.nvir)) / self.naux
... | ir), np.eye(self.nmo, self.nvir))
vv1, vev1 = _agf2.build_mats_dfragf2_outcore(qxi, qja, gf_occ.energy, gf_vir.energy)
vv2, vev2 = _agf2.build_mats_dfragf2_incore(qxi, qja, gf_occ.energy, gf_vir.energy)
self.assertAlmostEqual(np.max(np.absolute(vv1-vv2)), 0.0, 10)
self.assertAlmostEqual(... |
GNOME/orca | test/keystrokes/gnome-clocks/timer_flat_review.py | Python | lgpl-2.1 | 3,398 | 0.000896 | #!/usr/bin/python
from macaroon.playback import *
import utils
sequence = MacroSequence()
sequence.append(PauseAction(3000))
sequence.append(KeyComboAction("F10"))
sequence.append(KeyComboAction("Tab"))
sequence.append(KeyComboAction("Tab"))
sequence.append(KeyComboAction("Tab"))
sequence.append(KeyComboAction("Tab"... | append(utils.StartRecordingAction())
sequence.append(KeyComboAction("KP_8"))
sequence.append(utils.AssertPresentationAction(
"7. Review current line",
["BRAILLE LINE: '00 ∶ 04 ∶ 3[0-9] \\$l'",
" VISIBLE: '00 ∶ 04 ∶ 3[0-9] \\$l', cursor=1",
"SPEECH OUTPUT: '00 ∶ 04 ∶ 3[0-9]'"]))
sequence.append(... | esentationAction(
"8. Review current line",
["BRAILLE LINE: '00 ∶ 04 ∶ 2[0-9] \\$l'",
" VISIBLE: '00 ∶ 04 ∶ 2[0-9] \\$l', cursor=1",
"SPEECH OUTPUT: '00 ∶ 04 ∶ 2[0-9]'"]))
sequence.append(utils.AssertionSummaryAction())
sequence.start()
|
tnemis/staging-server | baseapp/views/class_studying_views.py | Python | mit | 3,912 | 0.005624 | from django.views.generic import ListView, DetailView, CreateView, \
DeleteView, UpdateView, \
ArchiveIndexView, DateDetailView, \
DayArchiveView, MonthArchiveView, \
TodayArchiveView, Wee... | StudyingView, DeleteView):
def get_success_url(self):
from django.core.urlresolvers import reverse
return reverse('baseapp_class_studying_list')
class Class_StudyingDetailView(Class_StudyingView, DetailView):
| def get_success_url(self):
from django.core.urlresolvers import reverse
return reverse('baseapp_class_studying_list')
class Class_StudyingListView(Class_StudyingBaseListView, ListView):
def get_success_url(self):
from django.core.urlresolvers import reverse
return reverse('baseap... |
GeosoftInc/gxpy | geosoft/gxapi/GXRA.py | Python | bsd-2-clause | 5,242 | 0.00744 | ### extends 'class_empty.py'
### block ClassImports
# NOTICE: Do not edit anything here, it is generated code
from . import gxapi_cy
from geosoft.gxapi import GXContext, float_ref, int_ref, str_ref
### endblock ClassImports
### block Header
# NOTICE: The code generator will not replace the code in this bloc | k
### endblock Header
### block ClassImplementation
# NOTICE: Do not edit anything here, it is generated code
class GXRA(gxapi_cy.WrapRA):
"""
GXRA class.
The `GXRA <geosoft.gxapi.GXRA>` class is used to access ASCII files sequentially or
by line number. The files are opened in read-only mode, so no
... | """
A null (undefined) instance of `GXRA <geosoft.gxapi.GXRA>`
:returns: A null `GXRA <geosoft.gxapi.GXRA>`
:rtype: GXRA
"""
return GXRA()
def is_null(self):
"""
Check if this is a null (undefined) instance
:returns: True if this... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.