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
wzyuliyang/ceph-note
aws2/python/usage_count/putCurrentBucket.py
Python
mit
656
0.012195
import requests import l
ogging from datetime import * from requests_toolbelt.utils import dump from awsauth import S3Auth # host = 'yuliyangdebugwebjewel.tunnel.qydev.com' host = 'yuliyangdebugweb68.tunnel.qydev.com' host = '10.254.9.20:7480' host = '127.0.0.1:7480' logging.basicConfig(level=logging.DEBUG) access_key = 'date2' secret_key = 'd...
%s' % (host,cmd) response = requests.put(url,auth=S3Auth(access_key, secret_key,service_url=host)) data = dump.dump_all(response) print(data.decode('utf-8'))
RedhawkSDR/framework-codegen
redhawk/packagegen/templates/__init__.py
Python
lgpl-3.0
847
0.002361
# # This file is protected by Copyright. Please refer to the COPYRIGHT file # distributed with this source distribution. # # This file is p
art of REDHAWK code-generator. # # REDHAWK code-generator is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) any # later version. # # REDHAWK code-gener...
uted 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 Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License # along with this p...
Vayne-Lover/Python
dictionary/test1.py
Python
apache-2.0
828
0.066425
#!/usr/local/bin/python #items=[('a','b'),(1,2)] #b=dict(items) #print b #c=dict(name='c',age=42) #print c #print len(c) #c['sex']='female' #print c #del c['age'] #print c #print 'sex' in c #c['age']=25 #print c #print c.clear() #print c #x={'name':'a','age':'14'} #y=x #print y #z=y.copy() #z.clear() #print x #print y ...
romkeys(['name','age'],'(hahaha)') #print b #print b.get('name') #print b.get('hi','N/A') #c={} #print c.has_key('name') #c['name']='Eric' #print c.has_key('name') #x={'name':'a','age':'14'} #print x.items() #print x.pop('age') #print x #y={} #print y.setdefault('name','N/A') #print y #y['name']='Apple' #y.setdefault('...
t x.values()
abrt/faf
src/pyfaf/storage/migrations/versions/1b264b21ca91_add_semrel_to_build.py
Python
gpl-3.0
2,436
0.002874
# Copyright (C) 2014 ABRT Team # Copyright (C) 2014 Red Hat, Inc. # # This file is part of faf. # # faf is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) ...
, sa.Integer), sa.Column("epoch", sa.Integer), sa.Column("version", sa.String(length=64)), sa.Column("release", sa.String(length=64)),
sa.Column("semver", custom_types.Semver()), sa.Column("semrel", custom_types.Semver()), ) for b in get_bind().execute(sa.select([build.c.id, build.c.release])): bid, brel = b brel = custom_types.to_semver(brel) get_bind().execute((bui...
mark-burnett/filament-dynamics
actin_dynamics/numerical/zero_crossings.py
Python
gpl-3.0
1,179
0.000848
# Copyright (C) 2011 Mark Burnett # # 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 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 ...
ssings(x, y, interpolate=True): zero_crossings = numpy.where(numpy.diff(numpy.sign(y)))[0] if not interpolate: return [x[i] for i in zero_crossings] results = [] for i in zero_crossings: results.append(interpolation.linear_project(y[i], x[i], ...
jabbalaci/FirefoxChecker
systray.py
Python
mit
4,260
0.000704
#!/usr/bin/env python2 # encoding: utf-8 """ A system tray icon indicates whether Firefox is running or not. I use Firefox and I have lots of tabs opened in it (I'm lazy to delete the old ones). As a result, when I close Firefox before shutting down my machine, Firefox needs several seconds to fully close (on one of ...
y_rc #PROCESS_NAME = 'gedit' # for testing PROCESS_NAME
= 'firefox' WAIT = 1.0 def is_process_running(name): """ Tell if a process is running. The proc object is cached so it doesn't need to be looked up every time. """ if not hasattr(is_process_running, "proc"): is_process_running.proc = None # it doesn't exist yet, so init it if is_...
vtemian/buffpy
examples/profiles.py
Python
mit
878
0
from pprint import pprint as pp from colorama import Fore from buffpy.api import API from buffpy.managers.profiles import Profiles # check http://bufferapp.com/developers/apps to retrieve a token # or generate one with the example token = "awesome_token" # instantiate the api object api = API(client_id="client_id"...
t_secret", access_token=token) # get all profiles profiles = Profiles(api=api) print(profiles.all()) # filter profiles using some criteria profile = Profiles(api=api).filter(service="twitter")[0] print(profile) # get schedules of my twitter profile profile = Profiles(api=api).filter(service
="twitter")[0] print(profile.schedules) # update schedules times for my twitter profile profile = Profiles(api=api).filter(service="twitter")[0] profile.schedules = { "days": ["tue", "thu"], "times": ["13:45"] }
lumig242/Video-Share-System
comments/models.py
Python
mit
335
0.00597
from
django.db import models from django.contrib.auth.models import User from video.models import Video # Create your models here. class Comment(models.Model): author = models.ForeignKey(User) video = models.ForeignKey(Video) content = models.TextField() time = models.DateTimeField(auto_now=
True, auto_now_add=True)
eduNEXT/edunext-platform
import_shims/studio/contentstore/rest_api/v1/serializers.py
Python
agpl-3.0
431
0.009281
"""Deprecated import support. Auto-generated by import_shims/generate_shims.sh.""" # pylint: disable=redefined-builtin,wrong-import-position,wildcard-import,useless-suppression,line-too-long from import_shims.warn import warn_deprecated_impo
rt warn_deprecated_import('contentstore.rest_api.v1.serializers', 'cm
s.djangoapps.contentstore.rest_api.v1.serializers') from cms.djangoapps.contentstore.rest_api.v1.serializers import *
messagebird/python-rest-api
messagebird/validation.py
Python
bsd-2-clause
173
0
from messagebird.error
import ValidationError def validate_is_not_blank(value, message): if value is None or not value.strip():
raise ValidationError(message)
cltrudeau/django-yacon
yacon/tests/test_site.py
Python
mit
4,408
0.002722
from django.test import TestCase from yacon.models.common import Language from yacon.models.site import Site, ParsedPath from yacon.models.hierarchy import BadSlug # ============================================================================ class SiteTests(TestCase): def test_hierarchy(self): british =...
de, grandchild2) self.assertEquals(pp.language, french) # test path parser with a mismatched path pp = site.parse_path('/foo') self.assertEquals(pp.path, '/foo') self.assertEquals(pp.slugs_in_path, []) self.assertEquals(pp.slugs_after_item, ['foo']) self.assertEq...
(pp.item_type, ParsedPath.UNKNOWN) # test path parser with a good path, including bits past the node parsed = site.parse_path('/child1/grandchild2/foo/b') self.assertEquals(parsed.path, '/child1/grandchild2/foo/b') self.assertEquals(parsed.slugs_in_path, ['child1', 'grandchild2']) ...
frogbywyplay/genbox_xbuilder
xbuilder/consts.py
Python
gpl-2.0
1,713
0
#!/usr/bin/python # # Copyright (C) 2006-2018 Wyplay, All Rights Reserved. # This file is part of xbuilder. # # xbuilder 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 # (a...
UILDER_LOGFILE = 'build.log' XBUILDER_REPORT_FILE = 'report.xml.bz2' XBUILDER_DEFTYPE = 'beta' XBUILDER_TARGET_COMMIT = False # Default values that can be modified in the config file # Keep only N beta releases, put 0 to disable XBUILDER_MAX_BETA_TARGETS = 5 XBUILDER_CLEAN_WORKDIR = True XBUILDER_TARGET_C
OMMIT = True XBUILDER_FEATURES = '' XBUILDER_WORKDIR = '/usr/targets/xbuilder' XBUILDER_ARCHIVE_DIR = '/opt/xbuilder' XBUILDER_COMPRESSION = 'xz' XBUILDER_MAIL_FROM = '[email protected]' XBUILDER_MAIL_TO = '[email protected]' XBUILDER_MAIL_SMTP = 'localhost' XBUILDER_MAIL_LOG_SIZE = 20 * 1024 XBUILDER_MAIL_URI...
lisa-lab/pylearn2
pylearn2/models/gsn.py
Python
bsd-3-clause
36,325
0.001514
""" Generative Stochastic Networks This is described in: - "Generalized Denoising Auto-Encoders as Generative Models" Bengio, Yao, Alain, Vincent. arXiv:1305.6663 - "Deep Generative Stochastic Networks Trainable by Backprop" Bengio, Thibodeau-Laufer. arXiv:1306.1091 There is an example of training both unsuper...
identity from pylearn2.models.autoencoder import Autoencoder from pylearn2.models.model import Model from pylearn2.utils import safe_zip # Enforce correct restructured text list format. # Be sure to re-run docgen.py and make sure there are no wa
rnings if you # modify the module-level docstring. assert """: - """ in __doc__ class GSN(StackedBlocks, Model): """ .. todo:: WRITEME Parameters ---------- autoencoders : list A list of autoencoder objects. As of now, only the functionality from the base Autoencoder clas...
mrmiguez/citrus_harvest
citrus_harvest/pyoaiharvester/pyoaiharvest.py
Python
mit
4,976
0.002814
#!/usr/bin/env python2 #created by Mark Phillips - https://github.com/vphill import sys import urllib2 import zlib import time import re import xml.dom.pulldom import operator import codecs from optparse import OptionParser nDataBytes, nRawBytes, nRecoveries, maxRecoveries = 0, 0, 0, 3 def getFile(serverString, com...
mdPrefix = options.mdp
refix if options.setName: oaiSet = options.setName else: print usage if not serverString.startswith('http'): serverString = 'http://' + serverString print "Writing records to %s from archive %s" % (outFileName, serverString) ofile = codecs.lookup('utf-8')[-1](file(...
plotly/python-api
packages/python/plotly/plotly/validators/surface/_meta.py
Python
mit
480
0
import _plotly_utils.basevalidators class MetaValidator(_plotly_utils.basevalidators.AnyValidator): def __init__(self, plotly_name="meta", parent_name="surface", **kwarg
s): super(Me
taValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, array_ok=kwargs.pop("array_ok", True), edit_type=kwargs.pop("edit_type", "plot"), role=kwargs.pop("role", "info"), **kwargs )
Daniel-CA/odoo-addons
product_stock_on_hand/models/product.py
Python
agpl-3.0
1,953
0
# -*- coding: utf-8 -*- # Copyright 2017 Ainara Galdona - AvanzOSC # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from openerp import models, fields, api from openerp.addons import decimal_precision as dp class ProductTemplate(models.Model): _inherit = 'product.template' @api.depends('pro...
def _compute_stock_on_hand(self): for record in self: record.stock_on_hand = sum( record.quant_ids.filtered( lambda x: x.location_id.stock_on_hand and not x.reservation_id).mapped('qty')) stock_on_hand = fields.Float( string="Stoc...
_ids = fields.One2many(comodel_name='stock.quant', inverse_name='product_id', string='Quants')
owtf/owtf
owtf/plugins/web/external/[email protected]
Python
bsd-3-clause
305
0
from owtf.managers.resource import get_resources from owtf.plugin.helper import plugin_helper DESCRIPTION = "Plugin to assist manual testing" def run(PluginInfo): resource = get_resources("Externa
lSSL") Content = plugin_h
elper.resource_linklist("Online Resources", resource) return Content
xran-deex/Toury-Django
Toury/admin.py
Python
mit
91
0
f
rom django.contrib import admin from Toury.models import * admin.site.regis
ter(Marker)
NECCSiPortal/NECCSPortal-dashboard
nec_portal/dashboards/admin/history/views.py
Python
apache-2.0
8,004
0
# -*- coding: utf-8 -*- # 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, ...
rt_value == '' or end_value == '': start_value = default_term[0] end_value = default_term[1] SESSION_DICTIONARY['start'] = start_value
SESSION_DICTIONARY['end'] = end_value request.session[SESSION_HISTORY_KEY] = SESSION_DICTIONARY elif referer_url is not None and request.path in referer_url: # When reload screen, value get from session data. search_value = session.get('search', search_value) ...
sdh11/gnuradio
gr-fec/python/fec/extended_tagged_decoder.py
Python
gpl-3.0
6,542
0.000611
#!/usr/bin/env python # # Copyright 2014 Free Software Foundation, Inc. # # This file is part of GNU Radio # # SPDX-License-Identifier: GPL-3.0-or-later # # from gnuradio import gr, blocks, digital from . import fec_python as fec from .bitflip import read_bitlist class extended_tagged_decoder(gr.hier_block2): ...
r_input_item_size(decoder_obj), fec.get_decoder_output_item_size(decoder_obj), ) ) else: self.block
s.append( fec.tagged_decoder( decoder_obj, fec.get_decoder_input_item_size(decoder_obj), fec.get_decoder_output_item_size(decoder_obj), lentagname, mtu, ) ...
thesealion/writelightly
writelightly/tests/base.py
Python
mit
4,192
0.00334
import curses import random class Screen(object): def __init__(self, maxy, maxx): self.setmaxyx(maxy, maxx) self.pos = (0, 0) def clear(self, *args): if not args: y, x = self.getmaxyx() self.lines = [] for i in range(y): self.lines.ap...
ame = keyname curses.start_color = lambda: None curses.patched = True def get_ran
dom_lines(num=None, width=None): letters = [chr(c) for c in range(97, 123)] + [' '] if not num or not width: y, x = get_screen().getmaxyx() if not num: num = y + 50 if not width: width = x - 1 def get_line(): line = ''.join([random.choice(letters) ...
developerQuinnZ/this_will_work
student-work/hobson_lane/exercism/python/isogram/isogram.py
Python
mit
428
0.002336
def is_isogram(s): """ Determine if a word or phrase
is an isogram. An isogram (also known as a "nonpattern word") is a word or phrase without a repeating letter. Examples of isograms: - lumberjacks - background - downstream """ from collections import Counter s = s.lower().strip() s = [c for c in s if c.isalpha()] counts = Cou...
r [1]) == 1
racker/txzookeeper
txzookeeper/retry.py
Python
gpl-3.0
10,571
0
# # Copyright (C) 2011 Canonical Ltd. All Rights Reserved # # This file is part of txzookeeper. # # Authors: # Kapil Thangavelu # # txzookeeper is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, ei...
WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GN
U Lesser General Public License # along with txzookeeper. If not, see <http://www.gnu.org/licenses/>. # """ A retry client facade that transparently handles transient connection errors. """ import time import zookeeper from twisted.internet.defer import inlineCallbacks, returnValue, Deferred __all__ = ["retry", ...
NoBodyCam/TftpPxeBootBareMetal
nova/tests/test_plugin_api_extensions.py
Python
apache-2.0
2,869
0.000349
# Copyright 2011 OpenStack LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
service_list.append(service_name) class MockEntrypoint(pkg_resources.EntryPoint): def load(self): return TestPluginClass class APITestCase(test.TestCase): """Test case for the plugin api extension interface""" def test_add_extension(self): def mock_load(_s): return TestPlu...
return [MockEntrypoint("fake", "fake", ["fake"])] self.stubs.Set(pkg_resources, 'iter_entry_points', mock_iter_entry_points) global service_list service_list = [] # Marking out the default extension paths makes this test MUCH faster. self.flags(osapi_compu...
angvp/gord
gord/common.py
Python
apache-2.0
3,534
0.010187
#!/usr/bin/python2.4 # # Copyright 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
henticationError): """T
he auth ticket was valid, but access was denied.""" class InvalidMethod(Fatal): """An invalid (non-existent or _private) method was called on GORD.""" class InvalidOption(Fatal): """An invalid option was specified to a GORD method.""" class InvalidArgumentsError(Fatal): """Invalid arguments were passed.""" ...
hyperNURb/ggrc-core
src/tests/ggrc_workflows/notifications/test_recurring_cycles.py
Python
apache-2.0
3,679
0.008154
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: [email protected] # Maintained By: [email protected] import random from tests.ggrc import TestCase from freezegun import freeze_time ...
"contact": person_dict(self.assignee.id), "description": self.generator.random_str(10
0), "relative_start_day": 5, "relative_start_month": 2, "relative_end_day": 25, "relative_end_month": 2, }, ], }, ] } self.all_workflows = [ self.quarterly_wf_1, ]
mlundblad/telepathy-gabble
tests/twisted/sasl/saslutil.py
Python
lgpl-2.1
5,861
0.004949
# hey, Python: encoding: utf-8 from twisted.words.protocols.jabber.xmlstream import NS_STREAMS from gabbletest import XmppAuthenticator from base64 import b64decode, b64encode from twisted.words.xish import domish import constants as cs import ns from servicetest import (ProxyWrapper, EventPattern, assertEquals, ...
features = domish.Element((NS_STREAMS, 'features')) bind = features.addElement((ns.NS_XMPP_BIND, 'bind')) self.xmlstream.send(features) self.xmlstr
eam.addOnetimeObserver( "/iq/bind[@xmlns='%s']" % ns.NS_XMPP_BIND, self.bindIq) else: features = domish.Element((NS_STREAMS, 'features')) mechanisms = features.addElement((ns.NS_XMPP_SASL, 'mechanisms')) for mechanism in self._mechanisms: mecha...
mupen64plus-ae/mupen64plus-ae
ndkLibs/miniupnp/minissdpd/submit_to_minissdpd.py
Python
gpl-3.0
1,938
0.004644
#!/usr/bin/env python3 # vim: sw=4 ts=4 expandtab # (c) 2021 Thomas BERNARD # Python3 module to submit service to running MiniSSDPd # MiniSSDPd: See http://miniupnp.free.fr/minissdpd.html import socket, os def codelength(s): """ returns the given string/bytes as bytes, prepended with the 7-bit-encoded length """ ...
t.SOCK_STREAM) try: sock.connect(sockpath) sock.send(b'\x04' + codelength(st) + codelength(usn) + codelength(server) + codelength(url)) ex
cept socket.error as msg: print(msg) return -1, msg finally: sock.close() return 0, "OK" if __name__ == "__main__": # Example usage rc, message = submit_to_minissdpd( b'urn:schemas-upnp-org:device:InternetGatewayDevice:1', b'uuid:73616d61-6a6b-7a74-650a-0d24d4a5...
jamespcole/home-assistant
homeassistant/components/dlib_face_detect/image_processing.py
Python
apache-2.0
2,155
0
""" Component that will help set the Dlib face detect processing. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/image_processing.dlib_face_detect/ """ import logging import io from homeassistant.core import split_entity_id # pylint: disable=unused-impo...
, discovery_info=None): """Set up the Dlib Face detection platform.""" entities = [] for camera in config[CONF_SOURCE]: entities.append(DlibFaceDetectEntity( camera[CONF_ENTITY_ID], camera.get(CONF_NAME) )) add_entities(entities) class DlibFaceDetectEntity(ImageProcessingF...
"""Initialize Dlib face entity.""" super().__init__() self._camera = camera_entity if name: self._name = name else: self._name = "Dlib Face {0}".format( split_entity_id(camera_entity)[1]) @property def camera_entity(self): "...
sk89q/Plumeria
plumeria/core/scoped_config/__init__.py
Python
mit
4,341
0.002534
import logging from plumeria.command import commands, CommandError from plumeria.core.storage import pool from plumeria.core.user_prefs import prefs_manager from plumeria.message import Message from plumeria.message.mappings import build_mapping from plumeria.perms import direct_only from plumeria.core.scoped_config.m...
await prefs_manager.put(pref, message.author, raw_value) shown_value = raw_value if not pref.private else "(private)" return "Set **{}** to '{}' for yourself.".format(name, shown_value) except (NotImplementedError, ValueError) as e: raise CommandError("Could not set **{}**: {}".
format(name, str(e))) @commands.create('pref unset', 'prefs unset', 'punset', cost=4, category='User Preferences') @direct_only async def unset(message: Message): """ Remove a user preference that you have set. Example:: /punset ifttt_maker_key """ pref = find_preference(message.content....
MD-Studio/MDStudio
core/logger/logger/application.py
Python
apache-2.0
4,843
0.003097
# -*- coding: utf-8 -*- from logger.log_repository import LogRepository from mdstudio.api.api_result import APIResult from mdstudio.api.comparison import Comparison from mdstudio.api.endpoint import endpoint, cursor_endpoint from mdstudio.api.exception import CallException from mdstudio.component.impl.core import CoreC...
): try: event = request['event'] tags = event.pop('tags') res = yield self.logs.insert(self._clean_claims(claims), [self._map_level(event)], tags) except CallException as _: return_value(APIResult(error='The database is not online, please try again later.'...
) def authorize_request(self, uri, claims): connection_type = LogType.from_string(claims['logType']) if connection_type == LogType.User: return ('username' in claims) is True elif connection_type == LogType.Group: return ('group' in claims) is True elif conn...
nandub/yammer
lib/KeyStore.py
Python
gpl-2.0
2,728
0.025293
# Copyright 2002, 2004 John T. Reese. # email: jtr at ofb.net # # This file is part of Yammer. # # Yammer 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...
0: try: yg= YGaleClient() msg= 'new key: %(id)s %(name)s' % locals() if
source is not None: msg += ' (via %s)' % source yg.gsend(id, ['_gale.notice.' + id], msg) except: pass return else: return error
bobflagg/deepER
notebook/evaluation.py
Python
apache-2.0
5,910
0.00643
from collections import OrderedDict def _update_chunk(candidate, prev, current_tag, current_chunk, current_pos, prediction=False): if candidate == 'B-' + current_tag: if len(current_chunk) > 0 and len(current_chunk[-1]) == 1: current_chunk[-1].append(current_pos - 1) current_chunk.a...
tot_prec=total_precision, tot_recall=total_recall, tot_f1=total_f1)) def _print_tag_metrics(tag, tag_results): print(('\t%12s' % tag) + ': precision: {tot_prec:6.2f}%; ' \ 'recal...
redicted:4d}\n'.format(tot_prec=tag_results['precision'], tot_recall=tag_results['recall'], tot_f1=tag_results['f1'], ...
DE-IBH/cmk_cisco-dom
perfometer/cisco_dom.py
Python
gpl-2.0
1,321
0.004542
#!/usr/bin/python # -*- encoding: utf-8; py-indent-offset: 4 -*- # cmk_cisco-dom - check-mk plugin for SNMP-based Cisco Digital-Optical-Monitoring monitoring # # Authors: # Thomas Liske <[email protected]> # # Copyright Holder: # 2015 - 2016 (C) IBH IT-Service GmbH [http://www.ibh.de/] # # License: # This program is ...
T ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this package; if not, write to the Free Software # Foundation, ...
def perfometer_cisco_dom(row, check_command, perf_data): color = { 0: "#a4f", 1: "#ff2", 2: "#f22", 3: "#fa2" }[row["service_state"]] return "%.1f dBm" % perf_data[0][1], perfometer_logarithmic(perf_data[0][1] + 20, 20, 2, color) perfometers["check_mk-cisco_dom"] = perfometer_cisco_dom
KHU-YoungBo/pybluez
bluetooth/__init__.py
Python
gpl-2.0
5,991
0.002337
import sys import os if sys.version < '3': from .btcommon import * else: from bluetooth.btcommon import * __version__ = 0.22 def _dbg(*args): return sys.stderr.write(*args) sys.stderr.write("\n") if sys.platform == "win32": _dbg("trying widcomm") have_widcomm = False dll = "wbtapi.dll...
mport * have_widcomm = True except ImportError: pass if not have_widcomm: # otherwise, fall back to the Microsoft stack _dbg("Widcomm not ready. falling back to MS stack") if
sys.version < '3': from .msbt import * else: from bluetooth.msbt import * elif sys.platform.startswith("linux"): if sys.version < '3': from .bluez import * else: from bluetooth.bluez import * elif sys.platform == "darwin": from .osx import * else: raise ...
ipfs/py-ipfs-api
test/unit/test_http_httpx.py
Python
mit
2,058
0.026725
# Only add tests to this file if they really are specific to the behaviour # of this backend. For cr
oss-backend or `http_common.py` tests use # `test_http.py` instead. import http.cookiejar import math import pytest pytest.importorskip("ipfshttpclient.http_httpx") import ipfshttpclient.http_httpx cookiejar = http.cookiejar.CookieJar() @pytest.mark.parametrize("kwargs,expe
cted", [ ({}, {}), ({ "auth": ("user", "pass"), "cookies": cookiejar, "headers": {"name": "value"}, "params": (("name", "value"),), "timeout": (math.inf, math.inf), }, { "auth": ("user", "pass"), "cookies": cookiejar, "headers": {"name": "value"}, "params": [("name", "value")], "timeout": (None...
clungzta/rsync_ros
src/rsync_server_node.py
Python
bsd-3-clause
4,108
0.003651
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2016, Alex McClung # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must ...
f.result.sync_success = self.rsync.sync() if not self.server.is_preempt_requested(): if self.rsync.stderr_block: rospy.logerr('\n{}'.format(self.rsync.stderr_block)) rospy.loginfo("Rsync command result '%s'", self.result.sync_success) self.server.set_succee...
RsyncActionServer(rospy.get_name()) rospy.spin() except rospy.ROSInterruptException: pass
katthjul/anifs
setup.py
Python
mpl-2.0
212
0.004717
#!/usr/bin/env python from distutils.core import setup s
etup(name='anifs', version='0.
1', packages=['anifs'], scripts=['bin/anifs'], install_requires=[ "adba", ], )
tarikgwa/nfd
newfies/dialer_contact/templatetags/dialer_contact_tags.py
Python
mpl-2.0
689
0
# # Newfies-Dialer License # http://www.newfies-di
aler.org # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (C) 2011-2014 Star2Billing S.L. # # The primary maintainer of this project is # Arezqui Belaid <...
.defaultfilters import register @register.filter(name='contact_status') def contact_status(value): """Contact status >>> contact_status(1) 'ACTIVE' >>> contact_status(2) 'INACTIVE' """ return str('ACTIVE') if value == 1 else str('INACTIVE')
zhengger/seafile
tests/sync-auto-test/test_cases/test_simple.py
Python
gpl-2.0
1,826
0.007119
#
coding: utf-8 import os import time from . import test_util def test_add_file(): test_util.mkfile(1, 'a.md', 'add a file') test_util.verify_result() def test_add_file_t(): test_util.mkfile(2, 'l/m/n/test.md', 'add l/m/n/test.md') test_
util.verify_result() def test_add_dir(): test_util.mkdir(1, 'ad') test_util.verify_result() def test_add_dir_t(): test_util.mkdir(2, 'tt/ee/st') test_util.verify_result() def test_modify_file(): test_util.modfile(1, 'a.md', 'modify a.md') test_util.verify_result() def test_rm_file(): tes...
deljuven/Guozijian
face/ImageDetector.py
Python
gpl-3.0
2,562
0
#!/usr/bin/env python2 # -*- coding: utf-8 -*- import time from io import BytesIO import requests from PIL import Image, ImageDraw from facepp import API, File API_KEY = '185839fab47af2675b5e458275215a39' API_SECRET = 'x7EXrX4c5WgIjAQ9un3SgI4-QYTad7Dx' class ImageDetector: ''' Image Detector class demo''' ...
red') del draw image.save(self.file_path) # return: face counts return face_counts # if __name__ == '__main__': # try: # vs = VideoService() # url = vs.take_picture() # detector = ImageDetector(url) # faces = detector.detect() # detector.save...
print e.msg
jku/telepathy-gabble
tests/twisted/vcard/update-get-failed.py
Python
lgpl-2.1
1,108
0.004513
""" Test the case where the vCard get made prior to a vCard set fails. """ from servicetest import call_async, EventPattern from gabbletest import ( acknowledge_iq, elem, exec_test, make_result_iq, sync_stream) import constants as cs import ns def test(q, bus, conn, stream): event = q.expect('stream-iq', to=...
GetSelfHandle() call_async(q, conn.Avatars, 'SetAvatar', 'william shatner',
'image/x-actor-name') event = q.expect('stream-iq', iq_type='get', to=None, query_ns='vcard-temp', query_name='vCard') reply = make_result_iq(stream, event.stanza) reply['type'] = 'error' reply.addChild(elem('error')( elem(ns.STANZA, 'forbidden')(), elem(ns.STANZA, 'text')(u'z...
TheCodingMonkeys/checkin-at-fmi
checkinatfmi_project/university/tests.py
Python
agpl-3.0
694
0
""" This file demonstrates writing tests using the unittest module.
These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ from django.test import TestCase from models import Place class SimpleTest(TestCase): def test_simple_place_creation(se
lf): """ Creates test place """ places = Place.objects.filter(name="Test Place") [place.delete() for place in places] place = Place() place.name = "Test Place" place.capacity = 20 place.save() place = Place.objects.filter(name="Test Place...
googleapis/python-certificate-manager
samples/generated_samples/certificatemanager_v1_generated_certificate_manager_update_certificate_async.py
Python
apache-2.0
1,628
0.001843
# -*- coding: utf-8 -*- # Copyright 2022 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...
ertificate_manager_v1.UpdateCertificateRequest( ) # Make the request operation = client.update_certificate(request=request) print("Waiting for operation to complete...") response = await operation.result() # Handle the response print(response) # [END c
ertificatemanager_v1_generated_CertificateManager_UpdateCertificate_async]
gsi-upm/SmartSim
smartbody/data/examples/Tutorials/7_FacialAnimationSpeech.py
Python
apache-2.0
2,969
0.000337
print "|--------------------------------------------|" print "| Starting Tutorial 7 |" print "|--------------------------------------------|" print 'media path = ' + scene.getMediaPath() # Add asset paths assetManager = scene.getAssetManager() assetManager.addAssetPath('motion', 'ChrBrad') ...
etManager.addAssetPath('script', 'scripts') # Load assets based on asset paths assetManager.loadAssets() # set the camera scene.setScale(1.0) scene.run('default-viewer.py') # run a Python script file scene.run('zebra2-map.py') zebra2Map = scene.getJointMapManager().getJointMap('zebra2') bradSkeleton = scen...
zebra2Map.applyMotionRecurse('ChrBrad') # Set up Brad brad = scene.createCharacter('ChrBrad', '') bradSkeleton = scene.createSkeleton('ChrBrad.sk') brad.setSkeleton(bradSkeleton) # Set standard controller brad.createStandardControllers() print 'Setting up Brad\'s face definition' bradFace = scene.createFa...
Jolopy/GimpHub
app/Gimp_Plugins_Bak/continious_test.py
Python
gpl-2.0
10,833
0.004154
#!/usr/bin/env python from socketIO_client import SocketIO, BaseNamespace from gimpfu import * import os import time from threading import Thread from array import array import requests import configparser import websocket import _thread import http.client class GimpHubImage(object): def __init__(self, drawabl...
pixelR = pixel[0] + "\x00\x00"
pixelG = "\x00" + pixel[1] + "\x00" pixelB = "\x00\x00" + pixel[2] # If the image has an alpha channel (or any other channel) copy his values. if (len(pixel) > 3): for k in range(len(pixel) - 3): ...
icarrera/django-imager
imagersite/imager_images/migrations/0005_photo.py
Python
mit
1,508
0.003979
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-13 14:53 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): dependencies = [ migrations.swappable_dependen...
shed', models.DateTimeField(blank=True, null=True)), ('published', models.CharField(choices=[('private', 'private'), ('share
d', 'shared'), ('public', 'public')], default='private', max_length=255)), ('photos', models.ManyToManyField(related_name='photos', to='imager_images.Album')), ('user', models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ...
Karaage-Cluster/karaage
karaage/management/commands/vacant_projects.py
Python
gpl-3.0
1,034
0.001934
import sys import django.db.transaction from django.core.management.base import BaseCommand from karaage.projects.models import Project class Command(BaseCommand): help = "return a list of projects with no currently active users" @django.db.transaction.non_atomic_requests def handle(self, *args, **opti...
for selectedProject in Project.objects.all(): members = selectedProject.group.members.all() memberCount = 0 invalidCount = 0 for person in members: if person.is_active and person.login_enabled: memberCount += 1 else: ...
stdout.write("{}: {} locked users".format(selectedProject.pid, invalidCount)) sys.stdout.write("\n") sys.stdout.write("{} inactive/unpopulated projects\n".format(badProjects)) sys.stdout.write("Done\n")
mbayon/TFG-MachineLearning
venv/lib/python3.6/site-packages/scipy/optimize/_trustregion_ncg.py
Python
mit
4,646
0
"""Newton-CG trust-region optimization.""" from __future__ import division, print_function, absolute_import import math import numpy as np import scipy.linalg from ._trustregion import (_minimize_trust_region, BaseQuadraticSubproblem) __all__ = [] def _minimize_trust_ncg(fun, x0, args=(), jac=None, hess=None, hess...
# do an iteration Bd = self.hessp(d) dBd = np.dot(d, Bd) if dBd <= 0: # Look at the two boundary points. # Find both values of t to get the boundary points such that # ||z + t d|| == trust_radius # and then choose the ...
f.get_boundaries_intersections(z, d, trust_radius) pa = z + ta * d pb = z + tb * d if self(pa) < self(pb): p_boundary = pa else: p_boundary = pb hits_boundary = True return p_boundary,...
pronexo-odoo/odoo-argentina
l10n_ar_receipt/report/receipt_print.py
Python
agpl-3.0
1,664
0.003005
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C)
2012 Silvina Fa
ner (<http://tiny.be>). # # 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 Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is dist...
fareskalaboud/pybugger
pybugger/pybugger.py
Python
gpl-3.0
4,133
0.003629
import random from pybugger import myaixterm color = myaixterm color.aix_init() def string_constructor(args, foreground="normal", background="normal"): if foreground != "rainbow": foreground = "" if foreground == "normal" else color.aix_fg(foreground) background = "" if background == "normal" els...
t you") print("") print("pybugger.custom(lyric, \"color119\", \"color93\")") custom("Never gonna make you cry", "color119", "color93") print("") print("pybugger.inverted(*lyric)") inverted("Never gonna say goodbye.") print("") print("pybugger.default(*lyric)")
default("Never gonna tell a lie and hurt you.\"") print("")
ael-code/libreant
webant/api/archivant_api.py
Python
agpl-3.0
6,972
0.001865
import json import tempfile import os from werkzeug import secure_filename from webant.util import send_attachment_file, routes_collector from flask import request, current_app, url_for, jsonify from archivant import Archivant from archivant.exceptions import NotFoundException from util import ApiError, make_success_re...
iError("volume not found", 404, details=str(e)) finally: # remove temp files os.remove(fileInfo['file']) link_self = url_for('.get_attachment', volumeID=volumeID, attachmentID=attach
mentID, _external=True) response = jsonify({'data': {'id': attachmentID, 'link_self': link_self}}) response.status_code = 201 response.headers['Location'] = link_self return response @route('/volumes/<volumeID>/attachments/<attachmentID>', methods=['GET']) def get_attachment(volumeID, attachmentID): ...
Azure/azure-sdk-for-python
sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/projects/aio/_configuration.py
Python
mit
3,321
0.004517
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
stionanswering/{}'.format(VERSION)) self._configure(**kwargs) def _configure(
self, **kwargs: Any ) -> None: self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(...
idlesign/django-sitetree
sitetree/management/commands/sitetreedump.py
Python
bsd-3-clause
2,050
0.003902
from django.core import serializers from django.core.management.base import BaseCommand, CommandError from django.db import DEFAULT_DB_ALIAS from sitetree.utils import get_tree_model, get_tree_item_model from sitetree.compat import CommandOption, option
s_getter MODEL_TREE_CLASS = get_tree_model() MODEL_TREE_ITEM_CLASS = get_tree_item_model() get_options = options_getter(( CommandOption( '--indent', default=None, dest='indent', type=int, help='Specifies the indent level to use when pretty-printing outpu
t.'), CommandOption('--items_only', action='store_true', dest='items_only', default=False, help='Export tree items only.'), CommandOption('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a specific database to export fixtures from. Defaults to the "def...
Outernet-Project/squery-lite
tests/test_squery.py
Python
bsd-3-clause
15,587
0
import mock import pytest from squery_lite import squery as mod MOD = mod.__name__ @mock.patch(MOD + '.sqlite3', autospec=True) def test_connection_object_connects(sqlite3): """ Connection object starts a connection """ conn = mod.Connection('foo.db') sqlite3.connect.assert_called_once_with( 'f...
cur.execute("insert into foo values ('c')") cur.execute("insert into foo values ('d')") cur.execute("insert into foo values ('e')") cur.execute("select concat(i) as a from foo order by i") assert cur.re
sult.a == 'abcde' @mock.patch(MOD + '.sqlite3') def test_db_connect(sqlite3): mod.Database.connect('foo.db') sqlite3.connect.assert_called_once_with( 'foo.db', detect_types=sqlite3.PARSE_DECLTYPES) @mock.patch(MOD + '.sqlite3') def test_db_uses_dbdict(sqlite3): """ The database will use a dbdict...
VRSandeep/icrs
website/urls.py
Python
mit
191
0
fr
om django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.home), url(r'^interviewer/$', views.interviewer), url(r'^candidate/$', views.
candidate), ]
all-of-us/raw-data-repository
rdr_service/lib_fhir/fhirclient_1_0_6/models/identifier.py
Python
bsd-3-clause
2,304
0.009549
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated from FHIR 1.0.2.7202 (http://hl7.org/fhir/StructureDefinition/Identifier) on 2016-06-23. # 2016, SMART Health IT. from . import element class Identifier(element.Element): """ An identifier intended for computation. A technical identifier - id...
nted as `dict` in JSON). """ self.use = None """ usual | official | temp | secondary (If known). Type `str`. """ self.value = No
ne """ The value that is unique. Type `str`. """ super(Identifier, self).__init__(jsondict=jsondict, strict=strict) def elementProperties(self): js = super(Identifier, self).elementProperties() js.extend([ ("assigner", "assigner", fhirreference.FHIRR...
galad-loth/DescHash
DeepHash/common/data.py
Python
apache-2.0
3,986
0.035625
import numpy as npy import struct import os from scipy import io as scio from mxnet import io as mxio def ReadFvecs(dataPath, dataFile, start=0, end=-1): filePath=os.path.join(dataPath,dataFile) with open(filePath,mode="rb") as fid: buf=fid.read(4) dimFeat=struct.unpack("i", buf[:4]) ...
d>numVec or start>end): print("Start/End index is out of the data range") numDataEntry=(end-start)*(dimFeat[0]+1) numReadByte=numDataEntry*4 fid.seek(start*numVecByte,0) buf=fid.read(numReadByte) data=npy.array(struct.unpack("f"*numDataEntry, buf[:numReadByte]))...
th,dataFile) with open(filePath,mode="rb") as fid: buf=fid.read(4) dimFeat=struct.unpack("i", buf[:4]) numVecByte=(dimFeat[0]+1)*4 fid.seek(0,2) numVec=fid.tell()/numVecByte if end<0: end=numVec if (start<0 or start>numVec or end...
mmpagani/oq-hazardlib
openquake/hazardlib/tests/gsim/utils_test.py
Python
agpl-3.0
2,240
0
# The Hazard Library # Copyright (C) 2014, GEM Foundation # # 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 Software Foundation, either version 3 of the # License, or (at your option) any later version. # # T...
OSE. 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/>. import unittest import numpy from openquake.hazardlib.gsim.utils import ( mblg_to_mw_johnston_96, ...
.TestCase): def test_mblg_to_mw_johnston_96(self): mblg = 5 mw = mblg_to_mw_johnston_96(mblg) self.assertAlmostEqual(mw, 4.6725) def test_mblg_to_mw_atkinson_boore_87(self): mblg = 5 mw = mblg_to_mw_atkinson_boore_87(mblg) self.assertAlmostEqual(mw, 4.5050) cla...
mastizada/kuma
vendor/packages/feedparser/docs/add_custom_css.py
Python
mpl-2.0
125
0
# Makes Sphinx cr
eate a <link> to feedparser.css in the HTML output def setup(app): app.add_stylesheet('feedparser.cs
s')
RyanDJLee/pyta
examples/invalid_range_index_example.py
Python
gpl-3.0
197
0
for i in range(0): i += 1 for j
in range(0, 1, 3): j += 1 for k in range(9, 1, -9): k += 1 for n
in range(0, 1.1): # Error on this line n += 1 for m in range(4, 5): m += 1
Br1an6/ACS_Netplumber_Implementation
hassel-c/net_plumbing/examples/stanford/generate_rules_json_file.py
Python
gpl-2.0
3,170
0.026814
''' Created on Sep 15, 2012 @author: peyman kazemian ''' from examples_utils.network_loader import load_network from config_parser.cisco_router_parser import cisco_router from utils.wildcard import wildcard_create_bit_repeat from utils.wildcard_utils import set_header_field from headerspace.hs import headerspace from ...
rtr", "bozb_rtr", "coza_rtr", "cozb_rtr", "goza_rtr", "gozb_rtr", "poza_rtr", "pozb_rtr", "roza_rtr", "rozb_
rtr", "soza_rtr", "sozb_rtr", "yoza_rtr", "yozb_rtr", ] table_id = 0 topo = json.load(open(in_path+"/"+"topology.tf.json")) topology = {"topology":[]} for rule in topo["rules"]: in_ports = rule["in_ports"] out_ports = rule["out_ports"] for in_port in in_po...
dwhickox/NCHS-Programming-1-Python-Programs
Chap 5/MoviesProj.py
Python
mit
954
0.01782
#D
avid Hickox #May 2 17 #Chap 5 test EC #sorts a list of movies and actors #variables # movie, Stores the movie data # actors, stotes the actor data print("Welcome to the (enter name here bumbblefack) Program\n") movie = [] actors = [] for i in range(5): movie.append((input("Movie "+str(i+1)+"? ")).title()) ...
movie[i]+"? ")).title()) rng = len(movie) sw = 1 while sw == 1: sw = 0 for i in range(rng): if movie[i]<movie[i-1] and i != 0: sw = 1 temp = movie[i] tempa = actors[i] movie[i] = movie[i-1] actors[i] = actors[i-1] movie[i-1] = tem...
koder-ua/nailgun-fcert
nailgun/nailgun/test/unit/test_deployment_serializer.py
Python
apache-2.0
4,224
0
# Copyright 2014 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
zer` function. """ @mock.patch( 'nailgun.orchestrator.deployment_serializers.extract_env_version', return_value='5.0') def test_retreiving_ha_for_5_0(self, _): cluster = mock.MagicMock(is_ha_mode=True) self.assertTrue( isinstance( ds.create_serial...
lizer)) @mock.patch( 'nailgun.orchestrator.deployment_serializers.extract_env_version', return_value='5.0') def test_retreiving_multinode_for_5_0(self, _): cluster = mock.MagicMock(is_ha_mode=False) self.assertTrue( isinstance( ds.create_serializer(cl...
openbroadcaster/obplayer
obplayer.py
Python
agpl-3.0
887
0.003382
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Copyright 2012-2015 OpenBroadcaster, Inc. This file is part of OpenBroadcaster Player. OpenBroadcaster Player 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...
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 PURPOS
E. 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 OpenBroadcaster Player. If not, see <http://www.gnu.org/licenses/>. """ import obplayer obplayer.main()
davidliwei/mageck
mageck/mageckCount.py
Python
bsd-3-clause
14,299
0.051542
#!/usr/bin/env python """ MAGeCK count module Copyright (c) 2014 Wei Li, Han Xu, Xiaole Liu lab This code is free software; you can redistribute it and/or modify it under the terms of the BSD License (see the file COPYING included with the distribution). @status: experimental @version: $Revision$ @author: Wei Li @c...
def mageckcount_printdict(dict0,args,ofile,sgdict,datastat,sep='\t'): ''' Write the table count to file ''' allfastq=args.fastq; nsample=len(allfastq); slabel=[datastat[f.split(',')[0]]['label'] for f in allfastq]; # print header print('sgRNA'+sep+'Gene'+sep+sep.join(slabel),file=ofile); # print items...
sep+sep.join([str(x) for x in v]),file=ofile); else: for (k,v) in dict0.iteritems(): if k not in sgdict: # only print those in the genedict continue; sx=sgdict[k]; print(sep.join([sx[0],sx[1]])+sep+sep.join([str(x) for x in v]),file=ofile); # print the remaining counts, fill with 0 ...
thiagopa/thiagopagonha
blog/urls.py
Python
bsd-3-clause
647
0.010819
from django.conf.urls.defaults import * from django.views.generic import list_detail, date_based from blog.models import * from blog.views import * urlpatterns = patterns('blog.views', (r"^preview/(\d+)$", "preview"), (r"^publish/(\d+)$", "publish"), (r
"^(?P<slug>[a-zA-Z0-9-]+)/$", "post"), (r"^notify$", "send_mail"), (r"^archive$", "archive"), (r"^category/(\d+)/$", "category"), #url(r'^category/(\d+)/$', blog_posts_by_category, name="blog_posts_by_category"), #url(r'^search/$', blog_post_search, name="blog_post_search"), u
rl(r'^(?P<template>\w+)/$', static_page, name="static_page"), (r"", "main"), )
wltrimbl/google-python-exercises3
basic/solution/mimic.py
Python
apache-2.0
3,158
0.00095
#!/usr/bin/python -tt # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ # Translated to python3 wltrimbl 2016 """Mimic pyquick exercise -- optional extra exerci...
file. Rather than read the file line by line, it's easier to read it into one giant string and split it once. Build a "mimic" dict that maps each word that appears in the file to a list of all the words that immediately follow that word in the file. The list of words can be be in any orde
r and should include duplicates. So for example the key "and" might have the list ["then", "best", "then", "after", ...] listing all the words which came after "and" in the text. We'll say that the empty string is what comes before the first word in the file. With the mimic dict, it's fairly easy to emit random text t...
amedina14/uip-iq17-pc3
clase 7/Documentacion/tests/TestITBMS.py
Python
mit
231
0.017316
import unittest
from app.itbms import calcular_itbms class TestITBMS(unittest.TestCase): def test_calcular_itbms(self): self.assertEqual(calcular_itbms(1.0),0.07) if __name__=='__main__': uni
ttest.main()
ankur-gupta91/horizon-net-ip
openstack_dashboard/test/helpers.py
Python
apache-2.0
25,725
0
# Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the...
} """ if stubs_to_create is None: stubs_to_create = {} if not isinstance(stubs_to_create, dict): raise TypeError("create_stub must be passed a dict, but a %s was " "
given." % type(stubs_to_create).__name__) def inner_stub_out(fn): @wraps(fn) def instance_stub_out(self, *args, **kwargs): for key in stubs_to_create: if not (isinstance(stubs_to_create[key], tuple) or isinstance(stubs_to_create[key], list)): ...
santazhang/BitTorrent-4.0.0-GPL
BitTorrent/btformats.py
Python
gpl-3.0
5,378
0.007066
# 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 is distributed in the hope that it will be useful, # bu...
alid announce interval' minint = message.get('min interval', 1) if type(minint) not in ints or minint <= 0: raise BTFailure, 'invalid min announce interval' if type(message.get('tracker id', '')) != str: raise BTFailure, 'invalid tracker id' npeers = message.get('num peers', 0) if ty...
e, 'invalid peer count' dpeers = message.get('done peers', 0) if type(dpeers) not in ints or dpeers < 0: raise BTFailure, 'invalid seed count' last = message.get('last', 0) if type(last) not in ints or last < 0: raise BTFailure, 'invalid "last" entry'
Akasurde/bodhi
bodhi/services/overrides.py
Python
gpl-2.0
8,799
0.001023
# This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # bu...
me for pkg in packages])) releases = data.get('releases') if releases is not None: query = query.join(BuildrootOverride.build).join(Build.release) query = query.filter(or_(*[Release.name==r.name for r in releases])) like = data.get('like') if like is not None: query = query.joi...
a.get('user') if submitter is not None: query = query.filter(BuildrootOverride.submitter==submitter) query = query.order_by(BuildrootOverride.submission_date.desc()) # We can't use ``query.count()`` here because it is naive with respect to # all the joins that we're doing above. count_quer...
dmlc/tvm
python/tvm/meta_schedule/testing/relay_workload.py
Python
apache-2.0
6,298
0.001905
# 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...
ze=batch_size, layout=layout, dtype=dtype,
image_shape=image_shape, ) elif name == "mobilenet": mod, params = relay.testing.mobilenet.get_workload( batch_size=batch_size, layout=layout, dtype=dtype, image_shape=image_shape ) elif name == "squeezenet_v1.1": assert layout == "NCHW", "squeezenet_v1.1 only supp...
amlyj/pythonStudy
2.7/standard_library/i18n/i18n.py
Python
mit
693
0.003241
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 17-9-28 下午5:22 # @Author : Tom.Lee # @CopyRight : 2016-2017 OpenBridge by yihecloud # @File
: test2.py # @Product : PyCharm # @Docs : # @Source : import gettext domain = 'test' locale_dir = 'locale/' # 这条语句会将_()函数自动放到python的内置命名空间中,必须使用 gettext.install(domain, locale_dir) zh_trans = gettext.translation(domain, locale_dir, languages=['zh_CN']) # en_trans = gettext.tra...
"_()"显示未定义不用管 _ = _ # print _("Hello world!")
PGer/incubator-hawq
tools/legacy/gpmlib.py
Python
apache-2.0
35,426
0.008553
from __future__ import with_statement import os, sys progname = os.path.split(sys.argv[0])[-1] if sys.version_info < (2, 5, 0): sys.exit( '''Error: %s is supported on Python versions 2.5.0 or greater Please upgrade python installed on this machine.''' % progname) #turning off Deprecation warnings (for now) import...
LIB_PATH=os.environ.get(ENV.LIB_TYPE) if not LIB_PATH: LIB_PATH='%s/lib:%s/ext/python/lib:.' % (GPHOME, GPHOME) PATH=os.environ.get('PATH') if not PATH: PATH='%s/bin:%s/ext/python/bin:.' % (GPHOME, GPHOME) PYTHONPATH=os
.environ.get('PYTHONPATH') if not PYTHONPATH: PYTHONPATH="%(gphome)s/lib/python" % {'gphome':GPHOME} return ('GPHOME=%s && export GPHOME ' '&& PATH=%s && export PATH ' '&& %s=%s && export %s ' '&& PYTHONPATH=%s && export PYTHONPATH ' '&& %s' %...
lsk112233/Clone-test-repo
minutes/management/commands/move_meeting_notes.py
Python
apache-2.0
1,113
0.000898
import datetime import re from django.core.management.base import BaseCommand from pages.models import Page from ...models import Minutes class Command(BaseCommand): """ Move meeting notes from Pages to Minutes app """ def parse_date_from_path(self, path): # Build our date from the URL path...
Exist: m = Minutes(date=date) m.content = p.content m.content_markup_
type = p.content_markup_type m.is_published = True m.save() p.delete()
TEAM-HRA/hra_suite
HRAMath/src/hra_math/time_domain/poincare_plot/poincare_plot.py
Python
lgpl-3.0
29,136
0.008649
''' Created on 27-07-2012 @author: jurek ''' from hra_math.utils.utils import print_import_error try: import os import argparse import glob from hra_core.datetime_utils import invocation_time from hra_core.misc import Separator from hra_core.introspection import print_private_properties fro...
e if disp: print('Using group data file: ' + self.data_file) if self.data_file: # data_file parameter is superior to data_dir parameter @IgnorePep8 _data_file = self.__shuffle_file__(self.data_file) if os.path.exists(_data_file) == False: ...
if self.__p__.check_data_indexes(_data_file, disp): _file_handler(_data_file, disp=disp, **params) else: for _file in self.__data_filenames__(): if os.path.isfile(_file): file_counter = file_counter + 1 if dis...
alexis-roche/nipy
nipy/algorithms/clustering/bgmm.py
Python
bsd-3-clause
36,777
0.000353
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ Bayesian Gaussian Mixture Model Classes: contains the basic fields and methods of Bayesian GMMs the high level functions are/should be binded in C The base class BGMM relies on an implementation that p...
array of shape(n,n), the precision parameters of the second density """ tiny = 1.e-15 dim = np.size(m1) if m1.shape != m2.shape: raise ValueError("incompatible dimensions for m1 and m2") if P1.shape != P2.shape: raise ValueError("incompatible dimensions for P1 and P2") i...
[0] != dim: raise ValueError("incompatible dimensions for m1 and P1") d1 = max(detsh(P1), tiny) d2 = max(detsh(P2), tiny) dkl = np.log(d1 / d2) + np.trace(np.dot(P2, inv(P1))) - dim dkl += np.dot(np.dot((m1 - m2).T, P2), (m1 - m2)) dkl /= 2 return dkl def dkl_wishart(a1, B1, a2, B2): ...
lowks/SDST
setup.py
Python
mit
788
0.005076
from setuptools import setup, find_packages import sys, os, glob
version = '0.7.1' setup(name='seqtools', version=version, description="", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?
%3Aaction=list_classifiers keywords='', author='Sean Davis', author_email='[email protected]', url='https://github.com/seandavi/seqtools', license='MIT', scripts=glob.glob('scripts/*'), packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_da...
npuichigo/ttsflow
third_party/tensorflow/tensorflow/contrib/framework/python/ops/ops.py
Python
apache-2.0
2,599
0.002309
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the L
icense at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed und
er 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. # ============================================================================== """Classe...
NinjaMSP/crossbar
sitecustomize.py
Python
agpl-3.0
85
0
try: import c
overag
e coverage.process_startup() except ImportError: pass
MathewWi/cube64-dx
notes/read-sram.py
Python
gpl-2.0
447
0.004474
#!/usr/bin/env python # # Read the memory pak's 32k SRAM to a binary file specified on the command line.
# # --Micah Dowty <[email protected]> # from bus import Bus import sys b = Bus() if b.probe() != "memory": sys.exit(1) f = open(sys.argv[1], "wb") addr = 0x0000 while addr < 0x8000: sys.stdout.write("\r0x%04X (%.02f%%)" % (addr, addr * 100.0 / 0x8000)) f.write(b.read(addr)) addr += 32 sys.stdout.write(...
###
explosiveduck/ed2d
ed2d/__init__.py
Python
bsd-2-clause
161
0.006211
de
f _init(): # any modules that need to be initialized early will be imported here import ed2d.debug ed2d.debug.debug('Debug module init.') _init(
)
tylertian/Openstack
openstack F/glance/setup.py
Python
apache-2.0
2,108
0
#!/usr/bin/python # Copyright (c) 2010 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import setuptools from glance.openstack.common import setup from glance.version import version_
info as version requires = setup.parse_requirements() depend_links = setup.parse_dependency_links() setuptools.setup( name='glance', version=version.canonical_version_string(always=True), description='The Glance project provides services for discovering, ' 'registering, and retrieving virt...
jeremiah-c-leary/vhdl-style-guide
vsg/token/element_declaration.py
Python
gpl-3.0
366
0
from vsg import parser class colon(parser.colon): ''' unique_id = element_declaration : colon '''
def __init__(self, sString=':'): parser.colon.__init__(self) class semicolon(parser.semicolon): ''' unique_id = element_declaration : semicolon ''' def __init__(self, sString=';'): parser.semicolon.__i
nit__(self)
huyhg/runtimes-common
runtime_builders/builder_util.py
Python
apache-2.0
5,271
0
#!/usr/bin/python # Copyright 2017 Google Inc. All rights reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by app...
CS! {0}' .format(e.output)) return False def verify_manifest(manifest): """Verify that the provided runtime manifest is valid before publishing. Aliases are provided for runtime 'names' that can be included in users' application configuration files: this method ensures that ...
ilder node. Example formatting of the manifest, showing both an 'alias' and an actual builder file: runtimes: java: target: runtime: java-openjdk java-openjdk: target: file: gs://runtimes/java-openjdk-1234.yaml deprecation: message: "openjd...
xskh2007/zjump
jumpserver/urls.py
Python
gpl-2.0
955
0.002094
from django.conf.urls import patterns, include, url urlpatterns = patterns('jumpserver.views', # Examples: url(r'^$', 'index', name='index'), # url(r'^api/user/$', 'api_user'), ur
l(r'^skin_config/$', 'skin_config', name='skin_config'), url(r'^login/$', 'Login', name='login'), url(r'^logout/$', 'Logout', name='logout'), url(r'^exec_cmd/$', 'exec_cmd', name='exec_cmd'), url(r'^file/upload/$', 'upload', name='file_upload'), url(r'^file/download/$', 'dow
nload', name='file_download'), url(r'^setting', 'setting', name='setting'), url(r'^terminal/$', 'web_terminal', name='terminal'), url(r'^mylog/$', 'mylog', name='mylog'), url(r'^juser/', include('juser.urls')), url(r'^jasset/', include('jasset.urls')), url(r'^jlog/', include('jlog.urls')), u...
metaperl/clickmob
src/dhash.py
Python
mit
2,158
0.000463
__author__ = 'anicca' # core import math import sys from itertools import izip # 3rd party from PIL import Image, ImageChops import argh def dhash(image, hash_size=8): # Grayscale and shrink the image in one step. image = image.convert('L').resize( (hash_size + 1, hash_size), Image.ANTIALIAS...
if len(i1.getbands()) == 1: # for gray-scale jpegs dif = sum(abs(p1 - p2) for p1, p2 in pairs) else: dif = sum(abs(c1 - c2) for p1, p2 in pairs for c1, c2 in zip(p1, p2)) ncomponents =
i1.size[0] * i1.size[1] * 3 retval = (dif / 255.0 * 100) / ncomponents return retval def rmsdiff_2011(im1, im2): "Calculate the root-mean-square difference between two images" im1 = Image.open(im1) im2 = Image.open(im2) diff = ImageChops.difference(im1, im2) h = diff.histogram() sq =...
hasgeek/hasjob
migrations/versions/449914911f93_post_admins.py
Python
agpl-3.0
812
0.002463
"""Post admins Revision ID: 449914911f93 Revises: 2420dd9c9949 Create Date: 2013-12-03 23:03:02.404457 """ # revision identifiers, used by Alembic. revision = '449914911f93' down_revision = '2420dd9c9949' from alembic import op import sqlalchemy as sa def upgrade(): op.create_table( 'jobpost_admin', ...
e=False), sa.ForeignKeyConstraint(['jobpost_id'], ['jobpost.id']), sa.ForeignKeyConstraint(['user_id'], ['user.id']), sa.Prim
aryKeyConstraint('user_id', 'jobpost_id'), ) def downgrade(): op.drop_table('jobpost_admin')
Abdoctor/behave
tests/issues/test_issue0453.py
Python
bsd-2-clause
2,081
0.003029
# -*- coding: UTF-8 -*- """ MAYBE: DUPLICATES: #449 NOTE: traceback2 (backport for Python2) solves the problem. def foo(stop): raise Exception(u"по русски") Result: File "features/steps/steps.py", line 8, in foo raise Exception(u"по Ñ�Ñ�Ñ�Ñ�ки") <-- This is not Exception: по русски...
because traceback.format_exc() creates incorrect text. You then convert it using _text() and result is also bad. To fix it, you may take e.message which is correct and traceback.format_tb(sys.exc_info()[2]) which is also correct. """ from __future
__ import print_function from behave.textutil import text from hamcrest.core import assert_that, equal_to from hamcrest.library import contains_string import six import pytest if six.PY2: import traceback2 as traceback else: import traceback def problematic_step_impl(context): raise Exception(u"по русски"...
CODAIT/graph_def_editor
graph_def_editor/reroute.py
Python
apache-2.0
19,100
0.006283
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
ction. Raises: TypeError: if `ts0` or `ts1` cannot be converted to a list of `gde.
Tensor`. TypeError: if `can_modify` or `cannot_modify` is not `None` and cannot be converted to a list of `gde.Node`. """ a2b, b2a = _RerouteMode.check(mode) ts0 = util.make_list_of_t(ts0) ts1 = util.make_list_of_t(ts1) _check_ts_compatibility(ts0, ts1) if cannot_modify is not None: cannot_mod...
rbuffat/pyidf
tests/test_setpointmanagerfollowsystemnodetemperature.py
Python
apache-2.0
3,028
0.004293
import os import tempfile import unittest import logging from pyidf import ValidationLevel import pyidf from pyidf.idf import IDF from pyidf.setpoint_managers import SetpointManagerFollowSystemNodeTemperature log = logging.getLogger(__name__) class TestSetpointManagerFollowSystemNodeTemperature(unittest.TestCase): ...
_setpoint_temperature, var_maximum_limit_setpoint_temperature) self.assertAlmostEqual(idf2.setpointmanagerfollowsystemnodetemperatures[0].minimum_limit_setpoint_temperature, var_minimum_limit_setpoint_temperature) self.assertEqual(idf2.setpointmanagerfollowsys
temnodetemperatures[0].setpoint_node_or_nodelist_name, var_setpoint_node_or_nodelist_name)
KiChjang/servo
tests/wpt/web-platform-tests/tools/third_party/h2/test/test_settings.py
Python
mpl-2.0
16,680
0
# -*- coding: utf-8 -*- """ test_settings ~~~~~~~~~~~~~ Test the Settings object. """ import pytest import h2.errors import h2.exceptions import h2.settings from hypothesis import given, assume from hypothesis.strategies import ( integers, booleans, fixed_dictionaries, builds ) class TestSettings(object): ...
""" Acknowledging settings returns the changes. """ s = h2.settings.Settings(client=True) s[h2.settings.SettingCodes.HEADER_TABLE_SIZE] = 8000 s[h2.settings.SettingCode
s.ENABLE_PUSH] = 0 changes = s.acknowledge() assert len(changes) == 2 table_size_change = ( changes[h2.settings.SettingCodes.HEADER_TABLE_SIZE] ) push_change = changes[h2.settings.SettingCodes.ENABLE_PUSH] assert table_size_change.setting == ( h...
bgris/ODL_bgris
lib/python3.5/site-packages/qtawesome/iconic_font.py
Python
gpl-3.0
14,406
0.000208
r""" Iconic Font =========== A lightweight module handling iconic fonts. It is designed to provide a simple way for creating QIcons from glyphs. From a user's viewpoint, the main entry point is the ``IconicFont`` class which contains methods for loading new iconic fonts with their character map and methods returnin...
_active'], options['off_active']), QIcon.Selected: (options['color_off_selected'], options['off_selected']) } } color
, char = color_options[state][mode] painter.setPen(QColor(color)) # A 16 pixel-high icon yields a font size of 14, which is pixel perfect # for font-awesome. 16 * 0.875 = 14 # The reason why the glyph size is smaller than the icon size is to # account for font bearing. ...
russellgeoff/blog
Control/Controllers/target_list.py
Python
gpl-3.0
2,121
0.003772
''' Copyright (C) 2014 Travis DeWolf 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 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 P...
long with this program. If not, see <http://www.gnu.org/licenses/>. ''' import numpy as np class Shell(object): """ """ def __init__(self, controller, target_list, threshold=.01, pen_down=False): """ control Control instance: the controller to use pen_down bool...
istommao/wechatkit
wechatkit/exceptions.py
Python
mit
437
0
"""Wechatkit exception module.""" cl
ass WechatKitBaseException(Exception): """Wechatkit base Exception.""" def __init__(self, error_info): """Init.""" super(WechatKitBaseException, self).__init__(error_info) self.error_info = error_info class WechatKitException(WechatKitBaseException): """Wechatkit Exception.""" c...
gn Exception."""
kliput/onezone-gui
bamboos/docker/environment/appmock.py
Python
mit
6,421
0.000312
# coding=utf-8 """Authors: Łukasz Opioła, Konrad Zemek Copyright (C) 2015 ACK CYFRONET AGH This software is released under the MIT license cited in 'LICENSE.txt' Brings up a set of appmock instances. """ import copy import json import os import random import string from timeouts import * from . import common, docker...
(appmock_node, appmock_instance, uid), 'oz_worker': worker.worker_erl_node_n
ame(appmock_node, appmock_instance, uid) }.get(mocked_app, appmock_erl_node_name(appmock_node, uid)) if 'vm.args' not in cfg['nodes']['node']: cfg['nodes']['node']['vm.args'] = {} vm_args = cfg['nodes']['node']['vm.args'] vm_args['name'] = node_name # If cookie is not specified, set random ...
3ptscience/steno3dpy
steno3d/examples/airports.py
Python
mit
3,650
0
"""airports.py provides an example Steno3D project of airports""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np from .base import BaseExample, exampleproperty from ..point import Mesh0D, Point fr...
oject(), respectively. """ @exampleproperty def filenames(self): """airport files""" return ['airports.dat', 'latitude.npy', 'longitude.npy', 'altitude.npy', 'license.txt'] @exampleproperty def datafile(self): """full path to airport data file""" ret...
verbose=False) @exampleproperty def latitude(self): """Airport lat, degrees, from openflights.org""" return np.load(Airports.fetch_data(filename='latitude.npy', download_if_missing=False, ...
russbishop/swift
utils/swift_build_support/tests/test_cmake.py
Python
apache-2.0
12,511
0.00008
# test_cmake.py - Unit tests for swift_build_support.cmake -*- python -*- # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See http://swift.org/LICENSE.txt for ...
lf): args = self.default_args() args.enable_ubsan = True cmake = self.cmake(args) self.assertEqual( list(cmake.common_options()), ["-G", "Ninja", "-DLLVM_USE_SANITIZER=Undefined",
"-DCMAKE_C_COMPILER:PATH=/path/to/clang", "-DCMAKE_CXX_COMPILER:PATH=/path/to/clang++"]) def test_common_options_asan_ubsan(self): args = self.default_args() args.enable_asan = True args.enable_ubsan = True cmake = self.cmake(args) self.assertEqual( ...
partofthething/home-assistant
tests/components/binary_sensor/test_device_condition.py
Python
apache-2.0
8,860
0.001693
"""The test for binary_sensor device automation.""" from datetime import timedelta from unittest.mock import patch import pytest import homeassistant.components.automation as automation from homeassistant.components.binary_sensor import DEVICE_CLASSES, DOMAIN from homeassistant.components.binary_sensor.device_conditi...
ry.add_to_hass(hass) device_entry = device_reg.async_get_or_create( config_entry_id=config_entry.entry_id, connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, ) entity_reg.asyn
c_get_or_create(DOMAIN, "test", "5678", device_id=device_entry.id) expected_capabilities = { "extra_fields": [ {"name": "for", "optional": True, "type": "positive_time_period_dict"} ] } conditions = await async_get_device_automations(hass, "condition", device_entry.id) for co...