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 |
|---|---|---|---|---|---|---|---|---|
fert89/prueba-3-heroku-flask | fabfile.py | Python | bsd-3-clause | 534 | 0 | from fabric.api import *
# start with the default server
def run():
""" Start with the default server """
local('python runserver.py')
# start with unicorn server.
def grun():
""" Start with gunicorn server """
local('gunicorn -c gunicorn.conf runserver:app')
# run tests
def tests():
""" Run u... | rt iteractive shell within the flask environm | ent
def shell():
""" Start interactive shell within flask environment """
local('python shell.py')
|
Acehaidrey/incubator-airflow | airflow/providers/jdbc/hooks/jdbc.py | Python | apache-2.0 | 3,656 | 0.001915 | #
# 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... | nection's autocommit setting.
"""
conn.jconn.setAutoCommit(autocommit)
def get_autocommit(self, conn: jaydebeapi.Connection) -> bool:
"""
Get autocommit setting for the provided connection.
Return True if conn.autocommit is set to True.
Return False if conn.autocommi... | nnection autocommit setting.
:rtype: bool
"""
return conn.jconn.getAutoCommit()
|
anhstudios/swganh | data/scripts/templates/object/mobile/shared_tanc_mite_hue.py | Python | mit | 582 | 0.041237 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DON | E IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_tanc_mite_hue.iff"
result.attribute_template_id = 9
result.stfName("monster_name","tanc_mite")
#### BEGIN MODIFICATIONS ####
result.... | p_status = PVPSTATUS.PvPStatus_None
#### END MODIFICATIONS ####
return result |
stvstnfrd/edx-platform | openedx/features/enterprise_support/signals.py | Python | agpl-3.0 | 5,796 | 0.004141 | """
This module contains signals related to enterprise.
"""
import logging
import six
from django.conf import settings
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver
from ent... | SMENT_GRADE_CHANGED
from openedx.features.enterprise_support.api import enterprise_enabled
from openedx.features.enterprise_support.tasks import clear_enterprise_customer_data_consent_share_cache
from openedx.features.enterprise_support.utils impo | rt clear_data_consent_share_cache, is_enterprise_learner
from common.djangoapps.student.signals import UNENROLL_DONE
log = logging.getLogger(__name__)
@receiver(post_save, sender=EnterpriseCustomerUser)
def update_email_marketing_user_with_enterprise_vars(sender, instance, **kwargs): # pylint: disable=unused-argume... |
lampwins/netbox | netbox/extras/tests/test_customfields.py | Python | apache-2.0 | 13,178 | 0.003035 | from datetime import date
from django.contrib.contenttypes.models import ContentType
from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from dcim.models import Site
from extras.constants import CF_TYPE_TEXT, CF_TYPE_INTEGER, CF_TYPE_BOOLEAN, CF_TYPE_DATE, CF_TYPE_SELECT... | ': 'test-site-1',
'custom_fields': {
'magic_word': 'Foo bar baz',
}
}
url = reverse('dcim-api:site-detail', kwargs={'p | k': self.site.pk})
response = self.client.put(url, data, format='json', **self.header)
self.assertHttpStatus(response, status.HTTP_200_OK)
self.assertEqual(response.data['custom_fields'].get('magic_word'), data['custom_fields']['magic_word'])
cfv = self.site.custom_field_values.get(fiel... |
Remi-C/LOD_ordering_for_patches_of_points | script/loading benchmark/rforest_on_patch_lean.py | Python | lgpl-3.0 | 8,121 | 0.046915 | # -*- coding: utf-8 - | *-
"""
Created on Sat Dec 6 17:01:05 2014
@author: remi
@TODO :
in the function train_RForest_with_kfold we should keep all result proba for each class, this could be very intersting.
"""
import numpy as np ; #efficient arrays
impor | t pandas as pd; # data frame to do sql like operation
import sklearn
reload(sklearn)
from sklearn.ensemble import RandomForestClassifier ; #base lib
from sklearn import cross_validation, preprocessing ; #normalizing data, creating kfold validation
def create_test_data(feature_number, data_size, class_list):
"... |
GuillaumeDerval/INGInious | common/task_file_managers/manage.py | Python | agpl-3.0 | 1,952 | 0.004098 | import os.path
from common.base import INGIniousConfiguration
from common.task_file_managers.yaml_manager import TaskYAMLFileManager
_task_file_managers = [TaskYAMLFileManager]
def get_readable_tasks(courseid):
""" Returns the list of all available tasks in a course """
tasks = [
task for task in os... | xt in get_available_task_file_managers().keys()]:
if os.path.isfile(os.path.join(directory, filename)):
return True
return False
def get_task_file_manager(courseid, taskid):
| """ Returns the appropriate task file manager for this task """
for ext, subclass in get_available_task_file_managers().iteritems():
if os.path.isfile(os.path.join(INGIniousConfiguration["tasks_directory"], courseid, taskid, "task.{}".format(ext))):
return subclass(courseid, taskid)
return... |
jayme-github/CouchPotatoServer | couchpotato/core/downloaders/synology/main.py | Python | gpl-3.0 | 3,961 | 0.009089 | from couchpotato.core.downloaders.base import Downloader
from couchpotato.core.helpers.encoding import isInt
from couchpotato.core.logger import CPLog
import httplib
import json
import urllib
import urllib2
log = CPLog(__name__)
class Synology(Downloader):
type = ['torrent_magnet']
log = CPLog(__name__)
... |
return False
def _logout(self):
args = {'api':'SYNO.API.Auth', 'version':1, 'method':'logout', 'session':self.session_name, '_sid':self.sid}
return self._req(self.auth_url, args)
def _req(self, url, args):
req_url = url + '?' + urllib.urlencode(args)
try:
... | json.loads(req_open.read())
if response['success'] == True:
log.info('Synology action successfull')
return response
except httplib.InvalidURL, err:
log.error('Invalid Transmission host, check your config %s', err)
return False
except urlli... |
TeamGhostBuster/restful-api | app/api/article/controller.py | Python | apache-2.0 | 8,039 | 0.000373 | from app.util import ElasticSearchUtil
from app.util import JsonUtil, RequestUtil, ResponseUtil
from app.util.AuthUtil import *
import os
@app.route('/user/article/<string:article_id>', methods=['GET'])
@authorized_required
def get_article(user, article_id):
"""
@api {get} /user/article/:id Get a article in p... | "content": "i hate it",
"created_at": "2017-02-04-19-59-59",
"author": "tester@ualberta.ca"
}],
"tags": ["science", "computer"]
}
@apiUse UnauthorizedAccessError
"""
# Find article from the database
article = MongoUtil.find_ar... | f the article does not exist
if article is None:
return jsonify(msg='Articles does not exist'), 404
app.logger.info('User {} Get article {}'.format(user, article))
return jsonify(JsonUtil.serialize(article)), 200
@app.route('/user/list/<string:list_id>/article', methods=['POST'])
@authorized_requ... |
eve-basil/common | tests/__init__.py | Python | apache-2.0 | 98 | 0 | from __future__ import absolute_import
f | rom hamcrest.library import *
from hamcrest.core impor | t *
|
lliss/python-omgeo | omgeo/preprocessors.py | Python | mit | 11,304 | 0.006723 | from omgeo.processor import _Processor
import re
class _PreProcessor(_Processor):
"""Takes, processes, and returns a geocoding.places.PlaceQuery object."""
def process(self, pq):
raise NotImplementedError(
'PreProcessor subclasses must implement process().')
class ReplaceRangeWithNumber(_P... | in self.country_map:
pq.country = self.country_map[pq.countr | y]
if pq.country != '' and \
self.acceptable_countries != [] and \
pq.country not in self.acceptable_countries:
return False
return pq
def __repr__(self):
return '<%s: Accept %s mapped as %s>' % (self.__class__.__name__,
self.acceptable_countrie... |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/tests/test_cli_mgmt_network_endpoint.py | Python | mit | 15,915 | 0.004147 | # 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.
#----------------------------------------------------------------------... | }
}
]
}
result = self.mgmt_client.private_link_services.begin_create_or_update(resource_group_name=RESOURCE_GROUP, service_name=SERVICE_NAME, parameters=BODY)
result = result.result()
# /PrivateEndpoints/put/Create private endpoint[put]
BODY = {
... | "name": SERVICE_NAME, # TODO: This is needed, but was not showed in swagger.
"private_link_service_id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Network/privateLinkServices/" + SERVICE_NAME,
# "group_ids": [
# "groupI... |
antoinecarme/pyaf | tests/artificial/transf_Difference/trend_MovingAverage/cycle_12/ar_12/test_artificial_1024_Difference_MovingAverage_12_12_100.py | Python | bsd-3-clause | 273 | 0.084249 | import pyaf.Bench.TS_datas | ets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "MovingAverage", cycle_length = 12, transform = | "Difference", sigma = 0.0, exog_count = 100, ar_order = 12); |
kg-bot/SupyBot | plugins/Sshd/__init__.py | Python | gpl-3.0 | 2,534 | 0.000395 | ###
# Copyright (c) 2005, Ali Afshar
# 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 notice,
# this list of conditions, a... | . IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR |
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT ... |
cboling/SDNdbg | docs/old-stuff/pydzcvr/doc/neutronclient/v2_0/client.py | Python | apache-2.0 | 54,103 | 0 | # Copyright 2012 OpenStack Foundation.
# 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 requ... | _path = "/security-groups/%s"
security_group_rules_path = "/security-group-rules"
security_grou | p_rule_path = "/security-group-rules/%s"
vpnservices_path = "/vpn/vpnservices"
vpnservice_path = "/vpn/vpnservices/%s"
ipsecpolicies_path = "/vpn/ipsecpolicies"
ipsecpolicy_path = "/vpn/ipsecpolicies/%s"
ikepolicies_path = "/vpn/ikepolicies"
ikepolicy_path = "/vpn/ikepolicies/%s"
ipsec_site_... |
arthurdejong/python-stdnum | stdnum/damm.py | Python | lgpl-2.1 | 3,297 | 0 | # damm.py - functions for performing the Damm checksum algorithm
#
# Copyright (C) 2016-2021 Arthur de Jong
#
# This library 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 2.1 of the L... | etect all
single-digit errors and all adjacent transposition errors. Based on
anti-symmetric quasigroup of order 10 it uses a substitution table.
This implementation uses the table from Wikipedia by default but a custom
table can be provided.
More information:
* https://en.wikipedia.org/wiki/Damm_algorithm
>>> vali... | = (
... (0, 2, 3, 4, 5, 6, 7, 8, 9, 1),
... (2, 0, 4, 1, 7, 9, 5, 3, 8, 6),
... (3, 7, 0, 5, 2, 8, 1, 6, 4, 9),
... (4, 1, 8, 0, 6, 3, 9, 2, 7, 5),
... (5, 6, 2, 9, 0, 7, 4, 1, 3, 8),
... (6, 9, 7, 3, 1, 0, 8, 5, 2, 4),
... (7, 5, 1, 8, 4, 2, 0, 9, 6, 3),
... (8, 4, 6, 2, 9, 5, 3, 0, 1,... |
tlecomte/friture | friture/level_view_model.py | Python | gpl-3.0 | 2,390 | 0.00879 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2021 Timothée Lecomte
# This file is part of Friture.
#
# Friture is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as published by
# the Free Software Foundation.
#
# Friture is distri... | evel_data_slow(self):
return self._level_data_slow
@pyqtProperty(LevelData, constant = True)
def level_data_slow_2(self):
return self._level_data_slow_2
@pyqtProperty(LevelData, constant = True)
def level_data_ballistic(self):
return self._level_data_ballistic
... | :
return self._level_data_ballistic_2 |
asnorkin/shad_testing_script | conftest.py | Python | gpl-3.0 | 8,688 | 0.002532 | import pytest
import sys
from inspect import isgeneratorfunction
from logging import getLogger
from subproce | ss import Popen, PIPE
from re import search
from input_generation import user_input_generator
DELIMITER = "; "
def get_input_generator_from_list(lst):
def _generator():
for line in lst:
yield line
return _generator
def get_input_generat | or(request, iterations):
input = request.config.getoption("--input")
if not input:
input = user_input_generator(iterations)
if not input:
raise ValueError("No input data expression or file or user defined function specified")
if isgeneratorfunction(input):
return... |
hydroshare/hydroshare_temp | hs_core/tests/api/native/test_set_access_rules.py | Python | bsd-3-clause | 5,046 | 0.003171 | __author__ = 'lisa_stillwell'
from unittest import TestCase
from hs_core.hydroshare import resource
from hs_core.hydroshare import users
from hs_core.models import GenericResource
from django.contrib.auth.models import User
import datetime as dt
class TestSetAccessRules(TestCase):
def setUp(self):
# cre... | s_id, user=self.test_user, group=None, access=users.EDIT, allow=False)
self.assertFalse(
self.new_res.edit_users.filter(pk= | self.test_user.pk).exists(),
msg="Failure when trying to remove EDIT access for user"
)
# test EDIT access with no user id provided
self.assertRaises(
TypeError,
lambda: users.set_access_rules(self.new_res, user=None, group=None, access=users.EDIT, allow=True... |
RoasterBot/roasterbot-analytics | python/threaded_temp.py | Python | cc0-1.0 | 7,664 | 0.014875 | #! /usr/bin/env python
# -*- codes: utf-8 -*-
print 'Starting ...'
#Basic imports
from ctypes import *
import sys
import time
import threading
import logging
#Phidget specific imports
from Phidgets.PhidgetException import PhidgetErrorCodes, PhidgetException
from Phidgets.Events.Events import AttachEventA... | range(inputCount):
print("Input %i Sensitivity: %f" % (i, temperatureSensor.getTemperatureChangeTrigger(i)))
# | Event Handler Callback Functions
def TemperatureSensorAttached(e):
attached = e.device
print("TemperatureSensor %i Attached!" % (attached.getSerialNum()))
def TemperatureSensorDetached(e):
detached = e.device
print("TemperatureSensor %i Detached!" % (detached.getSerialNum()))
def TemperatureS... |
findgriffin/hactar | test/base.py | Python | gpl-2.0 | 6,991 | 0.004291 |
from hashlib import sha1
import shutil
import re
import json
import time
from dateutil.parser import parse
from datetime import datetime as dtime
from datetime import timedelta as tdelta
from flask.ext.testing import TestCase
from app import db, app
import hactar.models
class BaseTest(TestCase):
_multiprocess_... | at, why, new=True, flash=None,
last=True):
rjson = json.loads(resp.data)
isuri = hactar.models.is_uri(what)
if flash:
self.assertEquals([flash], rjson['flashes'])
elif last and new:
msg = u'New meme was successfully added'
self.assertEqual... | self.assertEquals(meme_id, int(meme['id']))
else:
meme = self.get_meme(rjson, meme_id)
self.assertEquals(len(meme.keys()), 9)
self.assertEquals(what, meme['uri'] if isuri else meme['title'])
self.assertEquals(why, meme['text'])
now = int(time.time())
a... |
wdecoster/NanoPlot | nanoplotter/__init__.py | Python | gpl-3.0 | 32 | 0 | from .nanoplott | er_main | import *
|
gdementen/larray | larray/inout/stata.py | Python | gpl-3.0 | 1,657 | 0.002414 | import pandas as pd
from larray.core.array import Array
from larray.inout.pandas import from_frame
__all__ = ['read_stata']
def read_stata(filepath_or_buffer, index_col=None, sort_rows=False, sort_columns=False, **kwargs) -> Array:
r"""
Reads Stata .dta file and returns an Array with the contents
Param... |
Whether or not to sort the columns alphabetically (sorting is more efficient than not sorting).
Defaults to False.
Returns
-------
Array
See Also
--------
Array.to_stata
Notes
-----
The round trip to Stata (Array.to_stata followed by read_stata | ) loose the name of the "column" axis.
Examples
--------
>>> read_stata('test.dta') # doctest: +SKIP
{0}\{1} row country sex
0 0 BE F
1 1 FR M
2 2 FR F
>>> read_stata('test.dta', index_col='row') # doctest: +SKI... |
BrainPad/FindYourCandy | robot-arm/dobot/command.py | Python | apache-2.0 | 6,883 | 0.001453 | # Copyright 2017 BrainPad Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | 'basement', 'rear', 'fore', 'end']
)
class GetAlarmsState(Comman | d):
def __init__(self):
super(GetAlarmsState, self).__init__(20, 0, 0)
class ClearAllAlarmsState(Command):
def __init__(self):
super(ClearAllAlarmsState, self).__init__(21, 1, 0)
class SetHomeCmd(Command):
def __init__(self):
super(SetHomeCmd, self).__init__(31, 1, 1)
sel... |
kball/ambry | ambry/database/csv.py | Python | bsd-2-clause | 6,934 | 0.010816 |
"""
Copyright (c) 2013 Clarinova. This file is licensed under the terms of the
Revised BSD License, included in this distribution as LICENSE.txt
"""
from __future__ import absolute_import
import unicodecsv
from . import DatabaseInterface
import anydbm
import os
from ..partitions import Partitions
from .inserter imp... | has_header:
self.header = row.keys()
self._writer = unicodecsv.DictWriter(f, self.header, delimiter=delimiter,
escapechar=self.escapechar, encoding=self.encod | ing)
if self.write_header:
self._writer.writeheader()
self._inserter = self._write_dict
elif row_is_list and has_header:
self._writer = unicodecsv.writer(f, delimiter=delimiter,
escapechar=... |
open-synergy/opnsynid-stock-logistics-warehouse | stock_inventory_by_moving_product/models/__init__.py | Python | agpl-3.0 | 167 | 0 | # -*- coding: utf-8 -*-
# Copyright 2019 OpenSynergy | Indonesia
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from . | import (
stock_inventory,
)
|
edmorley/django | tests/admin_changelist/tests.py | Python | bsd-3-clause | 38,622 | 0.001139 | import datetime
from django.contrib import admin
from django.contrib.admin.models import LogEntry
from django.contrib.admin.options import IncorrectLookupParameters
from django.contrib.admin.templatetags.admin_list import pagination
from django.contrib.admin.tests import AdminSeleniumTestCase
from django.contrib.admin... | = reverse('admin:admin_changelist_child_change', args=(new_child.id,))
row_html = build_tbody_html(new_child.id, link, '<td class="field-parent nowrap">???</td>')
self.assertNotEqual(table_output.find(row_html), -1, 'Failed to find expected row element: %s' % table_output)
def test_result_list_set... | or individual fields.
"""
new_child = Child.objects.create(name='name', parent=None)
request = self.factory.get('/child/')
m = EmptyValueChildAdmin(Child, admin.site)
cl = m.get_changelist_instance(request)
cl.formset = None
template = Template('{% load admin_list... |
hinance/www | hinance-www/weboob/modules/fakeshop/__init__.py | Python | mit | 64 | 0 | from | .module import FakeShopModule
__all__ = | ['FakeShopModule']
|
geowurster/Acronym | acronym/tests/test_vector_transform.py | Python | bsd-3-clause | 4,230 | 0.003783 | #!/usr/bin/env python
# This document is part of Acronym
# https://github.com/geowurster/Acronym
# =================================================================================== #
#
# New BSD License
#
# Copyright (c) 2014, Kevin D. Wurster
# All rights reserved.
#
# Redistribution and use in source and bi... | nditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and | the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * The names of its contributors may not be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS... |
zrafa/ev | python+tk+opencv/ejemplo-funciona.py | Python | gpl-2.0 | 2,626 | 0.011805 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import cv2
from Tkinter import *
from PIL import Image, ImageTk
import tkFileDialog
appname = "example"
class App(object):
def __init__(self, root=None):
if not root:
root = Tk()
self.root = root
self.initUI()
def initUI(self):
... | 50x150+300+300")
app = App(root)
app.run()
if __name__ == '__m | ain__':
main()
|
hyqneuron/pylearn2-maxsom | pylearn2/scripts/papers/LocateReLU/mytrain.py | Python | bsd-3-clause | 8,524 | 0 | #!/usr/bin/env python
"""
This script is copied from pylearn2/scripts/train.py, so that we can put this
LocateReLU folder on PYTHON_PATH automatically, so that we can import local
modules without extra work
Script implementing the logic for training pylearn2 models.
This is a "driver" that we recommend using for all ... | store_true',
help='Display the log level (e.g. DEBUG, INFO) '
'for each logged message')
parser.add_argument('--timestamp', '-T',
action='store_true',
help='Display human-readable timestamps for '
... | budget in seconds. Stop training at '
'the end of an epoch if more than this '
'number of seconds has elapsed.')
parser.add_argument('--verbose-logging', '-V',
action='store_true',
help='Display timestamp, log ... |
badp/ganeti | lib/client/gnt_node.py | Python | gpl-2.0 | 38,700 | 0.008191 | #
#
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Google Inc.
#
# 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... | S)
(_, root_keyfiles) = \
ssh.GetAllUserFiles(constants.SSH_LOGIN_USER, mkdir=False, dircheck=False)
root_keys = _ReadSshKeys(root_keyfiles)
(_, cert_pem) = \
utils.ExtractX509Certificate(utils.ReadFile(pathutils.NODED_CERT_FILE))
data = {
constants.SS | HS_CLUSTER_NAME: cluster_name,
constants.SSHS_NODE_DAEMON_CERTIFICATE: cert_pem,
constants.SSHS_SSH_HOST_KEY: host_keys,
constants.SSHS_SSH_ROOT_KEY: root_keys,
}
bootstrap.RunNodeSetupCmd(cluster_name, node, pathutils.PREPARE_NODE_JOIN,
options.debug, options.verbose, Fal... |
WillisXChen/django-oscar | oscar/lib/python2.7/site-packages/phonenumbers/data/region_BS.py | Python | bsd-3-clause | 1,927 | 0.007265 | """Auto-generated file, do not edit by hand. BS metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_BS = PhoneMetadata(id='BS', country_code=1, international_prefix='011',
general_desc=PhoneNumberDesc(national_number_pattern='[2589]\\d{9}', possible_number_pattern='\... | Desc(national_number_pattern='242(?:3(?:02|[236][1-9]|4[0-24-9]|5[0-68]|7[3467]|8[0-4]|9[2-467])|461|502|6(?:0[12]|12|7[67]|8[78]|9[89])|702)\\d{4}', possible_number_pattern='\\d{7}(?:\\d{3})?', example_number='2423456789'),
mobile=PhoneNumberDesc(national_number_pattern='242(?:3(?:5[79]|[79]5)|4(?:[2-4][1-9]|5[1-8... | |5[1-9]|65|77)|6[34]6|727)\\d{4}', possible_number_pattern='\\d{10}', example_number='2423591234'),
toll_free=PhoneNumberDesc(national_number_pattern='242300\\d{4}|8(?:00|44|55|66|77|88)[2-9]\\d{6}', possible_number_pattern='\\d{10}', example_number='8002123456'),
premium_rate=PhoneNumberDesc(national_number_pa... |
LordCorellon/plugin.video.9anime | resources/lib/ui/control.py | Python | gpl-3.0 | 3,032 | 0.014512 | import re
import sys
import xbmc
import xbmcaddon
import xbmcplugin
import xbmcgui
import http
try:
import StorageServer
except:
import storageserverdummy as StorageServer
HANDLE=int(sys.argv[1])
ADDON_NAME = re.findall('plugin:\/\/([\w\d\.]+)\/', sys.argv[0])[0]
__settings__ = xbmcaddon.Addon(ADDON_NAME)
__l... | l():
addon_base = addon_url()
assert sys.argv[0].startswith(addon_base), "something bad happened in here"
return sys.argv[0][len(addon_base):]
def keyboard(text):
keyboard = xbmc.Keyboard("", text, False)
keyboard.doModal()
if keyboard.isConfirmed():
return keyboard.getText()
return... | liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
liz.setInfo('video', infoLabels={ "Title": name })
liz.setProperty("fanart_image", __settings__.getAddonInfo('path') + "/fanart.jpg")
liz.setProperty("Video", "true")
liz.setProperty("IsPlayable", "true")
liz.addCon... |
Fewbytes/cosmo-manager-rest-client | cosmo_manager_rest_client/swagger/DeploymentsApi.py | Python | apache-2.0 | 6,880 | 0 | ########
# Copyright (c) 2013 GigaSpaces Technologies Ltd. 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... | nt.deserialize(response.json(),
'list[Execution]')
def eventsHeaders(self, id, responseHeadersBuffers):
"""Get headers for events associated with t | he deployment
Args:
id, str: ID of deployment that needs to be fetched (required)
responseHeadersBuffers, dict: a buffer for the response headers
Returns:
"""
resource_path = '/deployments/{0}/events'.format(id)
url = self.api_client.resource_url(resource... |
armstrong/armstrong.esi | armstrong/esi/utils.py | Python | bsd-3-clause | 5,702 | 0.00228 | from cStringIO import StringIO
from email.utils import parsedate
import gzip
import logging
import re
import time
from urlparse import urljoin
from django.conf import settings
from django.http import HttpResponse
from django.middleware.gzip import GZipMiddleware
from django.utils.cache import cc_delim_re
from django.u... | ', re.I)
def reduce_vary_headers(response, additional):
'''Merges the Vary header values so all headers are included.'''
original = response.get('Vary', None)
if original is not None:
additional.append(original)
# Keep track of | normalized, lowercase header names in seen_headers while
# maintaining the order and case of the header names in final_headers.
seen_headers = set()
final_headers = []
for vary_value in additional:
headers = cc_delim_re.split(vary_value)
for header in headers:
if header.lower... |
BunsenLabs/fluxbb-activity | fluxbbactivity/__init__.py | Python | gpl-3.0 | 6,198 | 0.01081 | #!/usr/bin/env python3
from argparse import ArgumentParser
from bottle import abort, route, run, static_file
import MySQLdb
import calendar
import datetime
import dateutil.parser
import json
import logging
import os
import pathlib
import sqlite3
import sys
import threading
import time
APIVER = 0
BACKEND_URL = 'https:... | ().__init__()
self.cconf = cconf
self.queries = queries
self.timeout = timeout
self.journal = journalpath
self.public = {}
def run(self):
self.event = threading.Event()
self.update()
while not self.event.wait(timeout=self.timeout):
self.up... | global PUBLIC
PUBLIC = self.query()
logging.info("Fetcher.update() finished.")
def query(self):
t = { "history": dict() }
with MySQLdb.connect(**self.cconf) as cur:
with Journal(self.journal) as jur:
for cat in self.queries:
t[cat] = {... |
PythonCharmers/orange3 | Orange/tests/test_score_feature.py | Python | gpl-3.0 | 4,389 | 0.000456 | import unittest
import numpy as np
from Orange.data import Table, Domain, DiscreteVariable
from Orange.preprocess import score
from Orange import preprocess
class FeatureScoringTest(unittest.TestCase):
def setUp(self):
self.zoo = Table("zoo") # disc. features, disc. class
self.housing = Table(... | y = 4 + (-3*X[:, 1] + X[:, 3]) // 2
domain = Domain.from_numpy(X, y)
domain = Domain(domain.attributes,
DiscreteVariable('c', values=np.unique(y)))
| data = Table(domain, X, y)
scorer = score.ANOVA()
sc = [scorer(data, a) for a in range(ncols)]
self.assertTrue(np.argmax(sc) == 1)
def test_regression(self):
nrows, ncols = 500, 5
X = np.random.rand(nrows, ncols)
y = (-3*X[:, 1] + X[:, 3]) / 2
data = Tab... |
NathanLawrence/lunchbox | app_config.py | Python | mit | 2,936 | 0.003065 | #!/usr/bin/env python
"""
Project-wide application configuration.
DO NOT STORE SECRETS, PASSWORDS, ETC. IN THIS FILE.
They will be exposed to users. Use environment variables instead.
See get_secrets() below for a fast way to access them.
"""
import os
"""
NAMES
"""
# Project name to be used in urls
# Use dashes, n... | riables will be set at runtime. See configure_targets() below
S3_BUCKET = None
S3_BASE_URL = None
S3_DEPLOY_URL = None
DEBUG = True
"""
Utilities
"""
def get_secrets():
"""
A method for accessing our secrets.
"""
secrets_dict = {}
for k,v in os.environ.items():
if k.startswith(PROJECT_SLUG... | crets_dict
def configure_targets(deployment_target):
"""
Configure deployment targets. Abstracted so this can be
overriden for rendering before deployment.
"""
global S3_BUCKET
global S3_BASE_URL
global S3_DEPLOY_URL
global DEBUG
global DEPLOYMENT_TARGET
global ASSETS_MAX_AGE
... |
beproud/bp-cron | src/handlers/github_reminder.py | Python | mit | 4,990 | 0.000213 | from collections import defaultdict
from datetime import date
from itertools import count, product
from string import ascii_uppercase
from urllib.parse import urlparse
from github import Github
from slacker import Error
from src import settings
from src.utils import slack
from src.utils.google_api import get_service
... | me="GitHub Information Bot",
icon_emoji=BOT_EMOJI,
attachments=[{
"pretext": "案件のリポジトリを確認してGitHubを利用していないメンバーがいたら外しましょう。",
"color": "#e83a3a",
"text": f"<{setting | s.GITHUB_SPREADSHEET_URL}|メンバー一覧>"
}],
link_names=True,
)
except Error:
pass
|
alexholcombe/words-calculate | anagramsCalculate.py | Python | mit | 3,348 | 0.020012 | from __future__ import print_function
import pandas as pd
import os
#This program will find all the compound words in a long list of words, by
#taking the lexicon of all half-as-many-letters words and checking them against
#the long list.
print(os.getcwd()) #os.chdir() If using within psychopy, might start out in wr... | words['Word'][i]
#print('thisWord=',thisWord)
#print('thisWord[:halfNumLtrs]=',thisWord[:3])
try:
words['firstHalf'][i] = thisWord[:halfNumLtrs]
except Exception,e:
print(e)
print('i=',i)
words['secondHalf'][i] = thisWord[halfNumLtrs:]
print('words.head=',words.head())
#print... | t row is bad, probably because carriage return at end
wordsHalfAsManyLtrs = wordsHalfAsManyLtrs[:-1] #remove last item
#For each word, find out whether both firsthalf and second half is a word
halfLengthWords = wordsHalfAsManyLtrs['Word'].astype(str)
halfLengthWords = list(halfLengthWords)
halfLengthWords = [ x.u... |
istresearch/scrapy-cluster | crawler/tests/online.py | Python | mit | 3,708 | 0.005394 | '''
Online link spider test
'''
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import next
import unittest
from unittest import TestCase
import time
import sys
from os import path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__... |
def thread_func():
time.sleep(20)
reactor.stop()
thread = threading.Thread(target=thread_func)
thread.start()
reactor.run()
message_count = 0
| m = next(self.consumer)
if m is None:
pass
else:
the_dict = json.loads(m.value)
if the_dict is not None and the_dict['appid'] == 'test' \
and the_dict['crawlid'] == 'abc12345':
message_count += 1
self.assertEquals(mess... |
bam2332g/proj1part3 | rahulCode_redo/project1Part3/nba/parseCurrentPlayers.py | Python | mit | 422 | 0.037915 | # parsing the dump to get all the keys for the current players
import json
dic={}
with open('currentPlayerDump.json','r') as f:
data=json.load(f)
print data["resultSets"][0]["headers"]
print len(data["resultSets"] | [0]["rowSet"])
for obj in data["resultSets"][0]["rowSet"]:
if obj[0] not in dic:
dic[obj[0]]=obj[1]
with open('playerKey','w') as f1:
for key in dic:
f1.write(s | tr(key)+" : "+ str(dic[key])+"\n") |
Aptitudetech/ERPNext | erpnext/selling/doctype/quotation/test_quotation.py | Python | cc0-1.0 | 2,733 | 0.02232 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import flt
import unittest
test_dependencies = ["Product Bundle"]
class TestQuotation(unittest.TestCase):
def test_ma... | .75)/100 + 1500)
test_records[0]['items'][0]['price_list_rate'] = 1500
test_records[0]['items'][0]['margin_type'] = 'Percentage'
test_records[0]['items'][0]['margin_rate_or_amount'] = 18.75
quotation = frappe.copy_doc(test_records[0])
quotation.insert()
self.assertEquals(quotation.get("items")[0].rate, r... | name)
quotation.submit()
sales_order = make_sales_order(quotation.name)
sales_order.naming_series = "_T-Quotation-"
sales_order.transaction_date = "2016-01-01"
sales_order.delivery_date = "2016-01-02"
sales_order.insert()
self.assertEquals(quotation.get("items")[0].rate, rate_with_margin)
sales_orde... |
CloverHealth/airflow | airflow/hooks/mysql_hook.py | Python | apache-2.0 | 4,635 | 0.000216 | # -*- coding: utf-8 -*-
#
# 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
#... | schema", None)
def set_autocommit(self, conn, autocommit):
"""
MySql connection sets autocommit in a different way.
"""
conn.autocommit(autocommit)
def get_autocommit(self, conn):
"""
MySql connection gets autocommit in a different wa | y.
:param conn: connection to get autocommit setting from.
:type conn: connection object.
:return: connection autocommit setting
:rtype bool
"""
return conn.get_autocommit()
def get_conn(self):
"""
Returns a mysql connection object
"""
... |
amandolo/ansible-modules-core | commands/raw.py | Python | gpl-3.0 | 1,845 | 0.001626 | # this is a virtual module that is entirely implemented server side
DOCUMENTATION = '''
---
module: raw
version_added: historical
short_description: Executes a low-down and dirty SSH command
options:
free_form:
description:
- the raw module takes a free form command to run
required: true
executable:
... | of using M(command) unless M(shell) is
explicitly r | equired. When running ad-hoc commands, use your best
judgement.
author:
- Ansible Core Team
- Michael DeHaan
'''
EXAMPLES = '''
# Bootstrap a legacy python 2.4 host
- raw: yum -y install python-simplejson
'''
|
sebalander/sebaPhD | dev/intrinsicCalibFullPyMC3.py | Python | bsd-3-clause | 80,011 | 0.005601 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Jan 2018
do metropolis sampling to estimate PDF of chessboard calibration. this involves
intrinsic and extrinsic parameters, so it's a very high dimensional search
space (before it was only intrinsic)
@author: sebalander
"""
# %%
# import glob
import os
i... | mport bayesLib as bl
import pickle
from calibration.calibrator import datafull, real, realdete, realbalk, realches
from calibration.calibrator import synt, syntextr, syntches, syntintr
print('libraries imported')
# %%
def stereoFromFisheye(distcoeffs):
'''
takes 4 distcoeffs of the opencv fisheye model and... | tps://www.wolframalpha.com/input/?i=integral+of+K*tan(x%2F2)+-+(x%2Bk1*x%5E3%2Bk2*x%5E5%2Bk3*x%5E7%2Bk4*x%5E9)+from+0+to+pi%2F2
'''
piPow = np.pi**(np.arange(1,6)*2)
numAux = np.array([3840, 480, 80, 15, 3])
fisheyeIntegral = np.sum(piPow * numAux) / 30720
return fisheyeIntegral / np.log(2)
'''
pa... |
mwiebe/blaze | blaze/io/storage.py | Python | bsd-3-clause | 7,420 | 0.000809 | """URI API
This file contains the part of the blaze API dealing with URIs. The
"URI API". In Blaze persistence is provided by the means of this URI
API, that allows specifying a "location" for an array as an URI.
The URI API allows:
- saving existing arrays to an URI.
- loading an array into memory from an URI.
- ... | # This is a workaround for raw windows paths like
# 'C:/x/y/z.csv', for which urlparse parses 'C' as
# the scheme and '/x/y/z.csv' as the path.
self._path = uri
if not self._path:
raise ValueError("Unable to extract path from uri: %s", uri)
_, exten... | _from_up = None
if up.scheme in self.SUPPORTED_FORMATS:
format_from_up = up.scheme
if format and format_from_up != format_from_up:
raise ValueError("URI scheme and file format do not match. Given uri: %s, format: %s" %
(up.geturl(), format))
... |
lavalamp-/ws-backend-community | wselasticsearch/query/all.py | Python | gpl-3.0 | 754 | 0.001326 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from .base import BaseElasticsearchQuery
class AllElasticsearchQuery( | BaseElasticsearchQuery):
"""
This is an Elasticsearch query class that is meant to query all of th | e document types in
a given index.
"""
# Class Members
# Instantiation
# Static Methods
# Class Methods
@classmethod
def get_queried_class(cls):
return None
# Public Methods
# Protected Methods
def _validate_queryable_field(self, field):
pass
# Pr... |
hall-lab/svtyper | tests/test_singlesample.py | Python | mit | 3,138 | 0.001912 |
from .context import singl | esample as s
import unittest, | os, subprocess
HERE = os.path.dirname(__file__)
in_vcf = os.path.join(HERE, "data/example.vcf")
in_bam = os.path.join(HERE, "data/NA12878.target_loci.sorted.bam")
lib_info_json = os.path.join(HERE, "data/NA12878.bam.json")
out_vcf = os.path.join(HERE, "data/out.vcf")
expected_out_vcf = os.path.join(HERE, "data/exampl... |
niwinz/cobrascript | cobra/base.py | Python | bsd-3-clause | 3,602 | 0.003054 | # -*- coding: utf-8 -*-
import argparse
import ast
import functools
import io
import sys
from . import ast as ecma_ast
from . import compiler
from . import translator
from . import utils
def parse(data:str) -> object:
"""
Given a string with python s | ource code,
returns a python ast tree.
"""
return ast.parse(data)
def translate(data:object, **kwargs) -> object:
"""
Given a python ast tree, translate it to
ecma ast.
"""
return translator.TranslateVisitor(**kwargs).translate(data)
def compile(data:str, translate_options=None, co... | translate_options = {}
if compile_options is None:
compile_options = {}
# Normalize
data = utils.normalize(data)
# Parse python to ast
python_tree = parse(data)
# Translate python ast to js ast
ecma_tree = translate(python_tree, **translate_options)
# Compile js ast to js s... |
RoozbehFarhoodi/McNeuron | train2.py | Python | mit | 16,582 | 0.000422 | """Collection of functions to train the hierarchical model."""
from __future__ import print_function
import numpy as np
from keras.optimizers import RMSprop, Adagrad, Adam
import models2 as models
import batch_utils
import plot_utils
import matplotlib.pyplot as plt
def clip_weights(model, weight_constraint):
... | learning rate for optimization of generator
weight_constraint: array
upper and lower bounds of weights (to clip)
verbose: bool
print relevant progress throughout training
Returns
-------
geom_model: list of keras model objects
geome | try generators for each level
cond_geom_model: list of keras model objects
conditional geometry generators for each level
morph_model: list of keras model objects
morphology generators for each level
cond_morph_model: list of keras model objects
conditional morphology generators for ... |
RBT-itsec/TLS-SAK | lib/tls/tlsconnection.py | Python | gpl-3.0 | 5,605 | 0.002319 | # TLS-SAK - TLS Swiss Army Knife
# https://github.com/RBT-itsec/TLS-SAK
# Copyright (C) 2016 by Mirko Hansen / ARGE Rundfunk-Betriebstechnik
#
# 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, eit... | g = self._readPackage()
if type(pkg) is TLS_pkg_Alert:
raise TLS_Alert_Exception(pkg.getLevel(), pkg.getDescription())
elif type(pkg) is not TLS_pkg_Handshake:
raise TLS_Protocol_Exception('handshake package expected, but received other package')
# th... | if type(hs) is TLS_Handshake_pkg_ServerHello:
self.cipher_suite = hs.cipher_suite
self.compression_method = hs.compression_method
self.server_protocol_version = hs.version
elif type(hs) is TLS_Handshake_pkg_ServerHelloDone:
... |
johnathanvidu/ppman | ppman/cli.py | Python | apache-2.0 | 181 | 0.005525 | import sys
def main(args= | None):
if args is None:
args = sys.argv[1:]
print('entry point - it worked')
if __name__ == "__main__":
sys.exit(main()) | |
mhuwiler/rootauto | bindings/pyroot/JupyROOT/__init__.py | Python | lgpl-2.1 | 170 | 0 | from JupyROOT import cppcompleter, uti | ls
if '__IPYTHON__' in __builti | ns__ and __IPYTHON__:
cppcompleter.load_ipython_extension(get_ipython())
utils.iPythonize()
|
mneedham91/PyPardot4 | pypardot/objects/accounts.py | Python | mit | 1,042 | 0.003839 | class Accounts(object):
"""
A class to query and use Pardot accounts.
Account field reference: http://developer.pardot.com/kb/object-field-references/#account
"""
def __init__(self, client):
self.client = client
def read(self, **kwargs):
"""
Returns the data for the ac... | requests for the Account object."""
if params is None:
| params = {}
response = self.client.get(object_name=object_name, path=path, params=params)
return response
def _post(self, object_name='account', path=None, params=None):
"""POST requests for the Account object."""
if params is None:
params = {}
response =... |
jhseu/tensorflow | tensorflow/python/ops/clip_ops.py | Python | apache-2.0 | 15,309 | 0.003789 | # 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... | ximum L2-norm.
Given a tensor `t`, and a maximum clip value `clip_norm`, this operation
normalizes `t` so that its L2-norm is less than or equal to `clip_norm`,
| along the dimensions given in `axes`. Specifically, in the default case
where all dimensions are used for calculation, if the L2-norm of `t` is
already less than or equal to `clip_norm`, then `t` is not modified. If
the L2-norm is greater than `clip_norm`, then this operation returns a
tensor of the same type ... |
patriczek/faf | src/pyfaf/actions/pull_components.py | Python | gpl-3.0 | 6,262 | 0.00016 | # Copyright (C) 2013 ABRT Team
# Copyright (C) 2013 Red Hat, Inc.
#
# This file is part of faf.
#
# faf 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) ... | onents = [c.component.name for c in db_release.components]
remote_components = osplugin.get_components(db_release.version)
for remote_component in remote_components:
if remote_component in db_components:
continue
db_component = get_component_... | elease.opsys.name)
if db_component is None:
key = (db_release.opsys, remote_component)
if key in new_components:
db_component = new_components[key]
else:
self.log_info("Creating new component '{0... |
mcgonagle/ansible_f5 | library/bigip_device_dns.py | Python | apache-2.0 | 11,184 | 0.000715 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017 F5 Networks Inc.
# 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__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | self.client = client
self.have = None
self.want = Parameters(self.client.module.params)
self.changes = Parameters()
def _update_changed_options(self):
changed = {}
for key in Parameters.updatables:
if getattr(self.want, key) is not None:
attr1 = g... | self.changes = Parameters(changed)
return True
return False
def exec_module(self):
changed = False
result = dict()
state = self.want.state
try:
if state == "present":
changed = self.update()
elif state == "absent":
... |
android/android-test | tools/android/emulator/resources.py | Python | apache-2.0 | 2,873 | 0.004873 | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | ther express or implied.
# See th | e License for the specific language governing permissions and
# limitations under the License.
"""Local implementation of resources.
"""
import os
import sys
_GOOGLE_STR = os.sep + 'android_test_support' + os.sep
def GetRunfilesDir():
starting_point = sys.argv[0]
return FindRunfilesDir(os.path.abspath(startin... |
sangoma/switchy | switchy/apps/measure/sys.py | Python | mpl-2.0 | 3,923 | 0 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. | 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
Rudimentary system stats collection using ``psutil``.
"""
import time
from switchy import event_callback, utils
def sys_stats(df):
"""Reindex on the call index to allign with call metrics data
... | """
df.index = df.call_index
ci = df.pop('call_index')
# iterpolate all system stats since the arrays will be sparse
# compared to the associated call metrics data.
return df.reindex(range(int(ci.iloc[-1]) + 1)).interpolate()
class SysStats(object):
"""A switchy app for capturing system per... |
cjlee112/socraticqs2 | mysite/chat/migrations/0011_auto_20170614_0341.py | Python | apache-2.0 | 636 | 0.001572 | from django.db import models, migrations
def update_last_modify_timestamp(apps, schema_editor):
Chat = apps.get_model('chat', 'Chat')
for chat in Chat.objects.all():
if not chat.last_modify_timestamp:
last_msg = chat.message_set.all().order_by('-timestamp').first()
if last_ms | g:
chat.last_modify_timestamp = las | t_msg.timestamp
chat.save()
class Migration(migrations.Migration):
dependencies = [
('chat', '0010_auto_20170613_0632'),
]
operations = [
migrations.RunPython(update_last_modify_timestamp, lambda apps, se: None),
]
|
gion86/awlsim | awlsim/gui/icons/outputs.py | Python | gpl-2.0 | 5,539 | 0 | # AUTOMATICALLY GENERATED FILE
# DO NOT EDIT
# Generated from outputs.png
icon_outputs = b'iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAA'\
b'BHNCSVQICAgIfAhkiAAAAAlwSFlzAAAN1wAADdcBQiibeAAA'\
b'CuNJREFUaIHVmltsXcd1hr+Z2ftceZVoi4xFS6KdSlHkooGr'\
b'JgpyqWQEKFwkqNvaemrhINV... | b'zPv2zNj747NTlw/HNj0anP7BhzffbQ0AFqrwzUJobm4u43Rr'\
b'aTab1Gs1mvUGjUY22qI9h3LWmIyNRASlFLX5Cu+/M5qc+OXP'\
b'X6vNX30+OCevwhvparZ1XInlul5lORkYGEBECIKAsZMn6evv'\
b'p1AsUCwWl6Nd8TyDMQZrA86OvefePfbjS+fGT/5rHNSejy/9'\
b'7FQndnUMIEnSa53iKuHz7LPPEscxs3NzfHHv797IVMo4... | 7qWL3jKc07Z+uiPf+h++vaP'\
b'Khcnz7waBbVvplPHjwMrdIm3AUCsJQpCnHOEYciFC5MMbhpk'\
b'5J57SJOE4TBsg9m/fz8nxsbIFwpcuDB5I4gro00Z/PSrk+On'\
b'Upz93yRJXqfy3oqJelsAlFIkSUI+n0dpTblUZnjzMIVCnjiO'\
b'SZKETzYaxEnS/jYwODREpVJBxKFQSyu2tVM/+S8Lr/ER3P6u'\
b'CkBrT... |
william-richard/moto | tests/test_kinesis/test_kinesis_cloudformation.py | Python | apache-2.0 | 5,255 | 0.000761 | import boto3
import sure # noqa
from moto import mock_kinesis, mock_cloudformation
@mock_cloudformation
def test_kinesis_cloudformation_create_stream():
cf_conn = boto3.client( | "cloudformation", region_name="us-east-1")
stack_name = "MyStack"
template = '{"Resources":{"MyStr | eam":{"Type":"AWS::Kinesis::Stream"}}}'
cf_conn.create_stack(StackName=stack_name, TemplateBody=template)
provisioned_resource = cf_conn.list_stack_resources(StackName=stack_name)[
"StackResourceSummaries"
][0]
provisioned_resource["LogicalResourceId"].should.equal("MyStream")
len(provisio... |
Jaesin/OctoPrint | src/octoprint/plugins/appkeys/__init__.py | Python | agpl-3.0 | 13,069 | 0.028469 | # coding=utf-8
from __future__ import absolute_import
import flask
import threading
import os
import yaml
import codecs
import time
from binascii import hexlify
from collections import defaultdict
from flask_babel import gettext
import octoprint.plugin
from octoprint.settings import valid_boolean_trues
from octoprint... | ck, [user_token])
self.poll_timeout.start()
def external(self):
return dict(app_id=self.app_id,
user_id=self.user_id,
user_token=self.user_token)
def __repr__(self):
return u"PendingDecision({!r}, {!r}, {!r}, {!r}, timeout_callback=...)".format(self.app_id,
| self.app_token,
self.user_id,
self.user_token)
class ReadyDecision(object):
... |
masschallenge/django-accelerator | accelerator/migrations/0058_memberprofile1.py | Python | mit | 1,918 | 0 | # Generated by Django 2.2.10 on 2021-06-08 14:37
import django.db.models.deletion
from django.db import (
migrations,
models,
)
from accelerator.utils import copy_m2m_fields
def migrate_member_profile_data(apps, schema_editor):
MemberProfile = apps.get_model('accelerator', 'MemberProfile')
MemberPro... | _table': 'accelerator_memberprofile1',
},
bases=('accelerator.coreprofile',),
),
migrations.RunPython(migrate_mem | ber_profile_data,
migrations.RunPython.noop),
]
|
robotic-ultrasound-image-system/ur5 | universal_robot-kinetic-devel/ur_modern_driver-master/planvios.py | Python | apache-2.0 | 3,473 | 0.031097 | #!/usr/bin/env python
import sys
import copy
import rospy,sys
import moveit_commander
import actionlib
import roslib; roslib.load_manifest('ur_modern_driver')
import tf
from control_msgs.msg import *
from trajectory_msgs.msg import *
from sensor_msgs.msg import JointState
from geometry_msgs.msg import PoseStamped,Pos... | ax_acceleration_scaling_factor(0.05)
arm.set_named_target("reset")
arm.go()
rospy.sleep(1)
print "============ arrival reset "
print "============ start "
wpose.header=wpoint.header
wp | ose.header.frame_id="base_link"
wpose.pose.position=wpoint.point
print wpose
waypoints=[]
#arm.set_pose_target(wpose)
waypoints.append(arm.get_current_pose().pose)
waypoints.append(copy.deepcopy(wpose.pose))
## We want the cartesian path to be interpolated at a resolution of 1... |
larsks/cloud-init | tests/cloud_tests/platforms/lxd/instance.py | Python | gpl-3.0 | 9,690 | 0 | # This file is part of cloud-init. See LICENSE file for license information.
"""Base LXD instance."""
import os
import shutil
import time
from tempfile import mkdtemp
from cloudinit.util import load_yaml, subp, ProcessExecutionError, which
from tests.cloud_tests import LOG
from tests.cloud_tests.util import Platform... | self.py | lxd_container.unfreeze(wait=True)
def destroy(self):
"""Clean up instance."""
LOG.debug("%s: deleting container.", self)
self.unfreeze()
self.shutdown()
retries = [1] * 5
for attempt, wait in enumerate(retries):
try:
self.pylxd_container.d... |
hms-dbmi/clodius | scripts/exonU.py | Python | mit | 4,383 | 0.001825 | from __future__ import print_function
__author__ = "Alaleh Azhir,Peter Kerpedjiev"
import collections as col
import sys
import argparse
class GeneInfo:
def __init__(self):
pass
def merge_gene_info(gene_infos, gene_info):
"""
Add a new gene_info. If it's txStart and txEnd overlap with a previou... | 7150016,
"""
)
parser.add_argument("transcript_bed")
# parser.add_argument('-o', '--options', default='yo',
# help="Some option", type='str')
# parser.add_argument('-u', '--useless', action='store_true',
# help='Another useless option')
args = parser.parse_args()
inputFile = open(args.... | .strip().split("\t")
gene_info = GeneInfo()
try:
gene_info.chrName = words[0]
gene_info.txStart = words[1]
gene_info.txEnd = words[2]
gene_info.geneName = words[3]
gene_info.score = words[4]
gene_info.strand = words[5]
... |
tilezen/tilequeue | tilequeue/queue/sqs.py | Python | mit | 6,744 | 0 | import threading
from datetime import datetime
from tilequeue.queue import MessageHandle
from tilequeue.utils import grouper
class VisibilityState(object):
def __init__(self, last, total):
# the datetime when the message was last extended
self.last = last
# the total amount of time curre... | ption, self).__init__(
msg + ', caused by ' + repr(cause))
self.err_details = err_details
class SqsQueue(object):
def __init__(self, sqs_client, queue_url, read_size,
recv_wait_time_seconds, visibility_mgr):
self.sqs_client = sqs_client
self. | queue_url = queue_url
self.read_size = read_size
self.recv_wait_time_seconds = recv_wait_time_seconds
self.visibility_mgr = visibility_mgr
def enqueue(self, payload):
return self.sqs_client.send(
QueueUrl=self.queue_url,
MessageBody=payload,
)
de... |
Cadasta/ckanext-project | ckanext/project/logic/auth.py | Python | agpl-3.0 | 2,564 | 0 | import ckan.plugins.toolkit as toolkit
import ckan.model as model
from ckanext.project.model import projectAdmin
import logging
log = logging.getLogger(__name__)
def _is_project_admin(context):
'''
Determines whether user in context is in the project admin list.
'''
user = context.get('user', '')
... | All users can access a project list'''
return {'success': True}
def package_association_create(context, data_dict):
'''Create a package project association.
Only sysadmins or user listed as project Admins can create a
package/project association.
' | ''
return {'success': _is_project_admin(context)}
def package_association_delete(context, data_dict):
'''Delete a package project association.
Only sysadmins or user listed as project Admins can delete a
package/project association.
'''
return {'success': _is_project_admin(context)}
@... |
nion-software/nionswift | nion/swift/DataItemThumbnailWidget.py | Python | gpl-3.0 | 19,101 | 0.003508 | from __future__ import annotations
# standard libraries
import asyncio
import typing
# third party libraries
import numpy.typing
# local libraries
from nion.data import Image
from nion.swift import MimeTypes
from nion.swift import Thumbnails
from nion.swift.model import DisplayItem
from nion.swift.model import Docum... | Data, x: int, y: int) -> str:
if callable(self.on_drop_mime_data):
result = self.on_drop_mime_data(mime_data, x, y)
if result:
return result
return super().drop(mime_data, x, y)
def key_pressed(self, key: UserI | nterface.Key) -> bool:
if key.is_delete:
on_delete = self.on_delete
if callable(on_delete):
on_delete()
return True
return super().key_pressed(key)
def mouse_pressed(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> bool:
... |
afaquejam/Grok-Python | MultiProcessing/multi_process.py | Python | gpl-2.0 | 947 | 0.004224 | import random
import time
import multiprocessing
# This could be a consumer function, which is invoked when a n | ew RabbitMQ message arrives.
def busy_process(id):
print("Processing message ID: " + str(id))
loop_count = 1000
for outer in range(0, loop_count):
for inner in range(0, loop_count):
| random_sum = outer + inner
print("Finished processing the message bearing ID: " + str(id))
# This could be a callback function which the RabbitMQ invokes when a message arrives.
# However, we need to limit max. amount of concurrent threads that can execute.
def execute_busy_processes():
# Generating a new j... |
william-richard/moto | moto/resourcegroupstaggingapi/urls.py | Python | apache-2.0 | 215 | 0 | from __future__ import unicode_literals
from .responses import | ResourceGroupsTaggingAPIResponse
url_bases = ["https?://tagging.(.+).amazonaws.c | om"]
url_paths = {"{0}/$": ResourceGroupsTaggingAPIResponse.dispatch}
|
cflq3/getcms | plugins/Webluker_cdn.py | Python | mit | 127 | 0.007874 | #!/usr/bin/env python
# encoding: utf-8
def run(whatweb | , pluginname):
whatweb.recog_ | from_header(pluginname, "Webluker")
|
YuxuanLing/trunk | trunk/code/study/python/core_python_appilication/ch13/stock.py | Python | gpl-3.0 | 485 | 0 | #!/usr/bin/env python
from time import ctime
from urllib2 import urlopen
TICKs = ('yhoo', 'dell', 'cost', 'adbe', 'intc')
URL = 'http://quot | e.yahoo.com/d/quotes.csv?s=%s&f=sl1c1p2'
print '\nPrices quoted as of: %s\n' % ctime()
print 'TICKER', 'PRICE', 'CHANGE', '%AGE'
print '------', '-----', '------', '----'
u = urlopen(URL % ','.join(TICKs | ))
for row in u:
tick, price, chg, per = row.split(',')
print tick, '%.2f' % float(price), chg, per,
u.close()
|
wrshoemaker/ffpopsim | examples/genealogies_with_selection.py | Python | gpl-3.0 | 2,468 | 0.029173 | import FFPopSim as h
import numpy as np
from matplotlib import pyplot as plt
import random as rd
from Bio import Phylo
print "This script is meant to illustrate and explore the effect of\n\
positive selection on genealogies in asexual and sexual populations. \n\n\
Simulations are performed using an infinite sites mode... | neutral asexual: N=100 s=0.00001 r=0.0
#selected asexual: N=10000 s=0.01 r=0.0
#selected sexual: N=1000 s=0.01 r=1.0
L = 1000 #number of segregating sites
s = 1e-2 #single site effect
N = 10000 #population size
r = 0.0 #outcrossing rate
sample_size=30 #number of individuals whose genealogy is looked at
n... | 2000 #either ~5*N or 5/s, depending on whether coalescence is dominated by drift or draft
dt = 1000 #time between samples
#set up population, switch on infinite sites mode
pop=h.haploid_highd(L, all_polymorphic=True)
#set the population size via the carrying capacity
pop.carrying_capacity= N
#set the crossover ra... |
henriquenogueira/aedes | aedes_server/core/migrations/0009_auto_20160329_2208.py | Python | mit | 490 | 0.002041 | # -*- coding: utf-8 -*-
# G | enerated by Django 1.9.4 on 2016-03-30 01:08
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
| ('core', '0008_report_photo'),
]
operations = [
migrations.AlterField(
model_name='report',
name='photo',
field=models.ImageField(blank=True, upload_to='/upload/%Y/%m/%d/', verbose_name='foto'),
),
]
|
manuelcortez/socializer | src/wxUI/dialogs/creation.py | Python | gpl-2.0 | 975 | 0.002051 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import wx
import widgetUtils
class audio_album(widgetUtils.BaseDialog):
def __init__(self, *args, **kwargs):
super(audio_album, self).__init__(title=_("Create a new album"), parent=None)
panel = wx.Panel(self)
sizer = wx.BoxSi... | box.Add(lbl, 1, wx.ALL, 5)
box.Add(self.title, 1, wx.ALL, 5)
sizer.Add(box, 1, wx.ALL, 5)
ok = wx.Button(panel, wx.ID_OK, _("&OK"))
ok.SetDefault()
cancel = wx.Button(panel, wx.ID_CANCEL, _("&Close"))
btnsizer = wx.BoxSizer()
btnsizer.Add(ok, 0, wx.ALL, 5)
... | zer.CalcMin())
|
jnns/wagtail | wagtail/images/templatetags/wagtailimages_tags.py | Python | bsd-3-clause | 4,585 | 0.002181 | import re
from django import template
from django.core.exceptions import ImproperlyConfigured
from django.urls import NoReverseMatch
from django.utils.functional import cached_property
from wagtail.images.models import Filter
from wagtail.images.shortcuts import get_rendition_or_not_found
from wagtail.images.views.se... | rendition = get_rendition_or_not_found(image, self.filter)
if self.output_var_name:
| # return the rendition object in the given variable
context[self.output_var_name] = rendition
return ''
else:
# render the rendition's image tag now
resolved_attrs = {}
for key in self.attrs:
resolved_attrs[key] = self.attrs[key].res... |
franklingu/leetcode-solutions | questions/random-pick-with-weight/Solution.py | Python | mit | 1,988 | 0.003541 | """
You are given an array of positive integers w where w[i] describes the weight of ith index (0-indexed).
We need to call the function pickIndex() which randomly returns an inte | ger in the range [0, w.length - 1]. pickIndex() should return the integer proportional to its weight in the w array. For example, for w = [1, 3], the probability of picking the index 0 is 1 / (1 + 3) = 0.25 (i.e 25%) while the probabi | lity of picking the index 1 is 3 / (1 + 3) = 0.75 (i.e 75%).
More formally, the probability of picking index i is w[i] / sum(w).
Example 1:
Input
["Solution","pickIndex"]
[[[1]],[]]
Output
[null,0]
Explanation
Solution solution = new Solution([1]);
solution.pickIndex(); // return 0. Since there is only one single e... |
teeple/pns_server | work/install/Python-2.7.4/Misc/BeOS-setup.py | Python | gpl-2.0 | 23,664 | 0.008959 | # Autodetec | ting setup.py script for building the Python extensions
#
# Modified for BeOS build. Donn Cave, March 27 2001.
__version__ = "special BeOS after 1.37"
import sys, os
from distutils import sysconfig
from distutils import text_file
from distutils.errors import *
from distutils.core import Extension, setup
from distuti... | ef find_file(filename, std_dirs, paths):
"""Searches for the directory where a given file is located,
and returns a possibly-empty list of additional directories, or None
if the file couldn't be found at all.
'filename' is the name of a file, such as readline.h or libcrypto.a.
'std_dirs' is the lis... |
kristinn/casanova | casanova/http.py | Python | mit | 956 | 0.004184 | import re
import BaseHTTPServer
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
"""
Handle incoming GET requests.
We will only handle one request and an authorization_code GET parameter
must be present. We don't really care about the path being requ... | self.wfile.write(auth_code)
class HTTPServer(object):
def __init__(self, host, port):
self.addr = (host, port)
def serve(self):
"""
Listen for the Bitcasa auth callback.
"""
httpd = BaseHTTPServer.HTTPServer(self.addr, RequestHandler)
| httpd.handle_request()
|
sunyihuan326/DeltaLab | daily_learning/serving_learning/save_model.py | Python | mit | 4,825 | 0.001658 | # coding:utf-8
'''
created on 2018/8/22
@author:sunyihuan
'''
from __future__ import print_function
import os
import sys
# This is a placeholder for a Google-internal import.
import tensorflow as tf
import mnist_input_data
tf.app.flags.DEFINE_integer('training_iteration', 1000,
'numbe... | ) < 2 or sys.argv[-1].startswith('-'):
print('Usage: mni | st_saved_model.py [--training_iteration=x] '
'[--model_version=y] export_dir')
sys.exit(-1)
if FLAGS.training_iteration <= 0:
print('Please specify a positive value for training iteration.')
sys.exit(-1)
if FLAGS.model_version <= 0:
print('Please specify a positive ... |
codeAshu/nn_ner | nn/interfaces.py | Python | mit | 939 | 0.01065 | # -*- coding: utf8 -*-
"""
@author: Matthias Feys (matthiasfeys@gmail.com)
@date: %(date)
"""
import theano
class Layer(object):
def __init__(self,name, params=None):
self.name=name
self.input = input
self.params = []
if params!=None:
self.setParams(params=params... | for param in self.params:
params[param.name] = param.get_value()
return params
def setParams(self,params):
for pname,param in params.__dict__.iteritems():
self.__dict__[pname[:-(len(self.name)+1)]] = theano.shared(param, name=pname[:-(len(self.name)+1)]+'_'+self.name, b... |
class Network():
def __getstate__(self):
return dict([(layer.name,layer) for layer in self.layers])
|
scopatz/regolith | tests/test_validators.py | Python | cc0-1.0 | 876 | 0 | from | collections.abc import Sequence
import pytest
from regolith.schemas import SCHEMAS, validate, EXEMPLARS
from pprint import pprint
@pytest.mark.parametrize("key", SCHEMAS.keys())
def test_validation(key):
if isinstance(EXEMPLARS[key], Sequence):
for e in EXEMPLARS[key]:
validate(key, e, SCHE... | )
else:
validate(key, EXEMPLARS[key], SCHEMAS)
@pytest.mark.parametrize("key", SCHEMAS.keys())
def test_exemplars(key):
if isinstance(EXEMPLARS[key], Sequence):
for e in EXEMPLARS[key]:
v = validate(key, e, SCHEMAS)
assert v[0]
else:
v = validate(key, EXEMPL... |
grlee77/nipype | nipype/interfaces/elastix/tests/test_auto_Registration.py | Python | bsd-3-clause | 1,483 | 0.024275 | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from nipype.testing import assert_equal
from nipype.interfaces.elastix.registration import Registration
def test_Registration_inputs():
input_map = dict(args=dict(argstr='%s',
),
environ=dict(nohash=True,
usedefault=True,
),
fixed_image=dict... |
),
fixed_mask=dict(argstr='-fMask %s',
),
ignore_exception | =dict(nohash=True,
usedefault=True,
),
initial_transform=dict(argstr='-t0 %s',
),
moving_image=dict(argstr='-m %s',
mandatory=True,
),
moving_mask=dict(argstr='-mMask %s',
),
num_threads=dict(argstr='-threads %01d',
),
output_path=dict(argstr='-out %s',
mandatory=True... |
danielfm/pydozeoff | ez_setup.py | Python | bsd-3-clause | 10,286 | 0.004667 | #!python
"""Bootstrap setuptools installation
If you want to use setuptools in your package's setup.py, just include this
file in the same directory with it, and add this to the top of your setup.py::
from ez_setup import use_setuptools
use_setuptools()
If you want to require a specific version of setuptools... | :
from distutils import log
if delay:
log.warn("""
---------------------------------------------------------------------------
This script requires setuptools version %s to run (even to displa | y
help). I will attempt to download it for you (from
%s), but
you may need to enable firewall access for this script first.
I will start the download in %d seconds.
(Note: if this machine does not have network access, please obtain the file
%s
and place it in this directory before rerunning this script.)
-------... |
unitpoint/oxygine-objectscript | tools/src2/xml_processor.py | Python | mit | 9,313 | 0.01267 | from xml.dom import minidom
import os
import shutil
import process_atlas
import process_font
import process_starling_atlas
import oxygine_helper
class XmlWalker:
def __init__(self, src, folder, scale_factor, node, meta_node, scale_quality):
self.base = folder
self.path = folder
self.scale_f... |
self.helper = oxygine_helper.helper(os.path.split(__file__)[0] + "/../../")
self.register_processor(process_font.bmfc_font_Processor())
self.register_processor(process_font.font_Processor())
self.r | egister_processor(process_atlas.atlas_Processor())
self.register_processor(process_starling_atlas.starling_atlas_Processor())
self._current_processor = None
def register_processor(self, processor):
self.processors[processor.node_id] = processor
def get_apply_s... |
coringao/capitan | dependencies/alfont/freetype/src/autohint/mather.py | Python | gpl-3.0 | 1,699 | 0.021189 | #!/usr/bin/env python
#
#
# autohint math table builder
#
# Copyright 1996-2000 by
# David Turner, Robert Wilhelm, and Werner Lemberg.
#
# This file is part of the FreeType project, and may only be used, modified,
# and distr | ibuted under the terms of the FreeType project license,
# LICENSE.TXT. By continuing to use, modify, or distribute this file you
# indicate that you have read the license and understand and accept it
# fully.
import math
ag_pi = 256
def print_arctan( atan_bits ):
atan_base = 1 << atan_bits
pr... | arctan[1L << AG_ATAN_BITS] ="
print " {"
count = 0
line = " "
for n in range( atan_base ):
comma = ","
if ( n == atan_base - 1 ):
comma = ""
angle = math.atan( n * 1.0 / atan_base ) / math.pi * ag_pi
line = line + " " + repr( int( angle + 0... |
myles/pyconfluence | src/pyconfluence/confluence.py | Python | bsd-3-clause | 2,731 | 0.034053 | import os
import logging
import ConfigParser
from optparse import OptionParser
from pyconfluence import __version__, Confluence, ConfluenceException
USAGE = """%prog [options]
get_server_info:\t Retrieve some basic information about the server connected to.
get_spaces:\t\t All Space Summaries that the current user c... | ging.INFO, '2': logging.DEBUG}[options.verbosity]
logging.basicConfig(level=level, format="%(name)s: %(levelname)s: %(message)s")
log = logging.getLogger('pyconfluence')
if not args:
log.warn("You didn't tell me anything.") # FIXME
return
config = ConfigParser.ConfigPars | er()
config.read(os.path.expanduser("~/.pyconfluence.ini"))
confluence_url = options.confluence_url
username = options.username
password = options.password
if config.get('pyconfluence', 'url'):
confluence_url = config.get('pyconfluence', 'url')
if config.get('pyconfluence', 'username'):
username = confi... |
karstenw/nodebox-pyobjc | setup_large.py | Python | mit | 4,542 | 0.007266 | """
Script for building NodeBox
Usage:
python setup.py py2app
"""
from distutils.core import setup
from setuptools.extension import Extension
import py2app
import nodebox
NAME = 'NodeBox extended'
VERSION = nodebox.__version__
AUTHOR = "Frederik De Bleser",
AUTHOR_EMAIL = "frederik@pandora.be",
URL = "http://... | r graphics
* QuickTime export for animations
* Manipulate every num | eric variable in a script by command-dragging it, even during animation
* Creating simple user interfaces using text fields, sliders, and buttons
* Stop a running script by typing command-period
* Universal Binary
* Integrated bezier mathematics and boolean operations
* Command-line interface
* Zooming
"""
creator =... |
kubernetes-client/python | kubernetes/client/models/v1beta1_limited_priority_level_configuration.py | Python | apache-2.0 | 6,329 | 0 | # coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: release-1.23
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import si... | ram assured_concurrency_shares: The assured_concurrency_shares of this V1beta1LimitedPriorityLevelConfiguration. # noqa: E501
:type: int
"""
self._assured_concurrency_shares = assured_concurrency_shares
@property
def limit_response(self):
"""Gets the limit_response of this V1b... | :rtype: V1beta1LimitResponse
"""
return self._limit_response
@limit_response.setter
def limit_response(self, limit_response):
"""Sets the limit_response of this V1beta1LimitedPriorityLevelConfiguration.
:param limit_response: The limit_response of this V1beta1LimitedPrior... |
pybquillast/xkAddonIDE | toRecycle/baseUI.py | Python | gpl-3.0 | 32,423 | 0.018444 | '''
Created on 5/03/2014
@author: Alex Montes Barrios
'''
import sys
import os
import Tkinter as tk
import tkMessageBox
import tkFileDialog
import tkSimpleDialog
import ttk
import tkFont
import keyword
import pickle
import re
NORM_PROMPT = '>>> '
CELL_PROMPT = '... '
class PythonEditor(tk.Frame):
def __init__(se... | ModeOn(self):
return len(self.cellInput) > 0
def setNextIndentation(self,expr):
if len(expr):
nTabs = len(expr) - len(expr.lstrip('\t'))
if expr[-1] == ':': nTabs += 1
self.cellInput = nTabs * '\t'
else:
self.cellInput = ''
|
def keyHandler(self,event):
textw = event.widget
if event.keysym == 'Return':
strInst = textw.get('insert linestart', 'insert lineend')
self.setNextIndentation(strInst)
textw.insert('insert', '\n')
self.dispPrompt()
return "... |
skosukhin/spack | var/spack/repos/builtin/packages/fastphase/package.py | Python | lgpl-2.1 | 1,682 | 0.000595 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | our notice and the LGPL.
#
# This program 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) | version 2.1, February 1999.
#
# 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 terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You shoul... |
duyet-website/api.duyet.net | lib/gensim/test/test_word2vec.py | Python | mit | 34,696 | 0.003603 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 Radim Rehurek <radimrehurek@seznam.cz>
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""
Automated tests for checking transformation algorithms (the models package).
"""
import logging
import unittest
import os
import t... | _wv.vocab))
def testPersistenceWithConstructorRule(self):
"""Test storing/loading the entire model with a vocab trimming rule passed in the constructor."""
model = word2vec.Word2Vec(sentences, min_count=1, trim_rule=_rule)
model.save(testfile())
self.models_equal(model, word2vec.Wor... | trim_rule triggers min_count."""
model = word2vec.Word2Vec(sentences + [["occurs_only_once"]], min_count=2, trim_rule=_rule)
self.assertTrue("human" not in model.wv.vocab)
self.assertTrue("occurs_only_once" not in model.wv.vocab)
self.assertTrue("interface" in model.wv.vocab)
def te... |
postatum/nefertari-sqla | nefertari_sqla/documents.py | Python | apache-2.0 | 28,898 | 0.000069 | import copy
import logging
from datetime import datetime
import six
from sqlalchemy.orm import (
class_mapper, object_session, properties, attributes)
from sqlalchemy.orm.collections import InstrumentedList
from sqlalchemy.exc import InvalidRequestError, IntegrityError
from sqlalchemy.orm.exc import MultipleResult... | get_document_classes():
""" Get all defined not abstract document classes
Class is assumed to be non-abstract if it has `__table__` or
`__tablename__` attributes defined.
"""
document_classes = {}
re | gistry = BaseObject._decl_class_registry
for model_name, model_cls in registry.items():
tablename = (getattr(model_cls, '__table__', None) is not None or
getattr(model_cls, '__tablename__', None) is not None)
if tablename:
document_classes[model_name] = model_cls
... |
morpheby/levelup-by | common/lib/xmodule/xmodule/tests/__init__.py | Python | agpl-3.0 | 3,708 | 0.002157 | """
unittests for xmodule
Run like this:
rake test_common/lib/xmodule
"""
import json
import os
import unittest
import fs
import fs.osfs
import numpy
from mock import Mock
from path import path
import calc
from xblock.field_data import DictFieldData
from xmodule.x_module import ModuleSystem, XModuleDescriptor... | 'password': 'incorrect_pass',
'staff_grading' : 'staff_grading',
'peer_grading' : 'peer_grading',
'grading_controller' : 'grading_controller'
}
def get_test_system(course_id=''):
"""
Construct a test ModuleSystem instance.
By default, the render_template() | method simply returns the repr of the
context it is passed. You can override this behavior by monkey patching::
system = get_test_system()
system.render_template = my_render_func
where `my_render_func` is a function of the form my_render_func(template, context).
"""
return ModuleSyst... |
dmsurti/mayavi | integrationtests/mayavi/common.py | Python | bsd-3-clause | 25,780 | 0.001241 | """MayaVi test related utilities.
"""
# Author: Prabhu Ramachandran <prabhu@aero.iitb.ac.in>
# Copyright (c) 2005-2015, Enthought, Inc.
# License: BSD Style.
from __future__ import print_function
# Standard library imports
import gc
import os
import os.path
import sys
import logging
import traceback
from optparse imp... | usage) / usage
msg = "Memory leak of {:.2%}".format(difference)
raise AssertionError(msg)
def assertReturnsMemory(self, function, args=None, iterations=100,
slack=0.0, ms | g=None):
""" Assert that the function does not retain memory over a number of
runs.
Parameters
----------
func : callable
The function to check. The function should take no arguments.
args : tuple
The tuple of arguments to pass to the callable.
... |
rcbops/glance-buildpackage | glance/api/policy.py | Python | apache-2.0 | 3,392 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2011 OpenStack, LLC.
# 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... | raw_contents = fap.read()
self.policy_file_contents = json.loads(raw_contents)
self.policy_file_mtime = mtime
return self.policy_file_contents
def enforce(self, context, action, target):
"""Verifies that the action is valid on the target in this context.
:pa... | o be checked
:param object: Dictionary representing the object of the action.
:raises: `glance.common.exception.NotAuthorized`
:returns: None
"""
self.load_rules()
match_list = ('rule:%s' % action,)
credentials = {
'roles': context.roles,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.