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 |
|---|---|---|---|---|---|---|---|---|
krintoxi/NoobSec-Toolkit | NoobSecToolkit /scripts/pySteg/pysteg.py | Python | gpl-2.0 | 340 | 0.005882 | import sys
import os
print "-------------------------"
print "StegHide Options"
print "-------------------------"
print "Usage Example :"
print ""
print"To embed emb.txt in cvr.jpg: steghide embed -cf cvr.jpg -ef emb.txt"
print ""
print "To extract embedded data from stg.jpg: steghide ext | ract -sf stg.jpg"
cmd1 = os.system ("xt | erm ")
|
hyunoklee/turtlebot3_RBIZ | line_detect/include/duckietown_utils/bag_logs.py | Python | gpl-2.0 | 6,453 | 0.004029 | import numpy as np
from . import logger
from duckietown_utils.expand_variables import expand_environment
import os
__all__ = [
'd8n_read_images_interval',
'd8n_read_all_images',
'd8n_get_all_images_topic',
]
def d8n_read_images_interval(filename, t0, t1):
"""
Reads all the RGB data from the ba... | sAndTopicsTuple(msg_types={'sensor_msgs/Image': '060021388200f6f0f447d0fcd9c64743', 'dynamic_reconfigure/ConfigDescript
# ion': '757ce9d44ba8ddd801bb30bc456f946f', 'diagnostic_msgs/DiagnosticArray': '60810da900de1dd6ddd437c3503511da', 'rosgraph_
# msgs/Log': 'acffd30cd6b6de30f120938c17c593fb', 'sensor_msgs/CameraInfo':... | onfigure/Config': '958f16a05573709014982821e6822580', 'sensor_msgs/Joy': '5a9ea5f83505693b71e785041e67a8bb'}, top
# ics={'/rosberrypi_cam/image_raw/theora/parameter_updates': TopicTuple(msg_type='dynamic_reconfigure/Config', message_count=
# 1, connections=1, frequency=None), '/rosberrypi_cam/image_raw/theora': TopicTu... |
jimmy201602/django-gateone | applications/plugins/playback/playback.py | Python | gpl-3.0 | 3,927 | 0.009422 | # -*- coding: utf-8 -*-
#
# Copyright 2011 Liftoff Software Corporation
#
__doc__ = """\
playback.py - A plugin for Gate One that adds support for saving and playing
back session recordings.
.. note:: Yes this only contains one function and it is exposed to clients through a WebSocket hook.
Hooks
-----
This Py... | open(recording_template_path) as f:
#recording_template_data = f.read()
extra_theme_path = os.path.join(templates_path,'themes/black.css')
with io.open(extra_theme_path, mode='r',encoding='UTF-8') as f:
extra_theme = f.read()
rendered_recording = render_string(recording_template_path,**... | prefix=prefix,
theme=theme_css,
colors=colors_css,
colors_25... |
tbpmig/mig-website | bookswap/urls.py | Python | apache-2.0 | 747 | 0.022758 | from django.conf.urls import patterns, url
from bookswap import views
urlpatterns = patterns(
'',
#url(r'^$', views.index, name='index'),
url(r'^admin/start_transaction/$',
views.start_transaction, name='start_transaction'),
url(r'^admin/update_person/$',
views.update_person, name='update... | views.create_book_type, name='create_book_type'),
url(r'^admin/receive_book_start/(?P<uniqname>[a-z]{3,8})/$',
views.receive_book_start, name='receive_book_start'),
url(r'^admin/receive_book/(?P<uniqname>[a-z]{3,8})-(?P<book_type_id>\d+)/$',
views.receive_book, name='receive_book'),
url(r'^a... | views.admin_index, name='admin_index'),
)
|
georgemarshall/django | tests/middleware/urls.py | Python | bsd-3-clause | 299 | 0 | from django.urls import path, re_path
from . import views
urlpatterns = [
path('noslash', views.empty_view),
path('slash/', views.empty_view),
path('needsquoting#/', views.empty_view),
# Accepts | paths with two leading slashes.
re_path(r'^(.+)/security/$', vie | ws.empty_view),
]
|
vermaete/ipxact2systemverilog | ipxact2systemverilog/ipxact2hdlCommon.py | Python | gpl-2.0 | 46,497 | 0.003054 | #!/usr/bin/env python3
# This file is part of ipxact2systemverilog
# Copyright (C) 2013 Andreas Lindh
#
# 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... | :
def __init__(self, name, address, resetValue, size, access, desc, fieldNameList,
bitOffsetList, bitWidthList, fieldDescList, enumTy | peList):
assert isinstance(enumTypeList, list), 'enumTypeList is not a list'
self.name = name
self.address = address
self.resetValue = resetValue
self.size = size
self.access = access
self.desc = desc
self.fieldNameList = fieldNameList
self.bitOffs... |
polarkac/TaskTracker | tasks/utils.py | Python | mit | 837 | 0.003584 | from django.db.models import Sum
from django.contrib.auth.mixins import LoginRequiredMixin
from tasks.models import TimeLog
def get_total_project_spend_time(tasks):
unpaid_tasks = tasks.filter(paid=False)
total_time = (
TimeLog.objects.filter(comment__task__in=unpaid_tasks)
.aggregate(Sum('spe... | 'spend_time__sum']
return total_time
def annotate_total_time_per_task(tasks):
total_times = {}
times = (
TimeLog.objects.filter(comment__task__in=tasks).values('comment__task')
.annotate(Sum('spend_time'))
)
for time in times:
total_times.update({time['comment__task']: time... | t_field_name = None
|
aeslaughter/falcon | scripts/generate_input_syntax.py | Python | lgpl-2.1 | 949 | 0.011591 | #!/usr/bin/env python
import sys, os
# get the location of this script
app_path = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), ".."))
# Set the name of the application here and moose directory relative to the application
app_name = 'falcon'
MOOSE_DIR = os.path.abspath(os.path.join(app_pat | h, '..' 'moose'))
FRAMEWORK_DIR = os.path.abspath(os.path.join(app_path, '..', 'moose', 'framework'))
#### See if MOOSE_DIR is already in the environment instead
if os.environ.has_key("MOOSE_DIR"):
MOOSE_DIR = os.environ['MOOSE_DIR']
FRAMEWORK_DIR = os.path.join(MOOSE_DIR, 'framework')
if os.environ.has_key("FRAMEW... | append(FRAMEWORK_DIR + '/scripts/syntaxHTML')
import genInputFileSyntaxHTML
# this will automatically copy the documentation to the base directory
# in a folder named syntax
genInputFileSyntaxHTML.generateHTML(app_name, app_path, sys.argv, FRAMEWORK_DIR)
|
wayfinder/Wayfinder-CppCore-v3 | ngplib/generator_print.py | Python | bsd-3-clause | 2,826 | 0.010262 | #!/bin/env python
#
# Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
# 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 n... | WHETHER IN CONTRACT, STRICT LIABILITY, 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.
#
import parser_xml
def print_enum(enum):
print "Enum: ",enum.name
for value in enum.values:
prin | t value[0],"=",value[1]
def print_param(param):
print "id:",param.id,"name:",param.name,"default:",param.default, \
"description:",param.description
def print_member(member):
print "Name:",member.name
print "Type:",member.type
print "Comment:",member.comment
def print_struct(struct):
prin... |
raghavsub/gtkpass | gtkpass/main.py | Python | mit | 3,474 | 0.001727 | import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk
import os
from subprocess import call, Popen, PIPE, STDOUT
class GtkPassWindow(Gtk.Window):
def __init__(self):
self.search_text = ''
self.search_result_text = ''
self.get_pass_path()
self.build_gui()... | \n')
def on_key_release(self, widget, event):
if event.keyval == Gdk.KEY_Escape:
Gtk.main_quit()
self.search_text = self.text_entry.get_text().strip()
if self.search_text == '':
self.search_result_text = None
else:
search_result = self.fuzzy_find(... | elf.search_result_text = None
else:
self.search_result_text = search_result[0]
if self.search_result_text:
self.text_view.set_text(self.search_result_text)
else:
self.text_view.set_text('')
def on_button_release(self, widget, event):
self.... |
dimtruck/magnum | magnum/tests/unit/conductor/test_monitors.py | Python | apache-2.0 | 11,331 | 0 | # Copyright 2015 Huawei Technologies Co.,LTD.
#
# 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... | },
}
def setUp(self):
super(MonitorsTestCase, self).setUp()
bay = utils.get_test_bay(node_addresses=['1.2.3.4'],
api_address='https://5.6.7.8:2376')
self.bay = objects.Bay(self.context, **bay)
self.monitor = swarm_monitor.SwarmMonitor(self.conte... | self.bay)
p = mock.patch('magnum.conductor.swarm_monitor.SwarmMonitor.'
'metrics_spec', new_callable=mock.PropertyMock)
self.mock_metrics_spec = p.start()
self.mock_metrics_spec.return_value = self.test_metrics_spec
self.addCleanup(p.stop)
... |
rojassergio/Aprendiendo-a-programar-en-Python-con-mi-computador | Programas_Capitulo_01/Cap01_pagina_12.py | Python | mit | 407 | 0.007389 | '''
@author: Sergio Rojas
@contact: [email protected]
--------------------------
Contenido bajo
Atribución-NoComercial-CompartirIgual 3.0 Venezuela (CC BY-NC-SA 3.0 VE)
http://creativecommons.org/licenses/by-nc-sa/3.0/ve/
Creado en abril 18, 2016
'''
from sympy import *
a, b, | c, d, e, f, x, y = symbols ('a b c d e f x y ')
eqs = (a*x + b*y - e, | c*x + d*y -f)
res = solve(eqs , x, y)
print(res)
|
ppb/ppb-vector | tests/test_normalize.py | Python | artistic-2.0 | 477 | 0 | from hypothesis import assume, given
from utils import angle_isclose, isclose, vectors
@given(v=vectors())
def test_normal | ize_length(v):
"""v.normalize().length == 1 and v == v.length * v.normalize()"""
assume(v)
assert isclose(v.normalize().length, 1)
assert v.isclose(v.length * v.normali | ze())
@given(v=vectors())
def test_normalize_angle(v):
"""Normalization preserves direction."""
assume(v)
assert angle_isclose(v.normalize().angle(v), 0)
|
fedora-infra/bodhi | bodhi-server/bodhi/server/validators.py | Python | gpl-2.0 | 51,555 | 0.00128 | # Copyright © 2007-2019 Red Hat, Inc. and others.
#
# This file is part of Bodhi.
#
# This program is free software; you can redist | ribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundati | on; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details... |
R-daneel-olivaw/mutation-tolerance-voting | code/sf/sf_stv.py | Python | lgpl-3.0 | 1,610 | 0.004348 | '''
Created on Mar 13, 2015
@author: Akshat
'''
from pyvotecore.stv import STV
from code.pref_sf_conv import PrefSFConverter
class ImplSTV(object):
'''
classdocs
'''
def __init__(self, raw_pref):
'''
Constructor
'''
self.processed_pref = PrefSFConver... | print(output['winners'])
# print(output['rounds'])
# print('##STV Winners##')
| # print()
return output
|
crypt3lx2k/Imageboard-Web-Interface | iwi/web/Links.py | Python | mit | 1,469 | 0.017699 | import re
import urlparse
__all__ = ['Links']
class Links (ob | ject):
"""
Utility class for URL creation.
"""
scheme = 'http'
netloc = 'boards.4chan.org'
apiloc = 'a.4cdn.org'
imgloc = 'i.4cdn.org'
board_pattern = re.compile(r'/(\w+)$')
page_pattern = re.compile(r'/(\w+)/(\d+)$')
thread_pattern = re.compile(r'/(\w+)/thread/(\d+)')
@... | """
Creates an URL based on path, whether it is an API URL and optionally
a fragment for a specific post.
"""
return urlparse.urlunparse (
urlparse.ParseResult (
scheme = cls.scheme,
netloc = netloc,
path = path,
... |
architecture-building-systems/CEAforArcGIS | cea/interfaces/dashboard/api/glossary.py | Python | mit | 692 | 0.00289 |
from flask_restplus import Namespace, Resourc | e
from flask import current_app
from cea.glossary import read_glossary_df
api = Namespace('Glossary', description='Glossary for variables used in CEA')
@api.route('/')
class Glossary(Resource):
def get(self):
glossary = read_glossary_df(plugins=current_app.cea_config.plugins)
groups = glossary.g... | a('-')
data.append({'script': group if group != '-' else 'inputs', 'variables': result.to_dict(orient='records')})
return data
|
apollo17march/TweePY | json2csv/gen_outline.py | Python | gpl-3.0 | 2,679 | 0.004479 | #!/usr/bin/env python
import json
import os, os.path
def key_paths(d):
def helper(path, x):
if isinstance(x, dict):
for k, v in x.iteritems():
for ret in helper(path + [k], v):
yield ret
elif isinstance(x, list):
for i, item in enumerate(... | "Path to JSON data file to analyze")
parser.add_argument('-o', '--output-file', type=str, default=None,
help="Path to outline file to output")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-e', '--each-line', action="store_true", default=False,
... | ocess", metavar="KEY")
return parser
def main():
parser = init_parser()
args = parser.parse_args()
outline = make_outline(args.json_file, args.each_line, args.collection)
outfile = args.output_file
if outfile is None:
fileName, fileExtension = os.path.splitext(args.json_file.name)
... |
tomkralidis/geonode | geonode/services/migrations/0027_auto_20190429_0831.py | Python | gpl-3.0 | 401 | 0.002494 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.20 on 2019-04-29 08:31
from django.db import mig | rations
class Migration(migrations.Migration):
dependencies = [
('services', '0026_auto_20171130_0600_squashed_0041_auto_20190404_0820'),
]
operations = [
migrations.AlterModelManagers(
name='service',
managers=[
| ],
),
]
|
fnp/librarian | src/librarian/elements/headers/naglowek_scena.py | Python | agpl-3.0 | 297 | 0.003367 | from ..ba | se import WLElement
class NaglowekScena(WLElement):
SE | CTION_PRECEDENCE = 2
TXT_TOP_MARGIN = 4
TXT_BOTTOM_MARGIN = 2
TXT_LEGACY_TOP_MARGIN = 4
TXT_LEGACY_BOTTOM_MARGIN = 0
HTML_TAG = 'h3'
EPUB_TAG = 'h2'
EPUB_CLASS = 'h3'
EPUB_START_CHUNK = False
|
brendanwhitfield/python-OBD | obd/protocols/protocol_legacy.py | Python | gpl-2.0 | 7,623 | 0.002624 | # -*- coding: utf-8 -*-
########################################################################
# #
# python-OBD: A python OBD-II serial module derived from pyobd #
# #
# C... | [ Frame/Data ]
# 48 6B 10 41 00 BE 7F B8 13 ck
message.data = frames[0].data
else: # len(frames) > 1:
# generic multiline requests carry an order byte
# Ex.
# [ Frame ]
# 48 6B 1... | # 48 6B 10 49 02 02 44 34 47 50 ck
# 48 6B 10 49 02 03 30 30 52 35 ck
# etc... [] [ Data ]
# becomes:
# 49 02 [] 00 00 00 31 44 34 47 50 30 30 52 35
# | [ ] [ ] [ ]
# order byt... |
shaftoe/home-assistant | tests/components/device_tracker/test_unifi.py | Python | apache-2.0 | 4,732 | 0 | """The tests for the Unifi WAP device tracker platform."""
from unittest import mock
import urllib
import pytest
import voluptuous as vol
from homeassistant.components.device_tracker import DOMAIN, unifi as unifi
from homeassistant.const import (CONF_HOST, CONF_USERNAME, CONF_PASSWORD,
... | M_SCHEMA({
CONF_PLATFORM: unifi.DOMAIN,
CONF_USERNAME: 'foo',
CONF_PASSWORD: 'password',
CONF_HOST: 'myhost',
| 'port': 'foo', # bad port!
})
def test_config_controller_failed(hass, mock_ctrl, mock_scanner):
"""Test for controller failure."""
config = {
'device_tracker': {
CONF_PLATFORM: unifi.DOMAIN,
CONF_USERNAME: 'foo',
CONF_PASSWORD: 'password',
}
... |
jnns/wagtail | wagtail/contrib/frontend_cache/tests.py | Python | bsd-3-clause | 22,580 | 0.002834 | from unittest import mock
from urllib.error import HTTPError, URLError
import requests
from azure.mgmt.cdn import CdnManagementClient
from azure.mgmt.frontdoor import FrontDoorManagementClient
from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase
from django.test.utils import overri... | re': {
'BACKEND': 'wagtail.contrib.frontend_cache.backends.CloudflareBackend',
'EMAIL': 'test@ | test.com',
'API_KEY': 'this is the api key',
'ZONEID': 'this is a zone id',
'BEARER_TOKEN': 'this is a bearer token'
},
})
self.assertEqual(set(backends.keys()), set(['cloudflare']))
self.assertIsInstance(backends['cloudflare'], Cloudf... |
mirumee/wagtail-saleor | wagtailsaleor/wagtailsaleor/wsgi.py | Python | bsd-3-clause | 401 | 0.002494 | """
WSGI conf | ig for wagtailsaleor project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/depl | oyment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "wagtailsaleor.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
|
jonesyboynz/DuplicateFileFinder | unittests/HashTaskUnitTests.py | Python | gpl-3.0 | 4,641 | 0.023917 | """
Unit tests for the HashTask object
By Simon Jones
26/8/2017
"""
import unittest
from test.TestFunctions import *
from source.HashTask import *
from source.Channel import Channel
class HashTaskUnitTests(unittest.TestCase):
"""
Unit tests for the HashTask object
"""
def setUp(self):
self.task1_t_channel = Ch... | sk1_t_channel.put(str(TaskMessage("NOT_A_FLAG", 1, TaskMessage.REQUEST, "ERROR_TASK")))
delay_do_nothing()
self.task1_c_channel.put(str(TaskMessage(TaskMessage.FLAG_JOIN, 1, TaskMessage.REQUEST)))
self.task2_c_channel.put(str(TaskMessage(TaskMessage.FLAG_JOIN, 2, TaskMessage.REQUEST)))
self.task1.join()
self.... | task2_t_channel.get_in_queue(), 1)
empty_channel(self, self.task1_c_channel.get_in_queue(), 2)
empty_channel(self, self.task2_c_channel.get_in_queue(), 2)
def test_another_hash_task_case(self):
"""
Another test for robustness
:return:
"""
self.task1.start()
self.task2.start()
self.task1_t_channel.pu... |
efulet/pca | pca/main.py | Python | mit | 3,043 | 0.008216 | """
@created_at 2014-07-15
@author Exequiel Fuentes <[email protected]>
@author Brian Keith <[email protected]>
"""
# Se recomienda seguir los siguientes estandares:
# 1. Para codificacion: PEP 8 - Style Guide for Python Code (http://legacy.python.org/dev/peps/pep-0008/)
# 2. Para documentacion: PEP 257 - Docst... | #print y_pred_SK
#print y_pred_FK
# Se verifica si la lista esta vacia.
if y_pred_SK == y_pred_FK:
print "Son iguales los dos metodos!"
else:
print "No son iguales. :("
# Se grafica la informacion.
graph = Graph(my_pca_lda.fk_get_... | get_y_train())
graph.frequencies_histogram()
graph.probability_density_functions()
graph.conditional_probability(my_pca_lda.fk_get_lda_train(), my_pca_lda.fk_get_y_prob())
graph.show_graphs()
except Exception, err:
print traceback.format_exc()
finally:
sy... |
uclouvain/OSIS-Louvain | base/migrations/0527_auto_20200730_1502.py | Python | agpl-3.0 | 560 | 0.001786 | # Generated by Django 2.2.13 on 2020-07-30 15:02
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('base', '0526_unique_together_groupelementyear'),
]
operations = [
migrations.AlterField(
model_... | to='base.EducationGroupYear'),
),
]
| |
bizarrechaos/newsapi-client | tests/test_newsconfig.py | Python | apache-2.0 | 630 | 0.001587 | import pytest
from news import newsconfig
class TestNewsConfig(object):
def test_news_config_with_path(self):
n = newsconfig.NewsConfig('./news.cfg.exa | mple')
assert n.configpath == './news.cfg.example'
def test_news_config_without_path(self, capsys):
try:
with pytest.raises(SystemExit):
n = newsconfig.NewsConfig()
except:
n = newsconfig.NewsConfig()
assert n.apikey == n.set_api_key(None)... | newsconfig.NewsConfig('/tmp/notafile')
|
google-research/google-research | dedal/alignment.py | Python | apache-2.0 | 20,335 | 0.006934 | # 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 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... | [0, 1], [0, 0]], constant_values=v)
def alignments_to_paths(
alignments, len_x, len_y):
"""Converts sparse representation of align | ments into dense paths tensor.
Args:
alignments: A tf.Tensor<int>[batch, 3, align_len] = tf.stack([pos_x, pos_y,
enc_trans], 1) such that
(pos_x[b][i], pos_y[b][i], enc_trans[b][i]) represents the i-th
transition in the alignment for the b-th sequence pair in the minibatch.
Both pos_x a... |
llhe/tensorflow | tensorflow/python/ops/array_ops.py | Python | apache-2.0 | 79,903 | 0.004543 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 4, 4]]]
shape(t) ==> [2, 2, 3]
```
Args:
input: A `Tensor` or `SparseTensor`.
name: A name for the operation (optional).
out_type: (Optional) The specified output type of the operation
(`int32` or `int64`). Defaults to `tf.int32`.
Returns:
A `Tensor` of type `out_type`.
"""
return sh... | le=redefined-builtin
"""Returns the shape of a tensor.
Args:
input: A `Tensor` or `SparseTensor`.
name: A name for the operation (optional).
optimize: if true, encode the shape as a constant when possible.
out_type: (Optional) The specified output type of the operation
(`int32` or `int64`). D... |
jelly/calibre | src/calibre/gui2/tweak_book/check_links.py | Python | gpl-3.0 | 6,253 | 0.002239 | #!/usr/bin/env python2
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net>
from __future__ import (unicode_literals, division, absolute_import,
print_function)
from collections import defaultdict
from threading import Thread
from PyQt5.Qt import (
... | lnum, col in locations:
text += '<li>{name} \xa0<a href="loc:{lnum},{name}">[{line}: {lnum}]</a></li>'.format(
name=name, lnum=lnum, line=_('line number'))
text += '</ul></li><hr>'
self.results.setHtml(text)
def anchor_clicked(self, qurl):
url = qurl... | [4:])
err = self.errors[errnum]
newurl, ok = QInputDialog.getText(self, _('Fix URL'), _('Enter the corrected URL:') + '\xa0'*40, text=err[2])
if not ok:
return
nmap = defaultdict(set)
for name, href in {(l[0], l[1]) for l in err[0]}:
... |
kerimlcr/ab2017-dpyo | ornek/lollypop/lollypop-0.9.229/src/widgets_indicator.py | Python | gpl-3.0 | 7,051 | 0 | # Copyright (c) 2014-2016 Cedric Bellegarde <[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) any later vers... | self.play()
elif is_loved(self.__id):
self.loved()
def __on_queue_changed(self, unused):
"""
Update button widget
"""
self.update_button()
def __on_button_clicked(self, widget):
"""
Popup menu for track relative to button
... | if self.__id in Lp().player.get_queue():
Lp().player.del_from_queue(self.__id)
else:
Lp().player.append_to_queue(self.__id)
def __on_destroy(self, widget):
"""
Clear timeout
@param widget as Gtk.Widget
"""
if self.__signal_id is not... |
phe-bioinformatics/PHEnix | phe/metadata/__init__.py | Python | gpl-3.0 | 419 | 0.002387 | """Metadata related information.
:Date: 22 Sep, 2015
:Author: Alex Jironkin
"""
impo | rt abc
class PHEMetaData(object):
"""Abstract class to provide interface for meta-data creation."""
__metaclass__ = abc.ABCMeta
| def __init__(self):
pass
@abc.abstractmethod
def get_meta(self):
"""Get the metadata."""
raise NotImplementedError("get meta has not been implemented yet.")
|
loulich/Couchpotato | couchpotato/core/downloaders/synology.py | Python | gpl-3.0 | 10,004 | 0.009296 | import json
import traceback
from couchpotato.core._base.downloader.main import DownloaderBase
from couchpotato.core.helpers.encoding import isInt
from couchpotato.core.helpers.variable import cleanHost
from couchpotato.core.logger import CPLog
import requests
log = CPLog(__name__)
autoload = 'Synology'
class Syn... | return response
except requests.ConnectionError as err:
log.error('Synology connection error, check your config %s', err)
except requests.HTTPError as err:
log.error('SynologyRPC HTTP | Error: %s', err)
except Exception as err:
log.error('Exception: %s', err)
finally:
return response
def create_task(self, url = None, filename = None, filedata = None):
""" Creates new download task in Synology DownloadStation. Either specify
url or pair (file... |
Nixonite/Reddit-Bot-PipeTobacco | PipeTobaccoBot.py | Python | gpl-2.0 | 2,001 | 0.02099 | #!/usr/bin/python
from HTMLParser import HTMLParser
from ReddiWrap import ReddiWrap
import re
import time
import urllib2
tobaccoName = ""
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
global tobaccoName
if(tag == "meta"):
if 'itemprop' in dict(attrs):
if dict(attrs)['itemprop']... | _agent= | 'ReddiWrap')
USERNAME = 'PipeTobaccoBot'
PASSWORD = 'pipetobaccobot.py'
MOD_SUB = 'PipeTobacco' # A subreddit moderated by USERNAME
# Load cookies from local file and verify cookies are valid
reddit.load_cookies('cookies.txt')
# If we had no cookies, or cookies were invalid,
# or the user we are logging into wasn'... |
meduz/NeuroTools | src/parameters/__init__.py | Python | gpl-2.0 | 35,171 | 0.002985 | """
NeuroTools.parameters
=====================
A module for dealing with model parameters.
Classes
-------
Parameter
ParameterRange - for specifying a list of possible values for a given parameter.
ParameterReference - specify a parameter in terms of the value of another parameter.
ParameterSet - for representing... | ets.
ParameterTable - a sub-class of ParameterSet that can represent a table of parameters.
ParameterSpace - a collection of ParameterSets, | representing multiple points in
parameter space.
**Imported from NeuroTools.parameters.validators**
ParameterSchema - A sub-class of ParameterSet against which other ParameterSets can be validated
against using a Validator as found in the sub-package
... |
daxadal/Computational-Geometry | Practica_2/classify_plane_points_template1.py | Python | apache-2.0 | 2,030 | 0.010837 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 4 13:13:13 2017
@author: avaldes
"""
from __future__ import division, print_function
import numpy as np
import matplotlib.pyplot as plt
from MLP import MLP
#%% Create data
#np.random.seed(5)
nb_black = 50
nb_red = 50
nb_data = nb_black + nb... | j in range(10, 51):
for i in range(10, 51):
K_list = [D, i, j, K] #list of dimensions of layers
activation_functions = [np.tanh,
np.tanh,
MLP.sigmoid]
diff_activation_functions = [MLP.dtanh,
... | MLP.dsigmoid]
#%%
x_middle = (x_black + x_red) / 2
nb_middle = x_middle.shape[0]
t_middle = np.asarray([0.5] * nb_middle).reshape(nb_middle, 1)
mlp = MLP(K_list, activation_functions, diff_activation_functions)
for k in range(20):
... |
kobejohn/PQHelper | pqhelper/easy.py | Python | mit | 2,931 | 0.000682 | from pqhelper import base, capture, versus
# these parts are heavy so keep one common object for the module
_state_investigator = base.StateInvestigator()
def versus_summaries(turns=2, sims_to_average=2, async_results_q=None):
"""Return summaries of the likely resutls of each available action..
Arguments:
... | _capture()
if board is None:
return tuple()
steps = c | apture.capture(board)
return steps
if __name__ == '__main__':
pass
|
mike-lawrence/fileForker | fileForker/__init__.py | Python | gpl-3.0 | 916 | 0.050218 | import billiard
billiard.forking_enable(0)
########
# Define a class that spawns a new process
########
class childClass:
def __init__(self,childFile):
self.childFile = ch | ildFile
self.initDict = {}
self.qTo = billiard.Queue()
self.qFrom = billiard.Queue()
self.started | = False
def f(self,childFile,qTo,qFrom,initDict):
execfile(childFile)
import sys
sys.exit()
def start(self):
if self.started:
print 'Oops! Already started this child.'
else:
self.process = billiard.Process( target=self.f , args=(self.childFile,self.qTo,self.qFrom,self.initDict,) )
self.process.sta... |
dockerian/pyapi | demo/setup.py | Python | apache-2.0 | 1,256 | 0 | """
# setup module
"""
import os
from se | tuptools import setup, find_packages
HERE = os.path.abspath(os.path.dirname(__file__))
with o | pen(os.path.join(HERE, 'README.md')) as f:
README = f.read()
# with open(os.path.join(HERE, 'CHANGES.txt')) as f:
# CHANGES = f.read()
CHANGES = "Changes"
PREQ = [
'pyramid',
'python-keystoneclient',
'python-swiftclient',
'pyyaml',
'responses',
'sniffer',
'waitress',
]
PREQ_DEV = [... |
cpaulik/xray | xray/test/test_backends.py | Python | apache-2.0 | 38,439 | 0.000364 | from io import BytesIO
from threading import Lock
import contextlib
import itertools
import os.path
import pickle
import shutil
import tempfile
import unittest
import sys
import numpy as np
import pandas as pd
import xray
from xray import Dataset, open_dataset, open_mfdataset, backends, save_mfdataset
from xray.backe... | return self.array[key]
array = UnreliableArray([0])
with self.assertRaises(UnreliableArrayFailure):
array[0]
self.assertEqual(array[0], 0)
actual = robust_getitem(array, 0, catch=UnreliableArrayFailure,
initial_delay=0)
se... | ect):
pass
class DatasetIOTestCases(object):
def create_store(self):
raise NotImplementedError
def roundtrip(self, data, **kwargs):
raise NotImplementedError
def test_zero_dimensional_variable(self):
expected = create_test_data()
expected['float_var'] = ([], 1.0e9, {'... |
googleads/google-ads-python | google/ads/googleads/v9/common/types/metrics.py | Python | apache-2.0 | 52,950 | 0.001001 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | Average cost of viewable impressions
(``active_view_impressions``).
This field is a member of `oneof`_ ``_active_view_cpm``.
active_view_ctr (float):
Active view measurable clicks divided by
active view viewable impressions. This metric is
repo... | active_view_impressions (int):
A measurement of how often your ad has become
viewable on a Display Network site.
This field is a member of `oneof`_ ``_active_view_impressions``.
active_view_measurability (float):
The ratio of impressions that could be
... |
google/grr | grr/core/grr_response_core/lib/parsers/linux_release_parser_test.py | Python | apache-2.0 | 6,093 | 0.004103 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""Unit test for the linux distribution parser."""
import io
import os
from absl import app
from grr_response_core.lib.parsers import linux_release_parser
from grr_response_core.lib.rdfvalues import anomaly as rdf_anomaly
from grr_response_core.lib.rdfvalues import pa... | linux_release_parser.LinuxReleaseParser()
testdata = [
("/etc/lsb-release",
| os.path.join(self.parser_test_dir, "lsb-release-notubuntu")),
("/etc/oracle-release",
os.path.join(self.parser_test_dir, "oracle-release")),
]
pathspecs, files = self._CreateTestData(testdata)
result = list(parser.ParseFiles(None, pathspecs, files)).pop()
self.assertIsInstance(resu... |
PawarPawan/h2o-v3 | h2o-py/tests/testdir_algos/glm/pyunit_wide_dataset_largeGLM.py | Python | apache-2.0 | 1,540 | 0.01039 | import sys
sys.path.insert(1, "../../../")
import h2o
import numpy as np
def wide_dataset_large(ip,port):
print("Reading in Arcene training data for binomial modeling.")
trainDataResponse = np.genfromtxt(h2o.locate("smalldata/arcene/arcene_train_labels.labels"), delimiter=' ')
trainDataResponse ... | ("Check performance of predictions.")
performance = model.model_performance(validData)
print("Check that prediction AUC better than guessing (0.5).")
assert performance.auc() > 0.5, "predictions should be better then pure chance"
if __name__ == "__main_ | _":
h2o.run_test(sys.argv, wide_dataset_large)
|
inspirehep/sqlalchemy | test/orm/test_mapper.py | Python | mit | 101,238 | 0.005897 | """General mapper operations with an emphasis on selecting/loading."""
from sqlalchemy.testing import assert_raises, assert_raises_message
import sqlalchemy as sa
from sqlalchemy import testing
from sqlalchemy import MetaData, Integer, String, ForeignKey, func, util
from sqlalchemy.testing.schema import Table, Column
... | op_shadow(self):
"""A backref name may not shadow an existing property name."""
Address, addresses, users, User = (self.classe | s.Address,
self.tables.addresses,
self.tables.users,
self.classes.User)
mapper(Address, addresses)
mapper(User, users,
properties={
'addresses':relationship(Address, backref='email_a... |
QISKit/qiskit-sdk-py | qiskit/extensions/standard/u3.py | Python | apache-2.0 | 1,759 | 0 | # -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modif... | y.sin(theta / 2)
],
[
numpy.exp(1j * phi) * numpy.sin(theta / 2),
numpy.exp(1j * (phi + lam)) * numpy.cos(th | eta / 2)
]],
dtype=complex)
def u3(self, theta, phi, lam, q):
"""Apply u3 to q."""
return self.append(U3Gate(theta, phi, lam), [q], [])
QuantumCircuit.u3 = u3
|
h4ck3rm1k3/FEC-Field-Documentation | fec/version/v5_0/F2.py | Python | unlicense | 1,867 | 0.001071 | import fechbase
class Records(fechbase.RecordsBase):
def __init__(self):
fechbase.RecordsBase.__init__(self)
self.fields = [
{'name': 'FORM TYPE', 'number': '1'},
{'name': 'FILER FEC CAND ID', 'number': '2'},
{'name': 'CANDIDATE NAME', 'number': '3'},
... | {'name': 'CITY', 'number': '18'},
{'name': 'STATE', 'number': '19'},
{'name': 'ZIP', 'number': '20'},
{'name': 'FEC COMMITTEE ID NUMBER (Auth)', 'number': '21'},
{'name': 'COMMITTEE NAME (Auth)', 'number': '22'},
{'name': 'STREET 1', 'number': '23'},
... | ber': '24'},
{'name': 'CITY', 'number': '25'},
{'name': 'STATE', 'number': '26'},
{'name': 'ZIP', 'number': '27'},
{'name': 'NAME/CAN (as signed)', 'number': '28'},
{'name': 'Signed', 'number': '29-'},
{'name': 'PRI PERSONAL FUNDS DECLARED', 'numbe... |
CheckMateIO/checkmate_python | checkmate/test/test_properties.py | Python | mit | 1,134 | 0 | import unittest
import json
import responses |
import checkmate
class TestProperties(unittest.TestCase):
def setUp(self):
cm = checkmate.CheckMate(api_key='12345',
| api_base='http://partners.checkmate.dev')
self.properties_client = cm.properties
self.property_response = {
'id': 123,
'name': 'New Hotel'
}
self.search_params = {
'name': 'New Hotel',
'phone': '15555555555',
'... |
gppezzi/easybuild-framework | easybuild/toolchains/gqacml.py | Python | gpl-2.0 | 1,671 | 0.001795 | ##
# Copyright 2012-2019 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscen | trum.be),
# Flemish Research Foundation (FWO) (http://www.fwo.be/en)
# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en).
#
# https://github.com/easybuilders/easybuild
#
# EasyBuild is free software: you can redistribute it and/or modify
# it under the terms of the GNU Genera... | ublished by
# the Free Software Foundation v2.
#
# EasyBuild is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a c... |
hgl888/TeamTalk | win-client/3rdParty/src/json/scons-tools/targz.py | Python | apache-2.0 | 3,137 | 0.01562 | """tarball
Tool-specific initialization for tarball.
"""
## Commands to tackle a command based implementation:
##to unpack on the fly...
##gunzip < FILE.tar.gz | tar xvf -
##to pack on the fly...
##tar cvf - FILE-LIST | gzip -c > FILE.tar.gz
i | mport os.path
import SCons.Builder
import SCons.Node.FS
import SCons.Util
try:
import gzip
import tarfile
internal_targz = 1
except ImportError:
internal_ | targz = 0
TARGZ_DEFAULT_COMPRESSION_LEVEL = 9
if internal_targz:
def targz(target, source, env):
def archive_name( path ):
path = os.path.normpath( os.path.abspath( path ) )
common_path = os.path.commonprefix( (base_dir, path) )
archive_name = path[len(common_p... |
facoy/facoy | FrontEnd/wsgi.py | Python | apache-2.0 | 176 | 0 | from Server_GitHub import application
if __name__ == "__main__":
while True:
try:
| application.run()
except Exception as e:
| print e
|
kkaczkowski/Hoover | robot/motors/motor_i2c.py | Python | apache-2.0 | 6,150 | 0.003415 | #!/usr/bin/python3
import re
import smbus
# ===========================================================================
# I2C Class
# ===========================================================================
class MotorI2C(object):
@staticmethod
def getPiRevision():
"Gets the version number of the ... |
"Writes a 16-bit value to the specified register/address pair"
try:
self.bus.write_word_data(self.address, reg, value)
if self.debug:
print("I2C: Wrote 0x%02X to register pair 0x%02X,0x%02X" % (value, reg, reg + 1))
except IOErro as err:
retur... | elf.address, value)
if self.debug:
print("I2C: Wrote 0x%02X" % value)
except IOError as err:
return self.errMsg()
def writeList(self, reg, list):
"Writes an array of bytes using I2C format"
try:
if self.debug:
print("I2C: W... |
cbrunet/ouf | src/ouf/filemodel/filesystemitem.py | Python | gpl-3.0 | 455 | 0 | from PyQt5.QtCore import Qt
from ouf.filemodel.filemodelitem import FileModelI | tem, FileItemType
class FileSystemItem(FileModelItem):
def __init__(self, path):
super().__init__(FileItemType.filesystem, path)
def data(self, column, role=Qt.DisplayRole):
if column == 0:
if role == Qt.DisplayRole:
if self.is_root | :
return _("File System")
return super().data(column, role)
|
ytsarev/rally | tests/deploy/engines/test_devstack.py | Python | apache-2.0 | 4,266 | 0 | # Copyright 2013: Mirantis 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 b... | ]
self.assertEqual(calls, server.ssh.run.mock_calls)
filename = m_open.mock_calls[0][1][0]
self.assertTrue(filename.endswith('rally/deploy/engines/'
'devstack/install.sh'))
self.assertEqual([mock.call(filename, 'rb')], m_open.mock_calls)
@m... | ch('rally.deploy.engines.devstack.get_script')
@mock.patch('rally.deploy.serverprovider.provider.Server')
@mock.patch('rally.deploy.engines.devstack.objects.Endpoint')
def test_deploy(self, m_endpoint, m_server, m_gs, m_gus, m_gp):
m_gp.return_value = fake_provider = mock.Mock()
server = moc... |
devopshq/youtrack | youtrack/import_helper.py | Python | mit | 7,567 | 0.003568 | # -*- coding: utf-8 -*-
from youtrack import YouTrackException
def utf8encode(source):
if isinstance(source, str):
source = source.encode('utf-8')
return source
def _create_custom_field_prototype(connection, cf_type, cf_name, auto_attached=False, additional_params=None):
if additional_params is ... | t has wrong type.
YouTrackException: If something is wrong with que | ries.
"""
_create_custom_field_prototype(connection, cf_type, cf_name)
if cf_type[0:-3] not in connection.bundle_types:
value_names = None
elif value_names is None:
value_names = []
existing_project_fields = [item for item in connection.getProjectCustomFields(project_id) if
... |
MakeHer/edx-platform | lms/djangoapps/support/views/__init__.py | Python | agpl-3.0 | 180 | 0 | """
Aggregate all views for the support app.
"""
# pylint: disable=wildcard-import
f | rom .index import *
from .certificate import *
from .enrollm | ents import *
from .refund import *
|
labhackercd/colab-edemocracia-plugin | src/colab_edemocracia/views.py | Python | gpl-3.0 | 12,087 | 0 | # -*- coding: utf-8 -*-
from django.views.generic import View
from django.contrib import messages
from django.contrib.auth import get_user_model
from django.core.urlresolvers import reverse
from django.core.mail import EmailMultiAlternatives
from django.shortcuts import redirect, resolve_url
from django.views.decorator... |
http_method_names = [u'post']
@xframe_options_exempt
def dispatch(self, *args, **kwargs):
return super(WidgetS | ignUpView, self).dispatch(*args, **kwargs)
def post(self, request):
if request.user.is_authenticated():
if request.kwargs['next']:
return reverse(request.kwargs['next'])
else:
return HttpResponseBadRequest()
user_form = SignUpForm(request.POS... |
scheib/chromium | tools/perf/core/services/isolate_service_test.py | Python | bsd-3-clause | 2,741 | 0.004743 | # Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import base64
import json
import os
import shutil
import tempfile
import unittest
import zlib
import mock
from core.services import isolate_service
def C... | lf.assertEqual(isolate_service.Retrieve('hash'), b'OK!')
def testRetrieve_fromUrl(self):
self.mock_request.side_effect = UrlResponse('http://get/response', 'OK!')
self.assertEqual(isolate_service.Retrieve('hash'), b'OK!')
def testRetrieveCompressed_content(self):
self.mock_request.side_effect = Conten... | .assertEqual(isolate_service.RetrieveCompressed('hash'),
zlib.compress(b'OK!'))
def testRetrieveCompressed_fromUrl(self):
self.mock_request.side_effect = UrlResponse('http://get/response', 'OK!')
self.assertEqual(isolate_service.RetrieveCompressed('hash'),
zlib.compr... |
tjcsl/ion | intranet/apps/users/templatetags/grades.py | Python | gpl-2.0 | 329 | 0 | from django import template
from ..models import Grade
register = template.Library()
@register.filter
def to_grade_number(year):
"""Returns a `Grad | e` object f | or a year."""
return Grade(year).number
@register.filter
def to_grade_name(year):
"""Returns a `Grade` object for a year."""
return Grade(year).name
|
StevenMPhillips/arrow | python/benchmarks/array.py | Python | apache-2.0 | 2,575 | 0.000777 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | rom_pandas(self.data)
def peakmem_from_series(self, n, dtype):
A.Table.from_pandas(self.data)
class PandasConversionsFromArrow(Pand | asConversionsBase):
param_names = ('size', 'dtype')
params = ((1, 10 ** 5, 10 ** 6, 10 ** 7), ('int64', 'float64', 'float64_nans', 'str'))
def setup(self, n, dtype):
super(PandasConversionsFromArrow, self).setup(n, dtype)
self.arrow_data = A.Table.from_pandas(self.data)
def time_to_ser... |
zozo123/buildbot | master/buildbot/test/fake/fakebuild.py | Python | gpl-3.0 | 2,371 | 0.000422 | # This file is part of Buildbot. Buildbot 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, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; w | ithout 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
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street | , Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import mock
import posixpath
from buildbot import config
from buildbot import interfaces
from buildbot.process import factory
from buildbot.process import properties
from buildbot.test.fake import fakemaster
from twisted.python import compo... |
nuodb/nuodbTools | nuodbTools/cluster/domain.py | Python | bsd-3-clause | 4,530 | 0.018102 | # requests module available at http://docs.python-requests.org/en/latest/
import nuodbTools
import collections, inspect, json, re, requests, socket
class Domain():
'''
classdocs
'''
def __init__(self, rest_url=None, rest_username=None, rest_password=None):
args, _, _, values = inspect.getargvalu... | equests.ConnectionError, e:
# Can't connect to this guy, try the next
pass
else:
if req.status_code == 200:
if len(req.text) > 0:
return req.json()
else:
return {}
else:
d = {"content": req.content, "method":... | s = "Failed REST Request. DEBUG: %s" % json.dumps(d)
raise nuodbTools.RESTError(s)
# If we are here then we couldn't connect to anyone. Raise the flag.
raise nuodbTools.RESTNotAvailableError("Can't get a connection to any endpoint. Tried: %s" % ",".join(urls_tried))
def pp_re... |
ella/esus | tests/unit_project/tests/fixtures.py | Python | bsd-3-clause | 1,899 | 0.035808 | from django.contrib.auth.models import User
from esus.phorum.models import Category, Table
__all__ = ("user_super", "users_usual", "table_simple")
def user_super(case):
case.user_super = User.objects.create(
username = "superuser",
password = "sha1$aaa$b27189d65f3a148a8186753f3f30774182d | 923d5",
first_name = "Esus",
last_name = "master",
is_staff = True,
is_superuser = True,
)
def users_usual(case):
case.user_tester = User.objects.create(
username = "Tester",
password = "sha1$ | aaa$b27189d65f3a148a8186753f3f30774182d923d5",
first_name = "I",
last_name = "Robot",
is_staff = False,
is_superuser = False,
)
case.user_john_doe = User.objects.create(
username = "JohnDoe",
password = "sha1$aaa$b27189d65f3a148a8186753f3f30774182d923d5",
... |
varunagrawal/nuke | nuke/dirtree.py | Python | mit | 3,107 | 0.001293 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Utilities for getting directory tree."""
import os
from pathlib import Path
import crayons
from nuke.utils import parse_ignore_file
def fg(text, color):
"""Set text to foregound color."""
return "\33[38;5;" + str(color) + "m" + text + "\33[0m"
def bg(tex... | continue
# Check if it is the last element
if idx == len(filenames) - 1:
branch = subindent + last_file_link
else:
branch = subindent + file_link
element = {
"repr": "{}{}".format(branch, get_colorized(dirpath ... | h / fn),
}
element_list.append(element)
return element_list, ignore_patterns
|
pmclanahan/pytest-progressive | setup.py | Python | mit | 1,649 | 0.001213 | import sys
import codecs
# Prevent spurious errors during `python setup.py test`, a la
# http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html:
try:
import multiprocessing
except ImportError:
pass
from setuptools import setup, find_packages
extra_setup = {}
if sys.version_info >= (3,):
extra_setu... | ripti | on='A testrunner with a progress bar and smarter tracebacks',
long_description=codecs.open('README.rst', encoding='utf-8').read(),
author='Erik Rose',
author_email='[email protected]',
license='MIT',
packages=find_packages(exclude=['ez_setup']),
install_requires=['nose>=1.2.1', 'blessin... |
Sokrates80/air-py | aplink/messages/ap_save_tx_calibration.py | Python | mit | 2,515 | 0.00159 | """
airPy is a flight controller based on pyboard and written in micropython.
The MIT License (MIT)
Copyright (c) 2016 Fabrizio Scimia, [email protected]
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... | ions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIA... | ct
class SaveTxCalibration:
MESSAGE_TYPE_ID = 110
def __init__(self):
pass
@staticmethod
def decode_payload(payload):
"""
Decode message payload
:param payload: byte stream representing the message payload
:return: a list of 3 list of floats representing the ... |
glabilloy/fabrydb | fabrydb/conf/urls.py | Python | bsd-2-clause | 1,723 | 0.005804 | import re
from django.conf.urls import url, patterns, include
from django.conf import settings
from django.contrib import admin
from django.views.generic import TemplateView
from django.template import add_to_builtins
from fabrydb.admin import fadmin
add_to_builtins('avocado.templatetags.avocado_tags')
admin.autodisc... | workspace/', TemplateView.as_view(template_name='index.html'), name='workspace'),
url(r'^query/', TemplateView.as_view(template_name='index.html'), name='query'),
url(r'^results/', TemplateView.as_view(template_name='index.html'), name='r | esults'),
# Serrano-compatible Endpoint
url(r'^api/', include('serrano.urls')),
# Administrative components
url(r'^admin/', include(admin.site.urls)),
url(r'^fadmin/', include(fadmin.urls), name='fadmin'),
)
# if not settings.DEBUG:
urlpatterns += patterns(
'',
(r'^static/(?P<path>.*)$', ... |
lmazuel/azure-sdk-for-python | azure-mgmt-media/azure/mgmt/media/models/media_service_paged.py | Python | mit | 938 | 0.001066 | # 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 ... | _map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[MediaService]'}
}
def __init__(self, *args, **kwargs):
super(MediaServicePaged, self).__init__(*args, | **kwargs)
|
andrewklau/openshift-tools | openshift/installer/vendored/openshift-ansible-3.5.13/roles/lib_openshift/src/lib/volume.py | Python | apache-2.0 | 1,669 | 0.004194 | # pylint: skip-file
# flake8: noqa
class Volume(object):
''' Class to model an openshift volume object'''
volume_mounts_path = {"pod": "spec.containers[0].volumeMounts",
"dc": "spec.template.spec.containers[0].volumeMounts",
"rc": "spec.template.spec.contai... | {'name': volume_info['name']}
if volume_info['type'] == 'secret':
volume['secret'] = {}
volume[volume_info['type']] = {'secretName': volume_info['secret_name']}
volume_mount = {'mountPath': volume_info['path'],
'name': volume_info['name']}
... | me_info['path'],
'name': volume_info['name']}
elif volume_info['type'] == 'pvc':
volume['persistentVolumeClaim'] = {}
volume['persistentVolumeClaim']['claimName'] = volume_info['claimName']
volume['persistentVolumeClaim']['claimSize'] = volume_info... |
great-expectations/great_expectations | great_expectations/rule_based_profiler/types/attributes.py | Python | apache-2.0 | 604 | 0.003311 | from great_expectations.core import IDDict
from great_expectations.core.util import convert_to_json_serializable
from great_expectations.types import SerializableDotDict
# TODO: <Alex>If/when usage of this class gains traction, it can be moved to common general utilities location.</Alex>
class Attributes(Serializable... | y in order to hold generic attributes with unique ID.
"""
def to_dict(self) -> dic | t:
return dict(self)
def to_json_dict(self) -> dict:
return convert_to_json_serializable(data=self.to_dict())
|
cchristelis/feti | django_project/core/settings/test_travis.py | Python | bsd-2-clause | 592 | 0.001689 | # -*- coding: utf-8 -*-
from .test import * # noqa
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'test_db',
'USER': | 'postgres',
'PASSWORD': '',
'HOST': 'localhost',
# Set to empty string for default.
'PORT': '',
}
}
MEDIA_ROOT = '/tmp/media'
STATIC_ROOT = '/tmp/static'
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch | _backend.ElasticsearchSearchEngine',
'URL': 'http://127.0.0.1:9200/',
'INDEX_NAME': 'haystack',
},
}
|
pas256/troposphere | tests/test_ecs.py | Python | bsd-2-clause | 7,887 | 0 | import unittest
from troposphere import Ref
import troposphere.ecs as ecs
from troposphere import iam
class TestECS(unittest.TestCase):
def test_allow_placement_strategy_constraint(self):
task_definition = ecs.TaskDefinition(
"mytaskdef",
ContainerDefinitions=[
ecs... | ion.to_dict()
def test_port_mapping_does_not_require_protocol(self):
container_definition = ecs.ContainerDefinition(
Image="myimage",
Memory="300",
Name="mycontainer",
PortMappings=[
ecs.PortMapping(
ContainerPort=8125, Hos... | 25,
)
]
)
container_definition.to_dict()
def test_allow_container_healthcheck(self):
health_check_def = ecs.HealthCheck(
Command=[
"CMD-SHELL",
"curl -f http://localhost/ || exit 1"
],
Interval=... |
vdloo/raptiformica | tests/unit/raptiformica/settings/load/test_load_module_configs.py | Python | mit | 849 | 0.001178 | from mock import call
from raptiformica.settings import conf
from raptiformica.settings.load import load_module_configs
from tests.testcase | import TestCase
class TestLoadModuleConfigs(TestCase):
def setUp(self):
self.load_module_config = self.set_up_patch(
'raptiformica.settings.load.load_module_config'
)
self.load_module_config.return_value = [{}]
def test_load_module_configs_loads_module_configs(self):
... | self.load_module_config.mock_calls, expected_calls
)
def test_load_module_configs_flattens_module_configs(self):
ret = load_module_configs()
self.assertCountEqual(ret, [{}] * 2)
|
TwilioDevEd/webhooks-example-django | webhooks/views.py | Python | mit | 2,249 | 0.000889 | from django.conf import settings
from django.http import HttpResponse, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POS | T
from functools import wraps
from twilio.twiml.voice_response import VoiceResponse
from twilio.twiml.messaging_response import MessagingResponse
from twilio.util import RequestValidator
import os
def validate_twilio_request(f):
"""Validates that incomi | ng requests genuinely originated from Twilio"""
@wraps(f)
def decorated_function(request, *args, **kwargs):
# Create an instance of the RequestValidator class
validator = RequestValidator(os.environ.get('TWILIO_AUTH_TOKEN'))
# Validate the request using its URL, POST data,
# and... |
killpanda/Ailurus | ailurus/computer_doctor_pane.py | Python | gpl-2.0 | 6,390 | 0.003756 | #coding: utf-8
#
# Ailurus - a simple application installer and GNOME tweaker
#
# Copyright (C) 2009-2010, Ailurus developers and Ailurus contributors
# Copyright (C) 2007-2010, Trusted Digital Technology Laboratory, Shanghai Jiao Tong University, China.
#
# Ailurus is free software; you can redistribute it and/or modi... | .set_cell_data_func(render_type, self.render_type_func)
column_type.set_sort_column_id(1000)
self.column_text = column_text = gtk.TreeViewColumn()
| column_text.pack_start(render_text)
column_text.set_cell_data_func(render_text, self.render_text_func)
column_text.set_sort_column_id(1001)
self.view = view = gtk.TreeView(sortedstore)
view.set_rules_hint(True)
view.append_column(column_toggle)
view.append_column(colu... |
bthyreau/hippodeep | applyseg_unique.py | Python | mit | 11,344 | 0.024066 | from __future__ import print_function
import time
ct = time.time()
from lasagne.layers import get_output, InputLayer, DenseLayer, ReshapeLayer, NonlinearityLayer
from lasagne.nonlinearities import rectify, leaky_rectify
from lasagne.updates import nesterov_momentum, rmsprop, adamax
import sys, os, time
scriptpath = ... | = 3, pad = "same", name="conv")
l = Upscale3DLayer(l, scale_factor = 2, name="upscale")
l = l_convout1 = Conv3DLayer(l, flip_filters=False, num_filters = conv_num_filters, filter_size = 3, pad = 1, name="conv")
l = Upscale3DLayer(l, scale_factor = 2, name="upscale")
l_upscale = l
| l_convout2 = Conv3DLayer(l_upscale, flip_filters=False, num_filters = 16, filter_size = 3, pad = 1, name="conv")
# Original (before refinement) output
l_output1 = Conv3DLayer(l_convout2, flip_filters=False, num_filters = 1, filter_size = 1, pad = 'same', name="conv_1x", nonlinearity =lasagne.nonlinearities.sig... |
frodrigo/osrm-backend | scripts/gdb_printers.py | Python | bsd-2-clause | 17,883 | 0.011188 | import gdb.printing
# https://sourceware.org/gdb/onlinedocs/gdb/Pretty-Printing.html
# https://sourceware.org/gdb/onlinedocs/gdb/Writing-a-Pretty_002dPrinter.html
COORDINATE_PRECISION = 1e6
coord2float = lambda x: int(x) / COORDINATE_PRECISION
lonlat = lambda x: (coord2float(x['lon']['__value']), coord2float(x['lat']... | l; charset=utf-8"/>
<style>
svg { background-color: beige; }
.node { stroke: #000; stroke-width: 4; fill: none; marker-end: url(#forward) }
.node.forward { stroke-width: 2; stroke: #0c0; font-family: | sans; font-size: 42px }
.node.reverse { stroke-width: 2; stroke: #f00; font-family: sans; font-size: 42px }
.segment { marker-start: url(#osm-node); marker-end: url(#osm-node); }
.segment.weight { font-family: sans; font-size:24px; text-anchor:middle; stroke-width: 1; }
.segment.weight.forward { stroke... |
thica/ORCA-Remote | src/ORCA/widgets/core/ScrollableLabelLarge.py | Python | gpl-3.0 | 15,619 | 0.013573 | # -*- coding: utf-8 -*-
"""
ORCA Open Remote Control Application
Copyright (C) 2013-2020 Carsten Thielepape
Please contact me by : http://www.orca-remote.org/
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as publi... | 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 this program. If | not, see <http://www.gnu.org/licenses/>.
"""
from kivy.lang import Builder
from kivy.uix.recycleview import RecycleView
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.widget import Widget
from kivy.metrics i... |
walterbender/speak | eye.py | Python | gpl-3.0 | 4,073 | 0 | # Speak.activity
# A simple front end to the espeak text-to-speech engine on the XO laptop
# http://wiki.laptop.org/go/Speak
#
# Copyright (C) 2008 Joshua Minor
# This file is part of Speak.activity
#
# Parts of Speak.activity are based on code from Measure.activity
# Copyright (C) 2007 Arjun Sarwal - [email protected]... | d a copy of the GNU General Public License
# along with Speak.activity. If not, see <http://www.gnu.org/licenses/>.
import math
from gi.repository import Gtk
class Eye(Gtk.DrawingArea):
def __init__(self, fill_color):
Gtk.DrawingArea.__init__(self)
self.connect("draw", self.draw)
se... | has_left_center_right(self):
return False
def look_at(self, x, y):
self.x = x
self.y = y
self.queue_draw()
def look_ahead(self):
self.x = None
self.y = None
self.queue_draw()
# Thanks to xeyes :)
def computePupil(self):
a = self.get_all... |
ckan/ckanext-issues | ckanext/issues/logic/schema/__init__.py | Python | mit | 21 | 0 | from schema | impo | rt *
|
zhewang/lcvis | pca.py | Python | gpl-2.0 | 431 | 0.016241 | from matplotlib.mlab import PCA
i | mport gen_icp as icp
def calculate(ids, matrix, target=None):
results = PCA(matrix)
data = []
for obj_id, row in zip(ids, matrix):
data.append([round(results.project(row)[0],6),
round(results.project(row)[1],6)])
#target = []
data = icp.align(data, target)
#for obj_id... | #row.append(obj_id)
return data.tolist()
|
xiaoyongaa/ALL | 函数和常用模块/cash3.py | Python | apache-2.0 | 193 | 0.036269 | import re
a="2+1+3+3123123"
r=re | .findall(r"\d{0,}[\+\-]{0,}",a)
print(r)
with open("re.txt","w") as re:
for i in r:
re.write(i | )
with open("re.txt","r") as r:
r=r.read()
print(r) |
tensorflow/tpu | models/official/detection/projects/fashionpedia/configs/factory.py | Python | apache-2.0 | 1,161 | 0.003445 | # Copyright 2019 The TensorFlow A | uthors. 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 writing, software
# distributed under the License is distributed on an "AS ... |
gopalkoduri/vichakshana-public | vichakshana/SASD.py | Python | agpl-3.0 | 7,505 | 0.005463 | from __future__ import division
from os.path import expanduser, exists
from os import chdir, mkdir
import pickle
import numpy as np
from scipy import sparse
import networkx as nx
home = expanduser('~')
chdir(home+'/workspace/vichakshana/vichakshana/')
#CELERY
from mycelery import app
class SASD():
def __init__... | ickle'))
distance_data = sorted(dis | tance_data, key=lambda x: x[1])
related_entities = []
for i in distance_data:
if i[1] >= distance_threshold:
break
if len(related_entities) < n:
related_entities.append((self.fileindex_reverse[i[0]], i[1]))
return related_entities
|
timj/scons | test/Builder/multi/different-actions.py | Python | mit | 2,193 | 0.000456 | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
... | Clone(XXX = 'var')
env.B(target = 'file6.out', source = 'file6a.in')
env2.B(target = 'file6.out', source = 'fi | le6b.in')
""")
test.write('file6a.in', 'file6a.in\n')
test.write('file6b.in', 'file6b.in\n')
expect = TestSCons.re_escape("""
scons: *** Two environments with different actions were specified for the same target: file6.out
""") + TestSCons.file_expr
test.pass_test()
test.run(arguments='file6.out', status=2, stderr=... |
quantifiedcode-bot/invenio-base | tests/test_apps/flash_msg/views.py | Python | gpl-2.0 | 1,351 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later... | d 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 Invenio; if not, write ... | or displaying flash messages on base page."""
from flask import Blueprint, flash, render_template
from invenio_base.decorators import wash_arguments
blueprint = Blueprint('flash_msg', __name__, url_prefix='/flash_msg',
template_folder='templates', static_folder='static')
@blueprint.route('/'... |
1egoman/quail-flask | src/people.py | Python | mit | 1,454 | 0.020633 | from datetime import datetime
from json import loads, dumps
import os
DEFAULTCONFIG = """{"people": []}"""
PERSONTEMPLATE = {"name": None, "tags": None, "birthday": None, "pic": None, "frequency": 0}
class PeopleContainer(object):
def __init__(self, app):
self.data = []
self.cfgpath = os.path.join(app.get_... | ass Person(dict):
def __init__(self, *args, **kwargs):
super(self, Person).__init | __(*args, **kwargs)
self.__dict__ = self |
linuxmidhun/0install | tests/basetest.py | Python | lgpl-2.1 | 8,927 | 0.031814 | #!/usr/bin/env python
import locale
locale.setlocale(locale.LC_ALL, 'C')
import sys, tempfile, os, shutil, imp, time
import unittest, subprocess
import logging
import warnings
from xml.dom import minidom
if sys.version_info[0] > 2:
from io import StringIO, BytesIO
else:
from StringIO import StringIO
BytesIO = String... | ] = feed
xml = qdom.to_UTF8(feed.feed_element)
upstream_dir = basedir.save_cache_path(namespaces.config_site, 'interfaces')
cached = os.path.join(upstrea | m_dir, model.esca |
jorvis/biocode | taxonomy/create_taxonomic_profile_from_blast.py | Python | mit | 11,261 | 0.014031 | #!/usr/bin/env python3.2
import argparse
import os
import re
import sqlite3
from collections import OrderedDict
from biocode.utils import read_list_file
def main():
"""This is the second script I've written in Python. I'm sure it shows."""
parser = argparse.ArgumentParser( description='Reads a BLAST m8 fil... | file that will be read for taxonomy information
parser.add_argument( | '-t', '--taxonomy_db', type=str, required=True, help='Path to a taxonomy.db file created by "create_taxonomy_db.py"' )
## BLAST list file
parser.add_argument('-b', '--blast_list_file', type=str, required=True, help='List of BLAST files (m8 format)' )
## output file to be written
parser.add_argument('-... |
samueladam/worldgame | src/worldgame/forms.py | Python | bsd-3-clause | 737 | 0 | # -*- coding: utf-8 -*-
from django.contrib.gis import admin
from django import forms
from .models import Country
# create a geoadmin instance
geoadmin = admin.GeoModelAdmin(Country, admin.site)
geoadmin.num_zoom = 4
geoadmin.modifiable = False
geoadmin.layerswitcher = False
geoadmin.mouse_position = False
geoadmin.s... | he geom field
field = Country._meta.get_field('geom')
widget = geoadmin.get_map_widget(f | ield)
class CountryForm(forms.ModelForm):
"This form is a hack to display an OpenLayers map."
geom = forms.CharField(widget=widget)
class Meta:
model = Country
fields = ('name', 'geom',)
class Media:
js = (geoadmin.openlayers_url,)
|
minhphung171093/GreenERP_V9 | openerp/addons/l10n_no/__openerp__.py | Python | gpl-3.0 | 630 | 0.015898 | # -*- encoding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
"name" : "Norway - Accounting",
"version" : "1.1",
" | author" : "Rolv Råen",
"category" : "Localization/Account Charts",
"description": """This is the module to manage the accounting chart for Norway in Odoo.
Updated for Odoo 9 by Bringsvor Consulting AS <www.bringsvor.com>
""",
"depends" : ["account", "base_iban", "base_vat"],
"demo_xml" : [],
"data"... | stallable": True
}
|
Jorge-Rodriguez/ansible | lib/ansible/modules/cloud/vmware/vmware_host_vmnic_facts.py | Python | gpl-3.0 | 14,150 | 0.003322 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Abhijeet Kasurde <[email protected]>
# Copyright: (c) 2018, Christian Kotte <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_f... | : [],
"dvswitch": {
"dvs_0002": [
"vmnic1"
]
},
"num_vmnics": 2,
"used": [
"vmnic1",
"vmnic0"
],
"vmnic_details": [
... | l_speed": 10000,
"adapter": "Intel(R) 82599 10 Gigabit Dual Port Network Connection",
"configured_duplex": "Auto negotiate",
"configured_speed": "Auto negotiate",
"device": "vmnic0",
"driver": "ixgbe"... |
PandaWei/tp-libvirt | libvirt/tests/src/timer_management.py | Python | gpl-2.0 | 19,341 | 0.00031 | """
Test module for timer management.
"""
import os
import logging
import time
from autotest.client import utils
from autotest.client.shared import error
from virttest.libvirt_xml import vm_xml
from virttest import utils_test
from virttest import virsh
from virttest import data_dir
from virttest import virt_vm
CLOCK_... | = int(params.get("inject_times", 10))
logging.info("Trying to inject nmi %s times", inject_times)
while inject_times > 0:
try:
inject_times -= 1
virsh.inject_nmi(vm.name, debug=True, ignore_status=False)
except error.CmdError, detail:
... | int(params.get("dump_times", 10))
logging.info("Trying to dump vm %s times", dump_times)
while dump_times > 0:
|
certik/pyquante | PyQuante/MINDO3_Parameters.py | Python | bsd-3-clause | 4,890 | 0.038855 | """\
MINDO3.py: Dewar's MINDO/3 Semiempirical Method
This program is part of the PyQuante quantum chemistry program suite.
Copyright (c) 2004, Richard P. Muller. All Rights Reserved.
PyQuante version 1.2 and later is covered by the modified BSD
license. Please see the file LICENSE that is part of this
distrib... | 86, None,
None, None, None, -39.82, -56.23, -73.39, -98.99, None]
Upp = [ None, None, None,
None, None, -25.11, -39.18, -56.40, -78.80, -105.93, None,
None, None, None, -29.15, -42.31, -57.25, -76.43, None]
gss = [ None, 12.848, None,
None, None, 10.59, 12.23, 13.59, 15.42, 16.92, None,... | ne, None, None, 7.31, 8.64, 9.90, 11.30, None]
gsp = [ None, None, None,
None, None, 9.56, 11.47, 12.66, 14.48, 17.25, None,
None, None, None, 8.36, 10.08, 11.26, 13.16, None]
gppp = [ None, None, None,
None, None, 7.86, 9.84, 11.59, 12.98, 14.91, None,
None, None, None, 6.54, 7.68, 8.... |
Copenbacon/code-katas | katas/convert_array.py | Python | mit | 335 | 0 | """Convert a number (n) in a reverse list of the individual numbers."""
def digitize(n):
"""Convert a number into a reverse list of each individual number."""
str_list = list(str(n))
str_list.reverse()
num_list = []
for idx in range( | len( | str_list)):
num_list.append(int(str_list[idx]))
return num_list
|
admetricks/printer-webservice | tests.py | Python | mit | 1,374 | 0.000728 | """
html-pdf-webservice
Copyright 2014 Nathan Jones
See LICENSE for more details
"""
from unittest.case import TestCase
from werkzeug.test import Client
from werkzeug.wrappers import BaseResponse
from app import application
class AppTest(TestCase):
def setUp(self):
self.client = Client(appl... | response = self.client.post('/', data={'html': '<html><body><p>Hello</p></body></html>'})
self.assertEquals(200, response.status_code)
self.assertEquals('application/pdf', response.headers['Content-Type'])
def test_get_request_should_produce_method_not_allowed_response(self):
response = ... | quals(405, response.status_code)
self.assertEquals('POST', response.headers['Allow'])
def test_request_without_file_should_produce_bad_request(self):
response = self.client.post('/')
self.assertEquals(400, response.status_code)
self.assertIn('html is required', response.data)
|
bartTC/like | manage.py | Python | mit | 245 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "like.settings")
from django.core.management i | mport execute_from_co | mmand_line
execute_from_command_line(sys.argv)
|
Jheguy2/Mercury | qa/rpc-tests/smartfees.py | Python | mit | 4,241 | 0.008489 | #!/usr/bin/env python2
# Copyright (c) 2014 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test fee estimation code
#
from test_framework import BitcoinTestFramework
from bitcoinrpc.authproxy impo... | ["-blockprioritysize=1500", "-blockmaxsize=2000",
"-debug=mempool", "-debug=estimatefee"]))
connect_nodes(self.nodes[1], 0)
# Node2 is a stingy miner, that
# produces very small blocks (room for only 3 or so transactions)
node2ar... | "-debug=mempool", "-debug=estimatefee"]
self.nodes.append(start_node(2, self.options.tmpdir, node2args))
connect_nodes(self.nodes[2], 0)
self.is_network_split = False
self.sync_all()
def run_test(self):
# Prime the memory pool with pairs of transac... |
jiahaoliang/group-based-policy | gbpservice/neutron/services/servicechain/plugins/ncp/config.py | Python | apache-2.0 | 1,338 | 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... | "gbpservice.neutron.servicechain.ncp_plumbers "
"namespace."))
]
cfg.CONF.register_ | opts(service_chain_opts, "node_composition_plugin")
|
emsrc/algraeph | lib/graeph/graphml/graphview.py | Python | gpl-3.0 | 1,755 | 0.006268 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2013 by
# Erwin Marsi and TST-Centrale
#
#
# This file is part of the Algraeph program.
#
# The Algraeph 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; ... | NTABILITY 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 this program. If not, see <http://www.gnu.org/licenses/>.
"""
subclasses of GraphView and ViewMenu specific to Graphml format
"""
_... | l.com>"
import wx
from graeph.graphview import BasicGraphView, BasicViewMenu
from graeph.pubsub import subscribe, unsubscribe, send, receive
from graeph.graphml.dotgraph import GraphmlDotGraphPair
class GraphmlGraphView(BasicGraphView):
"""
Graph viewer for graph pairs in Graphml format
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.