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 |
|---|---|---|---|---|---|---|---|---|
pytest-dev/pluggy | testing/test_helpers.py | Python | mit | 1,664 | 0 | from pluggy._hooks import varnames
from pluggy._manager import _formatdef
def test_varnames() -> None:
def f(x) -> None:
i = 3 # noqa
class A:
def f(self, y) -> None:
pass
class B:
def __call__(self, z) -> None:
pass
assert varnames(f) == (("x",), ()... | class D:
pass
class E:
def __init__(self, x) -> None:
pass
class F:
pass
assert varnam | es(C) == (("x",), ())
assert varnames(D) == ((), ())
assert varnames(E) == (("x",), ())
assert varnames(F) == ((), ())
def test_varnames_keyword_only() -> None:
def f1(x, *, y) -> None:
pass
def f2(x, *, y=3) -> None:
pass
def f3(x=1, *, y=3) -> None:
pass
assert... |
allotria/intellij-community | python/testData/intentions/convertVariadicParamEmptySubscription.py | Python | apache-2.0 | 45 | 0 | def foo(**k | wargs):
doSomething | (kwargs[])
|
ucshadow/Fish_bot | even more.py | Python | lgpl-3.0 | 5,779 | 0.00173 | import pyscreenshot as img
import time
import msvcrt
import win32api
import win32con
import numpy as np
import tkinter as tk
import threading
import pyautogui
from win32api import GetKeyState
from ctypes import windll
class App(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwa... | rsorPos((x, y))
print('match!')
self.after(2000)'''
if abs(x - prev_position[0] >= 10) and abs(y - prev_position[2] >= 10):
prev_position[0] = x
prev_position[1] = y
... | y))
return self.wait_thread()
print('scan Finished with no match...')
def waiting_for_fish(self):
time.clock()
tolerance = t = 5
while True:
splash = (156, 150, 135)
density = []
image = img.grab()
colo... |
khchine5/xl | lino_xl/lib/finan/fixtures/unused_demo.py | Python | bsd-2-clause | 2,045 | 0.008802 | # -*- coding: UTF-8 -*-
# Copyright 2009-2013 Luc Saffre
# License: BSD (see file COPYING for details)
#import time
#from datetime import date
#from dateutil import parser as dateparser
#from lino.projects.finan import models as finan
#~ import decimal
from decimal import Decimal
from django.conf import settings
fro... | NERS.pop(),
account=ACCOUNTS.pop(),
amount=AMOUNT | S.pop()
)
#~ item.total_incl_changed(REQUEST)
#~ item.before_ui_save(REQUEST)
#~ if item.total_incl:
#~ print "20121208 ok", item
#~ else:
#~ if item.product.price:
#~ raise Exception("20121208")
... |
JackDanger/sentry | src/sentry/utils/performance/sqlquerycount.py | Python | bsd-3-clause | 3,221 | 0.00031 | from __future__ import absolute_import
import logging
import six
import threading
from collections import defaultdict
from sentry.debug.utils.patch_context import PatchContext
DEFAULT_MAX_QUERIES = 25
DEFAULT_M | AX_DUPES = 3
class State(threading.local):
def __init__(self):
self.count = 0
self.query_hashes = defaultdict(int)
def record_query(self, sql):
self.count += 1
self.query_hashes[has | h(sql)] += 1
def count_dupes(self):
return sum(1 for n in six.itervalues(self.query_hashes) if n > 1)
class CursorWrapper(object):
def __init__(self, cursor, connection, state):
self.cursor = cursor
self.connection = connection
self._state = state
def execute(self, sql, p... |
fulfilio/nereid-webshop | party.py | Python | bsd-3-clause | 3,061 | 0 | # -*- coding: utf-8 -*-
import os
import logging
from wtforms import TextField, validators
from trytond.pool import PoolMeta, Pool
from trytond.modules.nereid.party import AddressForm
from trytond.config import config
from nereid import request, current_app, current_user
from trytond.modules.nereid_checkout.i18n impo... | ddress.name,
street=address.street,
streetbis=address.streetbis,
zip=address.zip,
city=address.city,
country=address.country and address.country.id,
subdivision=address.subdi | vision and address.subdivision.id,
email=address.party.email,
phone=address.phone
)
else:
address_name = "" if current_user.is_anonymous else \
current_user.display_name
form = WebshopAddressForm(request.form, name=address_name)... |
Sibert-Aerts/c2p | src/main.py | Python | mit | 2,477 | 0.004441 | import sys
import c2p
import traceback
from antlr4 import * # type: ignore
from antlr4.error.ErrorListener import ErrorListener # type: ignore
from c2p.grammar.antlr.SmallCLexer import SmallCLexer
from c2p.grammar.antlr.SmallCParser import SmallCParser
from c2p.grammar.ast.visitor import ASTVisitor
from c2p.grammar.as... | :'.format(e.__class__.__name__, action))
print(e)
[print(l) for l in exceptiondata[-3:-1]]
except NotImplementedError as e:
exceptiondata = traceback.format_exc().splitlines()
print('Encountered {0} while {1}:'.format(e.__class__.__name__, action))
print(e)
if isinsta... | exceptiondata[-3:-1]]
if __name__ == '__main__':
run(sys.argv)
|
Laika-ETS/shiba | shiba_ws/src/shiba_teleop/script/teleop.py | Python | mit | 533 | 0.011257 | #!/usr/bin/env python
PACKAGE_NAME = 'shiba_teleop'
import roslib
roslib.load_manifest(PACKAGE_NAME)
import rospy
from geometry_msgs.msg import Twist
from sensor_msgs.msg import Joy
import rospkg
FORWARD = 1
BACKWARDS = 2
SPINNING = 3
STOPPED = 4
linear_increment = 0.3
max_linear_vel = 1.0
min_linear_vel = -1.0
de... | None
linear_vel = 0.0
angular_vel = 0.0
last_angular_acceleration = 0
rotating = False
state = STOPPED
| |
sbidoul/pip | src/pip/_internal/metadata/__init__.py | Python | mit | 2,036 | 0.000982 | from typing import List, Optional
from .base import BaseDistribution, BaseEnvironment, FilesystemWheel, MemoryWheel, Wheel
__all__ = [
"BaseDistribution",
"BaseEnvironment",
"FilesystemWheel",
"MemoryWheel",
"Wheel",
"get_default_environment",
"get_environment",
"get_wheel_distribution... | irectory(directory)
def get_wheel_distribution(wheel: Wheel, canonical_name: str) -> BaseDistribution:
"""Get the representation of the specified wheel's distribution metadata.
This returns a Distribution instance from the chosen backend based | on
the given wheel's ``.dist-info`` directory.
:param canonical_name: Normalized project name of the given wheel.
"""
from .pkg_resources import Distribution
return Distribution.from_wheel(wheel, canonical_name)
|
nsnam/ns-3-dev-git | src/propagation/bindings/modulegen__gcc_LP64.py | Python | gpl-2.0 | 277,968 | 0.014196 | from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers
import pybindgen.settings
import warnings
class ErrorHandler(pybindgen.settings.ErrorHandler):
def handle_error(self, wrapper, exception, traceback_):
warnings.warn("exception %r in wrapper %s" % (exception, wrapper))
... | d.h (module 'core'): ns3::TypeId [class]
module.add_class('TypeId', import_from_module='ns.core')
## type-id.h (module 'core'): ns3::TypeId::AttributeFlag [enumeration]
module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_fro... | module.add_enum('SupportLevel', ['SUPPORTED', 'DEPRECATED', 'OBSOLETE'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core')
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation [struct]
module.add_class('AttributeInformation', import_from_module='ns.core', outer_class=root_module... |
gsnbng/erpnext | erpnext/education/doctype/student/student_dashboard.py | Python | agpl-3.0 | 845 | 0.042604 | from __future__ import unicode_literals
from frappe import _
def get_data():
return {
'heatmap': True,
'heatmap_message': _('This is based on the attendance of this Student'),
'fieldname': 'student',
'non_standard_fieldnames': {
'Bank Ac | count': 'party'
},
'transactions': [
{
'label': _('Admission'),
'items': ['Program Enrollment', 'Course Enrollment']
},
{
'label': _('Student Activity'),
'items': ['Student Log', 'Student Group', ]
},
{
'label': _('Assessment'),
'items': ['Assessment Result']
},
{
'l... | ourse Activity', 'Quiz Activity' ]
},
{
'label': _('Attendance'),
'items': ['Student Attendance', 'Student Leave Application']
},
{
'label': _('Fee'),
'items': ['Fees', 'Bank Account']
}
]
}
|
mason-bially/windows-installer | packages/_Ghostview/_Ghostview.py | Python | mit | 169 | 0.017751 | '''
@author: KyleLevien
'''
from ..defaultpackage.package import Package
class _Ghostview(Package):
def __init__(self):
Package. | __init__(self)
| |
facebook/infer | infer/tests/testlock.py | Python | mit | 578 | 0 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
import sys
import fcntl
import subprocess
TESTS_DIR = os.path.dirname(os.path.realpath(__file__))
LOCKFILE ... | estlock.mutex')
args = sys.argv[1:]
with open(LOCKFILE, 'r') as lockfile:
fd = lockfile.fileno()
fcntl.flock(fd, fcntl.LOCK_ | EX)
try:
subprocess.call(args)
finally:
fcntl.flock(fd, fcntl.LOCK_UN)
|
ozturkemre/programming-challanges | 15-CollatzConjecture/CollatzConjecture.py | Python | mit | 409 | 0.03423 | try:
entry=int(input("Enter the number: \n"))
i=entry
x=entry
#biggest number
status=[]
while(i!=1):
#end
status.append(i)
if i%2==0:
i=int(i/2)
| else:
i=3*i+1
if(i>x):
x=i
status.append(i)
print(*status)
print("The biggest number: {}".format(x))
except V | alueError:
print("I said number!!!") |
rabramley/microMedicalSpirometerXmlToCsv | correctIds.py | Python | mit | 3,291 | 0.013066 | import csv, sys, getopt, argparse, os
import dbSettings
COLUMN_LOCAL_ID = 'LocalId'
COLUMN_UHL_SYSTEM_NUMBER = 'Uhl System Number'
COLUMN_NHS_NUMBER = 'NHS Number'
COLUMN_TITLE = 'Title'
COLUMN_LAST_NAME = 'Last Name'
COLUMN_FIRST_NAME = 'First Name'
COLUMN_DOB = 'Date of Birth'
COLUMN_GENDER = 'Gender'
COLUMN_ADDRES... | me")
args = parser.parse_args()
with open(args.outputfilename, 'w') as outputFile:
fieldnames = [
COLUMN_LOCAL_ID,
COLUMN_UHL_SYSTEM_NUMBER,
COLUMN_NHS_NUMBER,
COLUMN_TITLE,
COLUMN_LAST_NAME,
COLUMN_FIRST_NAME,
COLUMN_DOB,
COLUMN_GENDER,
COLUMN_ADDRESS_1,
... | COLUMN_ADDRESS_3,
COLUMN_ADDRESS_4,
COLUMN_POST_CODE]
output = csv.DictWriter(outputFile, fieldnames=fieldnames)
output.writeheader()
with pymssql.connect(dbSettings.DB_SERVER_NAME, dbSettings.DB_USERNAME, dbSettings.DB_PASSWORD, dbSettings.DB_DATABASE) as conn:
with open(args.inf... |
peragro/peragro-at | src/damn_at/analyzers/__init__.py | Python | bsd-3-clause | 21 | 0 | """
Analy | zers
"""
| |
PeachyPrinter/peachyinstaller | windows/test/run_all_tests.py | Python | apache-2.0 | 423 | 0 | import unittest
import os
import sys
print "Running all | tests"
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src', ))
loader = unittest.TestL | oader()
suite = loader.discover(os.path.dirname(__file__), pattern='test*.py')
runner = unittest.TextTestRunner(verbosity=2)
result = runner.run(suite)
problems = len(result.errors) + len(result.failures)
print("\nProblems: %s\n" % problems)
exit(problems)
|
antoinecarme/pyaf | tests/artificial/transf_Anscombe/trend_ConstantTrend/cycle_7/ar_12/test_artificial_32_Anscombe_ConstantTrend_7_12_100.py | Python | bsd-3-clause | 268 | 0.085821 | import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as ar | t
art.process_dataset(N = 32 , FREQ = 'D | ', seed = 0, trendtype = "ConstantTrend", cycle_length = 7, transform = "Anscombe", sigma = 0.0, exog_count = 100, ar_order = 12); |
ManchesterBioinference/BranchedGP | notebooks/Hematopoiesis.py | Python | apache-2.0 | 4,055 | 0.002466 | # ---
# jupyter:
# anaconda-cloud: {}
# jupytext:
# cell_metadata_filter: -all
# formats: ipynb,py:percent
# notebook_metadata_filter: all
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.6.0
# kernelspec:
# di... | version: 3.8.5
# ---
# %% [markdown]
# Branching GP Regression on hematopoietic data
# --
#
# *Alexis Boukouvalas, 2017*
#
# **Note:** this notebook i | s automatically generated by [Jupytext](https://jupytext.readthedocs.io/en/latest/index.html), see the README for instructions on working with it.
#
# test change
#
# Branching GP regression with Gaussian noise on the hematopoiesis data described in the paper "BGP: Gaussian processes for identifying branching dynamics ... |
sdpython/pyquickhelper | _unittests/ut_sphinxext/test_downloadlink_extension.py | Python | mit | 3,427 | 0 | """
@brief test log(time=4s)
@author Xavier Dupre
"""
import sys
import os
import unittest
import warnings
import sphinx
from pyquickhelper.pycode import get_temp_folder, ExtTestCase
from pyquickhelper.helpgen import rst2html
from pyquickhelper.sphinxext import process_downloadlink_role
from pyquickhelper.te... | adlink_md(self):
name = self.get_name()
content = """
:downloadlink:`gggg <md::{0}>`
""".replace(" | ", "").format(name)
out = rst2html(content,
writer="md", keep_warnings=True,
directives=None)
self.assertIn("test_rst_builder.py", out)
self.assertNotIn('Unknown interpreted text role', out)
temp = get_temp_folder(__file_... |
Kloudless/kloudless-python | kloudless/resources.py | Python | mit | 35,586 | 0.000169 | from .util import to_datetime, to_iso
from .http import request
from .exceptions import KloudlessException as KException
from . import config
import inspect
import json
import requests
import six
import warnings
class BaseResource(dict):
# {'key': (serializer, deserializer)}
_serializers = {
'create... | self._removed_keys = set()
self._parent_resource = parent_resource
if self._parent_resource_class is not None:
if self._parent_resource is None:
raise KException(
"A %s object or ID must be specif | ied as this "
"%s object's parent." %
(self._parent_resource_class,
self.__class__.__name__))
def populate(self, data):
"""
data: Response from Kloudless with data on this object.
"""
removed = set(self.keys()) - set(data.... |
gavinmcgimpsey/deckofcards | spades/settings.py | Python | mit | 1,928 | 0 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
DEBUG = True
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WAR... | common.CommonMiddleware',
'django.middleware.cs | rf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityM... |
TGM-HIT/eqep-api | eqep/shakemap/display/plotstyle.py | Python | mit | 898 | 0 | from abc import *
class PlotStyle(metaclass=ABCMeta):
"""The base interface for all ShakeMap formats/styles
It is a simple decorator and therefore allows arbitrarily deep nesting of
different styles.
>>> # `Style1` will | be applied first, then `Style2`, ...
>>> style = Style1(Style2(Style3()))
.. warning::
When decorating keep in mind that some styles may cancel out each other
when they are nested in the wrong order.
Attributes
----------
style : PlotStyle
the inner decorator style
"""... | plotting any data.
Parameters
----------
plot : Figure
the plot to apply the styling to
"""
pass
|
Bluscream/Discord-Selfbot | cogs/utils/checks.py | Python | gpl-3.0 | 7,337 | 0.002181 | import | json
import time
import git
import discord
import os
import aiohttp
from cogs.utils.dataIO import dataIO
from urllib.parse import quote as uriquote
try:
from lxml import etree
except ImportError:
from bs4 import BeautifulSoup
from urllib.parse import parse_qs, quote_plus
#from cogs.utils import c... | ional_config():
with open('settings/optional_config.json', 'r') as f:
return json.load(f)
# @common.deprecation_warn()
def load_moderation():
with open('settings/moderation.json', 'r') as f:
return json.load(f)
# @common.deprecation_warn()
def load_notify_config():
with open... |
esthermm/enco | enco_sale_order_ext/models/sale_order.py | Python | gpl-3.0 | 492 | 0.016327 | # -*- coding: utf-8 -*-
# (c) Manuel Guil
# © 2016 Esther Martín - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from openerp import models, fields, api
class SaleOrder(models.Model):
_inherit = "sale.order"
period_ack = fields.Char(string='ACK Period', size=6, required=True)
... | def action_button_confirm(self, cr, uid, ids, context=None):
return super(SaleOrder, self).action_button_confirm(cr, uid, ids, c | ontext)
|
YoshikawaMasashi/magenta | magenta/pipelines/lead_sheet_pipelines.py | Python | apache-2.0 | 2,760 | 0.003623 | # Copyright 2016 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... | Extractor(pipeline.Pipeline):
"""Extracts lead sheet fragments from a quantized NoteSequence."""
def _ | _init__(self, min_bars=7, max_steps=512, min_unique_pitches=5,
gap_bars=1.0, ignore_polyphonic_notes=False, filter_drums=True,
require_chords=True, all_transpositions=True, name=None):
super(LeadSheetExtractor, self).__init__(
input_type=music_pb2.NoteSequence,
output_t... |
pstjohn/cobrapy | cobra/core/Solution.py | Python | gpl-2.0 | 1,232 | 0 | class Solution(object):
"""Stores the solution from optimizing a cobra.Model. This is
used to provide a single interface to results from different
solvers that store their values in different w | ays.
f: The objective value
solver: A string indicating which solver package was used.
x: List or Array of the values from the primal.
x_dict: A dictionary of reaction ids that maps to the primal values.
y: List or Array of the values from the dual.
y_dict: A dictionary of reaction ids tha... | t=None,
solver=None, the_time=0, status='NA'):
self.solver = solver
self.f = f
self.x = x
self.x_dict = x_dict
self.status = status
self.y = y
self.y_dict = y_dict
def dress_results(self, model):
""".. warning :: deprecated"""
... |
raccoongang/edx-platform | lms/djangoapps/ccx/tests/test_field_override_performance.py | Python | agpl-3.0 | 10,116 | 0.002274 | # coding=UTF-8
"""
Performance tests for field overrides.
"""
import itertools
from datetime import datetime
import ddt
import mock
from ccx_keys.locator import CCXLocator
from courseware.field_overrides import OverrideFieldData
from courseware.testutils import FieldOverrideTestMixin
from courseware.views.views import... | ass FieldOverridePerformanceTestCase(FieldOverrideTestMixin, ProceduralCourseTestMixin, ModuleStoreTestCase):
"""
Base class for instrumenting SQL queries and Mongo reads for field override
providers.
"""
__test__ = False
# Tell Django to clean out all databases, not | just default
multi_db = True
# TEST_DATA must be overridden by subclasses
TEST_DATA = None
def setUp(self):
"""
Create a test client, course, and user.
"""
super(FieldOverridePerformanceTestCase, self).setUp()
self.request_factory = RequestFactory()
se... |
jameswatt2008/jameswatt2008.github.io | python/Python基础/截图和代码/函数-下/11-递归.py | Python | gpl-2.0 | 419 | 0.019093 | #4! = 4*3*2*1
#5! = 5*4 | *3*2*1
'''
i = 1
result = 1
while i<=4:
result = result * i
i+=1
print(result)
'''
#5! => 5*4!
#4! => 4*3!
'''
def xxx(num):
num * xxxx(num-1)
def xx(num):
num * xxx(num-1)
def getNums(num):
num * xx(num-1)
getNums(4)
'''
def getNums(num):
if num>1:
return num * getNu | ms(num-1)
else:
return num
result = getNums(4)
print(result)
|
mit-ll/CATAN | catan-services_1.0/catan/db/__init__.py | Python | bsd-3-clause | 37,288 | 0.00775 | """
This file contains all of CATAN database operations
(c) 2015 Massachusetts Institute of Technology
"""
import os
import logging
logger = logging.getLogger(__name__)
import sqlite3
import inspect
import json
import time
import re
import base64
import struct
import socket
import SocketServer
import mult... | picture_id, origin_node_id, picture_data)"
values = "('%s','%s',?)"%(picture_id, orig | in_node_id)
return "INSERT INTO %s %s VALUES %s"%(self.__class__.__name__,keys,values)
_SQL_CREATE = '''CREATE TABLE db_pictures
(picture_id int, origin_node_id int,
picture_data blob)'''
class db_person_pictures(DBSchema):
picture_description = None
... |
airbnb/airflow | airflow/secrets/__init__.py | Python | apache-2.0 | 1,267 | 0.000789 | #
# 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... | except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the Li | cense 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.
"""
Secrets framework provides means of getting connection objects from various sources, e.g. the... |
james-d-mitchell/libsemigroups-python-bindings | semigroups/semiring.py | Python | gpl-3.0 | 28,988 | 0.000276 | '''
This module contains classes for semirings.
'''
# pylint: disable = no-member, protected-access, invalid-name
# pylint: disable = too-few-public-methods
class SemiringABC:
r'''
A *semiring* is a set :math:`R`, together with two binary operations,
:math:`+` and :math:`\times`, such that :math:`(R, +)` i... | TypeError: If any argument is given.
Examples:
>>> from semigroups import MinPlusSemiring
>>> MinPlusSemiring().plus(3, float('inf'))
3
>>> MinPlusSemiring().prod(3, float('inf'))
inf
'''
@staticmethod
def plus(x, y):
'''
| A function to find the minimum of two elements of the min plus
semiring, since this is the additive operation of the min plus
semiring.
Args:
x (int or float): One of the elements to be added.
y (int or float): The other of the elements to be added.
Ret... |
AllMyChanges/allmychanges.com | allmychanges/management/commands/dev_extract_version.py | Python | bsd-2-clause | 846 | 0.00237 | # coding: utf-8
from optparse import make_option
from django.core.management.base import BaseCommand
from twiggy_goodies.django import LogMixin
from allmychanges.vcs_extractor import choose_version_extractor
class Command(LogMixin, BaseCommand):
help = u"""Command to test VCS log extractors' second step — versio... | ',
dest='pdb',
default=False,
help='Stop before extraction'),
)
def handle(self, *args, **options):
path = args[0] if args else '.'
get_version = choose_version_extractor(path)
if options.get('pdb'):
import pdb; pd... | ce() # DEBUG
print get_version(path, use_threads=False)
|
GoogleCloudPlatform/cloud-foundation-toolkit | dm/tests/unit/test_deployment.py | Python | apache-2.0 | 2,633 | 0.00076 | from six import PY2
from apitools.base.py.exceptions import HttpNotFoundError
import jinja2
import pytest
from ruamel.yaml import YAML
from cloud_foundation_toolkit.deployment import Config
from cloud_foundation_toolkit.deployment import ConfigGraph
from cloud_foundation_toolkit.deployment import Deployment
if PY2:
... | aths)
for level in config_list:
assert isinstance(level, list)
for c in level:
assert isinstance(c, | Config)
def test_deployment_object(configs):
config = Config(configs.files['my-networks.yaml'].path)
deployment = Deployment(config)
assert deployment.config['name'] == 'my-networks'
def test_deployment_get(configs):
config = Config(configs.files['my-networks.yaml'].path)
deployment = Deployment... |
tylertian/Openstack | openstack F/nova/nova/virt/vmwareapi/io_util.py | Python | apache-2.0 | 5,907 | 0.000508 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2011 Citrix Systems, Inc.
# Copyright 2011 OpenStack LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# htt... | he reader
to the write using a LightQueue as a Pipe between the reader and the writer.
"""
from eventlet import event
from eventlet import greenthread
from eventlet import queue
from nova import exception
from nova.openstack.common import log as logging
LOG = logg | ing.getLogger(__name__)
IO_THREAD_SLEEP_TIME = .01
GLANCE_POLL_INTERVAL = 5
class ThreadSafePipe(queue.LightQueue):
"""The pipe to hold the data which the reader writes to and the writer
reads from."""
def __init__(self, maxsize, transfer_size):
queue.LightQueue.__init__(self, maxsize)
s... |
syed/PerfKitBenchmarker | perfkitbenchmarker/openstack/utils.py | Python | apache-2.0 | 6,884 | 0.001453 | # Copyright 2015 PerfKitBenchmarker 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 appli... | lient
self.__connection = ksclient.Client(
auth_url=self.__url,
username=self.__user,
password=self.__password,
tenant=self.__tenant)
self.__connect | ion.authenticate()
def get_token(self):
return self.GetConnection().get_token(self.__session)
def get_tenant_id(self):
raw_token = self.GetConnection().get_raw_token_from_identity_service(
auth_url=self.__url,
username=self.__user,
password=self.__password,
... |
buffer/thug | tests/functional/test_jquery.py | Python | gpl-2.0 | 8,746 | 0.003659 | import os
import logging
from thug.ThugAPI.ThugAPI import ThugAPI
log = logging.getLogger("Thug")
class TestJQuerySamples(object):
cwd_path = os.path.dirname(os.path.realpath(__file__))
jquery_path = os.path.join(cwd_path, os.pardir, "samples/jQuery")
def do_perform_test(self, caplog, sample, expect... | ath, "test-jquery-19.html")
expected = ["[Windo | w] Alert Text: child"]
self.do_perform_test(caplog, sample, expected)
def test_jquery_20(self, caplog):
sample = os.path.join(self.jquery_path, "test-jquery-20.html")
expected = ["[Window] Alert Text: parent",
"[Window] Alert Text: surrogateParent1",
... |
Python3WebSpider/ProxyPool | proxypool/crawlers/public/xicidaili.py | Python | mit | 969 | 0 | from pyquery import PyQuery as pq
from proxypool.schemas.proxy import Proxy
from proxypool.crawlers.base import BaseCrawler
from loguru import logger
BASE_URL = 'https://www.xicidaili.com/'
class XicidailiCrawler(BaseCrawler):
"""
xididaili crawler, https://www.xicidaili.com/
"""
urls = [BASE_URL]
| ignore = True
def parse(self, html):
"""
parse html file to get proxies
:return:
"""
doc = pq(html)
items = doc('#ip_list tr:contains(高匿)').items()
for item in items:
country = item.find('td.country').text()
if not country or count... | continue
host = item.find('td:nth-child(2)').text()
port = int(item.find('td:nth-child(3)').text())
yield Proxy(host=host, port=port)
if __name__ == '__main__':
crawler = XicidailiCrawler()
for proxy in crawler.crawl():
print(proxy)
|
Affirm/suds-jurko | tests/test_wsse.py | Python | lgpl-3.0 | 1,605 | 0.000623 | # -*- coding: utf-8 -*-
# This program is free software; you can redistribute it and/or modify
# it under the terms of the (LGPL) GNU Lesser General Public License as
# published by the Free Software Foundation; either version 3 of the
# L | icense, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library Lesser General Public License for more detai | ls at
# ( http://www.gnu.org/licenses/lgpl.html ).
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# written by: Jurko Gospodnetić ( jurko.gospodn... |
nyrocron/tracking-server | tracker/migrations/0001_initial.py | Python | mit | 2,159 | 0.00139 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Create... | ('key', models.CharField(max_length=32, primary_key=True, serialize=False)),
('user', models.OneToOneField(to=settings.AUTH_USER_MODEL)),
],
options={
},
bases=(models.Model,),
),
migrations.CreateModel(
name='TrackingS... | ime', models.DateTimeField()),
('end_time', models.DateTimeField(null=True, blank=True)),
('active', models.BooleanField(default=True)),
('viewkey', models.CharField(max_length=32)),
('is_cleaned', models.BooleanField(default=False)),
('use... |
chadgates/locmaster | mylocation/migrations/0005_auto_20160216_1419.py | Python | bsd-3-clause | 1,700 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-02-16 14:19
from __future__ import unicod | e_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mylocation', '0004_delete_portterminal'),
]
operations = [
migrations.RenameField(
model_name='worldborder',
old_name='geom',
new_name='mpoly... | x_length=2, verbose_name='FIPS Code'),
),
migrations.AlterField(
model_name='worldborder',
name='iso2',
field=models.CharField(max_length=2, verbose_name='2 Digit ISO'),
),
migrations.AlterField(
model_name='worldborder',
name='... |
fcaneto/can_i_beat_redis | gen_test.py | Python | mit | 506 | 0.005929 | import time
import random
import uuid
def timefunc(f):
def f_timer(*args, **kwargs):
start = time.time()
result = f(*args, **kwargs | )
end = time.time()
return result
return f_timer
with open("write.test", 'w') as sample:
for _ in range(10000):
sample.write("%s %s\n" % (random.randint(1000000, 9999999), random.randint(1, 99)))
# redis_server = redis.StrictRedis(host='localhost', port=6379, db=0)
# pipe = redis_ser... | line(transaction=False)
|
pjdelport/django | django/core/management/sql.py | Python | bsd-3-clause | 7,970 | 0.003764 | from __future__ import unicode_literals
import codecs
import os
import re
from django.conf import settings
from django.core.management.base import CommandError
from django.db import models
from django.db.models import get_models
def sql_create(app, style, connection):
"Returns a list of the CREATE TABLE SQL sta... | e associated Django
models and are in INSTALLED_APPS will be included.
"""
if only_django:
tables = connection.introspection.django_table_names(only_existing=True) |
else:
tables = connection.introspection.table_names()
seqs = connection.introspection.sequence_list() if reset_sequences else ()
statements = connection.ops.sql_flush(style, tables, seqs)
return statements
def sql_custom(app, style, connection):
"Returns a list of the custom table modifyi... |
pyxll/pyxll-examples | multiprocessing/running_object_table.py | Python | unlicense | 5,066 | 0.001184 | """
Example code to show how to use the 'Running Object Table' to find the right
Excel Application object to use from a child process.
When spawning a child process (or processes) from Excel sometimes it's
useful to be able to get a reference to the Excel Applciation object
corresponding to the parent process (to writ... | run in a child process of the main Excel process.
"""
# Initialize logging (since we're now running outside of Excel this isn't done for us).
logging.basicConfig(filename=logfile, level=logging.INFO)
log = logging.getLogger(__name__)
log.info("Child process %d starting" % os.getpid())
try:
... | xl_app = get_xl_app()
# Write to the target cell in the parent Excel.
cell = xl_app.Range(target_address)
message = "Child process %d is running..." % os.getpid()
cell.Value = message
# Run for a few seconds updating the value periodically
for i in range(300):
... |
nextgis/nextgisweb_log | nextgisweb_log/log_handler.py | Python | gpl-2.0 | 998 | 0.003006 | import logging
from .model import LogEntry, LogLevels
class NGWLogHandler(logging.Handler):
"""
Simple standard log handler for nextgisweb_lo | g
"""
def __init__(self, level=LogLevels.default_value, component=None, group=None):
logging.Handler.__init__(self, level=level)
self.component = component
self.group = group
def emit(self, record):
self.format(record)
if record.exc_info:
record. | exc_text = logging._defaultFormatter.formatException(record.exc_info)
else:
record.exc_text = None
# Insert log record:
log_entry = LogEntry()
log_entry.component = self.component
log_entry.group = self.group
log_entry.message_level = record.levelno
... |
TobbeTripitaka/src | user/zhiguang/Mfdlsrtm.py | Python | gpl-2.0 | 715 | 0.029371 | #!/usr/bin/python
'F | inite difference RTM as a linear operator'
import os, sys, tempfile, subprocess
import rsf.prog, rsf.path
# Madagascar bin directory
bindir=os.path.join(rsf.prog.RSFROOT,'bin')
# Madagascar | DATAPATH
datapath=rsf.path.datapath().rstrip('/')
# Madagascar commands
cp=os.path.join(bindir,'sfcp')
rtm=os.path.join(bindir,'sfmpifdlsrtm')
# Random files for input and output
inpd,inpfile=tempfile.mkstemp(dir=datapath)
outd,outfile=tempfile.mkstemp(dir=datapath)
p=subprocess.Popen([cp],stdout=inpd, close_fds=Tru... |
riccardocagnasso/useless | setup.py | Python | mit | 576 | 0 | from setuptools import setup, find_ | packages
print(find_packages('src'))
setup(
name="Useles2s",
version='0.1',
author='Riccardo Cagnasso',
author_email="[email protected]",
description='Useless is useless. Oh yeah, and parses bit and pieces' +
| 'of ELF and PE dynamic libraries',
license="MIT",
packages=find_packages('src'),
package_dir={'useless': 'src/useless/',
'useless.elf': 'src/useless/elf/'},
scripts=['src/usls.py'],
install_requires=[
'cached_property',
'prettytable'])
|
ArneBab/gamification-engine | gengine/metadata.py | Python | mit | 1,091 | 0.021082 | from sqlalchemy.orm.session import Session, sessionmaker
import transaction
from sqlalchemy.orm.scoping import scoped_session
from zope.sqlalchemy.datamanager import ZopeTransactionExtension
from sqlalchemy.ext.declarative.api import declarative_base
class MySession(Session):
"""This allow us to use the flask-admi... | (sessionmaker(e | xtension=ZopeTransactionExtension(), class_=MySession))
Base=None
def init_declarative_base(override_base=None):
global Base
if override_base:
Base=override_base
else:
Base = declarative_base()
def init_db(engine):
DBSession.configure(bind=engine)
Base.metadata.bind = eng... |
monetate/sqlalchemy | lib/sqlalchemy/sql/sqltypes.py | Python | mit | 111,751 | 0 | # sql/sqltypes.py
# Copyright (C) 2005-2021 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: https://www.opensource.org/licenses/mit-license.php
"""SQL specific types.
"""
import codecs
import datetime as dt
import decimal
imp... | onnect what the
string-returning behavior of character-based datatypes is.
This is the default value for DefaultDialect.unicode_returns under
Python 2.
This may be applied to the
:attr:`.DefaultDialect.returns_unicode_strings` attribute under
Python 2 only. The value ... | .. versionadded:: 1.4
.. deprecated:: 1.4 This value will be removed in SQLAlchemy 2.0.
""",
)
@util.deprecated_params(
convert_unicode=(
"1.3",
"The :paramref:`.String.convert_unicode` parameter is deprecated "
"and will be removed in a future r... |
DarkFenX/Phobos | miner/fsd_lite.py | Python | gpl-3.0 | 3,930 | 0.002545 | #===============================================================================
# Copyright (C) 2014-2019 Anton Vorobyov
#
# This file is part of Phobos.
#
# Phobos 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 ... | n None
| return m.group('fname')
def __check_cache(self, resource_path):
"""Check if file is actually SQLite database and has cache table."""
file_path = self._resbrowser.get_file_info(resource_path).file_abspath
try:
dbconn = sqlite3.connect(file_path)
c = dbconn.cursor()
... |
jucimarjr/IPC_2017-1 | lista05/lista05_lista02_questao55.py | Python | apache-2.0 | 1,372 | 0.002208 | # encoding: utf-8
# --------------------------------------------------------------------------
# Introdução a Programação de Computadores - IPC
# Universidade do Estado do Amazonas - UEA
# Prof. Jucimar Jr
# ULISSES ANTONIO ANTONINO DA COSTA - 1515090555
# TIAGO FERREIRA ARANHA - 1715310047
# VÍTOR SIMÕES AZEVEDO - 171... | rima a seqüência a seguir e o resultado.
# N! / 0! – (N-1)! / 2! + (N-2)! / 4! – (N-3)! / 6! + ... 0! / (2N)!
# --------------------------------------------------------------------------
numero1 = int(input("Informe inteiro: "))
numero2 = 0
operacao = 1
resultado = 0
sequencia = ""
while numero1 >= 0:
i = 1
... |
fatorial2 = 1
while i <= numero2:
fatorial2 = fatorial2 * i
i += 1
resultado = resultado + (fatorial1 / fatorial2) * operacao
if operacao == 1:
sequencia = sequencia + " + " + str(numero1) + "!/" + str(numero2) + "!"
else:
sequencia = sequencia + " - " + str(numero... |
0xkag/tornado | tornado/iostream.py | Python | apache-2.0 | 59,061 | 0.000203 | #!/usr/bin/env python
#
# Copyright 2009 Facebook
#
# 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... | ault
``read_chunk_size`` to 64KB.
"""
self.io_loop = io_loop or ioloop.IOLoop.current()
self.max_buffer_size = max_buffer_size or 104857600
# A chunk size that is too close to max_buffer_size can cause
# spurious failures.
self.read_chunk_ | size = min(read_chunk_size or 65536,
self.max_buffer_size // 2)
self.max_write_buffer_size = max_write_buffer_size
self.error = None
self._read_buffer = collections.deque()
self._write_buffer = collections.deque()
self._read_buffer_size = 0
... |
pacoqueen/cican | utils/mapa.py | Python | gpl-3.0 | 6,423 | 0.009199 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# TODO: PORASQUI: BUG: Cerrar la ventana no detiene el GMapCatcher y se queda
# como un proceso de fondo en espera bloqueante... Ni atiende al Ctrl+C
# siquiera.
import sys, os.path
dirfichero = os.path.realpath(os.path.dirname(__file__))
if os.path.realpath(os.path.cur... | # Es la conf. por defecto. Ver
# utils/gmapatcher/map.py para más detalles.
gmc.mapLogging.init_logging(logging_path)
gmc.log.info("Starting %s version %s." % (gmc.NAME, gmc.VERSION))
self.gmcw = gmc.MainWindow(config_path = conf_path)
s... | TODO: PORASQUI: Hacer un traslado de escala entre el zoom de
# GMC que va -creo- desde -2 (cerca) a más de 10 (lejos) al de
# OSM, que va al contrario y 13 es cerca. Ver las "constantes"
# definidas en cada caso (MAX_ZOOM_no_sé_qué en GMC).
self.osm = self.gmcw.containe... |
twistedretard/LaserSimulatedSecurityTurret | src/streaming/server.py | Python | mit | 272 | 0.007353 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import subprocess
running = os.system("nc -u -l -p 5001 | mpl | ayer -cache 1024 -")
#subprocess.check_call('/opt/vc/bin/raspivid -n -w 800 -h 600 -fps 24 -t 0 -o - | socat - udp-sendto:' + '129.16.194.248' + ':5001' | )
|
divio/django-shop | shop/cascade/segmentation.py | Python | bsd-3-clause | 317 | 0.003155 | from cmsp | lugin_cascade.segmentation.mixins import EmulateUserModelMixin, EmulateUserAdminMixin
from shop.admin.customer import CustomerProxy
class EmulateCustomerModelMixin(EmulateUserModelMixin):
UserModel = CustomerProxy
class EmulateCustomerA | dminMixin(EmulateUserAdminMixin):
UserModel = CustomerProxy
|
zhaochl/python-utils | verify_code/Imaging-1.1.7/build/lib.linux-x86_64-2.7/ImtImagePlugin.py | Python | apache-2.0 | 2,203 | 0.003177 | #
# The Python Imaging Library.
# $Id$
#
# IM Tools support for PIL
#
# history:
# 1996-05-27 fl Created (read 8-bit images only)
# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.2)
#
# Copyright (c) Secret Labs AB 1997-2001.
# Copyright (c) Fredrik Lundh 1996-2001.
#
# See the README file for informatio... | if k == "width":
xsize = int(v)
self.size = xsize, ysize
| elif k == "height":
ysize = int(v)
self.size = xsize, ysize
elif k == "pixel" and v == "n8":
self.mode = "L"
#
# --------------------------------------------------------------------
Image.register_open("IMT", ImtImageFile)
#
# no ... |
Nahnja/PyIoC | pyioc.py | Python | mit | 730 | 0.005479 | from functools import partial
from types import MethodType
class IoCList(list):
def __getitem__(self, cls):
return sorted(
[item for item in self if cls in item.mro()],
key=lambda item: item.mro().index(cls)
)[0]
def inject_dependency(self, **kwargs):
def decora... | function
def method(*args, **kwargs):
| return partial(fun, **keywords)(*args, **kwargs)
return method
return decorator
|
fluo-io/fluo-deploy | lib/muchos/config/ec2.py | Python | apache-2.0 | 9,189 | 0 | #
# 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 us... | "Only hvm architecture is supported!".format(instance_type)
)
def insta | nce_tags(self):
retd = {}
if self.has_option("ec2", "instance_tags"):
value = self.get("ec2", "instance_tags")
if value:
for kv in value.split(","):
(key, val) = kv.split(":")
retd[key] = val
return retd
def ini... |
mitodl/ccxcon | webhooks/models.py | Python | agpl-3.0 | 992 | 0 | """
Webhook models.
"""
import uuid
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
class ActiveManager(models.Manager):
"""
Manager which returns only enabled webhooks.
"""
def get_quer | yset(self, *args, **kwargs):
"""
Returns only enabled webhooks.
"""
# pylint: disable=super-on-old-class
qs = super(ActiveManager, self).get_queryset(*args, **kwargs)
return qs.filter(enabled=True)
def get_uuid_hex():
"""
Get uuid hex. Required to serialize meth... | ossibly outgoing webhooks.
"""
url = models.URLField()
secret = models.CharField(max_length=32, default=get_uuid_hex)
enabled = models.BooleanField(default=True)
objects = models.Manager()
active = ActiveManager()
def __str__(self):
return self.url
|
biomodels/BIOMD0000000199 | setup.py | Python | cc0-1.0 | 377 | 0.005305 | from setuptools import setup, find_packages
setup(name='BIOMD0000000199',
version=20140916,
description='BIOMD0000000199 from BioModels',
url='http://www.ebi.ac.uk/biomodels-main | /BIOMD0000000199',
maintainer='Stanley Gu',
maintainer_url='[email protected]',
packages=find_packages(),
package_data={'': [' | *.xml', 'README.md']},
) |
Pistachitos/Sick-Beard | sickbeard/history.py | Python | gpl-3.0 | 2,727 | 0.006234 | # Author: Nic Wolfe <[email protected]>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of Sick Beard.
#
# Sick Beard 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 Lice... | showid, season, episode, quality, resource, provider])
def logSnatch(searchResult):
for curEpObj in searchResult.episodes:
showid = int(curEpObj.show.tvdbid)
season = int(curEpObj.season)
episode = int(curEpObj.episode)
qualit | y = searchResult.quality
providerClass = searchResult.provider
if providerClass != None:
provider = providerClass.name
else:
provider = "unknown"
action = Quality.compositeStatus(SNATCHED, searchResult.quality)
resource = searchResult.name
_log... |
pheanex/fail2ban | setup.py | Python | gpl-2.0 | 5,567 | 0.027124 | #!/usr/bin/python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: t -*-
# vi: set ft=python sts=4 ts=4 sw=4 noet :
# This file is part of Fail2Ban.
#
# Fail2Ban 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 So... | st_suite': "fail2ban.tests.utils.gatherTests",
'use_2to3': True,
}
else:
setup_extra = {}
data_files_extra = []
if os.path.exists('/var/run'):
# if we are on the system with /var/run -- we are to u | se it for having fail2ban/
# directory there for socket file etc
data_files_extra += [('/var/run/fail2ban', '')]
# Get version number, avoiding importing fail2ban.
# This is due to tests not functioning for python3 as 2to3 takes place later
exec(open(join("fail2ban", "version.py")).read())
setup(
name="fail2ban",
... |
odyssey4me/monitoring-scripts | check_virsh_domains.py | Python | apache-2.0 | 18,638 | 0.004346 | #!/usr/bin/python
#
# Script to determine the performance statistics and other information
# related to libvirt guests
# https://github.com/odyssey4me/monitoring-scripts
#
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may o... | 'if_%s_tx_bytes' % if_num, int(if_stats[4]))
setattr(self, 'if_%s_tx_packets' % if_num, int(if_stats[5]))
setattr(self, 'if_%s_tx_errors' % if_num, int(if_stats[6]))
setattr(self, 'if_%s_tx_drop' % if_num, int(if_stats[7]))
# Compile the block device stats fo... | for blk_dev in blk_devices:
#Get the block device stats
blk_stats = vir_dom.blockStats(blk_dev)
# Set class attributes using the device name
setattr(self, 'blk_%s_rd_req' % blk_dev, int(blk_stats[0]))
setattr(self, 'blk_%s_rd_by... |
hryamzik/ansible | lib/ansible/modules/cloud/azure/azure_rm_sqlserver.py | Python | gpl-3.0 | 10,749 | 0.002233 | #!/usr/bin/python
#
# Copyright (c) 2017 Zim Kalinowski, <[email protected]>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | s):
"""Main module execution method" | ""
for key in list(self.module_arg_spec.keys()) + ['tags']:
if hasattr(self, key):
setattr(self, key, kwargs[key])
elif kwargs[key] is not None:
if key == "location":
self.parameters.update({"location": kwargs[key]})
el... |
alex/sentry | sentry/templatetags/sentry_admin_helpers.py | Python | bsd-3-clause | 965 | 0 | """
sentry.templatetags.sentry_admin_helpers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import datetime
from django import template
from django.db.models import Sum
register = template.Library()
@r... | gte=datetime.datetime.now() - datetime.timedelta(days=30),
).values_list('project').annotate(
total_events=Sum('times_seen'),
).values_list('project', 'total_events'))
for project in project_list:
avg = results.get(project.pk, 0) / 30.0
if avg < 5:
avg = '%.1f' % avg
... | = int(avg)
yield project, avg
|
rcbops/quantum-buildpackage | quantum/plugins/cisco/ucs/cisco_ucs_inventory_configuration.py | Python | apache-2.0 | 1,019 | 0 | """
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2011 Cisco Systems, 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.ap... | KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
# @author: Sumit Naiksatam, Cisco Systems, Inc.
#
"""
import os
from quantum.common.config import find_config_file
from quantum.plugins.cisco.common import cisco_configparser... | None, "ucs_inventory.ini")
CP = confp.CiscoConfigParser(CONF_FILE)
INVENTORY = CP.walk(CP.dummy)
|
wojtask/CormenPy | test/test_chapter16/test_textbook16_2.py | Python | gpl-3.0 | 1,705 | 0.002346 | import random
from unittest import TestCase
from hamcrest import *
from array_util import get_random_array
from chapter16.textbook16_2 import fractional_knapsack
from datastructures.array import Array
from util import between
def part_item_value(item_partial_weight, item_total_weight, item_value):
return item_p... | m_value
def fractional_knapsack_heuristic(w, v, W, i=1):
if i == w.length:
return part_item_value(min(w[i], W), w[i], v[i])
value_no_item = frac | tional_knapsack_heuristic(w, v, W, i + 1)
value_half_item = part_item_value(min(w[i] // 2, W), w[i], v[i]) + \
fractional_knapsack_heuristic(w, v, W - min(w[i] // 2, W), i + 1)
value_full_item = part_item_value(min(w[i], W), w[i], v[i]) + \
fractional_knapsack_heuristic(w, v, W - min(w[i], W), i... |
sserrot/champion_relationships | venv/Lib/site-packages/notebook/tests/selenium/conftest.py | Python | mit | 4,894 | 0.000409 | import json
import nbformat
from nbformat.v4 import new_notebook, new_code_cell
import os
import pytest
import requests
from subprocess import Popen
import sys
from tempfile import mkstemp
from testpath.tempdir import TemporaryDirectory
import time
from urllib.parse import urljoin
from selenium.webdriver import Firefo... | om .utils import Notebook
pjoin = os.path.join
def _wait_for_server(proc, info_file_path):
"""Wait 30 seconds for the notebook server to start"""
for i in range(300):
if proc.poll() is not None:
raise RuntimeError("Notebook server failed to start")
if os.path.exists(info_f | ile_path):
try:
with open(info_file_path) as f:
return json.load(f)
except ValueError:
# If the server is halfway through writing the file, we may
# get invalid JSON; it should be ready next iteration.
pass
... |
cklb/PyMoskito | pymoskito/mpl_settings.py | Python | bsd-3-clause | 1,697 | 0.000589 | import logging
import matplotlib as mpl
from .tools import get_figure_size
_ | logger = logging.getLogger("mpl_settings")
orig_settings = {**mpl.rcParams}
latex_settings = {
# change this if using contex, xetex or lualatex
"pgf.texsystem": "pdflatex",
# use LaTeX to write all text
"text.usetex": True,
'font.family': 'lmodern',
# blank entries should cause plots to inherit... | onts from the document
# "font.serif": [],
# "font.sans-serif": [],
# "font.monospace": [],
# "text.fontsize": 11,
"legend.fontsize": 9, # Make the legend/label fonts a little smaller
"xtick.labelsize": 9,
"ytick.labelsize": 9,
"figure.figsize": get_figure_size(1), # default fig size o... |
rcoup/traveldash | traveldash/mine/views.py | Python | bsd-3-clause | 7,758 | 0.001547 | import json
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.template.response import TemplateResponse
from django.views.decorators.cache import cache_control
from django.views.decorators.vary import vary_on_cookie
from django.views.generic import DeleteView
from django.contrib.auth.deco... | lookup
geoip = GeoIP().geos(request.META['REMOTE_ADDR'])
if geoip:
initial['city'] = City.objects.distance(geoip).order_by('-distance')[0]
form = DashboardForm(initial=initial)
| route_formset = RouteFormSet(instance=Dashboard())
context = {
'form': form,
'route_formset': route_formset,
'title': 'New Dashboard',
'stopFusionTableId': settings.GTFS_STOP_FUSION_TABLE_ID,
'city_data': json.dumps(City.objects.get_map_info()),
}
return TemplateRes... |
anhstudios/swganh | data/scripts/templates/object/tangible/ship/crafted/weapon/shared_quick_shot_upgrade_mk4.py | Python | mit | 484 | 0.045455 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXA | MPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/ship/crafted/weapon/shared_quick_shot_upgrade_mk4.iff"
result.attribute_template_id = 8
result.stfName("space_crafting_n","quick_shot_upgrade_mk4")
#### BEGIN MODIFICATIONS ####
#### END MO | DIFICATIONS ####
return result |
heartsucker/securedrop | securedrop/alembic/versions/2d0ce3ee5bdc_added_passphrase_hash_column_to_.py | Python | agpl-3.0 | 1,753 | 0.002282 | """added passphrase_hash column to journalists table
Revision ID: 2d0ce3ee5bdc
Revises: fccf57ceef02
Create Date: 2018-06-08 15:08:37.718268
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2d0ce3ee5bdc'
down_revision = 'fccf57ceef02'
branch_labels = None
depe... | load it from a temp table
op.rename_table('journalists', 'journalists_tmp')
op.create_table( | 'journalists',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('username', sa.String(length=255), nullable=False),
sa.Column('pw_salt', sa.Binary(), nullable=True),
sa.Column('pw_hash', sa.Binary(), nullable=True),
sa.Column('is_admin', sa.Boolean(), nullable=True),
... |
Letractively/aha-gae | aha/widget/tests/test_fields.py | Python | bsd-3-clause | 5,382 | 0.026756 | # -*- coding: utf-8 -*-
from unittest import TestCase
import logging
log = logging.getLogger(__name__)
from formencode import validators, Invalid
from nose.tools import *
import formencode
from coregae.widget.field import *
class TestBasefield(TestCase):
def test_basefield(self):
"""
Test for ... | assert_true( 'name = "foo"' in body)
as | sert_true( 'id = "AB1234"' in body)
body = bf.render_body(value = 'VALUESTRING')
assert_true("VALUESTRING" in body)
bf.title = 'THETITLE'
assert_true("THETITLE" in bf.get_title())
def test_validate(self):
"""
Test for MediaHandler, validation
"""
v... |
jscn/django | tests/logging_tests/tests.py | Python | bsd-3-clause | 18,252 | 0.001041 | # -*- coding:utf-8 -*-
from __future__ import unicode_literals
import logging
import warnings
from admin_scripts.tests import AdminScriptTestCase
from django.conf import settings
from django.core import mail
from django.core.files.temp import NamedTemporaryFile
from django.db import connection
from django.test impor... | thod
def setUpClass(cls):
super(SetupDefaultLoggingMixin, cls).setUpClass()
cls._logging = settings.LOGGING
logging.config.dictConfig(DEFAULT_LOGGING)
@classmethod
def tearDownClass(cls):
super(SetupDefaultLoggingMixin, cls).tearDownClass()
logging.config.dictConfig(... | test_django_logger(self):
"""
The 'django' base logger only output anything when DEBUG=True.
"""
self.logger.error("Hey, this is an error.")
self.assertEqual(self.logger_output.getvalue(), '')
with self.settings(DEBUG=True):
self.logger.error("Hey, this is an... |
adaptive-learning/robomission | backend/learn/tests/locustfile.py | Python | gpl-3.0 | 3,918 | 0.000766 | """Configuration for a load testing using Locust.
To start load testing, run `make server` and `make test-load`.
"""
import random
from json.decoder import JSONDecodeError
from django.urls import reverse
from locust import HttpLocust, TaskSet, task
class SolvingTaskBehavior(TaskSet):
"""Describes interaction of ... | sponse = self.client.get('/learn/api/tasks/')
self.save_cookies(response)
self.task_names = [task['name'] for task in response.json()]
def save_action_urls(self):
"""The session and lazy user is created. Now tasks can be solved.
"""
user_response = self.client.get('/learn/ap... | student_url = user_response.json()['student']
student_response = self.client.get(student_url)
self.save_cookies(student_response)
self.action_urls['start_task'] = student_response.json()['start_task']
self.action_urls['edit_program'] = student_response.json()['edit_program']
... |
HydrelioxGitHub/home-assistant | homeassistant/components/neato/switch.py | Python | apache-2.0 | 3,290 | 0 | """Support for Neato Connected Vacuums switches."""
import logging
from datetime import timedelta
import requests
from homeassistant.const import STATE_OFF, STATE_ON
from homeassistant.helpers.entity import ToggleEntity
from homeassistant.components.neato import NEATO_ROBOTS, NEATO_LOGIN
_LOGGER = | logging.getLo | gger(__name__)
DEPENDENCIES = ['neato']
SCAN_INTERVAL = timedelta(minutes=10)
SWITCH_TYPE_SCHEDULE = 'schedule'
SWITCH_TYPES = {
SWITCH_TYPE_SCHEDULE: ['Schedule']
}
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Neato switches."""
dev = []
for robot in hass.dat... |
mvendra/mvtools | tests/convcygpath_test.py | Python | mit | 3,080 | 0.007143 | #!/usr/bin/env python3
import os
import shutil
import unittest
from unittest import mock
from unittest.mock import patch
import mvtools_test_fixture
import convcygpath
import get_platform
class ConvCygPathTest(unittest.TestCase):
def setUp(self):
v, r = self.delegate_setUp()
if not v:
... | vtools_envvars.mvtools_envvar_read_cygwin_install_path", return_value=(False, "error-message")):
self.assertEqual(convcygpath.convert_cygwin_path_to_win_path("/home/user | /folder"), "C:/cygwin/home/user/folder")
with mock.patch("mvtools_envvars.mvtools_envvar_read_cygwin_install_path", return_value=(True, "D:/cygwin_custom_install_folder/cygwin")):
self.assertEqual(convcygpath.convert_cygwin_path_to_win_path("/home/user/folder"), "D:/cygwin_custom_install_fol... |
mpescimoro/stripp3r | lessonEntity.py | Python | gpl-3.0 | 1,603 | 0.007486 | __author__ = 'Paolo Bellagente'
# Documentation for this module.
#
# More details.
################################## DATABASE ##############################################
from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
impor... | start hour
hour = Column(TIME)
# lesson's day of the week coded form 0 to 6 where 0 is monday and 6 is sunday.
day = Column(INTEGER)
subject = Column(VARCHAR(200))
rooms = Column(VARCHAR(30))
address = Column(VARCHAR(50))
| teacher = Column(VARCHAR(50))
def __init__(self):
self.teacher = ''
# persist the entity into the database
def persist(self):
Session = sessionmaker(bind=engine)
session = Session()
session.add(self)
session.commit()
session.close()
# todo: create new en... |
PisiLinux-PyQt5Port/pisilinux-desktop-services | pds/quniqueapp.py | Python | gpl-2.0 | 2,838 | 0.002468 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Pardus Desktop Services
# Copyright (C) 2010, TUBITAK/UEKAE
# 2010 - Gökmen Göksel <gokmen:pardus.org.tr>
# 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 Founda... |
def exec_(self):
if self.readyToRun:
# Let Ctrl+C work ;)
signal.signal(signal.SIGINT, signal.SIG_DFL)
QApplication.exec_()
def cleanup(self):
self.control.removeServer(self.catalog)
def sendToInstance(self, data = ''):
socket = QLocalSocket()
... | et.write(data)
socket.flush()
socket.close()
return True
return False
def onControlConnect(self):
self.socket = self.control.nextPendingConnection()
self.socket.readyRead.connect(self.onControlRequest)
def onControlRequest(self):
request ... |
piedev/przepisnik | przepisnik/app.py | Python | apache-2.0 | 242 | 0 | #! | /usr/bin/env python
from mongoengine import connect
from flask import Flask
from api import blueprint as api
app = Flask(__name__)
app.register_blueprint(api)
connect('przepisnik001')
if __name__ == '__main__':
app.run(debug=True) | |
tomchristie/django | tests/gis_tests/tests.py | Python | bsd-3-clause | 3,659 | 0.00246 | import unittest
from django.core.exceptions import ImproperlyConfigured
from django.db import ProgrammingError
try:
from django.contrib.gis.db.backends.postgis.operations import PostGISOperations
HAS_POSTGRES = True
except ImportError:
HAS_POSTGRES = False
if HAS_POSTGRES:
class FakeConnection:
... | not expected to be called')
@unittest.skipUnless(HAS_POSTGRES, "The psycopg2 driver is needed for these tests")
class TestPostGISVersionCheck(unittest.TestCase):
"""
| The PostGIS version check parses correctly the version numbers
"""
def test_get_version(self):
expect = '1.0.0'
ops = FakePostGISOperations(expect)
actual = ops.postgis_lib_version()
self.assertEqual(expect, actual)
def test_version_classic_tuple(self):
expect = ... |
jruere/concurrent-iterator | concurrent_iterator/utils.py | Python | lgpl-3.0 | 246 | 0 | # vim: set fileencoding=utf-8
from decorator import deco | rator |
@decorator
def check_open(f, self, *args, **kwargs):
if self.closed:
raise ValueError("%s operation on closed Consumer" % f.__name__)
return f(self, *args, **kwargs)
|
Anderson0026/mapproxy | mapproxy/test/system/test_xslt_featureinfo.py | Python | apache-2.0 | 10,434 | 0.007284 | # This file is part of the MapProxy project.
# Copyright (C) 2010 Omniscale <http://omniscale.de>
#
# 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... | pected_req1 = ({'path': r'/service_a?LAYERs=a_one&SERVICE=WMS&FORMAT=image%2Fpng'
'&REQUEST=GetFeatureInfo&HEIGHT=200&CRS=EPSG%3A900913'
'&VERSION=1.3.0&BBOX=1000.0,400.0,2000.0,1400.0&styles='
'&WIDTH=200&QUERY_LAYERS... | {'body': fi_body1, 'headers': {'content-type': 'text/xml'}})
expected_req2 = ({'path': r'/service_b?LAYERs=b_one&SERVICE=WMS&FORMAT=image%2Fpng'
'&REQUEST=GetFeatureInfo&HEIGHT=200&SRS=EPSG%3A900913'
'&VERSION=1.1.1&BBOX=10... |
martinrusev/amonone | amon/templatetags/__init__.py | Python | mit | 155 | 0.012903 | # from django.t | emplate.base import add_to_builtins
# from amon.settings import AUTOLOAD_TAGS
# for tag in AUTOLOAD_TAGS:
# add_to_builtin | s(tag)
|
google/shopping-markup | plugins/cloud_utils/__init__.py | Python | apache-2.0 | 1,168 | 0.000856 | # coding=utf-8
# Copyright 2020 Google LLC..
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | , software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Copyright 2020 Google LLC
#
# Licensed under the Apache Lice... | apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# l... |
zhumengyuan/kallithea | kallithea/lib/vcs/backends/git/repository.py | Python | gpl-3.0 | 25,623 | 0.000702 | # -*- coding: utf-8 -*-
"""
vcs.backends.git.repository
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Git repository implementation.
:created_on: Apr 8, 2010
:copyright: (c) 2010-2011 by Marcin Kuzminski, Lukasz Balcerzak.
"""
import os
import re
import time
import urllib
import urllib2
import logging
import posix... | ate:
raise Reposito | ryError("Create should be set to True if src_url is "
"given (clone operation creates repository)")
try:
if create and src_url:
GitRepository._check_url(src_url)
self.clone(src_url, update_after_clone, bare)
return Rep... |
SaFi2266/odoo-rtl | website_rtl/models/ir_http.py | Python | agpl-3.0 | 1,637 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Odoo RTL support
# Copyright (C) 2014 Mohammed Barsi.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# publ... | stributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied w | arranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
############################... |
bincyber/beesly | beesly/__init__.py | Python | gpl-3.0 | 910 | 0.003297 | import sys
import os.path
from beesly._logging import structured_log
from beesly.config import ConfigError, initialize_config
from beesly.views import app, rlimiter
def create_app():
"""
Initializes the Flask application.
"""
structured_log(level='info', msg="Starting beesly...")
try:
s... | tical', msg="Failed to load configuration. Exiting...")
sys.exit(4)
# enable Swagger UI if running in DEV mode
if se | ttings["DEV"]:
app.static_folder = os.path.dirname(os.path.realpath(__file__)) + "/swagger-ui"
app.add_url_rule("/service/docs/<path:filename>", endpoint="/service/docs", view_func=app.send_static_file)
app.config.update(settings)
structured_log(level='info', msg="Successfully loaded configurat... |
anshulgarg324/calender | api/google.py | Python | gpl-2.0 | 2,438 | 0.005332 | """
This module handles the Google Signup for a new user
"""
from oauth2client import client
from django.contrib.auth.models import User
from django.shortcuts import redirect
from djan | go.shortcuts import render
from rest_framework.decorators import api_view, permission_classes
from rest_fra | mework.views import APIView
from rest_framework import authentication, permissions
from rest_framework.authtoken.models import Token
from models import GoogleData
import httplib2
import json
flow = client.flow_from_clientsecrets(
'./client_secrets.json',
scope='https://www.googleapis.com/auth/drive.m... |
PeerXu/reflector | server/app.py | Python | gpl-2.0 | 982 | 0.007128 | #!/usr/bin/env python2.7
from flask import Flask, make_response, render_template, request
import simplejson
app = Flask(__name__)
G = {
"cmds": [],
"outputs": {}
}
@app.route("/")
def index():
return render_template("index.html")
@app.route("/emit", methods=["POST"])
def emit():
G["cmds"].append(re... | "/cmd", methods=["GET"])
def cmd():
return '%s,%s' % (len(G["cmds"])-1, G["cmds"][-1])
@app.route("/result", methods=["POST"])
def result():
seq, data = request.data.split(',', 1)
seq = int(seq)
if seq < len(G["cmds"]) and seq not in G["outputs"]:
G["outputs"][int(seq)] = data
| return ''
@app.route("/display", methods=["GET", "POST"])
def display():
result = []
for k, v in enumerate(G["cmds"][-10:]):
result.append([k, G["cmds"][k], G["outputs"].get(k, "<not response yet>")])
return simplejson.dumps(result)
if __name__ == '__main__':
app.run(debug=True, port=4444)
|
MD-Studio/MDStudio | components/lie_echo/lie_echo/__main__.py | Python | apache-2.0 | 299 | 0.006689 | import sys
import os
modulepath = os.path.ab | spath(os.path.join(os.path.dirname(__file__), '../'))
if modulepath not in sys.path:
sys.path.insert(0, modulepath)
from mdstudio.runner import main
from lie_echo.application import EchoComponent
if __name__ == '__main__':
main(EchoCompone | nt)
|
rht/zulip | zerver/webhooks/lidarr/tests.py | Python | apache-2.0 | 4,458 | 0.001803 | from zerver.lib.test_classes import WebhookTestCase
class LidarrHookTests(WebhookTestCase):
STREAM_NAME = "lidarr"
URL_TEMPLATE = "/api/v1/external/lidarr?api_key={api_key}&stream={stream}"
WEBHOOK_DIR_NAME = "lidarr"
def test_lidarr_test(self) -> None:
"""
Tests if lidarr test payloa... | me Around
* Rock With You
* Earth Song
* She’s Out of My Life
* D.S.
* Bad
* Money
* I Just Can’t Stop Loving You
* Man in the Mirror
* Come Together
* Thriller
* You Are Not Alone
* Beat It
* Childhood (theme from “Free Willy 2”)
[and 10 more tracks(s)]
""".strip() |
self.check_webhook(
"lidarr_tracks_imported_upgrade_over_limit", expected_topic, expected_message
)
|
gena/earthengine-api | python/ee/cli/eecli.py | Python | apache-2.0 | 2,385 | 0.007966 | #!/usr/bin/env python
"""Executable for the Earth Engine command line interface.
This executable starts a Python Cmd instance to receive and process command
line input entered by the user. If the executable is invoked with some
command line arguments, the Cmd is launched in the one-off mode, where
the provided argumen... | # errors, and print the error message without the irrelevant local
# stack trace. (Individual commands may also catch EEException if
# they want to be able to continue despite errors.)
try:
dispatcher.run(args, config)
except ee.EEException as e:
print(e)
sys.exit(1)
if __na | me__ == '__main__':
main()
|
jnez71/lqRRT | demos/lqrrt_ros/behaviors/boat.py | Python | mit | 3,195 | 0.005008 | """
Constructs a planner that is good for boating around!
"""
from __future__ import division
import numpy as np
import numpy.linalg as npl
from params import *
import lqrrt
################################################# DYNAMICS
magic_rudder = 8000
focus = None
def dynamics(x, u, dt):
"""
Returns next ... | u = B | .dot(np.min(ratios) * thrusts)
# M*vdot + D*v = u and pdot = R*v
xdot = np.concatenate((R.dot(x[3:]), invM*(u - D*x[3:])))
# First-order integrate
xnext = x + xdot*dt
return xnext
################################################# POLICY
kp = np.diag([250, 250, 2500])
kd = np.diag([5, 5, 0.001... |
GoogleCloudPlatform/plspm-python | tests/test_regression_metric.py | Python | gpl-3.0 | 7,199 | 0.005556 | #!/usr/bin/python3
#
# Copyright (C) 2019 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 3 of the License, or
# (at your option) any later version.
#
# This program... | ,plspm_calc.goodness_of_fit() | )
plspm_calc_path = Plspm(satisfaction, config, Scheme.PATH)
expected_outer_model_path = util.sort_cols(
pd.read_csv("file:tests/data/satisfaction.outer-model-path.csv", index_col=0).drop(["block"],
axis=1)).sort... |
bdell/pyPWA | pythonPWA/utilities/dataSimulator.py | Python | mit | 4,102 | 0.023403 | from random import random
from pythonPWA.fileHandlers.gampReader import gampReader
from pythonPWA.model.intensity import intensity
class dataSimulator(object):
"""description of class"""
def __init__(self,
mass=1010.,
waves=[],
resonances=[],
... | 1.:
# print"random filter:",(float(wn)/b)*100.,"%"
# lastPercent=(float(wn)/b)*100.
if wList[wn]>random(): #random()=random float on [0.0, 1.0)
#print"writing event",wn,"to",outputRawGampFile.name
inputGampEvents[wn].raw=True
... | ])
for rawGamps in rawGampEvents:
rawGamps.writeGamp(outputRawGampFile)
#lastPercent=0.
#c=float(len(inputGampEvents))
#acceptedGampEvents=[]
#passing through acceptance filter
#print"passing all events through acceptance filter"
... |
openstack/tempest | tempest/api/compute/floating_ips/test_list_floating_ips_negative.py | Python | apache-2.0 | 1,663 | 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... | tiveTestJSON(base.BaseFloatingIPsTest):
"""Negative tests of floating ip detail
Negative tests of floating ip detail with compute microversion less
than 2.36.
"""
max | _microversion = '2.35'
@decorators.attr(type=['negative'])
@decorators.idempotent_id('7ab18834-4a4b-4f28-a2c5-440579866695')
def test_get_nonexistent_floating_ip_details(self):
"""Test getting non existent floating ip should fail"""
# Creating a non-existent floatingIP id
if CONF.se... |
TissueMAPS/TmLibrary | tmlib/tools/base.py | Python | agpl-3.0 | 24,061 | 0.000249 | # TmLibrary - TissueMAPS library for distibuted image analysis routines.
# Copyright (C) 2016 Markus D. Herrmann, University of Zurich and Robin Hafen
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Softwa... | min and max
'''
logger.info(
'calculate min/max for objects of type "%s" and feature "%s"',
mapobject_type_name | , feature_name
)
with tm.utils.ExperimentSession(self.experiment_id) as session:
mapobject_type = session.query(tm.MapobjectType.i |
hail-is/hail | hail/python/hailtop/batch/docs/cookbook/files/run_gwas.py | Python | mit | 1,789 | 0.001677 | import argparse
import hail as hl
def run_gwas(vcf_file, phenotypes_file, output_file):
table = hl.import_table(phenotypes_file, impute=True).key_by('Sample')
hl.import_vcf(vcf_file).write('tmp.mt')
mt = hl.read_matrix_t | able('tmp.mt')
mt = mt.annotate_cols(pheno=table[mt.s])
mt = hl.sample_qc(mt)
mt = mt.filter_cols((mt.sample_qc.dp_stats.mean >= 4) & (mt.sample_ | qc.call_rate >= 0.97))
ab = mt.AD[1] / hl.sum(mt.AD)
filter_condition_ab = ((mt.GT.is_hom_ref() & (ab <= 0.1))
| (mt.GT.is_het() & (ab >= 0.25) & (ab <= 0.75))
| (mt.GT.is_hom_var() & (ab >= 0.9)))
mt = mt.filter_entries(filter_condition_ab)
mt = hl.... |
wsricardo/mcestudos | treinamento-webScraping/raspa/geo03.py | Python | gpl-3.0 | 602 | 0.008306 | from geolocation.main import GoogleMaps
google_maps = GoogleMaps(api_key='AIzaSyBCksh0B58c_C6k_Epm2k1ZQb-YF6kA6SE')
lat = -2.500044
lng = -44.288093
location = google_maps.search(lat=lat, lng=lng)
my_location = location.first()
if my_l | ocation.cit | y: print(my_location.city.decode('utf-8'))
if my_location.route: print(my_location.route.decode('utf-8'))
if my_location.street_number: print(my_location.street_number)
if my_location.postal_code: print(my_location.postal_code)
print(my_location.country)
print(my_location.country_shortcut)
print(my_location.f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.