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 |
|---|---|---|---|---|---|---|---|---|
Level-Up/python_log_io | log_io_handler/__init__.py | Python | gpl-3.0 | 1,702 | 0 | import logging
from emitter import Send
"""
log.io logging handler
======================
Handler for the python logging framework for log.io stateless TCP API
http://logio.org/
Usage:
::
from log_io_handler import LogIOHandler
Logger.addHandler(LogIOHandler)
#or dict_config
'handlers'
'log_io': {
... | ost',
port=28777):
logging.Handler.__init__(self)
self.logstream = logstream
self.node = node
self.h | ost = host
self.port = port
def emit(self, record):
message = self.format(record)
msg_string = "+log|%s|%s|info|%s\r\n" %\
(self.logstream, self.node, message)
Send.config_dict = {'host': self.host, 'port': self.port}
Send(msg_string)
|
awidegreen/tr064 | .ycm_extra_conf.py | Python | bsd-2-clause | 4,073 | 0.021606 | # This file is NOT licensed under the GPLv3, which is the license for the rest
# of YouCompleteMe.
#
# Here's the license text for this file:
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either... | LUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR TH... | re
# These are the compilation flags that will be used in case there's no
# compilation database set (by default, one is not set).
# CHANGE THIS LIST OF FLAGS. YES, THIS IS THE DROID YOU HAVE BEEN LOOKING FOR.
flags = [
'-Wall',
'-Wextra',
'-Werror',
#'-Wc++98-compat',
'-Wno-long-long',
'-Wno-variadic-macros',
'-fexce... |
MattWellie/FastqSimulator | read_condenser.py | Python | gpl-2.0 | 6,301 | 0.003968 | import os
__author__ = 'mwelland'
class Condenser:
"""
A class called from fqRunner.py, used to combine several FastQ files into a single file pair
For each gene and transcript, the modified contents are combined with the unmodified contents
For single transcripts this will mean each variant appear... | pairs.append([read_dict['ref'], filename, self.create_file_name(gene, name_length, filename, read)])
return file_pairs
@staticmethod
def create_file_name(gene, name_length, filename, read):
"""
Creates a new file name which combines the gene name, the transcript number and the read numb... | """
transcript = filename[name_length:name_length+1]
filename = '%s_transcript%s_R%d.fq' % (gene, transcript, read)
return filename
@staticmethod
def combine_files(read_pairs):
"""
This will combine the created files in memory and write the output to a new file
... |
nanolearning/edx-platform | common/lib/xmodule/xmodule/modulestore/xml_importer.py | Python | agpl-3.0 | 34,363 | 0.001484 | import logging
import os
import mimetypes
from path import path
import json
from .xml import XMLModuleStore, ImportSystem, ParentTracker
from xblock.runtime import KvsFieldData, DictKeyValueStore
from xmodule.x_module import XModuleDescriptor
from xmodule.modulestore.keys import UsageKey
from xblock.fields import Scop... |
assert(len(xml_module_store.modules) == 1)
# NOTE: the XmlModuleStore does not implement get_items()
# which would be a preferable means to enumerate the entire collection
# of course modules. It will be left as a TBD to implement that
# method on XmlModuleStore.
course_items = []
for ... | l_module_store.modules.keys():
if target_course_id is not None:
dest_course_id = target_course_id
else:
dest_course_id = course_key
if create_new_course:
# this tests if exactly this course (ignoring case) exists; so, it checks the run
if store.h... |
rcharp/Simple | dependencies/flask-user/flask_user/tests/tst_app.py | Python | bsd-2-clause | 7,602 | 0.00513 | import os
import datetime
from flask import Flask, render_template_string, request
from flask_babel import Babel
from flask_mail import Mail
from flask_sqlalchemy import SQLAlchemy
from flask_user import login_required, SQLAlchemyAdapter, UserManager, UserMixin
from flask_user import roles_required, confirm_email_requi... | AppName" # Used by email templates
USER_ENABLE_USERNAME = True
USER_ENABLE_EMAIL = True
US | ER_ENABLE_CONFIRM_EMAIL = True
USER_ENABLE_INVITATION = True
def init_app(app, test_config=None): # For automated tests
# Setup Flask and read config from ConfigClass defined above
app.config.from_object(__name__+'.ConfigClass')
# Load local_settings.py if file exists ... |
seismology/mc_kernel | tests/create_gabor_filter_test.py | Python | gpl-3.0 | 1,397 | 0 |
# coding: utf-8
# In[1]:
import filtering
import numpy as np
import matplotlib.pyplot as plt
# Load input time trace
signal_in_temp = np.loadtxt('../tests/gaborinput.txt')
len_signal = 1000
dt = 0.1
t = np.array(range(0, len_signal)) * dt
signal_in = np.zeros((len_signal, 1))
signal_in[:, 0] = signal_in_temp
# D... | nscale=1, fmult=2,
sigmaIfc=sigmaIfc[ifilt],
npad=2048,
tshift=(tshift[ifilt], 0))
fnam = '../tests/gaborresponse_%02d.txt' % (ifilt + 1)
with open(fnam, 'w') as f_response:... | , 0, 0], 'r')
fig.savefig('Gaborfilter_reference_data.png', dpi=200)
|
ghisvail/vispy | vispy/plot/tests/test_plot.py | Python | bsd-3-clause | 624 | 0.001603 | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
import vispy.plot as vp
from vispy.testing import (assert_raises, requires_application,
run_tests_if | _main)
@requires_application()
def test_figure_creation():
"""Test creating a figure"""
with vp.Fig(show=False) as fig:
fig[0, 0:2]
fig[1:3, 0:2]
ax_right = fig[1:3, 2]
assert fig[1:3, 2] is ax_right
# collision
assert_raises(ValueError, fi | g.__getitem__, (slice(1, 3), 1))
run_tests_if_main()
|
red-hood/calendarserver | txdav/caldav/datastore/scheduling/imip/test/test_inbound.py | Python | apache-2.0 | 15,369 | 0.002212 | ##
# Copyright (c) 2008-2015 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | d self.receiver.processDSN(calBody, "xyzzy"))
self.assertEquals(result, MailReceiver.INJECTION_SUBMITTED)
yield JobItem.waitEmpty(self.store.newTransaction, reactor, 60)
@inlineCallbacks
def test_processReply(self):
# Make sure an unknown token in an older email is deleted
msg... | ail.message_from_string(self.dataFile('good_reply_past'))
result = (yield self.receiver.processReply(msg))
self.assertEquals(result, MailReceiver.UNKNOWN_TOKEN_OLD)
# Make sure an unknown token is not processed
msg = email.message_from_string(self.dataFile('good_reply_future'))
... |
OCA/website | website_legal_page/hooks.py | Python | agpl-3.0 | 4,340 | 0.00023 | # Copyright 2020 Tecnativa - Alexandre Díaz
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from copy import deepcopy
from xml.sax.saxutils import escape
from lxml import etree as ElementTree
from odoo import SUPERUSER_ID, api
def _merge_views(env, xmlids):
old_view_ids = env["ir.ui.view"].searc... | views_done
# Create a new page with the changes
view_id = env["ir.ui.view"].create(
{
"arch": ElementTree.tostring(new_xml, encoding="unicode"),
"website_id": website_id.id,
"key": new_view_id.key,
"name": new_view_id.name,
... | {
"name": new_website_page.name,
"url": new_website_page.url,
"view_id": view_id.id,
"is_published": True,
"website_id": website_id.id,
"website_indexed": True,
"website_published": True,
}
... |
andreasots/shodan | irc/__init__.py | Python | mit | 3,983 | 0.005021 | import asyncio
import irc.parser
import pyparsing
def unescape(value):
return value.replace("\\:", ";") \
.replace("\\s", " ") \
.replace("\\\\", "\\") \
.replace("\\r", "\r") \
.replace("\\n", "\n")
class Connection:
def __init__(self, host, po... | e["nick"]
if len(source) == 1:
source = (source[0], None, None)
elif len(s | ource) == 2:
source = (source[0], None, source[1])
else:
source = (source[0], source[1], source[2])
else:
source = self.host
command = command.lower()
if co... |
jmartinezchaine/OpenERP | openerp/addons/auth_openid/res_users.py | Python | agpl-3.0 | 4,045 | 0.003214 | #!/usr/bin/env python
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2010-2011 OpenERP s.a. (<http://openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of th... | ####################################################
from openerp.osv import osv, fields
import openerp.exceptions
import tools
import utils
class res_users(osv.osv):
_inherit = 'res.users'
# TODO create helper fields for autofill openid_ | url and openid_email -> http://pad.openerp.com/web-openid
_columns = {
'openid_url': fields.char('OpenID URL', size=1024),
'openid_email': fields.char('OpenID Email', size=256,
help="Used for disambiguation in case of a shared OpenID URL"),
'openid_key': ... |
jessevig/bertviz | bertviz/transformers_neuron_view/tokenization_bert.py | Python | apache-2.0 | 20,131 | 0.00298 | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
#
# 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/LICEN... | asking-vocab.txt",
'bert-large-cased-whole-word-masking': "https://s3.amazonaws.com/models.h | uggingface.co/bert/bert-large-cased-whole-word-masking-vocab.txt",
'bert-large-uncased-whole-word-masking-finetuned-squad': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-finetuned-squad-vocab.txt",
'bert-large-cased-whole-word-masking-finetuned-squad': "https... |
GoogleCloudPlatform/sap-deployment-automation | third_party/github.com/ansible/awx/awx/main/management/commands/cleanup_tokens.py | Python | apache-2.0 | 1,286 | 0.001555 | import logging
from django.core import management
from django.core.management.base import BaseCommand
from awx.main.models import OAuth2AccessToken
from oauth2_provider.models import RefreshToken
class Command(BaseCommand):
def init_logging(self):
| log_levels = dict(enumerate([logging.ERROR, logging.INFO,
logging.DEBUG, 0]))
self.logger = logging.getLogger('awx.main.commands.cleanup_tokens')
self.logger.setLevel(log_levels.get(self.verbosity, 0))
handler = logging.StreamHandler()
handler.setFo... | s'))
self.logger.addHandler(handler)
self.logger.propagate = False
def execute(self, *args, **options):
self.verbosity = int(options.get('verbosity', 1))
self.init_logging()
total_accesstokens = OAuth2AccessToken.objects.all().count()
total_refreshtokens = RefreshTok... |
cdt15/lingam | tests/test_rcd.py | Python | mit | 9,689 | 0.001651 | import os
import numpy as np
import pandas as pd
from lingam.rcd import RCD
def test_fit_success():
# causal direction: x5 --> x0, x3 --> x1 --> x2, x4 <-- x6
get_external_effect = lambda n: np.random.normal(0.0, 0.5, n) ** 3
n_samples = 100
x5 = get_external_effect(n_samples)
x6 = get_external_e... |
get_external_effect = lambda n: np.random.normal(0.0, 0.5, n) ** 3
n_samples = 100
x5 = get_external_effect(n_samples)
x6 = get_external_effect(n_sam | ples)
x0 = 0.6*x5 + get_external_effect(n_samples)
x3 = 0.5*x5 + get_external_effect(n_samples)
x1 = 1.0*x0 + 1.0*x3 + get_external_effect(n_samples)
x2 = 0.8*x1 - 0.6*x6 + get_external_effe |
tscholak/smbkmeans | tfidf_smbkmeans.py | Python | mit | 5,558 | 0.002339 | # -*- coding: utf-8 -*-
import os
import sys
import inspect
cmd_folder = os.path.realpath(
os.path.abspath(
os.path.split(
inspect.getfile(
inspect.currentframe()
)
)[0]
)
)
if cmd_folder not in sys.path:
sys.path.insert... | t SON
from pymongo import MongoClient
from monary import Monary
import bz2
try:
import cPickle as pickle
except:
import pickle
settings = {
'mongo_host': 'server.local',
'mongo_db_name': 'mydb',
'mongo_port': 27017,
'tfidf_collection': 'tfidf',
'models_per_k': 25,
... | 'companies': [10000],
'categories': [0]
}
if __name__ == "__main__":
# establish PyMongo connection:
mongo_client = MongoClient(settings['mongo_host'],
settings['mongo_port'])
mongo_db = mongo_client[settings['mongo_db_name']]
# get collection:
tfid... |
dedalusj/PaperChase | backend/paperchase/helpers/favicon.py | Python | mit | 1,942 | 0 | import re
import requests
from urlparse import urlparse, urljoin
from bs4 import BeautifulSoup
class FaviconFetcher():
def _htc(self, m):
return chr(int(m.group(1), 16))
def _url_decode(self, url):
rex = re.compile('%([0-9a-hA-H][0-9a-hA-H])', re.M)
return rex.sub(self._htc, url)
... | on_at_root(self, domain):
root_icon_path | = domain + "/favicon.ico"
r = requests.get(root_icon_path)
if r.status_code == 200:
return root_icon_path
return None
def icon_in_page(self, url):
path = self._extract_path(url)
r = requests.get(path)
if r.status_code == 200:
page_soup = Beau... |
minghuascode/pyj | pyjs/src/pyjs/lib_trans/pycompiler/astpprint.py | Python | apache-2.0 | 2,379 | 0.003363 | """Python AST pretty-printer.
Copyright(C) 2007, Martin Blais <blais@furius.ca>
This module exports a function that can be used to print a human-readable
version of the AST.
This code is downloaded verbatim from:
http://code.activestate.com/recipes/533146/
"""
__author__ = 'Martin Blais <blais@furius.ca>'
impo... | write('(')
i = 0
for child in node.getChildren():
if not isinstance(child, astmod.Node):
continue
if i != 0:
write(',')
write('\n')
rec_node(astmod, child, level+ | 1, indent, write)
i += 1
if i == 0:
# None of the children as nodes, simply join their repr on a single
# line.
res = []
for child in node.getChildren():
res.append(repr(child))
write(', '.join(res))
else:
... |
LumPenPacK/NetworkExtractionFromImages | win_build/nefi2_win_amd64_msvc_2015/site-packages/networkx/algorithms/chordal/__init__.py | Python | bsd-2-clause | 56 | 0.017857 | from networkx.algorithms.chord | al.cho | rdal_alg import *
|
AdaHeads/Coverage_Tests | src/event_stack.py | Python | gpl-3.0 | 5,316 | 0.010534 |
import websocket
import logging
import json
import config
import threading
from time import sleep
from pprint import pformat
class TimeOutReached(Exception):
pass
class EventListenerThread(threading.Thread):
log = None
ws = None
messageStack = []
ws_uri = None
authto... | destination is None:
return True
elif item['call']['destination'] == destination:
return True
elif item['call']['i | d'] == call_id:
if destination == None:
return True
elif item['call']['destination'] == destination:
return True
return False
def WaitForOpen (self, timeout=3.0):
RESOLUTION = 0.1
timeSlept = 0.0
... |
danielwikstrom/Verificacion | tests/context.py | Python | mit | 150 | 0.026667 | # -*- coding: utf-8 -*-
import sys
impor | t os
sys.path.insert(0, os.path.abspath(os.path.joi | n(os.path.dirname(__file__), '..'))) #WTF?
import sample
|
cuckoo5/soap | Soap_know/handler/base.py | Python | gpl-3.0 | 2,274 | 0.006157 | #coding=utf-8
import tornado
import session
import util.config as config
class BaseHandler(tornado.web.RequestHandler):
def __init__(self, *argc, **argkw):
print 'bbbbbbbbbbbbbbbbbbbbbbbb'
super(BaseHandler, self).__init__(*argc, **argkw)
self.session = session.Session(self.application.se... | return user_json
else:
return None
def result(self, code, msg, result):
| ret = self.format(code, msg, result)
self.set_header("Content-Type", "application/json; charset=UTF-8")
self.write(ret)
def set_current_user(self, user):
# self.set_secure_cookie("user", tornado.escape.json_encode(user))
self.session["user"] = tornado.escape.json_encode(user)
... |
DemocracyClub/yournextrepresentative | ynr/apps/candidates/migrations/0030_merge.py | Python | agpl-3.0 | 234 | 0 | from dj | ango.db import migrations
class Migration(migrations.Migration):
dependencies = [
("candidates", "0029_add_ordering_to_fields_meta"),
("candidates", "0028_auto_20160411_1055"),
]
oper | ations = []
|
zijistark/zckTools | src/zck/token_codegen.py | Python | lgpl-3.0 | 1,078 | 0.029685 | #!/usr/bin/python3
import sys
from pathlib import Path
list_scope_path = Path("./list_scope_tokens.txt")
keyword_bit = 13
list_scope_bit = 14
def main():
if len(sys.argv) < 2:
print("Error: Must specify an argument of either 'tokens' or 'emitters'!", file=sys.stderr)
return 1
list_scopes = set()
with list_s... | sorted(list_scopes):
print(' {:<{width}} => T_{}(Lexeme);'.format('"' + t + '"', t.upper(), width = max_kw_len + 2))
else:
print("Error: Must specify an argument of either 'tokens' or | 'emitters'!", file=sys.stderr)
return 1
return 0
if __name__ == '__main__':
sys.exit(main())
|
arider/riderml | riderml/regression/SGD_regressor.py | Python | mit | 1,474 | 0 | from ..base import model
from gradient_descent import stochastic_gradient_descent
from ..util import loss_functions
import numpy
from ..util.preprocessing import as_matrix
class SGD_regressor(model):
def __init__(self,
function=loss_functions.linear,
dfunction=loss_functions.dli... | data = numpy.ones((tmp.shape[0], tmp.shape[1] + 1))
data[:, 1:] = tmp
else:
data = as_matrix(x)
self.theta = stochastic_gradient_descent(
self.function,
| self.dfunction,
data,
y,
self.theta,
iterations,
self.learning_rate,
shuffle=shuffle,
batch_size=batch_size)
def predict(self, data):
if self.fit_intercept:
tmp = as_matrix(data)
x = numpy.ones((... |
Tesora/tesora-horizon | openstack_dashboard/contrib/trove/content/database_configurations/panel.py | Python | apache-2.0 | 840 | 0 | # Copyright 2015 Tesora Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | ware
# 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.
from django.utils.translation import ugettext_lazy as _
... | :
name = _("Configuration Groups")
slug = 'database_configurations'
permissions = ('openstack.services.database',)
|
SiLab-Bonn/pyBAR | pybar/scans/scan_threshold.py | Python | bsd-3-clause | 4,996 | 0.003803 | import logging
from pybar.analysis.analyze_raw_data import AnalyzeRawData
from pybar.fei4.register_utils import invert_pixel_mask
from pybar.fei4_run_base import Fei4RunBase
from pybar.fei4.register_utils import scan_loop
from pybar.run_manager import RunManager
class ThresholdScan(Fei4RunBase):
'''Sta... | er.get_commands("WrRegister", name=['PlsrDAC']))
self. | register_utils.send_commands(commands)
with self.readout(PlsrDAC=scan_parameter_value):
cal_lvl1_command = self.register.get_commands("CAL")[0] + self.register.get_commands("zeros", length=40)[0] + self.register.get_commands("LV1")[0]
scan_loop(self, cal_lvl1_command, re... |
syci/partner-contact | base_location/tests/test_base_location.py | Python | agpl-3.0 | 10,304 | 0.001262 | # Copyright 2015 Yannick Vaucher, Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import psycopg2
from odoo.exceptions import ValidationError
from odoo.tests import common, tagged
from odoo.tools.misc import mute_logger
@tagged("post_install", "-at_install")
class TestBaseLocation(comm... | e(
{
"name": "Barcelona",
"state_id": cls.state_bcn.id,
"country_id": cls.env.ref("base.es").id,
}
)
cls.city_madrid = city_obj.create(
{
"name": "Madrid",
"state_id": cls.state_madrid.id,... | cls.city_lausanne = city_obj.create(
{
"name": "Lausanne",
"state_id": cls.state_vd.id,
"country_id": cls.env.ref("base.ch").id,
}
)
cls.lausanne = zip_obj.create({"name": "666", "city_id": cls.city_lausanne.id})
cls.barcelo... |
fstonezst/LightGBM | python-package/lightgbm/callback.py | Python | mit | 6,606 | 0.00106 | # coding: utf-8
# pylint: disable = invalid-name, W0105, C0301
from __future__ import absolute_import
import collections
from operator import gt, lt
from .compat import range_
class EarlyStopException(Exception):
"""Exception of early stopping.
Parameters
----------
best_iteration : int
The ... | ret[3]:
best_score.append(float('-inf'))
cmp_op.append(gt)
| else:
best_score.append(float('inf'))
cmp_op.append(lt)
def callback(env):
"""internal function"""
if not cmp_op:
init(env)
for i in range_(len(env.evaluation_result_list)):
score = env.evaluation_result_list[i][2]
if cmp_... |
glassesfactory/Shimehari | shimehari/core/manage/commands/create.py | Python | bsd-3-clause | 5,921 | 0.002141 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
u"""
===============================
Shimehari.core.manage.commands.create
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
アプリケーションを新たに作成する create コマンド
各コマンドモジュールは共通インターフェースとして
Command クラスを持ちます。
===============================
"""
import os
import sys
import e... | leCommand):
name = 'create'
summary = 'Create Shimehari Application'
usage = "Usage: %prog APPLICATION_NAME [OPTIONS]"
option_list = CreatableCommand.option_list + (
make_option('--path', '-p', action='store', type='string', dest='path', help='target create path'),
make_option('--templat... | def handle(self, appDir='app', *args, **options):
try:
importFromString(appDir)
except ImportError:
pass
else:
raise CommandError('%s mou aru' % appDir)
path = options.get('path')
if path is None:
appRootDir = os.path.join(os.getc... |
fjorba/invenio | modules/bibformat/lib/bibreformat.py | Python | gpl-2.0 | 23,401 | 0.005641 | ## -*- mode: python; coding: utf-8; -*-
##
## This file is part of Invenio.
## Copyright (C) 2007, 2008, 2010, 2011, 2012 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 ... | from invenio.bibformat import format_record
from invenio.bibformat_config import CFG_BIBFORMAT_USE_OLD_BIBFORMAT
from invenio.shellutils import split_cli_ids_arg
from invenio.bibtask import task_init, write_message, task_set_option, \
task_get_option, task_update_progress, task_has_option, \
... | n, task_sleep_now_if_required, \
task_get_task_param
import os
import time
import zlib
from datetime import datetime
except ImportError, e:
print "Error: %s" % e
sys.exit(1)
def fetch_last_updated(format):
select_sql = "SELECT last_updated FROM format WHERE code = %s"
row =... |
amanzi/ats-dev | tools/python_models/wrm_brookscorey.py | Python | bsd-3-clause | 2,012 | 0.012425 | import numpy as np
class BrooksCorey(object):
def __init__( self, lambd=0., alpha=0., sr=0.0, smoothing_interval=0. ):
self._lambda = lambd
self._alpha = alpha
self._sr = sr
self._pc0 = smoothing_interval
self._factor = -2.0 - (0.5 + 2.0) * self._lambda;
self._pc_bu... | / (self._pc0**3)
def capillaryPressure( self, s ):
se = (s - self._sr) / (1.0 - self._sr)
se = min(se, 1.0);
return pow(se, -1.0/self._lambda) / self._alpha
def d_capillaryPressure( self, s ):
se = (s - sel | f._sr) / (1.0 - self._sr)
se = min(se, 1.0);
return -1. / self._lambda * pow(se, -1.0/self._lambda - 1.) / self._alpha / (1. - self._sr);
def saturation( self, pc ):
if pc > self._pc_bubble:
return pow(self._alpha * pc, -self._lambda) * (1.0 - self._sr) + self._sr
else:
... |
pmisik/buildbot | master/buildbot/www/avatar.py | Python | gpl-2.0 | 9,042 | 0.001327 | # 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; without eve... | led searching user by commit: response code {res.co | de}')
return None
def _add_size_to_url(self, avatar, size):
parts = urlparse(avatar)
query = parts.query
if query:
query += '&'
query += f's={size}'
return urlunparse((parts.scheme,
parts.netloc, parts.path, parts.params,
query, pa... |
maxamillion/loopabull | loopabull/__init__.py | Python | gpl-3.0 | 261 | 0.003831 | import | logging
logging.basicConfig()
from enum import Enum
logger = logging.getLogger('loopabull')
logger.setLevel(logging.INFO)
class Result(Enum):
runfinished = 1
runerrored = 2
unrouted = 3 |
error = 4
# vim: set expandtab sw=4 sts=4 ts=4
|
geary/claslite | web/app/proxy/handlers.py | Python | unlicense | 1,485 | 0.070034 | # -*- coding: utf-8 -*-
'''
handlers.py for Earth Engine proxy
By Michael Geary - http://mg.to/
See UNLICENSE or http://unlicense.org/ for public domain notice.
'''
from main import fix_sys_path; fix_sys_path()
from tipfy import RequestHandler, Response
from tipfy.utils import json_encode
import cgi, re, urll... | )
debug = api.startswith( 'debug/' )
if debug:
api = api.replace( 'debug/', '', 1 )
if not re.match( allow, api ):
self.abort( 403 )
if test:
response = Response( api )
response.headers['Content-Type'] = 'text/plain'
return response
result = EarthEngine( self ).post( api, data )
... | bug:
json = json_encode( result, indent=4 )
else:
json = json_encode( result )
response = Response( json )
if debug:
response.headers['Content-Type'] = 'text/plain'
else:
response.headers['Content-Type'] = 'application/json'
return response
def get( self, path=None ):
return self._proxy( ... |
alxgu/ansible | lib/ansible/modules/network/avi/avi_useraccountprofile.py | Python | gpl-3.0 | 4,875 | 0.001641 | #!/usr/bin/python
#
# @author: Gaurav Rastogi (grastogi@avinetworks.com)
# Eric Anderson (eanderson@avinetworks.com)
# module_check: supported
# Avi Version: 17.1.1
#
# Copyright: (c) 2017 Gaurav Rastogi, <grastogi@avinetworks.com>
# GNU General Public License v3 | .0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'support | ed_by': 'community'}
DOCUMENTATION = '''
---
module: avi_useraccountprofile
author: Gaurav Rastogi (@grastogi23) <grastogi@avinetworks.com>
short_description: Module for setup of UserAccountProfile Avi RESTful Object
description:
- This module is used to configure UserAccountProfile object
- more examples at ... |
jamessqr/james-squires-dotcom | blog/models.py | Python | bsd-3-clause | 1,065 | 0.050704 | from django.db import models
import datetime
class Category(models.Model):
title = models.CharField(max_length=250, help_text='Maximum 250 characters')
slug = models.SlugField()
descripti | on = models.TextField()
class Meta:
ordering = ['title']
verbose_name_plural = "Categories"
class Admin:
pass
#TODO: This does not work!
#class CategoryAdmin(admin.ModelAdmin):
#prepopulated_fields = {"slug": ("title",)}
def __unicode__(self):
return self.title
def get_absolulte_url(self... | 0 characters')
excerpt = models.TextField(blank=True)
body = models.TextField()
slug = models.SlugField()
pub_date = models.DateTimeField(default=datetime.datetime.now)
class Meta:
ordering = ['title']
verbose_name_plural = "Entries"
class Admin:
pass
def __unicode__(self):
return self.title
def... |
maxwward/SCOPEBak | askbot/migrations/0141_auto__del_field_group_is_open.py | Python | gpl-3.0 | 32,000 | 0.007969 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'Group.is_open'
db.delete_column('askbot_group', 'is_open')
def backwards(self, orm):
... | e_together': "(('user', 'activity'),)", 'object_name': 'ActivityAuditStatus'},
'activity': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['askbot.Activity']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'status': ('django.db.models.fiel... | 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'askbot.anonymousproblem': {
'Meta': {'object_name': 'AnonymousProblem'},
'added_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'author... |
jbm950/pysunspec | sunspec/core/modbus/mbmap.py | Python | mit | 20,337 | 0.00177 |
"""
Copyright (C) 2017 SunSpec Alliance
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, merg... | > 0:
# print offset, data_list
for b in data_list:
c = struct.pack('B', int(b, 16))
if data is None:
data = c
else:
| data += c
mmr = ModbusMapRegs(offset, len(data)/2, data, MBMAP_REGS_ACCESS_RW)
self.regs.append(mmr)
f.close()
except Exception, e:
try:
f.close()
except:
pass
raise ModbusMapErro... |
pbmanis/acq4 | acq4/analysis/modules/MapImager/SpatialCorrelatorCtrlTemplate_pyqt5.py | Python | mit | 5,266 | 0.001899 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'acq4/analysis/modules/MapImager/SpatialCorrelatorCtrlTemplate.ui'
#
# Created by: PyQt5 UI code generator 5.8.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
... | "processBtn")
self.gridLayout.addWidget(self.processBtn, 6, 1, 1, 1)
self.groupBox = QtWidgets.QGroupBox(Form)
self.groupBox.setObjectName("groupBox")
self.gridLayout_2 = QtWidgets.QGridLayout(self.groupBox)
self.gridLayout_2.setContentsMargins(3, 3, 3, 3)
self.gridLayout... | self.gridLayout_2.setObjectName("gridLayout_2")
self.probabilityRadio = QtWidgets.QRadioButton(self.groupBox)
self.probabilityRadio.setChecked(True)
self.probabilityRadio.setObjectName("probabilityRadio")
self.gridLayout_2.addWidget(self.probabilityRadio, 0, 0, 1, 2)
self.thres... |
geertw/rdt-serviceinfo | tests/test_data.py | Python | gpl-3.0 | 3,353 | 0.000895 | import serviceinfo.data as data
import unittest
import datetime
class ServiceTest(unittest.TestCase):
def _create_service(self):
"""
Internal method to create a service object
:return: Service object
"""
service = data.Service()
service.servicenumber = 1234
... | self.assertEquals(repr(stop), "<ServiceStop @ ut>")
def test_stop_get_arrival_platform(self):
stop = data.ServiceStop("ledn")
stop.scheduled_arrival_platform = None
stop.actual_arrival_platform = None
self.assertIsNone(stop.get_arrival_platform())
stop.scheduled_arrival... | self.assertEquals(stop.get_arrival_platform(), "9a")
stop.scheduled_arrival_platform = "9a"
stop.actual_arrival_platform = "8a"
self.assertEquals(stop.get_arrival_platform(), "8a")
def test_stop_get_departure_platform(self):
stop = data.ServiceStop("ledn")
stop.schedu... |
alvaroaleman/ansible | lib/ansible/executor/module_common.py | Python | gpl-3.0 | 35,832 | 0.002623 | # (c) 2013-2014, Michael DeHaan <michael.dehaan@gmail.com>
# (c) 2015 Toshio Kuratomi <tkuratomi@ansible.com>
#
# This file is part of Ansible
#
# Ansible 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... | derr = stderr.read()
if not isinstance(stdout, (bytes, unicode)):
std | out = stdout.read()
if PY3:
sys.stderr.buffer.write(stderr)
sys.stdout.buffer.write(stdout)
else:
sys.stderr.write(stderr)
sys.stdout.write(stdout)
return p.returncode
def debug(command, zipped_mod, json_params):
# The code here normally doesn't run. It's only used for ... |
tomkralidis/GeoHealthCheck | docker/plugins/user/mywmsprobe.py | Python | mit | 1,652 | 0 | from GeoHealthCheck.probe import Probe
from GeoHealthCheck.result import Result
from owslib.wms import WebMapService
class MyWMSProbe(Probe):
"""
Example Probe for WMS Probe user plugin. This is a free-form Probe
that overrides perform_request with custom checks.
To configure a probe, use Docker Cont... | form the request.
See https://github.com/geopython/OWSLib/blob/
master/tests/doctests/wms_Ge | oServerCapabilities.txt
"""
# Test capabilities doc
result = Result(True, 'Test Capabilities')
result.start()
try:
wms = WebMapService(self._resource.url)
title = wms.identification.title
self.log('response: title=%s' % title)
except E... |
vialette/ultrastorage | ultrastorage/inserter/descendinggaugedinserter.py | Python | mit | 413 | 0 | # coding=utf-8
"""Descending gauged inserter.
.. moduleauthor:: Stéphane Vialette <vialette@gmail.com>
"""
from .gaugedinserter import GaugedInserter
class DescendingGaugedInserter(GaugedInserter):
def __init__(self | , storage_system):
"""Initialize this descending gauged inserter with a stroage system.
| """
super(DescendingGaugedInserter, self).__init__(storage_system, True)
|
pterk/django-tcc | tcc/templatetags/autopaginator.py | Python | mit | 9,909 | 0.00222 | try:
set
except NameError:
from sets import Set as set
from django.core.paginator import Paginator, Page, InvalidPage
from django.db.models import F
from django.http import Http404
from coffin import template
from jinja2 import nodes
from jinja2.ext import Extension
from jinja2.exceptions import TemplateSynta... | m + self.per_page
if top + self.orphans >= self.count:
object_list = self.object_list.filter(sortdate__lte=bottomdate)
else:
topdate = self.parentcomments[bottom+self.per_page-1].sortdate
object_list = self.object_list.filter(
sortdate__range=(topdate,... | he total number of objects, across all pages."
if self._count is None:
try:
self.parentcomments = self.object_list.filter(
parent__isnull=True)
self._count = self.parentcomments.count()
except (AttributeError, TypeError):
... |
mtoshi/rancidcmd | docs/source/conf.py | Python | mit | 11,597 | 0.006295 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# rancidcmd documentation build configuration file, created by
# sphinx-quickstart on Thu Apr 2 13:16:39 2015.
#
# 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
# ... | y_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: et... | e current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to us... |
wakiyamap/electrum-mona | electrum_mona/tests/test_lnpeer.py | Python | mit | 56,455 | 0.003135 | import asyncio
import tempfile
from decimal import Decimal
import os
from contextlib import contextmanager
from collections import defaultdict
import logging
import concurrent
from concurrent import futures
import unittest
from typing import Iterable, NamedTuple, Tuple, List, Dict
from aiorpcx import TaskGroup, timeou... | ate_changed(self, chan):
pass
def save_channel(self, chan):
print("Ignoring channel save")
def | diagnostic_name(self):
return self.name
async def stop(self):
await LNWallet.stop(self)
if self.channel_db:
self.channel_db.stop()
await self.channel_db.stopped_event.wait()
async def create_routes_from_invoice(self, amount_msat: int, decoded_invoice: LnAddr, *... |
owtf/owtf | owtf/plugins/web/grep/Cookies_attributes@OWTF-SM-002.py | Python | bsd-3-clause | 557 | 0.003591 | """
GREP Plugin for Cookies Attributes
NOTE: GREP plugins do NOT send traffic to the target and only grep the HTTP Transaction Log
"""
from owtf.plugin.helper import plugin_helper
DESCRIPTION = "Searches transaction DB for Cookie attributes"
def run(PluginInfo):
title = "This plugin looks for cookie setting head... | title)
Content | += plugin_helper.FindResponseHeaderMatchesForRegexpName(
"HEADERS_FOR_COOKIES"
)
# TODO: Fix up
return Content
|
yuewko/neutron | neutron/tests/unit/agent/common/test_polling.py | Python | apache-2.0 | 2,694 | 0 | # Copyright 2013 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... | mock_is_polling_ | required(self, return_value):
return mock.patch.object(self.pm, '_is_polling_required',
return_value=return_value)
def test_is_polling_required_returns_true_when_forced(self):
with self.mock_is_polling_required(False):
self.pm.force_polling()
... |
zoxuyu/rsplus | src/maths.py | Python | gpl-3.0 | 441 | 0.002268 | d | ef gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def modinv(a, b):
"""Returns a tuple (r, i, j) such that r = gcd(a, b) = ia + jb"""
x = 0
y = 1
lx = 1
ly = 0
oa = a
ob = b
while b != 0:
q = a // b
(a, b) = (b, a % b)
(x, lx) = ((lx - (q * x)),... | rn lx
|
moonso/genmod | genmod/annotate_variants/annotate.py | Python | mit | 2,975 | 0.004706 | import logging
from genmod.annotate_regions.get_features import get_region
from genmod.annotate_variants.read_tabix_files import (get_frequencies,
get_spidex_score, get_cadd_scores)
logger = logging.getLogger(__name__)
def annotate_variant(variant, annotation_arguments):
"""Annotate a variant based on what... | dd_scores['cadd_raw']))
# Rebuild the info string
if len(info) > 0:
| info_string = ';'.join(info)
else:
info_string = '.'
variant_info[7] = info_string
return '\t'.join(variant_info) |
jeffseif/dogWalkScore | static/py/flaskr.py | Python | bsd-3-clause | 1,701 | 0.008818 | #! /usr/bin/env python3
# Import
import dogWalkScore
from flask import Flask as Flask,\
jsonify as FlaskJSONify,\
render_template as FlaskRender,\
request as FlaskRequest
# Initialize
# Flask
app = Flask(__name__)
# Build graph
id2Node, id2Edge, id2Poi, id2Tree,... | ress
json = dogWalkScore.FindAddress(address, minutes, id2Node, id2Poi, graphIds, id2Tree)
# Check for bad address
if json is None:
return FlaskJSONify({})
# Update croppedIds
croppedIds.clear( | )
croppedIds.extend(json.get('croppedIds'))
# JSONify it
return FlaskJSONify(json)
@app.route('/routePOI')
def routePOI():
# Grab startId/poiId from url
startId = int(FlaskRequest.args.get('s', ''))
poiId = int(FlaskRequest.args.get('p', ''))
# Route to the POI
json = dogWalkScore... |
btat/Booktype | lib/booktype/apps/convert/urls.py | Python | agpl-3.0 | 1,060 | 0.000943 | # This file is part of Booktype.
# Copyright (c) 2013 Borko Jandras <borko.jandras@sourcefabric.org>
#
# Booktype 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) any later version.
#
# Booktype 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 Affero General Public Lice... |
irregulator/ganetimgr | ganeti/migrations/0012_auto__add_field_cluster_disable_instance_creation.py | Python | gpl-3.0 | 6,975 | 0.008172 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Cluster.disable_instance_creation'
db.add_column('ganeti_cluster', 'disable_instance_creatio... | ('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mo... | s.CharField', [], {'max_length': '100'})
},
'ganeti.cluster': {
'Meta': {'object_name': 'Cluster'},
'default_disk_template': ('django.db.models.fields.CharField', [], {'default': "'plain'", 'max_length': '255'}),
'description': ('django.db.models.fields.CharField', []... |
channelcat/sanic | tests/test_errorpages.py | Python | mit | 2,703 | 0 | import pytest
from sanic import Sanic
from sanic.errorpages import exception_response
from sanic.exceptions import NotFound
from sanic.request import Request
from sanic.response import HTTPResponse
@pytest.fixture
def app():
app = Sanic("error_page_testing")
@app.route("/error", methods=["GET", "POST"])
... | ACK_ERROR_FORMAT = "auto"
| _, response = app.test_client.get(
"/error", headers={"content-type": "application/json"}
)
assert response.status == 500
assert response.content_type == "application/json"
_, response = app.test_client.get(
"/error", headers={"content-type": "text/plain"}
)
assert response.sta... |
mrcrgl/gge-storage | gge_proxy_manager/models/jobs.py | Python | mit | 3,505 | 0.00485 | from __future__ import unicode_literals
from django.db import models
from django.utils.timezone import now, timedelta
Q = models.Q
class LogisticJob(models.Model):
LOCK_FOR = (
(60*15, '15 minutes'),
(60*30, '30 minutes'),
(60*45, '45 minutes'),
(60*60, '1 hour'),
(60*60*... | gnKey("gge_proxy_manager.Castle", related_name= | 'incoming_logistic_jobs')
speed = models.CharField(max_length=5, choices=SPEED)
is_active = models.BooleanField(default=True)
resource = models.CharField(max_length=6, choices=RESOURCE)
gold_limit = models.PositiveIntegerField(null=True, blank=True, default=None)
resource_limit = models.PositiveInte... |
ziima/pyvmd | pyvmd/analysis.py | Python | gpl-3.0 | 3,418 | 0.002926 | """
Utilities for structure analysis.
"""
from . import measure
from .atoms import Selection
__all__ = ['hydrogen_bonds', 'HydrogenBond']
class HydrogenBond(object):
"""
Represents hydrogen bond.
@ivar: Hydrogen donor atom
@ivar: Hydrogen atom
@ivar: Hydrogen acceptor atom
"""
def __init... | ydrogens are never donors.
donor_heavy = Selection('(%s) and noh' % donors.sele | ction, donors.molecule, donors.frame)
# Create selections of hydrogens for donor molecule. This will be used to find the hydrogen involved in the bond.
donor_hydrogens = Selection('hydrogen', donors.molecule, donors.frame)
if acceptors is None:
# Acceptor is same as donor, just copy
acceptor... |
rvinas/sentiment_analysis_tensorflow | predict.py | Python | apache-2.0 | 3,339 | 0.002995 | # predict.py: Uses a previously trained TensorFlow model to make predictions on a test set
# Copyright 2016 Ramon Vinas
#
# 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.apac... | '
'- model.ckpt.meta: Contains the TensorFlow graph definition \n')
FLAGS = tf.flags.FLAGS
if FLAGS.checkpoints_dir is None:
raise ValueError('Please, a valid checkpoints directory is required (--checkpoints_dir <file name>)')
# Load configuration
with open('{}/config.pkl'.format(FLAGS.chec... | sequence_len=config['sequence_len'],
n_samples=config['n_samples'],
test_size=config['test_size'],
val_samples=config['batch_size'],
random_state=config['random_state'],
ensure_preprocessed=True)
# Import graph and evaluate the... |
RafaelPalomar/girder | girder/utility/webroot.py | Python | apache-2.0 | 4,603 | 0.002172 | # -*- coding: utf-8 -*-
import json
import os
import re
import cherrypy
import mako
from girder import constants
from girder.models.setting import Setting
f | rom girder.settings import SettingKey
from girder.utility import config
class WebrootBase:
"""
Serves a template file in response to GET requests.
This will typically be the base class of any non-API endpoints.
"""
exposed = True
def __init__(self, templatePath):
self.vars = {}
| self.config = config.getConfig()
self._templateDirs = []
self.setTemplatePath(templatePath)
def updateHtmlVars(self, vars):
"""
If any of the variables in the index html need to change, call this
with the updated set of variables to render the template with.
""... |
goblinhack/crystaleer | python/things/wall.py | Python | lgpl-3.0 | 943 | 0.00106 | import tp
def thing_init(t):
return
def wall_init(name, short_name, tiles=[]):
x = tp.Tp(name)
x.set_short_name(short_name)
x.set_is_movement_blocking(True)
x.set_is_wall(True)
x.set_is_solid_ground(True)
if tiles is not None:
for t in tiles:
x.set_tile(t, delay_ms=... | wall4", short_name="A boring wall", tiles=["wall4"])
wall_init(name="wall5", short_name="A boring wall", ti | les=["wall5"])
wall_init(name="wall6", short_name="A boring wall", tiles=["wall6"])
wall_init(name="wall7", short_name="A boring wall", tiles=["wall7"])
init()
|
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_06_01/operations/_dscp_configuration_operations.py | Python | mit | 23,827 | 0.00491 | # 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 may ... | ame: The name of the resource.
:type dscp_configuration_name: str
:param parameters: Parameters supplied to the create or update dscp configuration operation.
:type parameters: ~azure.mgmt.network.v2020_06_01.models.DscpConfiguration
:keyword callable cls: A custom type or function that ... | be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling.
Pass in False for this operation to not poll, or pass in your own initialized polling object for a p... |
pinterb/st2 | st2common/st2common/services/action.py | Python | apache-2.0 | 4,646 | 0.002583 | # Licensed to the StackStorm, Inc ('StackStorm') 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 use th... | ' % liveaction.action)
runnertype_db = action_utils.get_runnertype_by_name(action_db.runner_type['name'])
if not hasattr(liveaction, 'parameters'):
liveaction.parameters = dict()
# Validate action parameters.
schema = util_schema.get_parameter_schema(action_db)
validator = util_schema.get... | rams are being overriden. Although possible to
# ignore the override it is safer to inform the user to avoid surprises.
immutables = _get_immutable_params(action_db.parameters)
immutables.extend(_get_immutable_params(runnertype_db.runner_parameters))
overridden_immutables = [p for p in six.iterkeys(live... |
gooddata/openstack-nova | nova/objects/request_spec.py | Python | apache-2.0 | 37,886 | 0.000106 | # Copyright 2015 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | (image, dict):
# NOTE(sbauza): Until Nova is fully providing an ImageMeta object
# for getting properties, we still need to hydrate it here
# TODO(sbauza): To be removed once all Request | Spec hydrations are
# done on the conductor side and if the image is an ImageMeta
self.image = objects.ImageMeta.from_dict(image)
else:
self.image = None
def _from_instance(self, instance):
if isinstance(instance, obj_instance.Instance):
# NOTE(sbauza... |
metamarcdw/nowallet | nowallet/nowallet.py | Python | mit | 46,341 | 0.001273 | import logging
import sys
import os
FORMAT = "%(asctime)s %(levelname)s: %(message)s" # type: str
stdout_hdlr = logging.StreamHandler(sys.stdout) # type: logging.StreamHandler
stdout_hdlr.setFormatter(logging.Formatter(FORMAT))
stdout_hdlr.setLevel(
logging.ERROR if os.environ.get("NW_LOG") == "ERR" else logging... | cert_verify=(proto != "s")
) # type: asyncio.Future
self.queue = None # type: asyncio.Queue
async def do_connect(self) -> None:
| """ Coroutine. Establishes a persistent connection to an Electrum server.
Awaits the connection because AFAIK an init method can't be async.
"""
await self.connection
logging.info("Connected to server")
async def listen_rpc(self, method: str, args: List) -> Any:
""" Coro... |
osmanbaskaya/text-entail | run/entail_utils.py | Python | mit | 1,076 | 0.003717 | #! /usr/bin/python
# -*- coding: utf-8 -*-
__author__ = "Osman Baskaya"
"""
Some utility functions for entailment project
"""
from collections import defaultdict as dd
from metrics import *
def get_eval_metric(metric_name):
if metric_name == "jaccard":
return jaccard_index
elif metric_name == "1":
... | l_score3
def get_test_pairs(test_pairs):
pairs = []
for line in open(test_pairs):
w1, w2, tag = line.split()
pairs.append((w1, w | 2, tag))
return pairs
def get_contexts_above_threshold(test_set, subs_file, threshold):
words = dd(set)
for line_num, line in enumerate(subs_file):
line = line.split()
#tw = line[0]
for i in xrange(1, len(line)-1, 2):
word = line[i]
if word in test_set:
... |
nicolargo/glances | glances/outputs/glances_curses.py | Python | lgpl-3.0 | 47,546 | 0.001367 | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# Copyright (C) 2019 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the Lic... | ANY | WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Curs... |
Adarnof/adarnauth-esi | esi/urls.py | Python | gpl-3.0 | 196 | 0 | from __future__ import unicode_literals
from django.conf.urls import url
import esi.views
app_name = 'esi'
urlpatterns = [
url(r'^callback | /$', esi.views.receive_callback, name | ='callback'),
]
|
kracekumar/bt | bt/server.py | Python | gpl-3.0 | 8,012 | 0.000874 | # -*- coding: utf-8 -*-
import os
import asyncio
import struct
from .logger import get_logger
from .protocol import PeerStreamIterator
from .message import (MessageID,
InterestedMessage,
HandshakeMessage,
BitFieldMessage,
NotInte... | _consume()
return UnchokeMessage()
elif message_id is MessageID.Have.value:
data = _data()
_consume()
return HaveMessage.decode(data)
elif message_id is MessageID.Piece.value:
... |
_consume()
return PieceMessage.decode(data)
elif message_id is MessageID.Request.value:
data = _data()
_consume()
return RequestMessage.decode(data)
elif message_id is MessageID.Cancel.va... |
Praesidio/syslog-ng-python-sqs | python_sqs_stdin.py | Python | gpl-2.0 | 871 | 0.001148 | #!/usr/bin/env python
import json, logging, sys
import python_sqs
log = None
line = None
encodings = ('UTF-8', 'WINDOWS-1252', 'ISO-8859-1')
try | :
python_sqs.init(json_input=True)
log = logging.getLogger(__name__)
line = sys.stdin.readline()
while line:
line = line.strip()
for encoding in encodings:
try:
line = unicode(line, | encoding)
break
except ValueError:
pass
else:
log.debug("Falling back to ascii w/replace")
line = unicode(line, errors='replace')
python_sqs.queue(line)
line = sys.stdin.readline()
except Exception, e:
if log:
log.e... |
EndPointCorp/lg_ros_nodes | lg_builder/setup.py | Python | apache-2.0 | 322 | 0 | #!/usr/bin/env python3
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutil | s_setup
d = generate_distutils_setup(
packages=['lg_builder'],
package_dir={'': 'src'},
scripts=['scripts/lg-ros-build'],
install_requires=['catkin_pkg', 'python-debian', 'rospkg'] |
)
setup(**d)
|
entomb/CouchPotatoServer | couchpotato/core/providers/nzb/__init__.py | Python | gpl-3.0 | 354 | 0 | config = [{
'name': 'nzb_providers',
'groups': [
| {
'label': 'Usenet Providers',
'description': 'Providers searching usenet for new releases',
'wizard': True,
'type': 'list',
'name': 'nzb_providers',
'tab': 'searcher',
| 'options': [],
},
],
}]
|
failys/CAIRIS | cairis/core/TrustBoundary.py | Python | apache-2.0 | 1,461 | 0.019165 | # 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 ownershi | p. The ASF licenses this file
# to you under the Apache License, V | ersion 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
# "A... |
sammyshj/nyx | nyx/panel/config.py | Python | gpl-3.0 | 11,732 | 0.011933 | # Copyright 2010-2016, Damian Johnson and The Tor Project
# See LICENSE for licensing information
"""
Panel presenting the configuration state for tor or nyx. Options can be edited
and the resulting configuration files saved.
"""
import curses
import os
import nyx.controller
import nyx.curses
import nyx.panel
import... | ot configured to show them
if name.startswith('__') and not CONFIG['features.config.state.showPrivateOptions']:
continue
elif value_type == 'Virtual' and not CONFIG['features.config.state.showVirtualOptions']:
continue
self._contents.append(ConfigEntry(name, value_type, man... | ield in self._sort_order])
except stem.ControllerError as exc:
log.warn('Unable to determine the configuration options tor supports: %s' % exc)
def show_sort_dialog(self):
"""
Provides the dialog for sorting our configuration options.
"""
sort_colors = dict([(attr, CONFIG['attr.config.sort... |
cbg-ethz/WES_Cancer_Sim | sim_cancer/tools/GemSIM_v1.6/GemErr.py | Python | apache-2.0 | 29,535 | 0.032673 | #!/usr/bin/python
# Copyright (C) 2011, Kerensa McElroy.
# kerensa@unsw.edu.au
# This file is part of the sequence simulator GemSIM.
# It is used to calculate a platform- and run- specific
# error model for generating realistic sequencing reads.
# Alternatively, users may employ one of the precomputed
# error models... | 0, 't':1, 'g':2, 'c':3, 'n':4}
RposL=pos-1 # | tracks leftmost pos of align against ref
RposR=pos-1 #tracks rightmost pos of align against ref
Rpos=0 #position within aligned reference slice
Spos=0 #sequence position within read
bPos=pos-1 #individual referenc... |
gwwfps/boxrps | werkzeug/contrib/atom.py | Python | mit | 14,976 | 0.000267 | # -*- coding: utf-8 -*-
"""
werkzeug.contrib.atom
~~~~~~~~~~~~~~~~~~~~~
This module provides a class called :class:`AtomFeed` which can be
used to generate feeds in the Atom syndication format (see :rfc:`4287`).
Example::
def atom_feed(request):
feed = AtomFeed("My Blog", feed... | ng, title, length
(all optional)
:param generator: the software that generated this feed. This must be
a tuple in the form ``(name, url, version)``. If
you don't want to specify one of them, set the item
to `None`.
:param entr... | with the entries for the feed. Entries can also
be added later with :meth:`add`.
For more information on the elements see
http://www.atomenabled.org/developers/syndication/
Everywhere where a list is demanded, any iterable can be used.
"""
default_generator = ('Werkzeug', Non... |
imankulov/linguee-api | linguee_api/utils.py | Python | mit | 592 | 0 | import importlib
def import_string(import_name: str):
"""
Import an object based | on the import string.
Separate module name from the object name with ":". For example,
"linuguee_api.downloaders:HTTPXDownloader"
"""
if ":" not in import_name:
raise RuntimeError(
f'{import_name} must separate module from object with ":". '
| f'For example, "linguee_api.downloaders:HTTPXDownloader"'
)
module_name, object_name = import_name.rsplit(":", 1)
mod = importlib.import_module(module_name)
return getattr(mod, object_name)
|
JazzeYoung/VeryDeepAutoEncoder | benchmark/regression/regression.py | Python | bsd-3-clause | 5,237 | 0.013366 | from __future__ import absolute_import, print_function, division
import theano
import numpy as N
from theano import tenso | r as T
from theano.tensor import nnet as NN
from six.moves import xrange
from theano.compile import module as M
class RegressionLayer(M.Module):
def __init__(self, input = None, target = None, regularize = True):
super(RegressionLayer, self).__init__() #boilerplate
# MODEL CONFIGURATION
sel... | ze = regularize
# ACQUIRE/MAKE INPUT AND TARGET
if not input:
input = T.matrix('input')
if not target:
target = T.matrix('target')
# HYPER-PARAMETERS
self.stepsize = T.scalar() # a stepsize for gradient descent
# PARAMETERS
self.w = T.matr... |
sebasvega95/HPC-assignments | CUDA/grayscale/timing.py | Python | mit | 2,425 | 0.003711 | from time import time
from os import remove
from matplotlib.image import imread
import json
import subprocess
import numpy as np
import matplotlib.pyplot as plt
def time_a_function(program, args):
start = time()
subprocess.call([program] + [args])
end = time()
return float(end - start)
def clean... | print 'Runnin | g {} with {} {} times...'.format(p, img, n),
for _ in range(n):
t.append(time_a_function(p, img))
mean_t = np.mean(t)
std_t = np.std(t)
print '({} +- {})s on average'.format(mean_t, std_t)
times[p].append((mean_t, std_t)... |
pouta/bitcoin | contrib/devtools/fix-copyright-headers.py | Python | mit | 1,484 | 0.015499 | #!/usr/bin/env python
'''
Run this script inside of src/ and it will look for all the files
that were changed this year that still have the last year in the
copyright headers, and it will fix the headers on that file using
a perl regex one liner.
For example: if it finds something like this and we're in 2014
// Copyr... | modifiedTime = getLastGitModifiedDate(filePath)
if len(modifiedTime) > 0 and str(year) in modifiedTime:
print n,"Last Git Modified: ", modifiedTime, " - ", filePath
os.popen(command % (last_year,y | ear,filePath))
n = n + 1
|
russloewe/PyGravity | tests/test.py | Python | gpl-2.0 | 17,139 | 0.02013 | import unittest
from PyGravity import PyGravity, round_sig, Particle, Physics, Data_IO
from math import sqrt
import numpy as np
import sys
'''
Unit Tests for PyGravity. These Unit tests will run tests against the
installed PyGravity module and not against the source files in this
package. So if you modify source, you... |
def test_force_of_gravity_magnitude_against_known_answer(self):
part1 = Particle('a',np.array(['1.0','1.0','1.0']),
| np.array(['0','0','0']),
5.0e10)
part2 = Particle('b',np.array(['11.0','1.0','1.0']),
np.array(['0','0','0']), 5.0e10)
force_vec = Physics.grav_force(part1, part2)
self.failUnless(np.linalg.norm(force_vec) == 1668460000)
def test_g... |
bd-j/prospector | prospect/models/__init__.py | Python | mit | 518 | 0.001931 | """This module includes | objects that store parameter specfications and
efficiently convert between parameter dictionaries and parameter vectors
necessary for fitting algorithms. There are submodules for parameter priors,
common parameter transformations, and pre-defined | sets of parameter
specifications.
"""
from .sedmodel import ProspectorParams, SedModel, SpecModel, PolySpecModel, SplineSpecModel
__all__ = ["ProspectorParams",
"SpecModel", "PolySpecModel", "SplineSpecModel",
"SedModel"]
|
john-soklaski/CoilSnake | coilsnake/util/eb/text.py | Python | gpl-3.0 | 2,207 | 0.002266 | class CharacterSubstitutions(object):
character_substitutions = dict()
def standard_text_from_block(block, offset, max_length):
str = ''
for i in range(offset, offset + max_length):
c = block[i]
if c == 0:
return str
else:
str += chr(c - 0x30)
return str... | num_bytes = len(byte_list)
if num_bytes > max_length:
raise ValueError("String cannot be written in {} bytes o | r less: {}".format(
max_length, text
))
elif num_bytes < max_length:
byte_list.append(0)
return byte_list
def standard_text_to_block(block, offset, text, max_length):
byte_list = standard_text_to_byte_list(text, max_length)
block[offset:offset+len(byte_list)] = byte_list |
simonwittber/middleman | clients/py/auth.py | Python | mit | 1,290 | 0.000775 | from collections import defaultdict
import serviceprovider
import textservice
import hashlib
import os
class Auth(serviceprovider.ServiceProvider, textservice.TextService):
salts = dict()
users = dict()
async def REQ_Salt(self, headers, msg):
conn = headers["cid"]
headers["salt"] = self.s... | eaders, msg): |
h = headers["hash"]
e = headers["email"]
if e in self.users:
headers["register"] = "N"
else:
headers["register"] = "Y"
self.users[e] = h
serviceprovider.run(Auth, require_uid=False)
|
achawkins/Forsteri | forsteri/gui/window/preferences.py | Python | mit | 5,406 | 0.00407 | #!/usr/bin/python
"""
Preferences Frame
Copyright (c) 2014, 2015 Andrew Hawkins
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 us... | choices=choice1, style=wx.CB_READONLY)
# Add the contents to the row 1 sizer.
row1Sizer.Add(row1Label, flag=wx.ALIGN_CENTER|wx.RIGHT, border=5)
row1Sizer.Add(self.row1Obj, flag=wx.ALIGN | _CENTER)
# Add all rows to the report sizer.
reportSizer.Add(row1Sizer, flag=wx.ALL, border=5)
#
## Finish Buttons
# Create the finish sizer.
finishSizer = wx.BoxSizer(wx.HORIZONTAL)
# Create the buttons.
okButton = wx.Button(masterPanel, id=wx.ID_OK... |
pnakis/qgis_vector_transform | test/test_vector_transform_dialog.py | Python | gpl-3.0 | 1,563 | 0.00128 | # coding=utf-8
"""Dialog test.
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__author__ = 'pna... |
def test_dialog_ok(self):
"""Test we can click OK."""
button = self.dialog.button_box.button(QDialogButtonBox.Ok)
button.click()
result = self.dialog.result()
self.assertEqual(result, QDialog.Accepted)
def test_dialog_cancel(self):
"""Test we can click cancel."... | f.dialog.result()
self.assertEqual(result, QDialog.Rejected)
if __name__ == "__main__":
suite = unittest.makeSuite(VectorTranformationDialogTest)
runner = unittest.TextTestRunner(verbosity=2)
runner.run(suite)
|
fujy/ROS-Project | src/rbx1/rbx1_nav/nodes/navynavy.py | Python | mit | 12,006 | 0.008163 | #!/usr/bin/env python
""" nav_test.py - Version 1.1 2013-12-20
Command a robot to move autonomously among a number of goal locations defined in the map frame.
On each round, select a new random sequence of locations, then attempt to move to each location
in succession. Keep track of success rate, time el... | self.ar_sub = rospy.Subscriber('ar_pose_marker', AlvarMarkers, self.doSomething)
self.is_visible = False;
# Make sure we have the initial pose
| while initial_pose.header.stamp == "":
rospy.sleep(1)
rospy.loginfo("Starting navigation test")
# Begin the main loop and run through a sequence of locations
while not rospy.is_shutdown():
# If we've gone through the current sequence,
... |
cogeorg/BlackRhino | examples/solow/abm_template/tests/tests_transaction.py | Python | gpl-3.0 | 44,588 | 0.002198 | #!/usr/bin/env python
# [SublimeLinter pep8-max-line-length:150]
# -*- coding: utf-8 -*-
"""
black_rhino is a multi-agent simulator for financial network analysis
Copyright (C) 2016 Co-Pierre Georg (co-pierre.georg@keble.ox.ac.uk)
Pawel Fiedor (pawel@fiedor.eu)
This program is free software: you can redistribute it a... | published by
the Free Software Foundation, version 3 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without e | ven 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/>.
"""
import logging
# --------------------------... |
avaquero/llibreria | usuaris/forms.py | Python | gpl-3.0 | 272 | 0.025735 | from django import forms
class formulariLogin(forms.Form):
usuari = forms.CharField(max_length=100 | )
contrasenya = forms.CharField(max | _length=100, widget=forms.PasswordInput() )
class formulariUsuari(forms.Form):
usuari = forms.CharField(max_length=100)
|
LivingInSyn/RestartMe | v1_python_kivy/installer/installer.py | Python | gpl-2.0 | 2,173 | 0.015647 | '''
Created by Jeremy Mill, originally for use in the hi tech classrooms at the University of CT
Licensed under the GPLv3
jeremymill@gmail.com
githu | b.com/livinginsyn
'''
import os
import shutil as util
import _winreg as wreg
import subprocess
#first thing to find is the version of the OS
try:
os.environ["PROGRAMFILES(X86)"]
ver = 64
except:
ver = 32
def sixty_folder():
directory = 'C:\\Program Files (x86)\\RestartMe\\'
if not os.path.exi... | s\\RestartMe\\'
if not os.path.exists(directory):
os.mkdir(directory)
else:
overwrite = True
return directory
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores pa... |
nealegibson/GeePea | examples/mean_function.py | Python | gpl-3.0 | 592 | 0.038851 | #!/usr/bin/env python
import GeePea
import numpy as np
#first define mean function in correct format
my_mean_func | = lambda p,x: p[0] + p[1] * x
#create test data
x = np.linspace(0,1,50)
y = my_mean_func([1.,3.],x) + np.sin(2*np.pi*x) + np.random.normal(0,0.1,x.size)
#define mean function parameters and hyperparameters
mfp = [0.8,2.]
hp = [1.,1.,0.1] # kernel hyperparameters (sq exponential takes 3 parameters | for 1D input)
#define the GP
gp = GeePea.GP(x,y,p=mfp+hp,mf=my_mean_func)
#print out the GP attributes
gp.describe()
#optimise and plot
gp.optimise()
gp.plot()
raw_input()
|
ddico/odoo | addons/im_livechat/__manifest__.py | Python | agpl-3.0 | 1,621 | 0.000617 | # -*- coding: utf-8 -*-
{
'name' : 'Live Chat',
'version': '1.0',
'sequence': 170,
'summary': 'Chat with your website visitors',
'category': 'Website/Live Chat',
'complexity': 'easy',
'website': 'https://www.odoo.com/page/live-chat',
'description':
"""
Live Chat Support
=========... | yse their feedback.
""",
'data': [
"data/mail_shortcode_data.xml",
"data/mail_data.xml",
"data/im_livechat_channel_data.xml",
'data/digest_data.xml',
"security/im_livechat_channel_security. | xml",
"security/ir.model.access.csv",
"views/rating_views.xml",
"views/mail_channel_views.xml",
"views/im_livechat_channel_views.xml",
"views/im_livechat_channel_templates.xml",
"views/res_users_views.xml",
"views/digest_views.xml",
"report/im_livechat_rep... |
mmcfarland/model-my-watershed | src/mmw/apps/user/views.py | Python | apache-2.0 | 7,827 | 0.000256 | from django.contrib.auth import (authenticate,
logout as auth_logout,
login as auth_login)
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.shortcuts import redirect, render_to_response
from django.cont... | atus=status.HTTP_400_BAD_REQUEST)
@decorators.api_view(['POST'])
@decorators.permission_classes((AllowAny, ))
def forgot(request):
form = PasswordResetForm(request.POST)
if form.is_valid():
email = form.cleaned_data['email']
try:
# If there are active user(s) that match email
... | (email))
form.save(request=request)
response_data = {'result': 'success',
'guest': True}
status_code = status.HTTP_200_OK
except StopIteration:
response_data = {'errors': ["Email cannot be found"]}
status_code = status.HTTP... |
yejia/order_system | product_order/urls.py | Python | mit | 568 | 0.005282 | from django.conf.urls import patterns, include, url
from product_order import views, data_views
urlpatterns = patterns('',
url(r'^$', views.index),
url(r'^order_state_machine/$', views.order_state_machine),
url(r'^make_order/$', views.make_order),
url(r'^make_order2/$', views.make_order2),
u... | ews.make_order3),
url(r'^create_order/$', views.create_order),
url(r'^order_state_machine/data/role/(?P<role>[^/]+)/$', data_views.get_ | actions),
url(r'^view_refund_sheet/$', views.view_refund_sheet),
)
|
pelson/cartopy | docs/make_projection.py | Python | lgpl-3.0 | 6,210 | 0 | # (C) British Crown Copyright 2011 - 2018, Met Office
#
# This file is part of cartopy.
#
# cartopy is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option)... | RJ_SORT_ORDER.get(cls.__name__, 100),
cls.__name__)
for prj in sorted(find_projections(), key=prj_class_sorter):
name = prj.__name__
table.write(name + '\n')
table.write('-' * len(name) + '\n\n')
| table.write('.. autoclass:: cartopy.crs.%s\n' % name)
if prj not in MULTI_PLOT_CASES:
# Get instance arguments and number of plots
instance_args = SPECIFIC_PROJECTION_KWARGS.get(prj, {})
prj_inst, instance_repr = create_instance(prj, instance_args)
aspect = (n... |
mhahn/stacker | stacker/config/translators/kms.py | Python | bsd-2-clause | 228 | 0 | # NOTE: The translator is going to | be deprecated in favor of the lookup
from ...lookups.handlers.kms import handler
def kms_simple_constructor(loader, node):
value = loader.co | nstruct_scalar(node)
return handler(value)
|
Southclaw/pawn-sublime-language | PawnBuildPath.py | Python | mit | 1,010 | 0 | import json
import sublime
import sublime_plugin
from .edit import Edit
class PawnBuildPathCommand(sublime_plugin.TextCommand):
def run(self, edit):
self.view.window().show_input_panel(
"Working directory that contains pawncc.exe",
"C:\\Pawno\\",
self.onPawnPathDone,
... | )
path = path.replace("\\", "/")
obj = {
"cmd": [
"pawncc.exe",
"$file",
"-o$file_path/$file_base_name",
"-;+",
"-(+",
"-d3"
],
"file_regex": r"(.*?)\(([0-9]*)[- 0-9]*\)",... | r": "source.pwn",
"working_dir": path
}
with Edit(view) as edit:
edit.insert(0, json.dumps(obj, indent=4))
view.set_name("Pawn.sublime-build")
view.run_command("save")
|
aperigault/ansible | lib/ansible/modules/cloud/vultr/vultr_ssh_key_info.py | Python | gpl-3.0 | 3,294 | 0.001215 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (c) 2018, Yanis Guenane <yanis+ansible@guenane.org>
# (c) 2019, René Moser <mail@renemoser.net>
# 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_function)
__metaclass__ = ... | esult = sshkey_info.get_result(parse_keys_list(sshkey_info.get_sshkeys()))
module.exit_json(**result)
if __name__ == '__main__ | ':
main()
|
lccp/URIJudgeProblemsPython | URIOnlineJudge_1002_AreaDoCirculo/area_do_circulo.py | Python | mit | 109 | 0.018349 | __author__ = 'lucas'
pi = 3.14159
| raio = float(input())
area = pi * (raio * raio)
print ("A=%.4f" % area) | |
Bystroushaak/attribute_wrapper | setup.py | Python | mit | 1,689 | 0 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: python 2.7
#
# Imports =====================================================================
from setuptools import setup, find_packages
# Variables ===================================================================
changelog = open('CHANGES.rst... | open('README.rst').read(),
changelog
])
# Functions & classes =========================================================
def allSame(s):
return not filter(lambda x: x != s[0], s)
def hasDigit(s):
return any(map(lambda x: x.isdigit(), s))
def getVersion(data):
data = data.split | lines()
return filter(
lambda (x, y):
len(x) == len(y) and allSame(y) and hasDigit(x) and "." in x,
zip(data, data[1:])
)[0][0]
setup(
name='attribute_wrapper',
version=getVersion(changelog),
description="Class wrapper, which maps attribute calls to HTTP API.",
long... |
fractalego/pynsett | pynsett/examples/negation.py | Python | mit | 294 | 0.003401 | import os
from pynsett.discourse import Discourse
from pynsett.drt import Drs
from pynsett.extractor import Extractor
fr | om pynsett.knowledge import Knowledg | e
_path = os.path.dirname(__file__)
text = "John Smith is not blond"
drs = Drs.create_from_natural_language(text)
drs.plot()
print(drs) |
pelson/conda-build | tests/test_api_inspect.py | Python | bsd-3-clause | 535 | 0.001869 | import os
import pytest
from conda_build import api
from | .utils import metadata_dir
thisdir = os.path.dirname(os.path.abspath(__file__))
@pytest.mark.sanity
def test_check_recipe():
"""Technically not inspect, but close enough to belong here"""
assert api.check(os.path.join(metadata_dir, "source_git_jinja2"))
# These tests are already being done in test_cli.py.... | jects():
pass
def test_installable():
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.