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 |
|---|---|---|---|---|---|---|---|---|
mtils/ems | ems/qt4/gui/notification/balloon_form_notifier.py | Python | mit | 2,764 | 0.002171 |
from PyQt4.QtCore import QObject, pyqtSignal
from ems.notification.abstract import FormNotifier
from ems.qt4.gui.widgets.balloontip import BalloonTip
from ems import qt4
from ems.qt4.util import variant_to_pyobject as py
class BalloonFormNotifier(FormNotifier):
def __init__(self):
self._widgetMap = {... | tLeft(True)
| self._balloons[key].setArrowAtTop(False)
def mapAll(self, widgetDict):
for fieldName in widgetDict:
self.map(fieldName, widgetDict[fieldName])
def showMessage(self, key, message, state=None):
state = self._defaultState if state is None else state
if not key in sel... |
kernevil/samba | python/samba/netcmd/domain_backup.py | Python | gpl-3.0 | 50,651 | 0.000138 | # domain_backup
#
# Copyright Andrew Bartlett <abartlet@samba.org>
#
# 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.
#
#... | %s (NetBIOS), %s (DNS realm)\n" %
(lp.get('workgroup'), lp.get('realm').lower()))
f.write("Backup contains domain | secrets: %s\n" % str(include_secrets))
if extra_info:
f.write("%s\n" % extra_info)
finally:
f.close()
# Add a backup-specific marker to the DB with info that we'll use during
# the restore process
def add_backup_marker(samdb, marker, value):
m = ldb.Message()
m.dn = ldb.Dn(sam... |
jfrygeo/solutions-geoprocessing-toolbox | utils/test/patterns_tests/IncidentDensityTestCase.py | Python | apache-2.0 | 4,288 | 0.011194 | # coding: utf-8
# -----------------------------------------------------------------------------
# Copyright 2015 Esri
# 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... |
# See the License for the specific language governing permissions and
# limitations under the License.
# -----------------------------------------------------------------------------
# ==================================================
# IncidentDensityTestCase.py
# --------------------------------------------------
... | ents: ArcGIS X.X, Python 2.7 or Python 3.4
# author: ArcGIS Solutions
# company: Esri
# ==================================================
# history:
# 12/16/2015 - JH - initial creation
# ==================================================
import unittest
import arcpy
import os
import UnitTestUtilities
import Configur... |
DinoCow/airflow | tests/api_connexion/schemas/test_connection_schema.py | Python | apache-2.0 | 7,097 | 0.000564 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | 'schema': 'testschema',
'port': 80,
},
)
def test_deserialize(self):
connection_dump_1 = {
'connection_id': "mysql_default_1",
'conn_type': 'mysql',
'host': 'mysql',
'login': 'login',
'schema': 'testschema',
... | ction_collection_item_schema.load(connection_dump_1)
result_2 = connection_collection_item_schema.load(connection_dump_2)
self.assertEqual(
result_1,
{
'conn_id': "mysql_default_1",
'conn_type': 'mysql',
'host': 'mysql',
... |
lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/version.py | Python | mit | 348 | 0 | # 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.
# -------------- | ------------------------------------------------------------
VERSION = "2.0.0rc1"
|
ezequielpereira/Time-Line | timelinelib/wxgui/components/filechooser.py | Python | gpl-3.0 | 2,868 | 0.001046 | # Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015 Rickard Lindberg, Roger Lindberg
#
# This file is part of Timeline.
#
# Timeline 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 th... | self._create_browse_button()
self._layout_components()
def _create_path_text_field(self):
self._path_text_field = wx.TextCtrl(self)
self._path_text_field.Bind(wx.EVT_TEXT, self._on_path_text_changed)
def _on_path_text_changed(self, evt):
wx.PostEvent(self, self.FilePathChan... | utton = wx.Button(self, wx.ID_OPEN)
self._browse_button.Bind(wx.EVT_BUTTON, self._on_browse_button_click)
def _on_browse_button_click(self, evt):
dialog = wx.FileDialog(self,
message=self._dialog_message,
defaultDir=self._dialog_dir,
... |
marrow/mongo | test/query/test_ops.py | Python | mit | 5,358 | 0.035274 | # encoding: utf-8
from __future__ import unicode_literals
import operator
import pytest
from marrow.mongo import Filter
from marrow.schema.compat import odict, py3
@pytest.fixture
def empty_ops(request):
return Filter()
@pytest.fixture
def single_ops(request):
return Filter({'roll': 27})
def test_ops_iterat... | le_ops
assert 'roll' in single_ops
def test_equality_inequality(self, empty_ops, single_ops):
assert empty_ops == {}
assert empty_ops != {'roll': 27}
assert single_ops != {}
assert single_ops == | {'roll': 27}
def test_get(self, single_ops):
assert single_ops.get('foo') is None
assert single_ops.get('foo', 42) == 42
assert single_ops.get('roll') == 27
def test_clear(self, single_ops):
assert len(single_ops.operations) == 1
single_ops.clear()
assert len(single_ops.operations) == 0
def test_po... |
sliwinski-milosz/json_validator | tests/test_json_validator.py | Python | mit | 4,213 | 0 | import unittest
import os
from json_validator.validator import validate_params, ValidationError
arg1 = "something"
arg2 = "something_else"
schema_dirpath = os.path.dirname(os.path.realpath(__file__))
schema_filepath = os.path.join(schema_dirpath, "schema.json")
correct_params = {"param1": "some string",
... | )
def save_schema_to_json():
'''
Save some example schema to json file
'''
import json
schema = {
"required": [
"param1"
],
"type": "object",
"properties": {
"param1": {
"type": "string"
},
"param2": {... | __main__':
unittest.main()
|
SKIRT/PTS | core/extract/scaling.py | Python | agpl-3.0 | 3,571 | 0.002241 | #!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
##... | ory usage tables
self.timeline = timeline
self.memory = memory
# Write the relevant of the cu | rrent simulation
self.write()
# Read in the extracted scaling table
self.read()
# Return the scaling table
return self.table
# -----------------------------------------------------------------
def write(self):
"""
This function ...
:return:
... |
bow/crimson | tests/test_star.py | Python | bsd-3-clause | 2,311 | 0 | """star subcommand tests"""
# (c) 2015-2021 Wibowo Arindrarto <contact@arindrarto.dev>
import json
import pytest
from click.testing import CliRunner
from crimson.cli import main
from .utils import get_test_path
@pytest.fixture(scope="module")
def star_fail():
runner = CliRunner()
in_file = get_test_path("s... | ("pctMappedTooManyLoci", 0.19),
("pctUniquelyMapped", 83.53),
("pctUnmappedForOther", 0.03),
("pctUnmappedForTooManyMismatches", 0.0),
| ("pctUnmappedForTooShort", 3.16),
("rateDeletionPerBase", 0.0),
("rateInsertionPerBase", 0.0),
("rateMismatchPerBase", 0.24),
("timeEnd", "Dec 11 19:01:56"),
("timeJobStart", "Dec 11 18:55:02"),
("timeMappingStart", "Dec 11 18:59:44"),
],
)
def test_star_v230_01(... |
rackn/container-networking-ansible | test/common/library/ec2_vpc_facts.py | Python | apache-2.0 | 1,587 | 0.00063 | #!/usr/bin/python
#
# Retrieve information on an existing VPC.
#
# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.ec2 import *
import boto.vpc
def main():
argument_s | pec = ec2_argument_spec()
argument_spec.update(dict(
resource_tags=dict(type='dict', required=True)
))
module = AnsibleModule(argument_spec=argument_spec)
ec2_url, aws_access_key, aws_secret_key, region = get_ec2_creds(module)
if not region:
module.fail_json(msg="region must be spe... | connection = boto.vpc.connect_to_region(
region,
aws_access_key_id=aws_access_key,
aws_secret_access_key=aws_secret_key)
except boto.exception.NoAuthHandlerFound, e:
module.fail_json(msg=str(e))
vpcs = connection.get_all_vpcs()
vpcs_w_resources = filter(
... |
ecolitan/projecteuler-answers | Multiples_of_3_and_5.py | Python | gpl-2.0 | 260 | 0.015385 | #If we list all the natural numbers below 10 that are multip | les of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
#Find the sum of all the multiples of 3 or 5 below 1000.
print sum([x for x in xr | ange(1,1000) if (x % 3 == 0) or (x % 5 == 0)])
|
ISS-Mimic/Mimic | Pi/kivytest/Test_Kivy.py | Python | mit | 225 | 0.026667 | import os
os.environ['KIVY_GL_BA | CKEND'] = 'gl' #need this to fix a kivy segfault that occurs with python3 for some reason
from kivy.app import App
class TestApp(App):
pa | ss
if __name__ == '__main__':
TestApp().run()
|
felipenaselva/felipe.repository | script.module.cryptopy/lib/crypto/cipher/rijndael.py | Python | gpl-2.0 | 14,723 | 0.051484 | # -*- coding: iso-8859-1 -*-
""" crypto.cipher.rijndael
Rijndael encryption algorithm
This byte oriented implementation is intended to closely
match FIPS specification for readability. It is not implemented
for performance.
Copyright © (c) 2002 by Paul A. Lambert
Read LICENSE.txt for license... | Nr+1)):
temp = w[i-1] # a four byte column
if (i%Nk) == 0 :
temp = temp[1:]+[temp[0]] # RotWord(temp)
temp = [ Sbox[byte] for byte in temp ]
temp[0] ^= Rcon[i/Nk]
elif Nk > 6 and i%Nk == 4 :
temp = [ Sbox[by | te] for byte in temp ] # SubWord(temp)
w.append( [ w[i-Nk][byte]^temp[byte] for byte in range(4) ] )
return w
Rcon = (0,0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80,0x1b,0x36, # note extra '0' !!!
0x6c,0xd8,0xab,0x4d,0x9a,0x2f,0x5e,0xbc,0x63,0xc6,
0x97,0x35,0x6a,0xd4,0xb3,0x7d,0xfa,0xef,0xc... |
metomi/rose | demo/rose-config-edit/demo_meta/app/05-validate/meta/lib/python/macros/null.py | Python | gpl-3.0 | 765 | 0 | #!/usr/bin/env python3
# Copyright (C) British Crown (Met Office) & Contributors.
# -----------------------------------------------------------------------------
import metomi.rose.macro
class NullChecker(metomi.rose.macro.MacroBase):
|
"""Class to report errors for missing or null settings."""
REPORTS_INFO = [
(None, None, None, "Warning for null section, null option"),
("made", "up", None, "Warning for non-data & non-metadata setting"),
]
def validate(self, config, meta_config):
"""Validate meaningless sett... | lue, message, is_warning=True)
return self.reports
|
gvnn/memd | setup.py | Python | mit | 208 | 0.004808 | #!/usr/bin/env pyth | on
from distutils.core import setup
setup(
name='memd',
version='0.0.1',
url='https://github.com/gvnn/memd',
packages=['memd'],
install_requires=['python-mem | cached']
) |
AdrianGaudebert/socorro | alembic/versions/495bf3fcdb63_fix_invalid_notice_in_update_signatures_hourly.py | Python | mpl-2.0 | 692 | 0.011561 | """fix invalid RAISE NOTICE in update_signatures_hourly.
Revision ID: 495bf3fcdb63
Revises: 3f007539efc
Create Date: 2014-07-07 20:33:34.634141
"""
# revision identifiers, used by Alembic.
revision = '495bf3fcdb63'
down_revision = '1baef149e5d1'
from alembic import op
from socorro.lib import citexttype, j | sontype, buildtype
from socorro.lib.migrations import fix_permissions, load_stored_proc
import sqlalchemy as sa
from sqlalchemy import types
from sqlalchemy.dialects import postgresql
from sqlalchemy.sql import table, column
|
def upgrade():
load_stored_proc(op, ['update_signatures_hourly.sql'])
def downgrade():
load_stored_proc(op, ['update_signatures_hourly.sql'])
|
Sofia2/python-api | src/ssap/utils/strings.py | Python | apache-2.0 | 334 | 0.015015 | # -*- codin | g: utf8 -*-
'''
Python SSAP API
Version 1.5
© Indra Sistemas, S.A.
2014 SPAIN
All rights reserved
'''
import sys
def bytes2String(data):
'''
Converts a Python 3 bytes object to a string.
'''
if sys.version_info[0] < 3:
return data
else:
return da | ta.decode("utf-8")
|
wojons/transcribe | helpers/workerBase.py | Python | mit | 4,287 | 0.013529 | import time, types, os, sys, signal
import multiprocessing
"""
This class is simple enough to allow workers which take incomming log lines and do things with them.
I really dont know what people will want to do with there logs and how they will want to output them
but this is where they will be able to control the out... | #print sys.stderr.write("Queue object: "+str(todo)+"\n")
| self.worker(todo[0], todo[1])
#time.sleep(1)
except Queue.Empty, e:
print (str(e))
time.sleep(1)
except Exception, e:
sys.stderr.write("worker_loop: "+str(e)+"\n")
exit()
return True
... |
joharei/QtChordii | utils/__init__.py | Python | gpl-3.0 | 21 | 0 | __a | uthor__ = | 'johan'
|
mlperf/training_results_v0.6 | Fujitsu/benchmarks/resnet/implementations/mxnet/3rdparty/tvm/topi/tests/python/test_topi_upsampling.py | Python | apache-2.0 | 2,484 | 0.002818 | """Test code for upsampling"""
import numpy as np
import tvm
import topi
import topi.testing
import math
def verify_upsampling(batch, in_channel, in_height, in_width, scale, layout='NCHW', method="NEAREST_NEIGHBOR"):
if layout == 'NCHW':
A = tvm.placeholder((batch, in_channel, in_height, in_width), name=... | LINEAR - NCHW
verify_upsampling(2, 2, 32, 32, 2, method="BILINEAR")
verify_upsampling(2, 2, 32, 32, 3, method="BILINEAR")
# BILINEAR - NHWC
verify_upsampling(2, 2, 32, 32, 2, layout="NHWC", method="BILINEAR")
verify_upsampling(2, 2, 32, 32, 3, layout="NHWC", method="BILINEAR")
if __name__ == "__ma | in__":
test_upsampling()
|
sniemi/SamPy | cosmology/cc.py | Python | bsd-2-clause | 6,151 | 0.017396 | import sys
from math import *
if __name__ == '__main__':
try:
if sys.argv[1] == '-h':
print '''Cosmology calculator ala Ned Wright (www.astro.ucla.edu/~wright)
input values = redshift, Ho, Omega_m, Omega_vac
ouput values = age at z, distance in Mpc, kpc/arcsec, apparent to abs mag conversion
... | *zage
DTT = 0.0
DCMR = 0.0
# do integral over a=1/(1+z) from az to 1 in n steps, midpoin | t rule
for i in range(n):
a = az+(1-az)*(i+0.5)/n
adot = sqrt(WK+(WM/a)+(WR/(a*a))+(WV*a*a))
DTT = DTT + 1./adot
DCMR = DCMR + 1./(a*adot)
DTT = (1.-az)*DTT/n
DCMR = (1.-az)*DCMR/n
age = DTT+zage
age_Gyr = age*(Tyr/H0)
DTT_Gyr = (Tyr/H0)*DTT
DCM... |
gabinetedigital/gd | gd/govpergunta/__init__.py | Python | agpl-3.0 | 11,253 | 0.00329 | # -*- coding:utf-8 -*-
#
# Copyright (C) 2011 Governo do Estado do Rio Grande do Sul
#
# Author: Lincoln de Sousa <lincoln@gg.rs.gov.br>
# Author: Rodrigo Sebastiao da Rosa <rodrigo-rosa@procergs.rs.gov.br>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Aff... | t(url_for('.index'))
# pairwise = fsession['pairwise']
# try:
# pairwise.vote(
# request.values.get('direction'),
# request.values.get('token'))
# fsession.modified = True
# | except InvalidTokenError:
# pass
# return redirect(url_for('.index'))
@govpergunta.route('/')
def index():
return redirect('/govpergunta/resultados/')
# pagination, posts = wordpress.getPostsByTag(
# tag='governador-pergunta')
# images = gallery.search('GovernadorPergunta', limit=2... |
grahambell/taco-python | doc/conf.py | Python | gpl-3.0 | 8,346 | 0.005991 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Taco Module for Python documentation build configuration file, created by
# sphinx-quickstart on Mon Feb 17 16:17:48 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are prese... | index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using... | pyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
... |
hpleva/pyemto | pyemto/examples/alloy_discovery/make_alloy_final.py | Python | mit | 8,645 | 0.014112 | import pyemto
import numpy as np
import os
latpath = "../../../../" # Path do bmdl, kstr and shape directories
# each system need to have same number of alloy elements
#systems = [['Fe','Al'],['Fe','Cr']]
#systems = [['Fe'],['Al']]
systems = [['Al']]
#concentrations = [[0.5,0.5]]
concentrations = [[1.0]]
magn = "NM... | , atoms = s,concs = c, xc='PBE')
swsrange = np.linspace(initialsws-0.1,initialsws+0.1,7) # A list of 7 different volumes
#alloy.lattice_constants_batch_generate(sws=swsrange)
sws0, c_over_a0, B0, e0, R0, cs0 | = alloy.lattice_constants_analyze(sws=swsrange,prn=False)
alloy.sws = sws0
ca = round(c_over_a0,3)
sc_res.append([e0,B0,sws0,c_over_a0])
# Check is bmdl, kstr and kstr exsist with correct c over a
hcpname ="hcp_"+str(ca) # Structure name
strucpath = "../"
# Check... |
robcarver17/pysystemtrade | systems/accounts/account_costs.py | Python | gpl-3.0 | 12,395 | 0.002098 | import pandas as pd
from syscore.algos import calculate_weighted_average_with_nans
from syscore.genutils import str2Bool
from syscore.dateutils import ROOT_BDAYS_INYEAR
from syscore.pdutils import turnover
from sysquant.estimators.turnover import turnoverDataForTradingRule
from systems.system_cache import diagnostic... | :returns: float
KEY OUTPUT
"""
transaction_cost = self.get_SR_transaction_cost_for_instrument_forecast(
instrument_code = instrument_code,
rule_variation_name = rule_variation_name
)
holding_cost = self.get_SR_holding_cost_only(instrument_code)
... | ation_name: str
) -> float:
"""
Get the SR cost for a forecast/rule combination
:param instrument_code: instrument to get values for
:type instrument_code: str
:param rule_variation_name: rule to get values for
:type rule_variation_name: str
:returns: float... |
Nebucatnetzer/tamagotchi | pygame/lib/python3.4/site-packages/faker/providers/barcode/__init__.py | Python | gpl-2.0 | 761 | 0 | # coding=utf-8
from __future__ import unicode_literals
from .. import BaseProvider
class Provider(BaseProvider):
def ean(self, length=13):
code = [self.random_digit() for i in range(length - 1)]
if length not in (8, 13):
raise AssertionError("length can only be 8 or 13")
if... | code.append | (check_digit)
return ''.join(str(x) for x in code)
def ean8(self):
return self.ean(8)
def ean13(self):
return self.ean(13)
|
lambdamusic/testproject | konproj/urls.py | Python | gpl-2.0 | 2,206 | 0.047597 | from django.conf.urls.defaults import *
from django.conf import settings
prefix = settings.URL_PREFIX
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic import RedirectView
urlpatterns = patterns('',) # init
# November 20, 2013
#
# We have three server types for now:
# ... | min/(concepts/)$', custom_admin_views.concepts),
# (r'^'+prefix+'admin/contributions/$', poms_custom_admin_views.contributions),
# standard admin urls
(r'^'+prefix+'admin/', include(admin.site.urls) ),
# url(r'^'+prefix+'databrowse/(.*)', databrowse.s | ite.root, name='databrowsehome'),
)
# standard urls for LOCAL & LIVE
urlpatterns += patterns('',
# Registration app
(r'^registration/', include('registration.backends.default.urls')),
# Koncepts app
url(r'^', include('koncepts.urls')),
)
if settings.LOCAL_SERVER: # ===> static fi... |
Qix-/starfuse | starfuse/fs/mapped_file.py | Python | mit | 7,231 | 0.001798 | """A pseudo-file mapped into memory
Provides better performance for frequent reads/writes,
and makes reading/writing easier via regions (windows)
of memory. Allows memory to be accessed via array reads/
writes as well.
"""
import mmap
import logging
log = logging.getLogger(__name__)
class ReadOnlyError(Exception):... | er(RegionOverflowError, self).__init__('region overflow offset: %d (did you allocate?)' % offset)
class Region(object):
"""A virtual region of mapped memory
This class is a 'faked' mmap() result that allows for the finer allocation of memory mappings
beyond/below what the filesystem really allows. It is ... | s__ = 'parent', 'base_offset', '__size', 'cursor'
def __init__(self, parent, base_offset, size):
self.parent = parent
self.base_offset = base_offset
self.__size = size
self.cursor = 0
def __len__(self):
return self.__size
def __str__(self):
return str(self.... |
miurahr/seahub | seahub/role_permissions/admin.py | Python | apache-2.0 | 102 | 0 | # Copyright (c) 2012-2016 Seafile Ltd.
from django.contrib import admin
# Register your models here. | ||
hasadna/anyway | anyway/parsers/schools_with_description_2020.py | Python | mit | 6,488 | 0.003967 | import logging
from datetime import datetime
import math
import numpy as np
import pandas as pd
from flask_sqlalchemy import SQLAlchemy
from ..models import SchoolWithDescription2020
from ..utilities import init_flask, time_delta, chunks, ItmToWGS84
school_fields = {
"school_id": "סמל_מוסד",
"school_name": "... | ples:
continue
el | se:
all_schools_tuples.append(school_tuple)
school = {
"school_id": get_numeric_value(school[school_fields["school_id"]], int),
"school_name": school_name,
"municipality_name": get_str_value(school[school_fields["municipality_name"]]),
"yishuv_name": g... |
MarsZone/DreamLand | muddery/utils/event_handler.py | Python | bsd-3-clause | 7,071 | 0.003253 | """
EventHandler handles all events. The handler sets on every object.
"""
import random
from muddery.utils import defines
from muddery.statements.statement_handler import STATEMENT_HANDLER
from muddery.utils import utils
from muddery.worlddata.data_sets import DATA_SETS
from django.conf import settings
from django.ap... | if function:
function(event, character)
return not triggered
def do_attack(self, event, character):
"" | "
Start a combat.
"""
rand = random.random()
# If matches the odds, put the character in combat.
# There can be several mods with different odds.
if rand <= event["odds"]:
# Attack mob.
character.attack_temp_target(event["mob"], event["level"], ev... |
splotz90/urh | tests/TestInstallation.py | Python | gpl-3.0 | 5,216 | 0.004793 | import unittest
from subprocess import call, DEVNULL
import time
from tests.docker import docker_util
class VMHelper(object):
def __init__(self, vm_name: str, shell: str = "", ssh_username: str = None, ssh_port: str = None):
self.vm_name = vm_name
self.shell = shell # like cmd.exe /c
sel... | ant test gentoo till this bug is fixed: https://github.com/docker/docker/issues/1916#issuecomment-184356102
]
for distribution in distributions:
self.assertTrue(docker_util.run_image(distribution, rebuild=False), msg=distribution)
def test_windows(self):
"""
Run the uni... | it.msc and go to:
Windows Settings
-> Security Settings
-> Local Policies
-> Security Options
-> Accounts: Limit local account use of blank passwords to console logon only
and set it to DISABLED.
configure pip on guest:
... |
jasonwee/asus-rt-n14uhp-mrtg | src/lesson_developer_tools/pdb_next.py | Python | apache-2.0 | 202 | 0.00495 | import pdb
def calc(i, n):
| j = i * n
return j
def f(n):
for i in range(n):
j = calc(i, | n)
print(i, j)
return
if __name__ == '__main__':
pdb.set_trace()
f(5)
|
GNOME/d-feet | src/dfeet/introspection_helper.py | Python | gpl-2.0 | 7,626 | 0.001574 | # -*- coding: utf-8 -*-
from gi.repository import GLib, GObject, Gio
from dfeet import dbus_utils
def args_signature_markup(arg_signature):
return '<small><span foreground="#2E8B57">%s</span></small>' % (arg_signature)
def args_name_markup(arg_name):
return '<small>%s</small>' % (arg_name,)
class DBusNod... | f args(self):
args = list()
for arg in self.signal_info.args:
sig = dbus_utils.sig_to_string(arg.signature)
args.append({'signature': sig, 'name': arg.name})
return args
@property
def args_markup_str(self):
result = ''
result += '<span foreground=... | 'signature'])) for arg in self.args)
result += '<span foreground="#FF00FF">)</span>'
return result
@property
def markup_str(self):
return "%s %s" % (self.signal_info.name, self.args_markup_str)
class DBusMethod(DBusInterface):
"""object to represent a DBus Method"""
def __init... |
openstates/openstates | openstates/ut/people.py | Python | gpl-3.0 | 3,136 | 0.001276 | from scrapelib import HTTPError
from openstates.utils import LXMLMixin
from pupa.scrape import Person, Scraper
class UTPersonScraper(Scraper, LXMLMixin):
def scrape(self):
PARTIES = {"R": "Republican", "D": "Democratic"}
representative_url = "http://house.utah.gov/rep/{}"
senator_url = "ht... | link)
address = info.get("address")
email = info.get("email")
fax = info.get("fax")
# Work phone seems to be the person's non-legislative
# office phone, and thus a last option
# For example, we called one and got the firm
# where he'... | ikely we think they are
# to actually get us to the person we care about.
phone = info.get("cell") or info.get("homePhone") or info.get("workPhone")
if address:
person.add_contact_detail(
type="address", value=address, note="District Office"
... |
jealousrobot/PlexArt | lib/cherrypy/_helper.py | Python | gpl-3.0 | 10,332 | 0.000194 | """
Helper functions for CP apps
"""
import six
from cherrypy._cpcompat import urljoin as _urljoin, urlencode as _urlencode
from cherrypy._cpcompat import basestring
import cherrypy
def expose(func=None, alias=None):
"""
Expose the function or class, optionally providing an alias or set of aliases.
"""... | ng slash from path_info as needed
# (this is to support mistyped URL's without redirecting | ;
# if you want to redirect, use tools.trailing_slash).
pi = cherrypy.request.path_info
if cherrypy.request.is_index is True:
if not pi.endswith('/'):
pi = pi + '/'
elif cher |
edisonlz/fruit | web_project/base/site-packages/django/conf/__init__.py | Python | apache-2.0 | 7,796 | 0.002437 | """
Settings and configuration for Django.
Values will be read from the module specified by the DJANGO_SETTINGS_MODULE environment
variable, and then from django.conf.global_settings; see the global settings file for
a list of all possible variables.
"""
import logging
import os
import sys
import time # Needed fo... | oneinfo_root) and not
os.path.exists(os.path.join(zoneinfo_root, *(self.TIME_ZONE.split('/'))))):
raise ValueError("Incorrect timezone setting: %s" % self.TIME_ZONE)
# Move the time zone info into os.environ. See ticket #2315 for why
# we don't do this uncondi... | ks Windows).
os.environ['TZ'] = self.TIME_ZONE
time.tzset()
class UserSettingsHolder(BaseSettings):
"""
Holder for user configured settings.
"""
# SETTINGS_MODULE doesn't make much sense in the manually configured
# (standalone) case.
SETTINGS_MODULE = None
def __i... |
sodafree/backend | build/ipython/IPython/quarantine/ipy_exportdb.py | Python | bsd-3-clause | 2,037 | 0.025037 | from IPython.core import ipapi
from IPython.core import macro
ip = ipapi.get()
import os,pprint
def export(filename = None):
lines = ['import IPython.core.ipapi', 'ip = IPython.core.ipapi.get()','']
vars = ip.db.keys('autorestore/*')
vars.sort()
varstomove = []
get = ip.db.get
macros = ... | 2) )
|
aliases = ip.db.get('stored_aliases', {} )
if aliases:
lines.extend(['','# === Alias definitions ===',''])
for k,v in aliases.items():
try:
lines.append("ip.define_alias('%s', %s)" % (k, repr(v[1])))
except (AttributeError, TypeError):
... |
charukiewicz/beer-manager | venv/lib/python3.4/site-packages/passlib/tests/__init__.py | Python | mit | 20 | 0 | " | ""passlib te | sts"""
|
pgmillon/ansible | lib/ansible/modules/cloud/vmware/vmware_host_firewall_manager.py | Python | gpl-3.0 | 17,107 | 0.003975 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# 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... | s:
- name: vvold
enabled: True
delegate_to: localhost
- name: Manage multiple rule set for an ESXi Host
vmware_host_firewall_manager:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
esxi_ | hostname: '{{ esxi_hostname }}'
rules:
- name: vvold
enabled: True
- name: CIMHttpServer
enabled: False
delegate_to: localhost
- name: Manage IP and network based firewall permissions for ESXi
vmware_host_firewall_manager:
hostname: '{{ vcenter_hostname }}'
username:... |
nickstenning/tagalog | tagalog/command/logship.py | Python | mit | 1,992 | 0.002008 | from __future__ import print_function, unicode_literals
import argparse
import json
import sys
import textwrap
from tagalog import io, stamp, tag, fields
from tagalog import shipper
parser = argparse.ArgumentParser(description=textwrap.dedent("""
Ship log data from STDIN to somewhere else, timestamping and prepro... | or msg in msgs:
payload = | json.dumps(msg)
if args.bulk:
command = json.dumps({'index': {'_index': args.bulk_index, '_type': args.bulk_type}})
payload = '{0}\n{1}\n'.format(command, payload)
shpr.ship(payload)
if __name__ == '__main__':
main()
|
ita1024/semantik | src/filters/others.py | Python | gpl-3.0 | 3,251 | 0.03199 | #! /usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2007-2018 GPLV3
import os, sys, tarfile, io
from xml.sax import make_parser
from xml.sax.handler import ContentHandler
def debug(s):
sys.stderr.write(s)
def protect(t):
lst = t.split('&')
t = "&".join(lst)
lst = t.split('<')
t = "<".join(lst)
lst =... | self.count += 1
#self.cur += 1
#debug(str(self.cur))
id = self.count
if len(self.ids) > 0:
par = self.ids[-1 | ]
self.links.append( (par, id) )
self.ids.append(id)
text = attrs.get('TEXT', '')
text = protect(text)
self.out.append('<item id="%d" summary="%s"/>\n' % (id, text))
def endElement(self, name):
txt = "".join(self.buf)
if name == 'node':
#self.cur -= 1
#debug(str(self.cur))
self.ids=self.... |
mistercrunch/airflow | airflow/sensors/external_task.py | Python | apache-2.0 | 14,311 | 0.003005 | #
# 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... | ptional[Iterable[str]] = None,
failed_states: Optional[Iterable[str]] = None,
execution_delta: Optional[datetime.timedelta] = None,
execution_date_fn: Optional[Callable] = None,
check_existence: bool = False,
**kwargs,
):
super().__init__(**kwargs)
self.allowe... | tal_states = set(self.allowed_states + self.failed_states)
if set(self.failed_states).intersection(set(self.allowed_states)):
raise AirflowException(
f"Duplicate values provided as allowed "
f"`{self.allowed_states}` and failed states `{self.failed_states}`"
... |
alimanfoo/petl | docs/conf.py | Python | mit | 7,473 | 0.006423 | # -*- coding: utf-8 -*-
#
# petl documentation build configuration file, created by
# sphinx-quickstart on Fri Aug 19 11:16:43 2011.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All co... | l'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'petl'
copyright = u'2014, Alistair Miles'
# The ver | sion info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = petl.__version__
# The full version, including alpha/beta/rc tags.
release = petl.__version__
# The language for cont... |
fnl/pymonad | setup.py | Python | bsd-3-clause | 824 | 0.033981 | from distutils.core import setup
setup(
name='PyMonad',
version='1.3',
author='Jason DeLaat',
author_email='jason.develops@gmail.com',
packages=['pymonad', 'pymonad.test'],
url='https://bitbucket.org/jason_delaat/pymonad',
license=open('LICENSE.txt').read(),
description='Co | llection of classes for programming with functors, applicative functors and monads.',
long_description=open('README.txt').read() + open("CHANGES.txt").read(),
classifiers=[ "Intended Audience :: Developers"
, "License :: | OSI Approved :: BSD License"
, "Operating System :: OS Independent"
, "Programming Language :: Python :: 2.7"
, "Programming Language :: Python :: 3"
, "Topic :: Software Development"
, "Topic :: Software Development :: Libraries"
, "Topic :: Utilities"
],
)
|
CMSS-BCRDB/RDSV1.0 | trove/guestagent/strategies/replication/__init__.py | Python | apache-2.0 | 955 | 0 | # Copyright 2014 Tesora, 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 ... | OR CONDITIONS OF ANY KIND | , either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
from trove.guestagent.strategy import Strategy
from trove.openstack.common import log as logging
LOG = logging.getLogger(__name__)
def get_replication_strategy(replication_driv... |
bridadan/mbed-ls | setup.py | Python | apache-2.0 | 1,786 | 0.004479 | """
This module defines the attributes of the
PyPI package for the mbed SDK test suite ecosystem tools
"""
"""
mbed SDK
Copyright (c) 2011-2015 ARM Limited
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the Licen... | a file (used for the README)
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='mbed-ls',
version='0.1.19',
description=DESCRIPTION,
long_description=read('README.md'),
author=OWNER_NAMES,
| author_email=OWNER_EMAILS,
maintainer=OWNER_NAMES,
maintainer_email=OWNER_EMAILS,
url='https://github.com/ARMmbed/mbed-ls',
packages=find_packages(),
license="Apache-2.0",
test_suite = 'test',
entry_points={
"console_scripts": [
"mbedls=mbed_lstools:mb... |
OLAPLINE/TM1py | TM1py/Services/PowerBiService.py | Python | mit | 6,310 | 0.004596 | from collections.abc import Iterable
from TM1py.Services import CellService
from TM1py.Services import ElementService
from TM1py.Utils import require_pandas
try:
import pandas as pd
_has_pandas = True
except ImportError:
_has_pandas = False
class PowerBiService:
def __init__(self, tm1_rest):
... | lated_members_selection) + "}"
member_selection = ",".join(
member["UniqueName"]
for member
in members)
mdx_with_block = ""
if calculated_mem | bers_definition:
mdx_with_block = "WITH " + " ".join(calculated_members_definition)
mdx = f"""
{mdx_with_block}
SELECT
{{ {member_selection} }} ON ROWS,
{{ {column_selection} }} ON COLUMNS
FROM [{self.elements.ELEMENT_ATTRIBUTES_PREFIX + dimension_name}]
... |
maxolasersquad/ninja-ide | ninja_ide/core/__init__.py | Python | gpl-3.0 | 712 | 0.001404 | # -*- coding: utf-8 -*-
#
# This file is part of NINJA-IDE (http://ninja-ide.org).
#
# NINJA-IDE 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
# any later version.
#
# NINJA-IDE is distributed in the hope that it will be useful,
# | but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>.
from .c... |
stephane-martin/salt-debian-packaging | salt-2016.3.3/salt/modules/openbsdservice.py | Python | apache-2.0 | 8,008 | 0.000999 | # -*- coding: utf-8 -*-
'''
The service module for OpenBSD
.. important::
If you feel that Salt should be using this module to manage services on a
minion, and it is using a different module (or gives an error similar to
*'service.start' is not available*), see :ref:`here
<module-provider-override>`.
'... | rc():
'''
Returns a dict where the key is the daemon's name and
the value a boolean indicating its status (True: enabled or False: disabled).
Check the daemons star | ted by the system in /etc/rc and
configured in /etc/rc.conf and /etc/rc.conf.local.
Also add to the dict all the localy enabled daemons via $pkg_scripts.
'''
daemons_flags = {}
try:
# now read the system startup script /etc/rc
# to know what are the system enabled daemons
wi... |
leohmoraes/weblate | weblate/trans/views/basic.py | Python | gpl-3.0 | 14,336 | 0 | # -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2015 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <http://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, eithe... | port Profile, notify_new_language
from weblate.trans.views.helper import (
get_project, get_subproject, get_translation,
try_set_language,
)
import weblate
import datetime
from urllib import urlencode
def home(request):
"""
Home page of Weblate showing list of projects, stats
and user links if lo... | .warning(
request,
_(
'You have activated your account, now you should set '
'the password to be able to login next time.'
)
)
return redirect('password')
wb_messages = WhiteboardMessage.objects.all()
projects = Project.object... |
sametmax/Django--an-app-at-a-time | ignore_this_directory/django/contrib/flatpages/migrations/0001_initial.py | Python | mit | 1,710 | 0.004678 | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sites', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='FlatPage',
fields=[
('id', models.AutoField(verbose_na | me='ID', serialize=False, auto_created=True, primary_key=True)),
('url', models.CharField(max_length=100, verbose_name='U | RL', db_index=True)),
('title', models.CharField(max_length=200, verbose_name='title')),
('content', models.TextField(verbose_name='content', blank=True)),
('enable_comments', models.BooleanField(default=False, verbose_name='enable comments')),
('template_... |
Irdroid/httpie | httpie/utils.py | Python | bsd-3-clause | 1,164 | 0.000859 | from __future__ import division
def humanize_bytes(n, precision=2):
# Author: Doug Latornell
# Licence: MIT
# URL: http://code.activestate.com/recipes/577081/
"""Return a humanized string representation of a number of bytes.
Assumes `from __future__ import division`. |
>>> humanize_bytes(1)
'1 B'
>>> humanize_bytes(1024, precision=1)
'1.0 kB'
>>> humanize_bytes(1024 * 123, precision=1)
'123.0 kB'
>>> h | umanize_bytes(1024 * 12342, precision=1)
'12.1 MB'
>>> humanize_bytes(1024 * 12342, precision=2)
'12.05 MB'
>>> humanize_bytes(1024 * 1234, precision=2)
'1.21 MB'
>>> humanize_bytes(1024 * 1234 * 1111, precision=2)
'1.31 GB'
>>> humanize_bytes(1024 * 1234 * 1111, precision=1)
'1.3 GB... |
DarthMaulware/EquationGroupLeaks | Leak #4 - Don't Forget Your Base/EQGRP-Auction-File/Linux/etc/autoutils.py | Python | unlicense | 22,459 | 0.005699 | #!/bin/env python
import os
import re
import sys
import time
import pickle
import random
import socket
import os.path
import traceback
import subprocess
from optparse import OptionParser
VERSION='1.1.0.7'
COLOR = {
'success' : '\33[2;32m', # Green
'fail' : '\033[2;31m', # Red
'bad' : '\033[31... | et.close()
sys.exit(0)
self.pid = os.getpid()
self.nopen.write('#NOGS\n')
self.nopen.flush()
# going to run -status every time because something could change
# between runs and don't want to get caught with something bad.
self.parsestatus()
#if not... | load(f)
# f.close()
self.loadState()
self.saveState()
return self.nopen
#
# Does any final stuff with the output, like sending it to a calling
# perl script, then returns back a string of the argument, or unchanged
# if mkstr is False.
#
def finish(s... |
Azure/azure-sdk-for-python | sdk/metricsadvisor/azure-ai-metricsadvisor/azure/ai/metricsadvisor/_generated/aio/_metrics_advisor.py | Python | mit | 3,345 | 0.003886 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights res | erved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
| # Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import Any, TYPE_CHECKING
from azure.core import AsyncPipelineClient
from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
fro... |
wileeam/airflow | tests/providers/jdbc/operators/test_jdbc.py | Python | apache-2.0 | 1,539 | 0.0013 | #
# 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... |
self.kwargs = dict(
sql='sql',
task_id='test_jdbc_operator',
dag=None
)
@patch('airflow.provi | ders.jdbc.operators.jdbc.JdbcHook')
def test_execute(self, mock_jdbc_hook):
jdbc_operator = JdbcOperator(**self.kwargs)
jdbc_operator.execute(context={})
mock_jdbc_hook.assert_called_once_with(jdbc_conn_id=jdbc_operator.jdbc_conn_id)
mock_jdbc_hook.return_value.run.assert_called_onc... |
JoePelz/SAM | spec/python/test_integrity.py | Python | gpl-3.0 | 4,602 | 0.002825 | from spec.python import db_connection
from sam import constants
from sam import common
from sam import integrity
import traceback
mysql_params = constants.dbconfig.copy()
sqlite_params = constants.dbconfig.copy()
mysql_params['dbn'] = 'mysql'
mysql_params['db'] = 'samapper_test'
sqlite_params['dbn'] = 'sqlite'
sqlite... | P(1234567890)')
assert rows.first().values()[0] == '73.150.2.210'
rows = db_mysql.query('SELECT encodeIP(12,34,56,78)')
assert rows.first().values()[0] == 203569230L
def test_sqlite_UDF():
integrity.fix_UDF_SQLite(db_sqlite)
rows = db_sqlite.query('SELECT decodeIP(1234567890)')
assert rows.fir... | _mysql_def_subscription():
try:
errors = integrity.check_default_subscription(db_mysql)
integrity.fix_default_subscription(db_mysql, errors)
except:
traceback.print_exc()
assert False
def test_sqlite_def_subscription():
try:
errors = integrity.check_default_subscrip... |
iwob/pysv | pysv/smt_common.py | Python | mit | 3,263 | 0.005823 | from pysv import ast_utils
from pysv import ssa_converter
from pysv import utils
from pysv import loops
from pysv import interm
from pysv.smt2 import ProgramSmt2
def get_code_in_smt2(code, code_pre, code_post, program_vars, env, holes_decls = None):
| """Converts source codes of specification elements into program in SMT-LIB 2.0 language.
:param code: (str) Source code (in arbitrary language) of the program.
:param code_pre: (str) Source code (in arbitrary language) of the expression representing all *pre-conditions*.
:param code_post | : (str) Source code (in arbitrary language) of the expression representing all *post-conditions*.
:param program_vars: (ProgramVars) Information about variables and their types.
:param env: (Options) Options of the currently realized task.
:param holes_decls: (list[HoleDecl]) Declarations of all holes in th... |
Tenchi2xh/cursebox | cursebox/__main__.py | Python | mit | 1,969 | 0.000542 | # -*- encoding: utf-8 -*-
from .cursebox import Cursebox
from .colors import colors
from .constants import EVENT_SKIP
from .utils import hex_to_rgb
logo = [u" █ ",
u"█▀█ █ █ █▀█ █▀▀ █▀█ █▀▄ █▀█ █▄█",
u"█ █ █ █ ▀▀█ █▄█ █ █ █ █ ▄█▄",
u"█▄█ █▄█ █ ▄▄█ █▄▄ █▄█ █▄█... | e) as cb:
widt | h, height = cb.width, cb.height
def draw_logo(t):
for y0, line in enumerate(logo):
y1 = (height - l_height) / 2 + y0
for x0, char in enumerate(line):
x1 = x0 + (width - l_width) / 2
offset = int(t + y0 + x_s * x0) % len(palette... |
alexis-roche/nireg | nireg/histogram_registration.py | Python | bsd-3-clause | 23,075 | 0.000563 | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
Intensity-based image registration
"""
from __future__ import absolute_import
from __future__ import print_function
import os
import numpy as np
import scipy.ndimage as nd
from nibabel import Nifti1Ima... | """
# Binning sizes
from_bins, to_bins = unpack(bins, int)
# Smoothing kernel sizes
self._from_sigma, self._to_sigma = unpack(sigma, float)
# Clamping of the `from` image. The number of bins may be
# overriden if unnecessarily large.
data | , from_bins_adjusted = clamp(from_img,
from_bins,
mask=from_mask,
sigma=self._from_sigma)
if not similarity == 'slr':
from_bins = from_bins_adjusted
self._from_img = Nif... |
tchellomello/home-assistant | tests/components/brother/test_sensor.py | Python | apache-2.0 | 10,659 | 0.000281 | """Test sensor of Brother integration."""
from datetime import datetime, timedelta
import json
from homeassistant.components.brother.const import UNIT_PAGES
from homeassistant.const import (
ATTR_DEVICE_CLASS,
ATTR_ENTITY_ID,
ATTR_ICON,
ATTR_UNIT_OF_MEASUREMENT,
DEVICE_CLASS_TIMESTAMP,
PERCENTA... | = hass.states.get("sensor.hl_l2340dw_black_drum_remaining_life")
assert state
assert state.attributes.get(ATTR_ICON) == "mdi:chart-donut"
assert state.attributes.get(ATTR_REMAINING_PAGES) == 16389
assert state.attributes.get( | ATTR_COUNTER) == 1611
assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == PERCENTAGE
assert state.state == "92"
entry = registry.async_get("sensor.hl_l2340dw_black_drum_remaining_life")
assert entry
assert entry.unique_id == "0123456789_black_drum_remaining_life"
state = hass.states.get("... |
ingadhoc/purchase | purchase_stock_ux/models/purchase_order_line.py | Python | agpl-3.0 | 7,593 | 0 | ##############################################################################
# For copyright and license notices, see __manifest__.py file in module root
# directory
### | ###########################################################################
from odoo import | models, fields, api, _
from odoo.exceptions import UserError
from odoo.tools import float_compare
from lxml import etree
import logging
_logger = logging.getLogger(__name__)
class PurchaseOrderLine(models.Model):
_inherit = 'purchase.order.line'
delivery_status = fields.Selection([
('no', 'Not purcha... |
bt3gl/NetAna-Complex-Network-Analysis | src/calculate_features_advanced/road.py | Python | mit | 577 | 0.015598 | #!/usr/bin/env python
__author__ = "Mari Wahl"
__copyright__ = "Copyright 2014, The Cogent | Project"
__credits__ = ["Mari Wahl"]
__license__ = "GPL"
__version__ = "4.1"
__maintainer__ = "Mari Wahl"
__email__ = "marina.w4hl@gmail.com"
from helpers import running, constants
# change here for type of net:
NETWORK_FILES = constants.NETWORK_FILES_UN_ROAD
TYPE_NET_DIR = "road/"
def main():
running.sam... | The end! \n")
if __name__ == '__main__':
main()
|
wubr2000/googleads-python-lib | examples/dfp/v201505/audience_segment_service/get_first_party_audience_segments.py | Python | apache-2.0 | 2,062 | 0.009214 | #!/usr/bin/python
#
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | press or impli | ed.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This code example gets all first party audience segments.
To create first party audience segments, run create_audience_segments.py.
"""
# Import appropriate modules from the client library.
from googleads i... |
devs1991/test_edx_docmode | venv/lib/python2.7/site-packages/django_openid_auth/management/commands/openid_cleanup.py | Python | agpl-3.0 | 1,732 | 0 | # django-openid-auth - OpenID integration for django.contrib.auth
#
# Copyright (C) 2009-2013 Canonical Ltd.
#
# 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 ... | AL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DA | TA, 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 OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from __future__ import unicode_liter... |
tkchafin/scripts | findBreaksVCF.py | Python | gpl-3.0 | 3,606 | 0.044925 | #!/usr/bin/python
import re
import sys
import os
import getopt
import vcf
def main():
params = parseArgs()
vfh = vcf.Reader(open(params.vcf, 'r'))
#grab contig sizes
contigs = dict()
for c,s in vfh.contigs.items():
contigs[s.id] = s.length
regions = list()
this_chrom = None
start = int()
stop = int()
... | 'h', 'help'):
pass
else:
assert False, "Unhandled option %r"%opt
#Check mandit | ory options are set
if not self.vcf:
self.display_help("Must provide VCF file <-v,--vcf>")
def display_help(self, message=None):
if message is not None:
print()
print (message)
print ("\nfindBreaksVCF.py\n")
print ("Contact:Tyler K. Chafin, University of Arkansas,tkchafin@uark.edu")
print ("\nUsage... |
nismod/energy_demand | energy_demand/validation/lad_validation.py | Python | mit | 33,133 | 0.003501 | """Compare gas/elec demand on Local Authority Districts with modelled demand
"""
import os
import operator
import logging
import copy
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
from energy_demand.basic import lookup_tables
from energy_demand import enduse_func
from energy_demand.profile... | ults(
'validation_temporal_electricity_weeks_selection.pdf',
result_paths['data_results_validation'],
elec_factored_yh,
ed_fueltype_yh,
'all_submodels',
days_to_plot,
plot_crit=plot_criteria)
return
def spatial_valid | ation_lad_level(
disaggregated_fuel,
data_results_validation,
paths,
regions,
reg_coord,
plot_crit
):
"""Spatial validation
"""
fuel_elec_regs_yh = {}
fuel_gas_regs_yh = {}
fuel_gas_residential_regs_yh = {}
fuel_gas_non_residential_regs_yh = {}... |
fedora-infra/bodhi | bodhi-server/bodhi/server/buildsys.py | Python | gpl-2.0 | 29,649 | 0.001889 | # Copyright 2007-2019 Red Hat, Inc. and others.
#
# This file is part of Bodhi.
#
# 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... | not self.multicall:
return func(self, *args, **kwargs)
# disable multicall during execution, so that inner func calls to other
# methods don't append their results as well
| self._multicall = False
result = func(self, *args, **kwargs)
self.multicall_result.append([result])
self._multicall = True
return wrapper
class DevBuildsys:
"""A dummy buildsystem instance used during development and testing."""
_side_tag_data = [{'id': 1234, 'name': 'f17-buil... |
hpproliant/ironic | ironic/tests/unit/drivers/modules/amt/test_management.py | Python | apache-2.0 | 10,845 | 0 | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | def setUp(self):
super(AMTManagementInteralMethodsTestCase, self).setUp()
mgr_utils.mock_the_extension_manager(driver='fake_amt')
self.node = obj_utils.create_test_node(self.context,
| driver='fake_amt',
driver_info=INFO_DICT)
def test__set_boot_device_order(self, mock_client_pywsman):
namespace = resource_uris.CIM_BootConfigSetting
device = boot_devices.PXE
result_xml = test_utils.build_soap_xml([{'ReturnValue': '0'}... |
wcmckee/hamiltoncomputerclub.org.nz | static/cache/.mako.tmp/comments_helper_googleplus.tmpl.py | Python | mit | 2,205 | 0.004989 | # -*- encoding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 8
_modified_time = 1399593695.26071
_enable_loop = True
_template_filename = u'/usr/lib/python2.7/site-packages/nikola/data/themes/base/templates/comments_h... | .caller_stack._push_frame()
try:
__M_writer = context.writer()
# SOURCE LINE 16
__M_writer(u'\n')
return ''
| finally:
context.caller_stack._pop_frame()
|
verma-varsha/zulip | zerver/lib/i18n.py | Python | apache-2.0 | 2,570 | 0.002724 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import operator
from django.conf import settings
from django.utils import translation
from django.utils.translation import ugettext as _
from django.utils.lru_cache import lru_cache
from six.moves import urllib, zip_longest, zip, range
from typing import ... | sts = list(range(0, firsts_end))
seconds = list(range(firsts_end, lang_len))
assert len(firsts) + len(seconds) == lang_len
for row in zip_longest(firsts, seconds):
item = {}
for position, ind in zip(['first', 'second'], row):
if ind is None:
continue
... | percent = name = lang['name']
if 'percent_translated' in lang:
percent = u"{} ({}%)".format(name, lang['percent_translated'])
item[position] = {
'name': name,
'code': lang['code'],
'percent': percent,
'sele... |
MaxTyutyunnikov/lino | obsolete/sales.old/fixtures/demo.py | Python | gpl-3.0 | 7,084 | 0.025692 | # -*- coding: UTF-8 -*-
## Copyright 2008-2011 Luc Saffre
## This file is part of the Lino project.
## Lino 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 op... | =1) # name="Furniture")
hosting = products.Product.objects.get(pk=5)
#~ order = Instantiator(sales.Order,
#~ "company creation_date start_date cycle imode",
#~ payment_term="30",journal=ORD).build
#~ invoice = Instantiator(sales.Invoice,
#~ "company creation_date imode",
#~ ... | mpany=Company.objects.get(pk=1),
creation_date=i2d(20080923),start_date=i2d(20080924),
cycle="M",imode=imode_e,
sales_remark="monthly order")
#~ o = order(1,"2008-09-23","2008-09-24","M","e",sales_remark="monthly order")
o.add_item(hosting,1)
yield o
o = ORD.create_document(
... |
griest024/PokyrimTools | pyffi-develop/pyffi/spells/cgf/check.py | Python | mit | 9,081 | 0.002313 | """Module which contains all spells that check something in a cgf file."""
# --------------------------------------------------------------------------
# ***** BEGIN LICENSE BLOCK *****
#
# Copyright (c) 2007-2012, NIF File Format Library and Tools.
# All rights reserved.
#
# Redistribution and use in source and binar... | newtangents = [tangent for tangent in branch.tangents_data.tangents]
self.toaster.msgblockbegin("validating and checking old with new")
for norm, oldtangent, newtangent in zip(branch.normals_data.normals,
oldtangents | , newtangents):
#self.toaster.msg("*** %s ***" % (norm,))
# check old
norm = (norm.x, norm.y, norm.z)
tan = tuple(x / 32767.0
for x in (oldtangent[0].x,
oldtangent[0].y,
oldtangent... |
Purg/SMQTK | python/smqtk/tests/utils/file_utils/test_FileModificationMonitor.py | Python | bsd-3-clause | 6,758 | 0.000444 | import atexit
import os
import tempfile
import time
import threading
import unittest
import nose.tools
import smqtk.utils.file_utils
__author__ = "paul.tunison@kitware.com"
class TestFileModificationMonitor (unittest.TestCase):
def _mk_test_fp(self):
fd, fp = tempfile.mkstemp()
os.close(fd)
... | p(append_interval)
m_thread = smqtk.utils.file_utils.FileModificationMonitor(fp,
| monitor_interval,
monitor_settle,
cb)
a_thread = AppendThread()
try:
m_thread.start()
a_thread.start()
time.sleep(m... |
vedujoshi/os_tempest | tempest/common/waiters.py | Python | apache-2.0 | 5,919 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | time.sleep(CONF.compute.ready_wait)
return
else:
return
time.sleep(client.build_interval)
resp, body = client.get_server(server_id)
server_status = body['status']
task_state = _get_task_state(body)
if (server_status != old_status)... | nsition "%s" ==> "%s" after %d second wait',
'/'.join((old_status, str(old_task_state))),
'/'.join((server_status, str(task_state))),
time.time() - start_time)
if (server_status == 'ERROR') and raise_on_error:
_console_dump(client, serv... |
giocastagno/I.W._Delpuppo_Kopech_Castagno | turismo/sitio/migrations/0001_initial.py | Python | mit | 2,730 | 0.003297 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-04-25 01:27
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migratio... | ]
operations = [
migrations.CreateModel(
name='Dia',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('descripcion', models.CharField(max_length=1000)),
],
),
migr... | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('descripcion', models.CharField(max_length=20)),
],
),
migrations.CreateModel(
name='Itinerario',
fields=[
('id', models.AutoField(auto_... |
ESS-LLP/erpnext-healthcare | erpnext/stock/doctype/delivery_note/delivery_note.py | Python | gpl-3.0 | 20,437 | 0.026423 | # 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
import frappe.defaults
from erpnext.controllers.selling_controller import SellingController
from erpnext.stock.doctype.batch.batch import... | lf.chec | k_credit_limit()
elif self.issue_credit_note:
self.make_return_invoice()
# Updating stock ledger should always be called after updating prevdoc status,
# because updating reserved qty in bin depends upon updated delivered qty in SO
self.update_stock_ledger()
self.make_gl_entries()
def on_cancel(self) |
ujvl/ray-ng | python/ray/tests/utils.py | Python | apache-2.0 | 4,953 | 0 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import fnmatch
import os
import subprocess
import sys
import tempfile
import time
import psutil
import ray
class RayTestTimeoutException(Exception):
"""Exception used to identify timeouts from test util... | ))
def wait_for_children_of_pid_to_exit(pid, timeout=20):
children = psutil.Process(pid).children()
if len(children) == 0:
return
_, alive = psutil.wait_procs(children, timeout=timeout)
if len(alive) > 0:
raise RayTestTimeoutException(
"Timed out while waiting | for process children to exit."
" Children still alive: {}.".format([p.name() for p in alive]))
def kill_process_by_name(name, SIGKILL=False):
for p in psutil.process_iter(attrs=["name"]):
if p.info["name"] == name:
if SIGKILL:
p.kill()
else:
... |
UBC-Victorious-410/project | tools/mock_pmd_parser.py | Python | mit | 330 | 0.060606 | import pickle
commits = {}
def main():
output = ""
for commit in range(0,3):
output += "c*\n"
for file in range(0,2):
smells = str(commit+file*2)
output += "class"+str(fi | le)+" smells="+smells+"\n"
result = open("mockpmdresult.txt","w")
result.write(output)
result.close()
if __name__ == "__main__":
main() | |
cytec/SickRage | lib/github/PaginatedList.py | Python | gpl-3.0 | 7,862 | 0.003689 | # -*- coding: utf-8 -*-
# ########################## Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> ... | der #
# the terms of the GNU Lesser General Public License as published by the Free #
# Software Foundation, either version 3 of the License, or (at your option) #
# any later version. #
# ... | ITY or FITNESS #
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more #
# details. #
# #
# You should have received a copy of the GNU Lesser Gener... |
ICGC-TCGA-PanCancer/pancancer-sandbox | pcawg_metadata_parser/pc_report-embl-dkfz_summary_counts.py | Python | gpl-2.0 | 8,651 | 0.007282 | #!/usr/bin/env python
import sys
import os
import glob
import json
import re
from argparse import ArgumentParser
from argparse import RawDescriptionHelpFormatter
def init_report_dir(metadata_dir, report_name):
report_dir = metadata_dir + '/reports/' + report_name
if not os.path.exists(report_dir):
os... | with open(report_dir + '/hist | _summary_compute_site_counts.json', 'w') as o: o.write(json.dumps(site_summary_report))
"""
def compute_site_report(metadata_dir, report_dir, today_donors):
compute_sites = {
"aws_ireland": set(),
"aws_oregon": set(),
"bsc": set(),
"dkfz": set(),
"ebi": set(),
"... |
webostin/django-btc | tests/template_tests/filter_tests/test_phone2numeric.py | Python | bsd-3-clause | 1,450 | 0.002069 | from django.template.defaultfilters import phone2numeric_filter
from django.test import SimpleTestCase
from django.utils.safestring import mark_safe
from ..utils import render, setup
class Phone2numericTests(SimpleTestCase):
@setup({'phone2numeric01': '{{ a|phone2numeric }} {{ b|phone2numeric }}'})
def test... | 00-call-me>', 'b': mark_safe('<1-800-call-me>')},
)
self.assertEqual(output, '<1-800-2255-63> <1-800-2255-63>')
@setup({'phone2numeric03': '{{ a|phone2numeric }}'})
def test_phone2numeric03(self):
output = render(
'phone2numeric03',
{'a': 'How razorback-jumping f... | 4 37647 226 53835 749 747833 49662787!'
)
class FunctionTests(SimpleTestCase):
def test_phone2numeric(self):
self.assertEqual(phone2numeric_filter('0800 flowers'), '0800 3569377')
|
mrshu/scikit-learn | sklearn/hmm.py | Python | bsd-3-clause | 46,104 | 0.000022 | # Hidden Markov Models
#
# Author: Ron Weiss <ronweiss@gmail.com>
# and Shiqiao Du <lucidfrontier.45@gmail.com>
# API changes: Jaques Grobler <jaquesgrobler@gmail.com>
"""
The :mod:`sklearn.hmm` module implements hidden Markov models.
**Warning:** :mod:`sklearn.hmm` is orphaned, undocumented and has known
numerical s... | -------
logprob : float
Log likelihood of the `obs`
See Also
| --------
eval : Compute the log probability under the model and posteriors
decode : Find most likely state sequence corresponding to a `obs`
"""
obs = np.asarray(obs)
framelogprob = self._compute_log_likelihood(obs)
logprob, _ = self._do_forward_pass(framelogprob)
... |
Jetpie/web-scraper | commercial_web_navigation/commercial_web_navigation/items.py | Python | mit | 429 | 0.011655 | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
"sample spider"
class DmozItem(scrapy.Item):
# | define the fields for your item here like:
# name = scrapy.Field()
title = scrapy.Field()
link = scrapy.Field()
desc = scrapy.Field()
class JDItem(scrapy.Item):
category = scr | apy.Field()
|
boyombo/django-stations | stations/api/urls.py | Python | mit | 2,383 | 0 | from django.conf.urls import url
from api import views
urlpatterns = [
url(r'stations/$', views.get_stations, name='api_stations'),
url(r'entry/(?P<station_id>\d+)/$', views.make_entry, name='api_entry'),
url(r'new/$', views.add_station, name='api_add_station'),
# Booking api
url(r'booking/(?P<res... | i
url(r'register_pharm/$', views.register_pharm, name='api_register_pharm'),
url(r'make_token/(?P<device_id>\d+)/$',
views.make_token, name='api_make_token'),
url(r'add_device/$', views.add_device, name='api_add_device'),
url(r'get_profile/$', views.get_profile, name='api_get_profile'),
url(... | e='api_update_pharm'),
url(r'add_outlet/(?P<device_id>\d+)/$',
views.add_outlet, name='api_add_outlet'),
url(r'delete_outlet/(?P<id>\d+)/$',
views.delete_outlet, name='api_delete_outlet'),
url(r'add_drug/$', views.add_drug, name='api_add_drug'),
url(r'edit_drug/(?P<id>\d+)/$', views.edit... |
chriskuech/wavelab | pitchanalysis.py | Python | mit | 5,174 | 0.018748 | #!/usr/bin/env python
"""
pitchanalysis.py
--
Christopher Kuech
cjkuech@gmail.com
--
Requires:
Python 2.7
Instructions:
python pitchanalysis.py [wav-file-name]
"""
import matplotlib
from math import log
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.fig... | column=0, pady=10)
wframe = tk.Frame(root)
wframe.grid( | row=2, column=0, pady=10, sticky="n")
tk.Radiobutton(wframe, **widgetps("rectangle", wtype)).grid(sticky="w", row=0)
tk.Radiobutton(wframe, **widgetps("hamming" , wtype)).grid(sticky="w", row=1)
tk.Radiobutton(wframe, **widgetps("hanning" , wtype)).grid(sticky="w", row=2)
# create the wsize controller and add it to ... |
fedora-desktop-tests/nautilus | features/environment.py | Python | gpl-2.0 | 3,002 | 0.001332 | # -*- coding: UTF-8 -*-
import os
from behave_common_steps import dummy, App
from dogtail.config import config
from time import sleep, localtime, strftime
import problem
import shutil
def before_all(context):
"""Setup nautilus stuff
Being executed before all features
"""
try:
# Cleanup abrt ... | er -o cat --since='%s'> /tmp/journal-session.log" % context.log_start_time)
data = open("/tmp/journal-session.log", 'r').read()
if data:
| context.embed('text/plain', data)
if hasattr(context, 'temp_dir'):
shutil.rmtree(context.temp_dir)
# Make some pause after scenario
sleep(1)
except Exception as e:
# Stupid behave simply crashes in case exception has occurred
print("Error in afte... |
qwiglydee/drf-mongo-filters | runtests.py | Python | gpl-2.0 | 751 | 0.001332 | #!/usr/bin/env python
import sys
from django.conf import settings
from django.core.management import execute_from_command_line
from tests import mongoutils
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memor | y:',
},
},
MONGO_DATABASES={
'default': {
'name': 'dumb',
},
},
INSTALLED_APPS=(
'tests',
),
MIDDLEWARE_CLASSES=(),
ROOT_URLCONF=None,
SECRET_KEY='foobar',
TEST_RUNNER='tests.mongoutils.TestRunner'
)
def runtests():
mongoutils.mongo_co... | rgv)
if __name__ == '__main__':
runtests()
|
khozzy/pyalcs | tests/lcs/agents/test_PerceptionString.py | Python | gpl-3.0 | 1,123 | 0 | from lcs.agents import PerceptionString
from lcs.representations import UBR
class TestPerceptionString:
def test_should_initialize_with_defaults(self):
assert len(PerceptionString("foo")) == 3
assert len(PerceptionString(['b', 'a', 'r'])) == 3
def test_should_create_empty_with_defaults(self)... | wildcard = UBR(0, 16)
# when
ps = PerceptionString.empty(length, wildcard, oktypes=(UBR,))
# then
assert len(ps) == 3
assert ps[0] == ps[1] == ps[2] == wildcard
assert ps[0] is not ps[1] is not ps[2]
def test_should_safely_modify_single_attribute(self):
... | ps = PerceptionString.empty(length, wildcard, oktypes=(UBR, ))
# when
ps[0].x1 = 2
# then (check if objects are not stored using references)
assert ps[1].x1 == 0
|
LabD/ecs-deplojo | tests/conftest.py | Python | mit | 3,378 | 0 | import json
import os
from textwrap import dedent
import boto3
import moto
import pytest
from moto.ec2 import ec2_backend
from moto.ec2 import utils as ec2_utils
from ecs_deplojo.connection import Connection
from ecs_deplojo.task_definitions import TaskDefinition
BASE_DIR = os.path.dirname(os.path.abspath(__file__))... | e="function")
def cluster():
with moto.mock_ecs(), moto.mock_ec2():
boto3.setup_default_session(region_name="eu-west-1")
ec2 = boto3.resource("ec2", region_name="eu-west-1")
ecs = boto3.client("ecs", region_name="eu-west-1")
known_amis = list(ec2_backend.describe_images())
... | test_instance = ec2.create_instances(
ImageId=known_amis[0].id, MinCount=1, MaxCount=1
)[0]
instance_id_document = json.dumps(
ec2_utils.generate_instance_identity_document(test_instance)
)
cluster = ecs.create_cluster(clusterName="default")
ecs.register... |
sunnychaudhari/gstudio | gnowsys-ndf/gnowsys_ndf/ndf/views/course.py | Python | agpl-3.0 | 54,618 | 0.005493 | ''' -- imports from python libraries -- '''
# from datetime import datetime
import datetime
import json
''' -- imports from installed packages -- '''
from django.http import HttpResponseRedirect # , HttpResponse uncomment when to use
from django.http import HttpResponse
from django.http import Http404
from django.sho... | m gnowsys_ndf.ndf.views.methods import create_gattribute, create_grelation, create_task
GST_COURSE = node_collection.one({'_type': "GSystemType", 'name': GAPPS[7]})
app = GST_COURSE
# @login_required
@get_execution_time
def course(request, group_id, course_id=None):
"""
* Renders a list of all 'courses' avai... | tId()
if ins_objectid.is_valid(group_id) is False:
group_ins = node_collection.find_one({'_type': "Group", "name": group_id})
auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })
if group_ins:
group_id = str(group_ins._id)
else:
auth = node... |
markrawlingson/SickRage | sickbeard/providers/iptorrents.py | Python | gpl-3.0 | 7,350 | 0.00449 | # Author: seedboy
# URL: https://github.com/seedboy
#
# This file is part of SickRage.
#
# SickRage 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 la... | t response:
logger.log(u"Unable to connect to pr | ovider", logger.WARNING)
return False
if re.search('tries left', response):
logger.log(u"You tried too often, please try again after 1 hour! Disable IPTorrents for at least 1 hour", logger.WARNING)
return False
if re.search('Password not correct', response):
... |
cloud-fan/spark | python/docs/source/conf.py | Python | apache-2.0 | 12,894 | 0.005584 | # -*- coding: utf-8 -*-
#
# pyspark documentation build configuration file, created by
# sphinx-quickstart on Thu Aug 28 15:17:47 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# A... | e
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyrigh... | e output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which th |
aubreyrjones/libesp | scons_local/scons-local-2.3.0/SCons/PathList.py | Python | mit | 8,536 | 0.000937 | #
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, incl... | 'dir1:$ROOT/dir2' and ['$ROOT/dir1', 'dir'] may logically
represent the same list if you're executing from $ROOT, but
we're not going to bother splitting strings into path elements,
or massaging strings into Nodes, to identify that equivalence.
We just want to eliminate obvious redun... | pathlist = tuple(SCons.Util.flatten(pathlist))
return pathlist
memoizer_counters.append(SCons.Memoize.CountDict('PathList', _PathList_key))
def PathList(self, pathlist):
"""
Returns the cached _PathList object for the specified pathlist,
creating and caching a new object as... |
ruediger/gcc-python-plugin | tests/plugin/functions/script.py | Python | gpl-3.0 | 3,300 | 0.003636 | # Copyright 2011 David Malcolm <dmalcolm@redhat.com>
# Copyright 2011 Red Hat, Inc.
#
# This is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) a... | l, gcc.FunctionDecl)
print('fn.decl.name: %r' % fn.decl.name)
assert isinstance(fn.decl, gcc.FunctionDecl)
#print(fn.decl.type)
#print(fn.dec | l.type.argument_types)
#pprint(fn.decl)
print('len(fn.local_decls): %r' % len(fn.local_decls))
for i, local in enumerate(fn.local_decls):
print('local_decls[%i]' % i)
print(' type(local): %r' % type(local))
print(' local.name: %r' % local.name)
... |
Programvareverkstedet/pensieve | pensieve.py | Python | gpl-2.0 | 789 | 0.017744 | #!/usr/bin/python
impo | rt os
import threading
import time
import Queue
import signal
import subprocess
import collections
from json_get import generate_list
q = Queue.Queue()
ls = collections.d | eque( generate_list())
def showstuff():
while ( True ):
sb = subprocess.Popen(["feh", "-Z", "-g" ,"800x400",ls[0]])
while( True ):
a = q.get()
print a
if ( a == "stop" ):
sb.terminate()
exit()
elif ( a == "next"):
... |
edusegzy/pychemqt | lib/mEoS/MD2M.py | Python | gpl-3.0 | 2,498 | 0.003205 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from lib.meos import MEoS
from lib import unidades
class MD2M(MEoS):
"""Multiparameter equation of state for decamethyltetrasiloxane"""
name = "decamethyltetrasiloxane"
CASNumber = "141-62-8"
formula = "C10H30Si4O3"
synonym = "MD2M"
rhoc = unidades.De... | Pc = unidades.Pressure(1227.0, "kPa")
M = 310.685 # g/mol
Tt = unidades.Temperature(205.2)
Tb = unidades.Temperature(467.51)
f_acent = 0.668
momentoDipolar = unidades.DipoleMoment(1.12, "Debye")
id = 39
# id = 1837
CP1 = {"ao": 331.9,
"an": [], "pow": [],
"ao_exp"... | ]}
helmholtz1 = {
"__type__": "Helmholtz",
"__name__": "Helmholtz equation of state for MD2M of Colonna et al. (2006).",
"__doi__": {"autor": "Colonna, P., Nannan, N.R., and Guardone, A.",
"title": "Multiparameter equations of state for siloxanes: [(CH3)3-Si-O1/2]2-[O-Si... |
enchuu/yaytp | video.py | Python | mit | 1,966 | 0.006104 | #!/usr/bin/env python
import subprocess
import time
from format import *
class Video():
""" Class to represent a Youtube video."""
def __init__(self, data):
self.id = data['id']
self.tit | le = data['title']
self.description = data['description']
self.user = data['uploader']
self.uploaded = time.strptime(data['uploaded'].replace(".000Z", "").replace("T", " "), "%Y-%m-%d %H:%M:%S")
self.views = int(data['viewCount' | ]) if 'viewCount' in data else 0
self.rating = float(data['rating']) if 'rating' in data else 0
self.likes = int(data['likeCount']) if 'likeCount' in data else 0
self.dislikes = int(data['ratingCount']) - self.likes if 'ratingCount' in data else 0
self.comment_count = int(data['commentCo... |
prefetchnta/questlab | bin/x64bin/python/37/Lib/importlib/_bootstrap_external.py | Python | lgpl-2.1 | 60,574 | 0.000528 | """Core implementation of path-based import.
This module is NOT meant to be directly imported! It has been designed such
that it can be bootstrapped into Python as the implementation of import. As
such it requires the injection of specific modules and attributes in order to
work. One should use importlib as the p... | a0: 62091 (with)
# Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
# Python 2.5b3: 62101 (fix wrong code: for x, in ...)
# Python 2.5b3: 62111 (fix wrong code: x += yield)
# Python 2.5c1: 62121 (fix wrong lnotab with for loops and
# storing constants that should | have been removed)
# Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
# Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
# Python 2.6a1: 62161 (WITH_CLEANUP optimization)
# Python 2.7a0: 62171 (optimize list comprehensions/change LIST_APPEND)
# Python 2.7... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.