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 |
|---|---|---|---|---|---|---|---|---|
googleapis/python-irm | docs/conf.py | Python | apache-2.0 | 11,253 | 0.000622 | # -*- coding: utf-8 -*-
#
# google-cloud-irm documentation build configuration file
#
# 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 default; values that ... | ied
# directly to the root of the documentation.
# html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct e... | templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}
# If false, no module index is generated.
# html_domain_indices = True
# If false, no index is generated.
# html_use_index = True
# If true, the index is split into individual pages for each letter.
# html_... |
ombt/ombt | pythonsrc/quick_python_book/chap6/string_format.py | Python | mit | 346 | 0.017341 | #!/usr/bin/python3.2
#
p1 = "mr"
p2 | = "duck"
p3 = "i'm"
p4 = "done"
p5 ="."
#
print("{0}. {1}, {2} {3}{4}".format(p1,p2,p3,p4,p5))
#
p1 = "mr. duck"
p2 = "i'm done"
print("{mrduck}. {imdone}".format(mrduck=p1,imdone=p2))
#
print("{0:{1}} is the food of the gods ...".format("Ambrosia", 15))
#
print("%s, %s." % ("mr. | duck", "i'm done"))
#
quit()
|
ax003d/sichu_web | sichu/apiserver/tests.py | Python | mit | 2,756 | 0.00254 | import json
from django.test import TestCase
from cabinet.factories import UserFactory, BookOwnFactory
from factories import ClientFactory, AccessTokenFactory
class BookOwnTest(TestCase):
fixtures = ['users.json', 'client.json', 'books.json',
'bookownerships.json']
def setUp(self):
... | HTTP_AUTHORIZATION="Bearer %s" % self.toke | n.token)
# print response.content
ret = json.loads(response.content)
self.assertTrue(ret.has_key(u'meta'))
# get friends books
response = self.client.get(
'/v1/bookown/?format=json&uid=2&trim_owner=1',
HTTP_AUTHORIZATION="Bearer %s" % self.token.token)
... |
thomasyu888/Genie | genie/validate.py | Python | mit | 10,061 | 0.000398 | #!/usr/bin/env python3
import importlib
import inspect
import logging
import sys
import synapseclient
try:
from synapseclient.core.exceptions import SynapseHTTPError
except ModuleNotFoundError:
from synapseclient.exceptions import SynapseHTTPError
from . import config
from . import example_filetype_format
fro... |
Retu | rns:
oncotree link
"""
if oncotree_link is None:
oncolink = databasetosynid_mappingdf.query(
'Database == "oncotreeLink"').Id
oncolink_ent = syn.get(oncolink.iloc[0])
oncotree_link = oncolink_ent.externalURL
return oncotree_link
def _upload_to_synapse(syn, file... |
tensorflow/lucid | lucid/scratch/parameter_editor.py | Python | apache-2.0 | 1,750 | 0.009143 | import numpy as np
import tensorflow as tf
class ParameterEditor():
"""Conveniently edit the parameters of a lucid model.
Example usage:
model = models.InceptionV1()
param = ParameterEditor(model.graph_def)
# Flip weights of first channel of conv2d0
param["conv2d0 | _w", :, :, :, 0] *= -1
"""
def __init__(self, graph_def):
self.nodes = {}
for node in graph_def.node:
if "value" in node.attr:
self.n | odes[str(node.name)] = node
# Set a flag to mark the fact that this is an edited model
if not "lucid_is_edited" in self.nodes:
with tf.Graph().as_default() as temp_graph:
const = tf.constant(True, name="lucid_is_edited")
const_node = temp_graph.as_graph_def().node[0]
graph_def.node... |
jamielennox/tempest | tempest/scenario/test_volume_boot_pattern.py | Python | apache-2.0 | 8,184 | 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
# d... | curity_groups
}
return sel | f.create_server(image='', create_kwargs=create_kwar |
stephane-martin/salt-debian-packaging | salt-2016.3.3/tests/unit/acl/client_test.py | Python | apache-2.0 | 1,751 | 0.001142 | # -*- coding: utf-8 -*-
# Import python libs
from __future__ import absolute_import
# Import Salt Libs
from salt import acl
# Import Salt Testing Libs
from salttesting import TestCase, skipIf
from salttesting.mock import (
NO_MOCK,
NO_MOCK_REASON,
)
from salttesting.helpers import ensure_in_syspath
ensure_i... | f.assertTrue(client_acl.user_is_blacklisted('penguin'))
self.assertFalse(client_acl.user_is_blacklisted('batman'))
self.assertFalse(client_acl.user_is_blacklisted('robin'))
def test_cmd_is_blacklisted(self):
'''
test cmd_is_blacklisted
'''
client_acl = acl.Publisher... | l.cmd_is_blacklisted('cmd.shell'))
self.assertFalse(client_acl.cmd_is_blacklisted('test.versions'))
self.assertTrue(client_acl.cmd_is_blacklisted(['cmd.run', 'state.sls']))
self.assertFalse(client_acl.cmd_is_blacklisted(['state.highstate', 'state.sls']))
if __name__ == '__main__':
from in... |
opennode/nodeconductor-assembly-waldur | src/waldur_mastermind/marketplace/migrations/0008_remove_offering_enable_dynamic_components.py | Python | mit | 357 | 0 | # Generated by Django 2.2.7 on 2019-12-04 09:18
from | dj | ango.db import migrations
class Migration(migrations.Migration):
dependencies = [
('marketplace', '0007_offering_enable_dynamic_components'),
]
operations = [
migrations.RemoveField(
model_name='offering', name='enable_dynamic_components',
),
]
|
pombreda/django-hotclub | libs/external_libs/docutils-0.4/extras/optparse.py | Python | mit | 51,584 | 0.00316 | """optparse - a powerful, extensible, and easy-to-use option parser.
By Greg Ward <[email protected]>
Originally distributed as Optik; see http://optik.sourceforge.net/ .
If you have problems with this module, please do not file bugs,
patches, or feature requests with Python; instead, use Optik's
SourceForge project ... | 'OptionValueError',
'BadOptionError']
__copyright__ = """
Copyright (c) 2001-2003 Gregory P. Ward. All rights reserved.
Copyright (c) 2002-2003 Python Software Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that... | ibutions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products... |
M4rtinK/pyside-android | tests/QtGui/bug_750.py | Python | lgpl-2.1 | 577 | 0.003466 | import unittest
from helper import UsesQApplication
from PySide.QtCore import QTimer
from PySide.QtGu | i import QPainter, QFont, QFontInfo, QWidget, qApp
class MyWidget(QWidget):
def paintEvent(self, e):
p = QPainter(self)
self._info = p.fontInfo()
self._app.quit()
class TestQPainter(UsesQApplication):
def testFontInfo(self):
w = MyWidget()
w._app = self.app
w._... | o = None
QTimer.singleShot(300, w.show)
self.app.exec_()
self.assert_(w._info)
if __name__ == '__main__':
unittest.main()
|
mathias4github/ripe-atlas-traceroute2kml | ipdetailscache.py | Python | mit | 9,640 | 0.024066 | # Copyright (c) 2014 Pier Carlo Chiodi - http://www.pierky.com
# Licensed under The MIT License (MIT) - http://opensource.org/licenses/MIT
#
# The MIT License (MIT)
# =====================
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation f... | ):
Result = {}
Result["TS"] = 0
Result["ASN"] = ""
Result["Holder"] = ""
Result["Prefix"] = ""
Result["HostName"] = ""
IP = in_IP
if not IP in self.IPAddressObjects:
self.IPAddressObjects[IP] = ipaddr.IPAddress(IP)
if self.IPAddressObjects[IP].version == 4:
if self.IPAddressObjects[IP].is_pri... | return Result
if self.IPAddressObjects[IP].version == 6:
if self.IPAddressObjects[IP].is_reserved or \
self.IPAddressObjects[IP].is_link_local or \
self.IPAddressObjects[IP].is_site_local or \
self.IPAddressObjects[IP].is_private or \
self.IPAddressObjects[IP].is_multicast or \
self.IPAddressO... |
danstowell/markovrenewal | experiments/plotynth.py | Python | gpl-2.0 | 12,698 | 0.0278 | #!/bin/env python
# plot results from ynthetictest.py
# by Dan Stowell, spring 2013
import os.path
import csv
from math import log, exp, pi, sqrt, ceil, floor
from numpy import mean, std, shape
import numpy as np
import random
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from mpl_toolkits.mplot3d import ... | pcols[0]), fontsize=plotfontsize)
plt.ylabel(readable_name(groupcols[1]), fontsize=plotfontsize)
plt.title(readable_name(summarycol), fontsize=plotfontsize)
plt.xticks(range(len(data['groupingvals'][groupcols[0]])), data['groupingvals'][groupcols[0]], fontsize=plotfontsize)
plt.yticks(range(len(data['groupingva... | max = max(data['groupingvals'][groupcols[0]])
xdatamin = min(data['groupingvals'][groupcols[0]])
plt.xlim(xmin=xdatamin-(xdatamax-xdatamin)*0.05, xmax=xdata |
ricardoy/coccimorph | coccimorph/segment.py | Python | gpl-3.0 | 5,932 | 0.000506 | import argparse
import cv2
import numpy as np
from coccimorph.aux import load_image
class Segmentator(object):
def __init__(self, filename, threshold, scale):
self.img = load_image(filename, scale)
self.img_bin = binaryze(self.img, threshold)
self.height, self.width, _ = self.img.shape
... | ot(next_pixel[0] == self.vx[0] and next_pixel[1] == self.vy[0]):
self.vx.append(int(next_pixel[0]))
self.vy.append(int(next_pixel[1]))
dpc = dcn
# w_vect = (next_pixel[0], next_pixel[1], dcn)
retvals = self._find_next(self.vx[-1], self.vy[... | n += 1
if n < 20:
i = 0
while(i < n-1):
if next_pixel[0] == self.vx[i] and \
next_pixel[1] == self.vy[i] and i > 0:
next_pixel = (self.vx[0], self.vy[0])
... |
inercia/evy | evy/io/convenience.py | Python | mit | 5,059 | 0.006523 | # Evy - a concurrent networking library for Python
#
# Unless otherwise noted, the files in Evy are under the following MIT license:
#
# Copyright (c) 2012, Alvaro Saurin
# Copyright (c) 2008-2010, Eventlet Contributors (see AUTHORS)
# Copyright (c) 2007-2010, Linden Research, Inc.
# Copyright (c) 2005-2006, Bob Ippoli... | param addr: Address of the server to connect to. For TCP sockets, this is a (host, port) tuple.
:param family: Socket family, optional. See :mod:`socket` documentation for available families.
:param bin | d: Local address to bind to, optional.
:return: The connected green socket object.
"""
sock = socket.socket(family, socket.SOCK_STREAM)
if bind is not None:
sock.bind(bind)
sock.connect(addr)
return sock
def listen (addr, family = socket.AF_INET, backlog = 50):
"""
Convenience ... |
olekw/cyphesis | data/rulesets/basic/scripts/mind/goals/humanoid/construction.py | Python | gpl-2.0 | 5,984 | 0.00234 | # This file is distributed under the terms of the GNU General Public license.
# Copyright (C) 2004 Al Riddoch (See the file COPYING for details).
import entity_filter
from atlas import Operation, Entity
from mind.goals.common.misc_goal import *
from mind.goals.common.move import *
from physics import *
# Gather a re... | move_me_area(place, range=range),
spot_something_in_area(seed, place, range=range, seconds_until_forgotten=360),
move_me_to_focus(seed),
self.do,
spot_something_in_area(source, place, range=range),
... | ntity_filter.Filter(source)
self.place = place
self.tool = tool
self.range = range
self.spacing = spacing
self.vars = ["seed", "source", "place", "tool", "range", "spacing"]
def do(self, me):
if (self.tool in me.things) == 0:
# print "No tool"
... |
marcoantoniooliveira/labweb | oscar/forms/widgets.py | Python | bsd-3-clause | 7,781 | 0 | import re
import six
from six.moves import filter
from six.moves import map
import django
from django import forms
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.forms.util import flatatt
from django.forms.widgets import FileInput
from django.template import Context
from django.template.lo... | d a section that checks
for whether the widget is disabled.
"""
def __init__(self, attrs=None, choices=(), disabled_values=()):
self.disabled_values = set(force_text(v) for v in disabled_values)
super(AdvancedSelect, self).__init__(attrs, choices)
def rend | er_option(self, selected_choices, option_value, option_label):
option_value = force_text(option_value)
if option_value in self.disabled_values:
selected_html = mark_safe(' disabled="disabled"')
elif option_value in selected_choices:
selected_html = mark_safe(' selected="s... |
sinkpoint/pynrrd | pynrrd/nrrd.py | Python | mit | 11,390 | 0.009745 | import numpy as np
from collections import OrderedDict
import os.path as path
import gzip
# Author: David Qixiang Chen
# email: [email protected]
#
# utility nrrd header reader for .nhdr
class NrrdHeader:
def fromNiftiHeader(nifti_header):
header = NrrdHeader()
aff = nifti_header.get_best_affi... | self.setValue('space dir | ections',dvec)
self.setValue('measurement frame', frame.tolist())
#self.setDwiGradients(dwivec)
print '==============after============'
print_info(self)
#dwivec = self.getDwiGradients()
#print dwivec
class NrrdReader:
grdkey = 'DWMRI_gradient'
b0num = 'b0num'
... |
google-research/google-research | kws_streaming/layers/random_stretch_squeeze_test.py | Python | apache-2.0 | 1,962 | 0.002039 | # coding= | utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file exce | pt in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, eith... |
dmaccarthy/sc8pr | sc8pr/misc/progress.py | Python | gpl-3.0 | 1,655 | 0.001813 | # Copyright 2015-2018 D.G. MacCarthy <http://dmaccarthy.github.io>
#
# This file is part of "sc8pr".
#
# "sc8pr" 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 o... | ributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with "sc8pr". If not,... | splay progress graphically"
def __init__(self, size=(128,16), color="grey", lower=0, upper=1):
super().__init__(size)
cfg = dict(anchor=BOTTOMLEFT, pos=(0, size[1]-1)) if tall(*size) else dict(anchor=TOPLEFT)
self += Image(bg=color).config(**cfg)
self.lower = lower
self.uppe... |
dreal/dreal4 | dreal/test/python/solver_test.py | Python | apache-2.0 | 5,260 | 0 | # -*- coding: utf-8 -*-
#
# Copyright 2017 Toyota Research Institute
#
# 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... | max_diam = diam_i
# max_diam_idx = var_i
# return max_diam_idx
# branching_dim = FindMaxDiam(box, active_set)
# if branching_dim >= 0:
# (b1, b2) = box.bisect(branching_dim)
# left.set(b1)
# ... | return -1
# ctx = Context()
# ctx.config.brancher = MyBrancher
# ctx.SetLogic(Logic.QF_NRA)
# ctx.DeclareVariable(x, -10, 10)
# ctx.DeclareVariable(y, -10, 10)
# ctx.Assert(cos(x) < sin(y))
# result = ctx.CheckSat()
# self.assertTrue(result)
# sel... |
dedoogong/asrada | HandPose_Detector/general.py | Python | apache-2.0 | 29,504 | 0.003186 | #
# ColorHandPose3DNetwork - Network for estimating 3D Hand Pose from a single RGB Image
# Copyright (C) 2017 Christian Zimmermann
#
# 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, eithe... | iases, 'biases: %s' % layer_name)
out_tensor = tf.matmul(in_tensor, weights) + biases
return out_tensor
@classmethod
def fully_connected_relu(cls, in_tensor, layer_name, out_chan, trainable=True):
tensor = cls.fully_connected(in_tensor, layer_name, out_chan, trainable)
... | f dropout(in_tensor, keep_prob, evaluation):
""" Dropout: Each neuron is dropped independently. """
with tf.variable_scope('dropout'):
tensor_shape = in_tensor.get_shape().as_list()
out_tensor = tf.cond(evaluation,
lambda: tf.nn.dropout(in_tensor,... |
mitodl/open-discussions | channels/conftest.py | Python | bsd-3-clause | 228 | 0 | """Test config for channels"""
import pytest
@ | pytest.fixture(autouse=True)
def mock_search_tasks(mocker):
"""Patch the helpers so they don't fire celery tasks"""
return mocker.patc | h("channels.api.search_task_helpers")
|
yannrouillard/weboob | weboob/applications/handjoob/handjoob.py | Python | agpl-3.0 | 4,944 | 0.000809 | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Bezleputh
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) ... | print >>sys.stderr, 'This command takes an argument: %s' % self.get_command_help('info', short=True)
return 2
job_advert = self.get_object(_id, 'get_job_advert')
if not job_advert:
print >>sys.stderr, | 'Job advert not found: %s' % _id
return 3
self.start_format()
self.format(job_advert)
|
dnjohnstone/hyperspy | hyperspy/tests/utils/test_eds.py | Python | gpl-3.0 | 2,070 | 0.005314 | # -*- coding: utf-8 -*-
# Copyright 2007-2020 The HyperSpy developers
#
# This file is part of HyperSpy.
#
# HyperSpy 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... |
lines ==
['Cr_Ka', ' | V_Kb', 'Pm_La', 'Pr_Lb1'])
lines = get_xray_lines_near_energy(E, only_lines=('a'))
assert (
lines ==
['Cr_Ka', 'Pm_La'])
def test_takeoff_angle():
np.testing.assert_allclose(40.,take_off_angle(30.,0.,10.))
np.testing.assert_allclose(40.,take_off_angle(0.,90.,10.,beta_tilt=30.))
np.t... |
xzturn/caffe2 | caffe2/experiments/python/convnet_benchmarks.py | Python | apache-2.0 | 19,876 | 0.00005 | ## @package convnet_benchmarks
# Module caffe2.experiments.python.convnet_benchmarks
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
"""
Benchmark for common convnets.
(NOTE: Numbers below prior with missing parameter=... | pool5, "fc6", 1024 * 6 * 6, 3072, ('XavierFill', {}),
('ConstantFill', {})
)
relu6 = model.Relu(fc6, "fc6")
fc7 = model.FC(
relu6, "fc7", 3072, 4096, ('XavierFill', {}), ('ConstantFill', {})
)
relu7 = model.Relu(fc7, "fc7")
fc8 = model.FC(
relu7, "fc8", 4096, 1000, ('X... | = model.LabelCrossEntropy([pred, "label"], "xent")
model.AveragedLoss(xent, "loss")
return model, 231
def VGGA(order):
model = cnn.CNNModelHelper(order, name='vgg-a',
use_cudnn=True, cudnn_exhaustive_search=True)
conv1 = model.Conv(
"data",
"conv1",
... |
addition-it-solutions/project-all | addons/account/wizard/account_chart.py | Python | agpl-3.0 | 5,123 | 0.004688 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | count.period')
fy_obj = self.pool.get('account.fiscalyear')
if context is None:
context = {}
data = self.read(cr, uid, ids, context=context)[0]
result = mod_obj.get_object_reference(cr, uid, 'account', 'action_account_tree')
id = result and result[1] or False
... | fiscalyear_id = data.get('fiscalyear', False) and data['fiscalyear'][0] or False
result['periods'] = []
if data['period_from'] and data['period_to']:
period_from = data.get('period_from', False) and data['period_from'][0] or False
period_to = data.get('period_to', False) and da... |
openvstorage/arakoon | src/client/python/__init__.py | Python | apache-2.0 | 572 | 0.001748 | """
Copyri | ght (2010-2014) INCUBAID BVBA
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, sof | tware
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.
"""
|
pkats15/hdt_analyzer | test/file_manager.py | Python | mit | 1,250 | 0.0032 | from os import path, listdir, remove
import zipfile
from pprint import pprint
import xmltodict
files_folder = path.join(path.dirname(path.abspath(__file__)), '..', 'files')
input_folder = path.join(files_folder, 'input')
temp_folder = path.join(files_folder, 'temp')
replay_file = path.join(files_folder, 'temp', 'repl... | tats.xml')
database_file = path.join(files_folder, 'database.json')
def find_deck_games(deck_name):
deck_xml = open(deck_file)
deck_stats = xmltodict.parse(deck_xml)
deck_xml.close()
files = []
for g in deck_stats['DeckStatsList']['DeckStats']['Deck']:
if g['Games'] != None:
fo... | yFile' in game and game['DeckName'] == deck_name:
files.append(game['ReplayFile'])
return files
def unzip_file(file_name):
for fn in listdir(temp_folder):
remove(path.join(temp_folder, fn))
if path.exists(path.join(input_folder, file_name)):
zip_file = zipfile.ZipFile(pa... |
e-koch/TurbuStat | turbustat/tests/test_mahalanobis.py | Python | mit | 1,382 | 0 | # # Licensed under an MIT open source license - see LICENSE
# from __future__ import print_function, absolute_import, division
# import pytest
# import warnings
# from ..statistics import Mahalanobis, Mahalanobis_Distance
# from ..statistics.stats_warnings import TurbuStatTestingWarning
# from ._testing_data import d... | ith warnings.catch_warnings(record=True) as w:
# mahala = Mahalanobis_Distance(dataset1['cube'], dataset1['cube'])
# # Warning is raised each time Mahalanobis is run (so twice)
# assert len(w) == 3
# assert w[0].category == TurbuStatTestingWarning
# assert str(w[0].message) == \
# ("Mah... | ance is an untested metric. Its use"
# " is not yet recommended.")
|
gitchs/shadowsocks | setup.py | Python | apache-2.0 | 1,323 | 0 | import codecs
from setuptools import setup
with codecs.open('README.rst', encoding='utf-8') as f:
long_description = f.read()
setup(
name="shadowsocks",
version="2.8.2.1",
license='http://www.apache.org/licenses/LICENSE-2.0',
description="A fast tunnel proxy that help you get through firewalls",
... | author='clowwindy',
author_email='[email protected]',
url='https://github.com/shadowsocks/shadowsocks',
packages=['shadowsocks', 'shadowsocks.crypto'],
package_data={
'shadowsocks': ['README.rst', 'LICENSE']
},
install_requires=[],
entry_points="""
[console_scripts]
ssloc... | classifiers=[
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
... |
nextgis/nextgisweb | nextgisweb/feature_layer/api.py | Python | gpl-3.0 | 25,791 | 0.000969 | import json
import os
import re
import uuid
import zipfile
import itertools
from urllib.parse import unquote
import tempfile
from collections import OrderedDict
from datetime import datetime, date, time
from osgeo import ogr, gdal
from pyramid.response import Response, FileResponse
from pyramid.httpexceptions import ... | o) for o in dsco]))
)
if display_name:
# CPLES_SQLI == 7
flds = [
'"{}" as "{}"'.format(
fld.keyname.replace('"', r'\"'),
fld.display_name.replace('"', r'\"'),
)
for fld in request.context.f... | ['FID as "{}"'.format(fid.replace('"', r'\"'))]
vtopts += ["-sql", 'select {} from ""'.format(", ".join(
flds if len(flds) > 0 else '*'))]
if driver.fid_support and fid is None:
vtopts.append('-preserve_fid')
gdal.VectorTranslate(
os.path.join(tmp_d... |
Aloomaio/googleads-python-lib | examples/ad_manager/v201811/proposal_service/create_proposals.py | Python | apache-2.0 | 2,591 | 0.005403 | #!/usr/bin/env python
#
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | r_id,
'type': 'ADVERTISER'
},
'primarySalesperson': {
'us | erId': primary_salesperson_id,
'split': '75000'
},
'secondarySalespeople': [{
'userId': secondary_salesperson_id,
'split': '25000'
}],
'primaryTraffickerId': primary_trafficker_id,
'probabilityOfClose': '100000',
'budget': {
'microAmount': '100... |
nvbn/guessit | guessit/transfo/split_path_components.py | Python | lgpl-3.0 | 1,367 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# GuessIt - A library for guessing information from filenames
# Copyright (c) 2013 Nicolas Wack <[email protected]>
#
# GuessIt is free software; you can redistribute it and/or modify it under
# the terms of the Lesser GNU General Public License as published by
# the Free ... | ame, ext ]
"""
components = fileutils.split_path(mtree.value)
basename = components.pop(-1)
| components += list(os.path.splitext(basename))
components[-1] = components[-1][1:] # remove the '.' from the extension
mtree.split_on_components(components)
|
deepmind/envlogger | envlogger/__init__.py | Python | apache-2.0 | 1,242 | 0 | # coding=utf-8
# Copyright 2022 DeepMind Technologies Limited..
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | R CONDITIONS OF ANY | KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A one-stop import for commonly used modules in EnvLogger."""
from envlogger import environment_logger
from envlogger import reader
from envlogger import step_data
from envlogger.b... |
actframework/FrameworkBenchmarks | frameworks/Python/web2py/gunicorn_conf.py | Python | bsd-3-clause | 448 | 0.002232 | import multiprocessing
import os
impo | rt sys
_is_travis = os.environ.get('TRAVIS') == 'true'
workers = multiprocessing.cpu_count() * 3
if _is_travis:
workers = 2
bind = "0.0.0.0:8080"
keepalive = 120
errorlog = '-'
pidfile = 'gunicorn.pid'
pythonpath = 'web2py'
worker_class = "meinhel | d.gmeinheld.MeinheldWorker"
def post_fork(server, worker):
# Disable access log
import meinheld.server
meinheld.server.set_access_logger(None)
|
shlopack/cursovaya | template/3_4.py | Python | mit | 108 | 0.058252 | template = ' R_{\\tex | t{6Д}} = \dfrac{R_6}{1- | K_{\\text{ОК}}} = 10 \cdot %.0f = %.0f~\\text{Ом}'%(R6,R6d) |
postlund/pyatv | tests/zeroconf_stub.py | Python | mit | 1,543 | 0 | """Stub for the zeroconf library.
As zeroconf does not provide a stub or mock, this implementation will serve as
stub here. It can fake immediate answers for any service.
"""
from zeroconf import ServiceInfo
class ServiceBrowserStub:
"""Stub for ServiceBrowser."""
def __init__(self, zeroconf, service_type, ... | return service
def register_service(self, service):
"""Save services registered services."""
self.registered_services.append(service)
def unregister_service(self, service):
"""Stub for unregistering services (does nothing)."""
pass
def close(self):
"""Stub for clo... | e, *services):
"""Stub a module using zeroconf."""
instance = ZeroconfStub(list(services))
module.Zeroconf = lambda: instance
module.ServiceBrowser = ServiceBrowserStub
return instance
|
edx/edx-platform | openedx/features/discounts/admin.py | Python | agpl-3.0 | 2,665 | 0.006754 | """
Django Admin pages for DiscountRestrictionConfig.
"""
from django.contrib import admin
from django.utils.translation import gettext_lazy as _
from openedx.core.djangoapps.config_model_utils.admin import St | ackedConfigModelAdmin
from .models import DiscountPercentageConfig, DiscountRestrictionConfig
class DiscountRestrictionConfigAdmin(StackedConfigModelAdmin):
| """
Admin to configure discount restrictions
"""
fieldsets = (
('Context', {
'fields': DiscountRestrictionConfig.KEY_FIELDS,
'description': _(
'These define the context to disable lms-controlled discounts on. '
'If no values are set, then th... |
lonvia/osgende | osgende/common/sqlalchemy/column_function.py | Python | gpl-3.0 | 2,328 | 0.00043 | # This file is part of Osgende
# Copyright (C) 2017 Sarah Hoffmann
#
# This 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 any later version.
#
# This program is distribu... | lf.key = name
self.type_ = type_
self.is_literal = False
@property
def _from_objects(self):
return []
def _make_proxy(self, selectable, name=None, attach=True,
| name_is_truncatable=False, **kw):
co = ColumnClause(self.name, self.type_)
co.table = selectable
co._proxies = [self]
if selectable._is_clone_of is not None:
co._is_clone_of = \
selectable._is_clone_of.columns.get(co.key)
if attach... |
GH1995/tools | archives/Python_江老师给的代码/chapter08/decorator1.py | Python | gpl-3.0 | 389 | 0.010782 | #decorat | or1.py
def foo(f):
"""foo fucntion Docstring"""
def wrapper(*x, **y):
"""wrapper fucntion Docstring"""
print('调用函数:', f.__name__)
return f(*x, **y)
return wrapper
@foo
def bar(x):
"""bar fucntion Docstring"""
return x**2
#测试代码
if __name__ == '__main__':
print(bar(2))
... | ar.__doc__)
|
google-research/torchsde | diagnostics/utils.py | Python | apache-2.0 | 4,683 | 0.005125 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | Nothing.
"""
im | g_dir = os.path.dirname(img_path)
if not os.path.exists(img_dir):
os.makedirs(img_dir)
if plots is None: plots = ()
if scatters is None: scatters = ()
if hists is None: hists = ()
if options is None: options = {}
plt.figure(dpi=300)
if 'xscale' in options: plt.xscale(options['xscal... |
hasteur/g13bot_tools_new | scripts/replicate_wiki.py | Python | mit | 9,039 | 0.000553 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This bot replicates pages in a wiki to a second wiki within one family.
Example:
python pwb.py replicate_wiki [-r] -ns 10 -family:wikipedia -o nl li fy
or
python pwb.py replicate_wiki [-r] -ns 10 -family:wikipedia -lang:nl li fy
to copy all templates from an nl... | s]
self.differences = {}
self.user_diff = {}
pywikibot.output('Syncing to ', newline=False)
for s in self.sites:
s.login()
self.differences[s] = []
self.user_diff[s] = []
pywikibot.output(str(s), newline= | False)
pywikibot.output('')
def check_sysops(self):
"""Check if sysops are the same on all wikis."""
def get_users(site):
userlist = [ul['name'] for ul in site.allusers(group='sysop')]
return set(userlist)
ref_users = get_users(self.original)
for sit... |
mikeywaites/flask-skeleton | {{PROJECT_NAME}}/config.py | Python | mit | 1,292 | 0 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from os import path, environ
class Config(object):
DEBUG = False
PORT = 5000
HOST = "0.0.0.0"
SQLALCHEMY_ECHO = True
BASE_URL = "http://{{ PROJECT_NAME }}.com"
PROJECT_ROOT = path.abspath(path.dirname(__file__))
TEMPLATE_FOLDER = path.join(PROJECT... | ass LIVE(Config):
SQLALCHEMY_ECHO = False
DEBUG = True
class TEST(Config):
SECRET_KEY = "2147d2df-759b-40ac-8013-f6154110a7d0"
TESTING = True
SQLALCHEMY_ECHO = False
SQLALCHEMY_DATABASE_U | RI = \
build_db_url(name='postgres_test',
addr=environ.get('DB_PORT_5432_TCP_ADDR'))
settings = globals()[environ.get('FASTER_CONFIG', 'DEV')]
|
mbayon/TFG-MachineLearning | venv/lib/python3.6/site-packages/scipy/spatial/tests/test_spherical_voronoi.py | Python | mit | 6,854 | 0.000875 | from __future__ import print_function
import numpy as np
import itertools
from numpy.testing import (assert_equal,
assert_almost_equal,
assert_array_equal,
assert_array_almost_equal)
from pytest import raises as assert_raises
from scipy.sp... | t_vertices_regions_translation_invariance(self):
sv_origin = SphericalVoronoi(self.points)
center = np.array([1, 1, 1])
sv_translated = SphericalVoronoi(self.points + center, None, center)
assert_array_equal(sv_origin.regions, sv_translated.regions)
assert_array_almost_equal(sv_o... | ted.vertices)
def test_vertices_regions_scaling_invariance(self):
sv_unit = SphericalVoronoi(self.points)
sv_scaled = SphericalVoronoi(self.points * 2, 2)
assert_array_equal(sv_unit.regions, sv_scaled.regions)
assert_array_almost_equal(sv_unit.vertices * 2,
... |
coobas/pydons | tests/test_file_browser_netcdf4.py | Python | mit | 740 | 0 | from pydons import MatStruct, FileBrowser, LazyDataset
import netCDF4
import numpy as np
import tempfile
import os
DATADIR = os.path.join(os.path.dirname(__file__), ' | data')
def test_netcdf4():
d = MatStruct()
data1 = np.random.rand(np.random.randint(1, 1000))
with tempfile.NamedTemporaryFile(suffix=".nc") as tmpf:
fh = netCDF4.Dataset(tmpf.name, mode='w')
grp = fh.createGroup('mygroup')
dim1 = grp.createDimension('dim1')
var1 = grp.cr... | fh.close()
dd = FileBrowser(tmpf.name)
assert 'mygroup' in dd
assert 'var1' in dd.mygroup
assert np.all(dd.mygroup.var1[:] == data1)
|
zigitax/king-phisher | tests/spf.py | Python | bsd-3-clause | 5,698 | 0.014918 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# tests/spf.py
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of condit... | sher.com')
check_host_result = s.check_host()
self.assertIsNotNone(check_host_result)
self.assertEqual(check_host_result, 'fail')
self.assertEqual(spf.check_host('1.2.3.4', 'king-phisher.com'), 'fail')
@testing.skip_if_offline
def test_spf_e | valuate_mechanism(self):
s = spf.SenderPolicyFramework('1.2.3.4', 'doesnotexist.king-phisher.com')
eval_mech = lambda m, r: s._evaluate_mechanism(s.ip_address, s.domain, s.sender, m, r)
self.assertTrue(eval_mech('all', None))
self.assertTrue(eval_mech('exists', '%{d2}'))
self.assertTrue(eval_mech('ip4', '1.2.... |
obask/lispify | src/python3/lis.py | Python | mit | 4,615 | 0.014085 | ################ Lispy: Scheme Interprete | r in Python
## (c) Peter Norvig, 2010-14; See http://norvig.com/lispy.html
################ Types
from __future__ import division
Symbol = st | r # A Lisp Symbol is implemented as a Python str
List = list # A Lisp List is implemented as a Python list
Number = (int, float) # A Lisp Number is implemented as a Python int or float
################ Parsing: parse, tokenize, and read_from_tokens
def parse(program):
"Read a Scheme expression ... |
luci/luci-py | appengine/components/components/datastore_utils/config.py | Python | apache-2.0 | 4,914 | 0.008751 | # Copyright 2014 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
"""Versioned singleton entity with global application configuration.
Example usage:
from components.datastore_utils import config
class MyCo... | onfiguration of the service.
All changes are stored in the revision log.
"""
# When this revision of configuration was created.
updated_ts = ndb.DateTimeProperty(indexed=False, auto_now_add=True)
# Who created this revision of configuration (as identity string).
updated_by = ndb.StringProperty(indexed=Fal... | ses
doesn't do any RPCs. Should be used for read-only access to config.
"""
# Build new class-specific fetcher function with cache on the fly on
# the first attempt (it's not a big deal if it happens concurrently in MT
# environment, last one wins). Same can be achieved with metaclasses, but no
... |
brookefitzgerald/neural-exploration | neural_exploration/visualize/serializers.py | Python | mit | 1,912 | 0.003138 | from django.apps import apps
from rest_framework import serializers
Experiment = apps.get_model("visualize", "Experiment")
class ExperimentSerializer(serializers.ModelSerializer):
"""JSON serialized representation of the Experiment Model"""
class Meta:
model = Experiment
fields = '__all__'
... | he Binned Data"""
bin_100_30=serializers.ListField(child=InnerList | Field())
bin_100_30_extents = serializers.ListField(child=IntInnerListField())
labels = serializers.ListField(child=serializers.CharField())
class ThirdBinSerializer(serializers.Serializer):
"""JSON representation of the Binned Data"""
bin_50_15=serializers.ListField(child=InnerListField())
bin_50... |
SUSE/azure-sdk-for-python | azure-mgmt-compute/azure/mgmt/compute/compute/v2015_06_15/operations/virtual_machines_operations.py | Python | mit | 48,648 | 0.002179 | # 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 ... | get(status_link)
if headers:
request.headers.update(headers)
return self._client.send(
request, header_parameters, **operation_config)
def get_long_running_output(response):
| if response.status_code not in [200, 202]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('Vir... |
50onRed/phillypug-concurrent | io_bound/phillypug_async_requests.py | Python | mit | 1,225 | 0.007347 | import gevent
from gevent import monkey
from gevent.pool import Pool
monkey.patch_all()
import requests
import json
import time
import os
def download_image(image_url):
filename = 'async_images/' + image_url.rsplit('/', 1)[-1]
print 'Downloading %s...' % filename
response = requests.get(image_url)
with... | in instagram_data['data']]
if __name__ == '__main__':
if not os.path.exists('async_images'):
os.mkdir('async_images')
get_popular_job = gevent.spawn(get_popular_instagram)
get_popular_job.join()
image_urls = get_popular_job.value
print 'Starting downloads...'
start_time = time.time()
... | ool.spawn(download_image, url) for url in image_urls]
gevent.joinall(jobs)
stop_time = time.time()
print 'Took %.3fs to download %d images' % (stop_time - start_time, len(image_urls))
|
anatolikalysch/VMAttack | lib/Register.py | Python | mit | 2,772 | 0.002525 | #!/usr/bin/env python
"""
@author: Tobias
"""
"""@brief List of register classes"""
_registerClasses = [
['al', 'ah', 'ax', 'eax', 'rax'],
['bl', 'bh', 'bx', 'ebx', 'rbx'],
['cl', 'ch', 'cx', 'ecx', 'rcx'],
['dl', 'dh', 'dx', 'edx', 'rdx'],
['bpl', 'bp', 'ebp', 'rbp'],
['dil', 'di', 'edi', 'rd... |
return None
reg_index = -1
if reg_size > 32: # 64-bit regs
reg_index = num_regs - 1
elif reg_size > 16: # 32-bit regs
reg_index = num_regs - 2
elif reg_size > 8: # 16-bit regs
reg_index = num_regs - 3
elif reg_size > 0: # 8-bit regs
reg_index = 0
else:
... | @brief Determines the size of the given register
@param reg Register
@return Size of register
"""
reg_class = get_reg_class(reg)
num_regs = len(_registerClasses[reg_class])
for index, test_reg in enumerate(_registerClasses[reg_class]):
if test_reg == reg:
break
else: ... |
erikr/django | django/contrib/gis/geos/prototypes/io.py | Python | bsd-3-clause | 11,671 | 0.001628 | import threading
from ctypes import POINTER, Structure, byref, c_char, c_char_p, c_int, c_size_t
from django.contrib.gis.geos.base import GEOSBase
from django.contrib.gis.geos.libgeos import GEOM_PTR, GEOSFuncFactory
from django.contrib.gis.geos.prototypes.errcheck import (
check_geom, check_sized_string, check_st... | # Getting the pointer with the constructor.
self.ptr = self._constructor()
# Loading the real destructor function at this point as doing it in
# _ | _del__ is too late (import error).
self._destructor.func = self._destructor.get_func(
*self._destructor.args, **self._destructor.kwargs
)
def __del__(self):
# Cleaning up with the appropriate destructor.
try:
self._destructor(self._ptr)
except (Attrib... |
modsy/incubator-airflow | airflow/contrib/hooks/gcs_hook.py | Python | apache-2.0 | 3,228 | 0.001239 | import httplib2
import logging
from airflow.contrib.hooks.gc_base_hook import GoogleCloudBaseHook
from airflow.hooks.base_hook import BaseHook
from apiclient.discovery import build
from apiclient.http import MediaFileUpload
from oauth2client.client import SignedJwtAssertionCredentials
logging.getLogger("google_cloud_... | ERROR: type should be string, got " https://cloud.google.com/storage/docs/authentication?hl=en#oauth-scopes\n :type scope: string\n \"\"\"\n super(GoogleCloudStorageHook, self).__init__(scope, google_cloud_storage_conn_id, delegate_to)\n\n def get_conn(self):\n \"\"\"\n" | Returns a Google Cloud Storage service object.
"""
http_authorized = self._authorize()
return build('storage', 'v1', http=http_authorized)
def download(self, bucket, object, filename=False):
"""
Get a file from Google Cloud Storage.
:param bucket: The bucket... |
saurabh6790/erpnext | erpnext/setup/install.py | Python | gpl-3.0 | 4,976 | 0.024317 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import print_function, unicode_literals
import frappe
from erpnext.accounts.doctype.cash_flow_mapper.default_cash_flow_mapper import DEFAULT_MAPPERS
from .default_success_acti... | l': _('Compact Item Print'),
'fieldname': 'compact_item_print',
'fieldtype': 'Check',
'default': 1,
'insert_after': 'with_letterhead'
})
def create_print_uom_after_qty_custom_field():
create_custom_field('Print Settings', {
'label': _('Print UOM after Quantity'),
'fieldname': 'print_uom_after_quantity',... | ault': 0,
'insert_after': 'compact_item_print'
})
def create_print_zero_amount_taxes_custom_field():
create_custom_field('Print Settings', {
'label': _('Print taxes with zero amount'),
'fieldname': 'print_taxes_with_zero_amount',
'fieldtype': 'Check',
'default': 0,
'insert_after': 'allow_print_for_cance... |
mrterry/yoink | yoink/simplify.py | Python | bsd-3-clause | 3,207 | 0.000312 | """Functions for simplifying line segments"""
from __future__ import division
import numpy as np
from skimage import img_as_bool
#from skimage.morphology import skeletonize
def rdp_indexes(points, eps2, dist2=None):
"""Indexes of points kept using the Ramer-Douglas-Peucker algorithm.
Parameters
--------... | len == M
Returns
-------
dist2 : array_like
distance**2 between | each point and line. shape == N
"""
p, l1, l2 = np.asarray(p), np.asarray(l1), np.asarray(l2)
ap = l1 - p
n = l2 - l1
n /= np.sqrt(sum(n**2))
dist = ap - np.outer(n, np.dot(ap, n)).T
return np.sum(dist**2, 1)
def img2line(img):
"""Convert an image to a sequence of indexes
Paramet... |
googleapis/python-bigquery | samples/query_external_sheets_permanent_table.py | Python | apache-2.0 | 3,135 | 0.000957 | # Copyright 2019 Google LLC
#
# L | icensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Lice | nse.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See ... |
kalyons11/kevin | kevin/tests/leet/test_product_except_self.py | Python | mit | 678 | 0 | """
https://leetcode.com/explore/interview/card/top-interview-que | stions-hard/116/arr | ay-and-strings/827/
"""
from unittest import TestCase
from kevin.leet.product_except_self import Solution, SolutionOptimized
class TestProductExceptSelf(TestCase):
def _base_test_product_except_self(self, nums, expected):
for sol_class in [Solution, SolutionOptimized]:
sol = sol_class()
... |
sirrice/dbtruck | bin/fixschema.py | Python | mit | 17,548 | 0.013905 | #!/usr/bin/env python
import random
import readline
import cmd
from sqlalchemy import *
from dbtruck.infertypes import infer_col_type
def err_wrapper(fn):
def f(self, *args, **kwargs):
if fn.__name__ != "do_connect" and not self.check_conn(): return
try:
return fn(self, *args, **kwargs)
except E... | = fn.__name__
f.__doc__ = fn.__doc__
return f
def pprint(table, padding=2):
ncols = max(map(len, table))
for row in table:
while len(row) < ncols:
row.append("")
cols = zip(*table)
lens = [ max(map(len, map(str, col)))+padding for col in cols ]
fmts = {}
for row in table:
if len(row) no... | row)
def tableize(l, padding = 2):
lens = map(len, map(str, l))
bestlen = max(lens) + padding
nitems = max(1, 80 / bestlen)
table = [[]]
for v in l:
if len(table[-1]) >= nitems:
table.append([])
table[-1].append(v)
return table
class SchemaFixer(cmd.Cmd):
prompt = "> "
intro = """
Sch... |
strahlex/machinekit | src/emc/rs274ngc/preview/previewclient.py | Python | lgpl-2.1 | 1,091 | 0.003666 | import sys
import zmq
from machinetalk.protobuf.message | _pb2 import Container
#pr | int "ZMQ=%s pyzmq=%s" % (zmq.zmq_version(), zmq.pyzmq_version())
context = zmq.Context()
preview = context.socket(zmq.SUB)
preview.setsockopt(zmq.SUBSCRIBE, "preview")
preview.connect(sys.argv[1])
status = context.socket(zmq.SUB)
status.setsockopt(zmq.SUBSCRIBE, "status")
preview.connect(sys.argv[2])
poll = zmq.Poll... |
bgottula/point | point/gemini_cmd.py | Python | mit | 1,195 | 0.001674 | #!/usr/bin/env python3
"""
A simple script for sending raw serial commands to Gemini.
"""
import time
import serial
import readline
def main():
ser = serial.Serial('/dev/ttyACM0', baudrate=9600)
while True:
cmd = input('> ')
if len(cmd) == 0:
continue
# losmandy native... | not in cmd:
print("Rejected: Native command must contain a ':' character")
continue
checksum = 0
for c in cmd:
checksum = checksum ^ ord(c)
checksum %= 128
checksum += | 64
cmd = cmd + chr(checksum) + '#'
print('Native command: ' + cmd)
# LX200 command format
elif cmd[0] == ':':
print('LX200 command: ' + cmd)
pass
else:
print("Rejected: Must start with ':', '<', or '>'")
continue
... |
KSanthanam/rethinkdb | packaging/osx/mac_alias/__init__.py | Python | agpl-3.0 | 435 | 0.009195 | from .alias import *
__all__ = [ 'ALIAS_K | IND_FILE', 'ALIAS_KIND_FOLDER',
'ALIAS_HFS_VOLUME_SIGNATURE',
'ALIAS_FIXED_DISK', 'ALIAS_NETWORK_DISK', 'ALIAS_400KB_FLOPPY_DISK',
'ALIAS_800KB_FLOPPY_DISK', 'ALIAS_1_44MB_FLOPPY_DISK',
'ALIAS_EJECTABLE_DISK',
'ALIAS_NO_CNID',
'AppleShareInfo',
... | 'Alias' ]
|
peppelinux/remmina_password_exposer | remmina_password_exposer/remmina_password_exposer.py | Python | gpl-2.0 | 2,034 | 0.0059 | #!/usr/bin/python
# 2018 Giuseppe De Marco <[email protected]>
import base64
import os
import re
import sys
try:
from Crypto.Cipher import DES3
except Exception as e:
print(e)
print('pip3 install --upgrade pycrypto')
sys.exit(1)
# ENV
HOME = os.path.expanduser("~")
CHARSET = 'utf-8'
REMMINA_... | mina_accounts(debug=False):
diz = {}
res = []
fs = open(REMMINA_PREF)
fso = fs.readlines()
fs | .close()
for i in fso:
if re.findall(r'secret=', i):
r_secret = i[len(r'secret='):][:-1]
if debug: print('**secret found {}'.format(r_secret))
for f in os.listdir(REMMINA_FOLDER):
if re.findall(REGEXP_ACCOUNTS, f):
fo = open( REMMINA_FOLDER+f, '... |
ntasfi/PyGame-Learning-Environment | tests/test_ple.py | Python | mit | 2,211 | 0.004071 | #!/usr/bin/python
"""
This tests that all the PLE games | launch, except for doom; we
explicitly check t | hat it isn't defined.
"""
import nose
import numpy as np
import unittest
NUM_STEPS=150
class NaiveAgent():
def __init__(self, actions):
self.actions = actions
def pickAction(self, reward, obs):
return self.actions[np.random.randint(0, len(self.actions))]
class MyTestCase(unittest.TestCas... |
deerwalk/voltdb | tests/sqlcoverage/sql_coverage_test.py | Python | agpl-3.0 | 38,815 | 0.005668 | #!/usr/bin/env python
# This file is part of VoltDB.
# Copyright (C) 2008-2017 VoltDB 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 limitati... | % (ke | y, testConfigKits[key])
if(host != defaultHost):
# Flush database
client.onecmd("updatecatalog " + testConfigKit["testCatalog"] + " " + testConfigKit["deploymentFile"])
statements_file = open(statements_path, "rb")
results_file = open(results_path, "wb")
while True:
try:
... |
Nick-Hall/gramps | gramps/gen/datehandler/_datestrings.py | Python | gpl-2.0 | 15,116 | 0.005162 | # -*- coding: utf-8 -*-
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2013 Vassilii Khachaturov
#
# 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 L... | # http://gramps-project.org/wiki/index.php?title=Translating_Gramps#Translating_dates
# to learn how to select proper inflection to be used in your localized
# DateDisplayer code!
_("|January", "localized lexeme inflections"),
_("|February", "localized lexeme inflections... | |
sharad1126/owtf | tests/test_cases/framework/plugin/plugin_params_tests.py | Python | bsd-3-clause | 4,663 | 0.001501 | from tests.testing_framework.base_test_cases import BaseTestCase
from flexmock import flexmock
from hamcrest import *
from framework.plugin.plugin_params import PluginParams
import re
from hamcrest.library.text.stringmatches import matches_regexp
class PluginParamsTests(BaseTestCase):
def before(self):
s... | .CheckArgList(args, plugin)
def test_SetArgsBasic_sets_the_args_to_the_plugin(self):
plugin = self._get_plugin_example()
args = {"arg1": "val1", "arg2": "val2"}
self.plugin_params.Args = args
assert_that(self.plugin_params.SetArgsBasic(args, plugin), equal_to([args]))
asser... | s"], matches_regexp(".*arg1=val1.*"))
assert_that(plugin["Args"], matches_regexp(".*arg2=val2.*"))
def test_SetConfig_is_a_wrapper(self):
self.core_mock.Config = flexmock()
self.core_mock.Config.should_receive("Set").with_args("_arg1", "val1").once()
args = {"arg1": "val1"}
... |
rhyolight/nupic.research | htmresearch/frameworks/pytorch/sparse_net.py | Python | gpl-3.0 | 10,344 | 0.005994 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2018, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | oosting).
:type boostStrength: float
:param boostStrengthFactor:
boost strength is multiplied by this factor after each epoch.
A value < 1.0 will decrement it every epoch.
:type boostStrengthFactor: float
:param dropout:
dropout probability used to train the second and subsequent lay... | er(SparseNet, self).__init__()
assert(weightSparsity >= 0)
# Validate CNN sdr params
if isinstance(inputSize, collections.Sequence):
assert(inputSize[1] == inputSize[2],
"sparseCNN only supports square images")
if type(outChannels) is not list:
outChannels = [outChannels]
... |
kaichogami/sympy | sympy/external/tests/test_codegen.py | Python | bsd-3-clause | 11,832 | 0.001775 | # This tests the compilation and execution of the source code generated with
# utilities.codegen. The compilation takes place in a temporary directory that
# is removed after the test. By default the test directory is always removed,
# but this behavior can be changed by setting the environment variable
# SYMPY_TEST_CL... | os.remove(filename)
safe_remove("codegen.f90" | )
safe_remove("codegen.c")
safe_remove("codegen.h")
safe_remove("codegen.o")
safe_remove("main.f90")
safe_remove("main.c")
safe_remove("main.o")
safe_remove("test.exe")
os.chdir(oldwork)
os.rmdir(work)
else:
print("TEST NOT REMOVED: %s"... |
Jgarcia-IAS/SAT | openerp/addons-extra/odoo-pruebas/odoo-server/addons-extra/l10n_pe_ple03/report/sunat_3_7.py | Python | agpl-3.0 | 1,980 | 0.00303 | # -*- e | ncoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (c) 2011 NUMA Extreme Systems (www.numaes.com) for Cubic ERP - Teradata SAC. (http://cubicerp.com).
#
# WARNING: This pro | gram as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract... |
btrent/knave | pychess/System/gstreamer.py | Python | gpl-3.0 | 1,803 | 0.007765 | from threading import Lock
from gobject import GObject, SIGNAL_RUN_FIRST, TYPE_NONE
from Log import log
try:
import pygst
pygst.require('0.10')
import gst
except ImportError, e:
log.error("Unable to import gstreamer. All sound will be mute.\n%s" % e)
class Player (GObject):
__gsignals__ = ... | def play(self, uri):
self.player.set_state(gst.STATE_READY)
self.pl | ayer.set_property("uri", uri)
self.player.set_state(gst.STATE_PLAYING)
def __del__ (self):
self.player.set_state(gst.STATE_NULL)
|
joshdrake/django_haystack_compat | tests/elasticsearch_tests/tests/elasticsearch_query.py | Python | bsd-3-clause | 6,603 | 0.002726 | import datetime
from django.test import TestCase
from haystack import connections
from haystack.inputs import Exact
from haystack.models import SearchResult
from haystack.query import SQ
from core.models import MockModel, AnotherMockModel
class ElasticsearchSearchQueryTestCase(TestCase):
def setUp(self):
... | t='why'))
self.sq.add_filter(SQ(title__startswith='haystack'))
self.assertEqual(self.sq.build_query(), u'(why AND title:haystack*)')
def test_clean(self):
self.assertEqual(self.sq.clean('hello world'), 'hello world')
self.assertEqual(self.sq.clean('hello AND world'), 'hello | and world')
self.assertEqual(self.sq.clean('hello AND OR NOT TO + - && || ! ( ) { } [ ] ^ " ~ * ? : \ world'), 'hello and or not to \\+ \\- \\&& \\|| \\! \\( \\) \\{ \\} \\[ \\] \\^ \\" \\~ \\* \\? \\: \\\\ world')
self.assertEqual(self.sq.clean('so please NOTe i am in a bAND and bORed'), 'so please NOT... |
taf3/taf | taf/testlib/dev_trextg.py | Python | apache-2.0 | 5,943 | 0.001683 | # Copyright (c) 2016 - 2017, Intel Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... | ce(str): Interface for changing MTU in host OS
mtu(int): New MTU value
Returns:
int: Original MTU value
Examples::
env.tg[1].set_os_mtu(iface=ports[('tg1', 'sw1')][1], mtu=1650)
"""
pass
ENTRY_TYPE = "tg"
INSTANCES = {"trex": Trex,
... | = "tg"
|
shoopio/shoop | shuup/admin/modules/customers_dashboard/dashboard.py | Python | agpl-3.0 | 802 | 0.001247 | # This file is part of Shuup.
#
# Copyright (c) 2012-2021, Shuup Commerce Inc. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in | the root directory of this source tree.
from django.utils.translation import ugettext | _lazy as _
from shuup.admin.dashboard import DashboardNumberBlock
from shuup.core.models import Order
def get_active_customers_block(request):
shop = request.shop
customer_ids = set(Order.objects.filter(shop=shop).since(30).values_list("customer_id", flat=True))
return DashboardNumberBlock(
id="... |
davidt/reviewboard | reviewboard/webapi/tests/test_file_attachment.py | Python | mit | 12,315 | 0 | from __future__ import unicode_literals
from django.utils import six
from djblets.webapi.errors import INVALID_FORM_DATA, PERMISSION_DENIED
from reviewboard.attachments.models import (FileAttachment,
FileAttachmentHistory)
from reviewboard.webapi.resources import resources
... | review_request = self.create_review_request(submitter=self.user,
| publish=True)
history = FileAttachmentHistory.objects.create(display_position=0)
review_request.file_attachment_histories.add(history)
self.assertEqual(history.latest_revision, 0)
with open(self.get_sample_image_filename(), "r") as f:
self.assertTrue(f)
rsp = s... |
rigdenlab/conkit | conkit/io/fasta.py | Python | bsd-3-clause | 4,455 | 0.000673 | # BSD 3-Clause License
#
# Copyright (c) 2016-21, University of Liverpool
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notic... | ----------
f_handle
Open file handle [write permissions]
hierarchy : :obj:`~conkit.core.sequencefile.SequenceFile`, :obj:`~conkit.core.sequence.Sequence`
"""
hierarchy = self._reconstruct(hierarchy)
content = ""
for remark in hierarchy.remark:
con... | for sequence_entry in hierarchy:
header = ">{}".format(sequence_entry.id)
if len(sequence_entry.remark) > 0:
header = "|".join([header] + sequence_entry.remark)
content += header + "\n"
sequence_string = sequence_entry.seq.upper() # UPPER CASE !!!
... |
dholm/voidwalker | voidwalker/framework/interface/__init__.py | Python | gpl-3.0 | 1,391 | 0 | # (void)walker command line interface
# Copyright (C) 2012 David Holm <[email protected]>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option... | 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 this program. If not, see <http://www.gnu.org/licenses/>.
from .command import BreakpointCommand
from .command import Command
from .command import CommandBuilder
from .command import CommandFactory
from .command import DataCommand
from .command import PrefixCommand
from .command import StackCommand
from .... |
ashwyn/eden-message_parser | modules/eden/dvi.py | Python | mit | 22,129 | 0.016224 | # -*- coding: utf-8 | -*-
| """ Sahana Eden DVI Model
@author: Dominic König <dominic[at]aidiq.com>
@copyright: 2009-2012 (c) Sahana Software Foundation
@license: MIT
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal... |
goosechooser/file-manip-toolkit | tests/eswap_cli_test.py | Python | mit | 794 | 0.002519 | import sys
import pytest
from file_manip_toolkit.eswap import cli
# tod | o - parameterize
def test_parse_args():
args = cli.parse_args(['test.py', 'filetemp', '-o', 'here'])
assert args.file
assert args.fo | rmat
assert args.output
with pytest.raises(AssertionError):
assert args.verbose
@pytest.mark.parametrize("test_input, expected", [
(['eswap_placeholder', 'test', 'filetemp', '-o', 'here'], 1),
(['eswap_placeholder', 'testdir\\vm3.13', 'h', '-o', 'there'], 0),
])
def test_main(tmpdir, test_inpu... |
jsebechlebsky/pptp_auditor | pptp_auditor/__main__.py | Python | gpl-3.0 | 68 | 0.014706 | from pptp_aud | itor import main
if __name__ == '__main__':
| main() |
lightcode/SeriesWatcher | serieswatcher/serieswatcher/tasks/getcover.py | Python | mit | 506 | 0 | # -*- coding: utf-8 -*-
from PyQt4.QtCore | import Qt |
from PyQt4 import QtCore, QtGui
class GetCoverTask(QtCore.QObject):
coverLoaded = QtCore.pyqtSignal(QtGui.QImage)
def __init__(self, coverPath):
super(GetCoverTask, self).__init__()
self._coverPath = coverPath
def run(self):
image = QtGui.QImage(self._coverPath)
image = ... |
nwinter/bantling | src/application/__init__.py | Python | mit | 1,104 | 0.002717 | """
Initialize Flask app
"""
from flask import Flask
import os
from flask_debugtoolbar import DebugToolbarExtension
from werkzeug.debug import DebuggedApp | lication
app = Flask('application')
if os.getenv('FLASK_CONF') == 'DEV':
# Development settings
app.config.from_object('application.settings.Development')
# Flask-DebugToolbar
toolbar = DebugToolbarExtension(app)
# Google app engine mini profiler
# https://github.com/kamens/gae_mini_ | profiler
app.wsgi_app = DebuggedApplication(app.wsgi_app, evalex=True)
from gae_mini_profiler import profiler, templatetags
@app.context_processor
def inject_profiler():
return dict(profiler_includes=templatetags.profiler_includes())
app.wsgi_app = profiler.ProfilerWSGIMiddleware(app.wsgi... |
BirdAPI/BirdJSON | tests/test.py | Python | mit | 277 | 0.00361 | from pprint import ppr | int
import birdjson
if __name__ == "__main__":
js = birdjson.load_file("config.json")
if js:
print js.settings.mysql.config.test[0].hello.int
print js.settings.mysql.config.test[1]._2.int
pprint(vars(js))
| |
klrmn/well-rested-tests | unittest/tests/test_loader.py | Python | mpl-2.0 | 2,850 | 0.000351 | import well_rested_unittest
import unittest2
import os
import sample_tests
from sample_tests import subdirectory
from sample_tests.subdirectory import test_class
class NewSuite(well_rested_unittest.ErrorTolerantOptimisedTestSuite):
pass
class TestAutoDiscoveringTestLoader(unittest2.TestCase):
maxDiff = Non... | lf):
loader = well_rested_unittest.AutoDiscoveringTestLoader()
self.assertEqua | l(loader.suiteClass,
well_rested_unittest.ErrorTolerantOptimisedTestSuite)
suite = loader.loadTestsFromNames(['sample_tests'], None)
self.assertEqual(len(suite._tests), 17)
def test_subdirectory(self):
loader = well_rested_unittest.AutoDiscoveringTestLoader()
... |
SanPen/GridCal | src/research/power_flow/iwamoto_1_bus_test.py | Python | lgpl-3.0 | 2,463 | 0.00203 | import numpy as np
from scipy.sparse import csc_matrix, lil_matrix
from GridCal.Engine.Simulations.PowerFlow.jacobian_based_power_flow import NR_LS
"""
From the paper:
Load-Flow Solutions for Ill-Conditioned Power Systems by a Newton-Like Method
"""
# Ybus in tripplets form as per the paper
triplets = [(1, 1, 0-14.939... | , 9, 0.104 - 1.042j),
(10, 10, 1.346 - 6.110j),
(10, 11, -0.374 + 3.742j),
(11, 11, 0.283 - 2.785j)]
# correct thr triplets indices to zero-base
Y = lil_matrix((11, 11), dtype=complex)
for i, j, v in triplets:
Y[i-1, j-1] = v
Ybus = Y.tocsc()
print('Ybus')
print(Ybus.todense())... |
0+0j,
-0.165-0.080j,
-0.09-0.068j,
0+0j,
0+0j,
-0.026-0.009j,
0+0j,
-0.158-0.057j])
V0 = np.ones_like(Sbus)
V0[0] = 1.024 + 0j
V, converged, norm_f, Scalc, iter_, elapsed = NR_LS(Yb... |
juanjux/python-driver | fixtures/repr.py | Python | gpl-3.0 | 8 | 0 | re | pr( | 1)
|
google-research/electra | run_finetuning.py | Python | apache-2.0 | 12,663 | 0.006791 | # coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | train_batch_size=config.train_batch_size,
eval_batch_size=config.eval_batch_size,
predict_batch_size=config.predict_batch_size)
def tr | ain(self):
utils.log("Training for {:} steps".format(self.train_steps))
self._estimator.train(
input_fn=self._train_input_fn, max_steps=self.train_steps)
def evaluate(self):
return {task.name: self.evaluate_task(task) for task in self._tasks}
def evaluate_task(self, task, split="dev", return_r... |
Xprima-ERP/odoo_addons | xpr_xis_connector/res_users.py | Python | gpl-3.0 | 1,160 | 0 | # -*- encoding: utf-8 -*-
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2014 Savoir-faire Linux
# (<http://www.savoirfairelinux.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# ... | 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILI | TY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import logging
from openerp.osv import osv, fields
_log... |
sdpython/pyquickhelper | _unittests/ut_helpgen/test_utils_sphinxdoc2.py | Python | mit | 2,612 | 0.001149 | """
@brief test log(time=1s)
@author Xavier Dupre
"""
import sys
import os
import unittest
import pyquickhelper.helpgen.utils_sphinx_doc as utils_sphinx_doc
from pyquickhelper.loghelper import fLOG
from pyquickhelper.pycode import ExtTestCase
class TestSphinxDoc2(ExtTestCase):
def test_apply_modifica... | "pyquickhelper",
"loghelper",
"pqh_exception.py"))
rootm = os.path.normpath(os.path.join(path, "..", "..", "src"))
rootrep = ("pyquickhelper.src.pyquickhelper.", "")
stor | e_obj = {}
def softfile(f):
return False
rst = utils_sphinx_doc.apply_modification_template(rootm, store_obj,
utils_sphinx_doc.add_file_rst_template,
file, rootrep, softfil... |
Ambahm/assignment_testing | unit/lesson_02/test_task_09.py | Python | mpl-2.0 | 540 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests lesson 02 task 09."""
# Import Python libs
imp | ort unittest
# Import student file
import inquisition
class L02T09T | estCase(unittest.TestCase):
"""
Tests for lesson 02 task 09.
"""
def test_module_docstring_length(self):
"""
Tests that the module has a docstring at least 3 lines long.
"""
numlines = len(inquisition.__doc__.splitlines())
self.assertGreaterEqual(numlines, 3)
... |
sk1tt1sh/python-docx | tests/test_text.py | Python | mit | 12,538 | 0 | # encoding: utf-8
"""
Test suite for the docx.text module
"""
from __future__ import (
absolute_import, division, print_function, unicode_literals
)
from docx.enum.text import WD_BREAK
from docx.oxml.text import CT_P, CT_R
from docx.text import Paragraph, Run
import pytest
from mock import call, Mock
from .ox... | plex_script', True), ('complex_script', False),
('complex_script', None),
('cs_bold', True), ('cs_bold', False), ('cs_bold', None),
('cs_italic', True), ('cs_italic', False), ('cs_italic', None),
('double_strike', True), ('double_strike', False),
('double_strike', None),
... | 'imprint', True), ('imprint', False), ('imprint', None),
('math', True), ('math', False), ('math', None),
('no_proof', True), ('no_proof', False), ('no_proof', None),
('outline', True), ('outline', False), ('outline', None),
('rtl', True), ('rtl', False), ('rtl', None),
('shadow'... |
vesellov/callfeed.net | mainapp/migrations/0012_auto_20150525_1959.py | Python | mit | 2,217 | 0.000902 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('mainapp', '0011_widget_is_raw'),
]
operations = [
migrations.AddField(
model_name='widget',
name='bl... | 8, choices=[(b'callfeed', b'Callfeed'), (b'client', b'Client')]),
preserve_default=True,
),
migrations.AddField(
model_name='widget',
name='speak_site_name',
field=models.BooleanField(default=False),
preserve_default=True,
),
mi... | els.IntegerField(default=0),
preserve_default=True,
),
]
|
tanglei528/nova | nova/tests/api/openstack/compute/contrib/test_shelve.py | Python | apache-2.0 | 5,679 | 0.001057 | # All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | d4()), {})
def test_shelve_offload_restricted_by_role(self):
| rules = policy.Rules({'compute_extension:shelveOffload':
policy.parse_rule('role:admin')})
policy.set_rules(rules)
req = fakes.HTTPRequest.blank('/v2/123/servers/12/os-shelve')
self.assertRaises(exception.Forbidden,
self.controller._shelve_offlo... |
cmek/radiusdev-web | radius/radauth/apps.py | Python | bsd-2-clause | 134 | 0.007463 | fro | m django.apps import AppConfig
class RadauthAppConfig(AppConfig):
name = 'radauth'
verbose_name = "Radius Au | thentication"
|
brandonPurvis/osf.io | admin/common_auth/admin.py | Python | apache-2.0 | 2,035 | 0.00344 | from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import Permission
from django.contrib.auth.forms import PasswordResetForm
from .models import MyUser
from forms import CustomUserRegistrationForm
class PermissionAdmin(admin.ModelAdmin):
search_fields ... | 'first_name',)
actions = ['send_email_invitation']
# TODO - include alternative messages for warning/failure
def send_email_invitation(self, request, queryset): |
for user in queryset:
reset_form = PasswordResetForm({'email': user.email}, request.POST)
assert reset_form.is_valid()
reset_form.save(
#subject_template_name='templates/emails/account_creation_subject.txt',
#email_template_name='templates/ema... |
letsencrypt/letsencrypt | certbot-dns-dnsmadeeasy/certbot_dns_dnsmadeeasy/__init__.py | Python | apache-2.0 | 3,576 | 0.001678 | """
The `~certbot_dns_dnsmadeeasy.dns_dnsmadeeasy` plugin automates the process of
completing a ``dns-01`` challenge (`~acme.challenges.DNS01`) by creating, and
subsequently removing, TXT records using the DNS Made Easy API.
.. note::
The plugin is not installed by default. It can be installed by heading to
`cer... | 57a
dns_dnsmadeeasy_secret_key = c9b5625f-9834-4ff8-baba-4ed5f32cae55
The path to this file can be provided interactively or using the
``--dns-dnsmadeeasy-credentials`` command-line argument. Certbot records the path
to this file for use during renewal, but does not store the file's contents.
.. caution::
You s... | the password to your
DNS Made Easy account. Users who can read this file can use these credentials
to issue arbitrary API calls on your behalf. Users who can cause Certbot to
run using these credentials can complete a ``dns-01`` challenge to acquire
new certificates or revoke existing certificates for assoc... |
Densvin/RSSVK | vkfeed/tools/html_parser.py | Python | bsd-2-clause | 8,733 | 0.004122 | '''A convenient class for parsing HTML pages.'''
from __future__ import unicode_literals
from HTMLParser import HTMLParser
import logging
import re
from RSSvk.core import Error
LOG = logging.getLogger(__name__)
LOG.setLevel(logging.INFO)
class HTMLPageParser(HTMLParser):
'''A convenient class for parsing HTML... | a character reference of the form &#ref;.'''
self.__accumulate_data('&#' + name + ';')
def handle_data(self, data):
'''Handles data.'''
self.__accumulate_data(data)
def handle_endtag(self, tag_name):
'''Handles end of a tag.'''
self.__handle_data_if_exists()
... | if self.__get_cur_tag()['name'] == tag_name:
self.__close_tag(self.__tag_stack.pop())
else:
for tag_id in xrange(len(self.__tag_stack) - 1, -1, -1):
if self.__tag_stack[tag_id]['name'] == tag_name:
for tag in reversed(self.__tag_stack[tag_id + 1:]):
... |
jacobajit/ion | intranet/apps/board/urls.py | Python | gpl-2.0 | 1,474 | 0.007463 | # -*- coding: utf-8 -*-
from django.conf.urls import url
from . import views
urlpatterns = [
url(r"^$", views.home, name="board"),
url(r"^/all$", views.all_feed, name="board_all"),
url(r"^/course/(?P<course_id>.*)?$", views.course_feed, name="board_course"),
url(r"^/submit/course/(?P<course_id>.*)?$... | _memes_json, name="board_get_memes_json"),
url(r"^/post/(?P<post_id>\d+)?$", views.view_post, name="board_post"),
url(r"^/post/(?P<post_id>\d+)/comment$", views.comment_view, name="board_comment"),
# url(r"^/add$", views.add_post_view, name="add_boardpost"),
url(r"^/post/(?P<id>\d+)/modify$", views.m... | t"),
url(r"^/comment/(?P<id>\d+)/delete$", views.delete_comment_view, name="board_delete_comment"),
url(r"^/post/(?P<id>\d+)/react$", views.react_post_view, name="board_react_post"),
]
|
AKSW/KBox | kbox.pip/kbox/kbox.py | Python | apache-2.0 | 1,180 | 0.002542 | import os
import subprocess
import click
DIR | _PATH = os.path.dirname(os.path.realpath(__file__))
JAR_EXECUTE = "java -jar " + DIR_PATH + "/kbox-v0.0.2-alpha.jar" # kbox-v0.0.2-alpha.jar
SPACE = " "
PUSH_COMMAND = 'push'
COMMAND_LIST = [PUSH_COMMAND]
@click. | command(context_settings={"ignore_unknown_options": True})
@click.argument('commands', nargs=-1)
def execute_kbox_command(commands):
args = SPACE
for item in commands:
args += item + SPACE
execute_commands = JAR_EXECUTE + args
try:
process = subprocess.Popen(execute_commands.split(), std... |
qhm123/the10000 | feed.py | Python | bsd-3-clause | 1,821 | 0.004942 | #!/usr/bin/env python
# coding=utf-8
import os
import datetime
from google.appengine.ext import webapp
from google.appengine.api import memcache
from google.appengine.ext import db
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
from v2ex.babel import Member
from v2ex.ba... | path = os.path.join(os.path.dirname(__file__), 'tpl', 'feed', 'index.xml')
output = template.render(path, template_values)
memcache.set('feed_index', output, 600)
self.response.out.write(output)
def main():
application = webapp.WSGIApplication([
('/index.xml', FeedHome... | in__':
main() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.