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
nikesh-mahalka/cinder
cinder/tests/unit/test_dellsc.py
Python
apache-2.0
85,579
0
# Copyright (c) 2014 Dell Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
Center 64702', u'scSerialNumber': 64702, u'controller': {u'instanceId': u'64702.64702',
u'instanceName': u'SN 64702', u'objectType': u'ScController'}, u'server': {u'instanceId': u'64702.30', u'instanceName': u'Server_iqn.1993-08.org.debian:01:3776df826e4f', ...
willvanwazer/offloading
offloading/wsgi.py
Python
mit
395
0.002532
""" WSGI config for offloading project. It exposes the WSGI callable as a module-level variable named ``application``. For more inf
ormation on this file, see https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "offloading.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi
_application()
ZwaConnection/TheGuildWeb
apps/member/decorators.py
Python
gpl-3.0
646
0.004644
from django.http import HttpResponseRedirect def anonymous_required(view, redirect_to= None): return AnonymousRequired(view, redirect_to) class AnonymousRequired(object): def __init__(self, view, redirect_to): if redirect_to is None: from django.conf import settings redirect_to...
if request.user is not None and request.user.is_authenticated: return HttpResponseRedirect(self.redirect_to)
return self.view(request, *args, **kwargs)
AlessandroZ/LaZagne
Linux/lazagne/softwares/chats/pidgin.py
Python
lgpl-3.0
2,313
0.000432
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import traceback from lazagne.config.module_info import ModuleInfo from xml.etree.cElementTree import ElementTree from lazagne.config import homes class Pidgin(ModuleInfo): def __init__(self): ModuleInfo.__init__(self, 'pidgin', 'chats') # If...
r _, session in homes.sessions(): try: bus = dbus.bus.BusConnection(session)
purple = bus.get_object( "im.pidgin.purple.PurpleService", "/im/pidgin/purple/PurpleObject", "im.pidgin.purple.PurpleInterface" ) acc = purple.PurpleAccountsGetAllActive() for x in range(len(acc)...
ztane/zsos
userland/lib/python2.5/logging/__init__.py
Python
gpl-3.0
47,144
0.003076
# Copyright 2001-2007 by Vinay Sajip. All Rights Reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose and without fee is hereby granted, # provided that the above copyright notice appear in all copies and that # both that copyright notice and this permissio...
out specific, written prior permission. # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF ...
ng package for Python. Based on PEP 282 and comments thereto in comp.lang.python, and influenced by Apache's log4j system. Should work under Python versions >= 1.5.2, except that source line information is not available unless 'sys._getframe()' is. Copyright (C) 2001-2007 Vinay Sajip. All Rights Reserved. To use, si...
JonasWallin/Mixture
test/speed_checks/speed_mixture.py
Python
gpl-3.0
1,989
0.025138
''' testing speedup of code Created on Sep 17, 2016 @author: jonaswallin ''' from Mixture.density import mNIG from Mixture.density.purepython import mNIG as pmNIG from Mixture import mixOneDims import numpy as np import numpy.random as npr import timeit # most speed here is used startup (iteration = 500, n = 1000) # ...
et_data(Y) paramMat = [npr.randn(2,4),npr.randn(2,4)] paramMat[0][0,0] = 1.1 paramMat[1][0,0] = -2 alpha = np.array(alpha_true) for i in range(iteration): # @UnusedVariable p, alpha, paramMat = mixObj.EMstep(alpha = alpha, paramMat = paramMat , precompute = precompute) # @UnusedVari...
antoinecarme/pyaf
tests/artificial/transf_BoxCox/trend_MovingMedian/cycle_0/ar_12/test_artificial_32_BoxCox_MovingMedian_0_12_20.py
Python
bsd-3-clause
264
0.087121
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 32 , FRE
Q = 'D', seed = 0, trendtype = "MovingMedian", cycle_length = 0, transform = "BoxCox", sigma = 0.0, exog_count = 20, a
r_order = 12);
servalproject/nikola
nikola/plugins/template_mako.py
Python
mit
3,347
0.000299
# Copyright (c) 2012 Roberto Alsina y otros. # Permission is hereby granted, free of charge, to any # person obtaining a copy of this software and associated # documentation files (the "Software"), to deal in the # Software without restriction, including without limitation # the rights to use, copy, modify, merge, pub...
lex = lexer.Lexer(text=text, filename=filename) lex.parse() deps = [] for n
in lex.template.nodes: keyword = getattr(n, 'keyword', None) if keyword in ["inherit", "namespace"]: deps.append(n.attributes['file']) # TODO: include tags are not handled return deps def set_directories(self, directories, cache_folder): """Create...
oneman/xmms2-oneman-old
wafadmin/Tools/suncxx.py
Python
lgpl-2.1
1,743
0.043603
#!/usr/bin/env python # encoding: utf-8 # Thomas Nagy, 2006 (ita) # Ralf Habacker, 2006 (rh) import os, optparse import Utils, Options, Configure import ccroot, ar from Configure import conftest @conftest def find_sxx(conf): v = conf.env cc = None if v['CXX']: cc = v['CXX'] elif 'CXX' in conf.environ: cc = conf.e...
= '-Wl,-h -Wl,%s' v['SHLIB_MARKER'] = '-Bdynamic' v['STATICLIB_MARKER'] = '-Bstatic' # program v['program_PATTERN'] = '%s' # s
hared library v['shlib_CXXFLAGS'] = ['-Kpic', '-DPIC'] v['shlib_LINKFLAGS'] = ['-G'] v['shlib_PATTERN'] = 'lib%s.so' # static lib v['staticlib_LINKFLAGS'] = ['-Bstatic'] v['staticlib_PATTERN'] = 'lib%s.a' detect = ''' find_sxx find_cpp find_ar sxx_common_flags cxx_load_tools cxx_add_flags '''
kaichogami/sympy
sympy/crypto/crypto.py
Python
bsd-3-clause
56,953
0.000755
# -*- coding: utf-8 -*- """ This file contains some classical ciphers and routines implementing a linear-feedback shift register (LFSR) and the Diffie-Hellman key exchange. """ from __future__ import print_function from string import whitespace, ascii_uppercase as uppercase, printable from sympy import nextprime fr...
ot in ``symbols``. A ValueError is raised if a) there
are duplicate characters in ``symbols`` or b) there are characters in ``key`` that are not in ``symbols``. Examples ======== >>> from sympy.crypto.crypto import padded_key >>> padded_key('PUPPY', 'OPQRSTUVWXY') 'PUYOQRSTVWX' >>> padded_key('RSA', 'ARTIST') Traceback (most recent ...
estnltk/pyvabamorf
pyvabamorf/__init__.py
Python
lgpl-3.0
304
0.016447
# -*- coding: utf-8 -*- import pyvabamorf.vabamorf as
vm import atexit if not vm.FSCInit(): raise Exception('Could not initiate pyvabamorf library. FSC
Init() returned false!') @atexit.register def terminate(): vm.FSCTerminate() from morf import analyze, synthesize from morf import PyVabamorf
schleichdi2/OPENNFR-6.3-CORE
opennfr-openembedded-core/meta/lib/oeqa/selftest/cases/fetch.py
Python
gpl-2.0
1,543
0.001296
# # SPDX-License-Identifier: MIT # import oe.path from oeqa.selftest.case import OESelftestTestCase from oeqa.utils.commands import bitbake class Fetch(OESelftestTestCase): def test_git_mirrors(self): """ Verify that the git fetcher will fall back to the HTTP mirrors. The recipe needs to b...
L_DIR = "%s" MIRRORS_forcevariable = "" PREMIRRORS_forcevariable = "" """ % dldir self.write_config(features) oe.path.remove(dldir, recurse=True) bitbake("dbus-wait -c fetch -f") # No mirrors and broken git, should fail features = """ DL_DIR = "%s" GIT_PROXY_COM
MAND = "false" MIRRORS_forcevariable = "" PREMIRRORS_forcevariable = "" """ % dldir self.write_config(features) oe.path.remove(dldir, recurse=True) with self.assertRaises(AssertionError): bitbake("dbus-wait -c fetch -f") # Broken git but a specific mirror features = ...
Shekharrajak/pydy
examples/babyboot/babyboot.py
Python
bsd-3-clause
2,234
0.002686
from sympy import symbols from sympy.physics.mechanics import * # -- Declare symbols. # Declare degrees of freedom, and their time derivatives. # TODO get rid of those which are unnecessary. qA, qB, uA, uB = dynamicsymbols('qA qB uA uB') qAd, qBd, uAd, uBd = dynamicsymbols('qA qB uA uB', 1) # Declare the constants i...
frameA) # Don't need this in MotionGenesis. Bcm = NO.locatenew('Bcm', - LB * frameA.z) Bcm.v2pt_theory(NO, N, frameA) # Don't need this in MotionGenesis. # Inertia dyadic. # TODO inertia dyadics are about a specific point, right? are
we requiring the user to define it about the COM always or something? idk if this info should be separate. we have inertia info floating about in 2 different locations. IA = inertia(frameA, IAx, 0, 0) IB = inertia(frameB, IBx, IBy, IBz) # Create rigid bodies. BodyA = RigidBody('BodyA', Acm, frameA, mA, (IA, Acm)) Bod...
zsdonghao/tensorlayer
tests/models/test_seq2seq_model.py
Python
apache-2.0
3,088
0.002915
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import unittest import numpy as np import tensorflow as tf from sklearn.utils import shuffle from tqdm import tqdm import tensorlayer as tl from tensorlayer.cost import cross_entropy_seq from tensorlayer.models.seq2seq import Seq2seq from tests.utils import Cus...
0 # start_token == 0 # Parameters cls.src_len = len(cls.trainX) cls.tgt_len = len(cls.trainY) assert cls.src_len == cls.tgt_len cls.num_epochs = 100 cls.n_step = cls.src_len // cls.batch_size @classmethod def tearDownClass(cls): pass def test_bas...
keras.layers.GRUCell, n_layer=3, n_units=128, embedding_layer=tl.layers.Embedding(vocabulary_size=self.vocab_size, embedding_size=self.embedding_size), ) optimizer = tf.optimizers.Adam(learning_rate=0.001) for epoch in range(self.num_epochs): mod...
ihash/jomlak
jomlak/urls.py
Python
mit
1,199
0.000834
"""jomlak URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app i
mport views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import
Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin from .vie...
vitan/openrave
python/ikfast_generator_cpp.py
Python
lgpl-3.0
127,669
0.011397
#!/usr/bin/env python # -*- coding: utf-8 -*- # Software License Agreement (Lesser GPL) # # Copyright (C) 2009-2012 Rosen Diankov <rosen.diankov@gmail.com> # # ikfast 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...
rtError: pass try: from itertools import izip, combinations except ImportError: def combinations(items,n): if n == 0: yield[] else: for i in xrange(len(items)):
for cc in combinations(items[i+1:],n-1): yield [items[i]]+cc try: # not necessary, just used for testing import swiginac using_swiginac = True except ImportError: using_swiginac = False import logging log = logging.getLogger('openravepy.ikfast') from sympy.core import function #...
kinow-io/kinow-python-sdk
kinow_client/models/video_response.py
Python
apache-2.0
18,886
0.000265
# coding: utf-8 """ Server API Reference for Server API (REST/Json) OpenAPI spec version: 2.0.6 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class VideoResponse(object): """ NOTE: This class is aut...
Sets the id_language of this VideoResponse. :param id_language: The id_language of this VideoResponse. :type: int """ self._id_language = id_language @property def language_filter(self): """ Gets the language_filter of this VideoResponse. :return: Th...
" return self._language_filter @language_filter.setter def language_filter(self, language_filter): """ Sets the language_filter of this VideoResponse. :param language_filter: The language_filter of this VideoResponse. :type: int """ self._language_filte...
steamclock/internetmap
Data-Pipeline/converttojson.py
Python
mit
646
0.017028
#import results # Not using results? import loc import json #asinfo = results.asinfo locinfo = loc.locinfo #fields = asinfo["fields"] #del asinfo["fields"] #print fields # for asn, dat in asinfo.items(): # if int(asn) in locinfo: # dat.extend(locinfo[int(asn)]) # else: # dat.extend([0, 0]) # # for asn, dat i...
print val # udata = val[0].decode("utf-8"); # val[0] = udata.encode("ascii", "ignore") # val[0] = unicode(val[
0]) # print val f = open("asinfo.json", "w") json.dump(locinfo, f) f.close()
SmartElect/SmartElect
voting/tests/test_models.py
Python
apache-2.0
15,122
0.000727
import datetime from unittest.mock import patch from django.conf import settings from django.core.exceptions import ValidationError from django.db import IntegrityError from django.test import TestCase from django.utils.timezone import now from pytz import timezone from libya_elections.utils import at_midnight from ....
elf.asse
rtTrue(election.get_due_unsent_reminders(from_, to)) self.assertFalse(ReminderQueued.objects.all().exists()) with patch('voting.models.message_reminder_task') as mock_task: election.schedule_due_reminders(from_, to) assert mock_task.delay.called self.assertTrue(ReminderQueued...
Spiderlover/Toontown
toontown/nametag/NametagGroup.py
Python
mit
12,905
0.00031
from direct.task.Task import Task from pandac.PandaModules import VBase4, PandaNode from toontown.margins.MarginVisible import MarginVisible from toontown.nametag import NametagGlobals from toontown.nametag.Nametag2d import Nametag2d from toontown.nametag.Nametag3d import Nametag3d class NametagGroup: CHAT_TIMEO...
d the tick task: self.tick
TaskName = self.getUniqueName() + '-tick' self.tickTask = taskMgr.add(self.tick, self.tickTaskName, sort=45) def destroy(self): if self.marginManager is not None: self.unmanage(self.marginManager) if self.tickTask is not None: taskMgr.remove(self.tickTask) ...
shoaibkamil/asp
tools/debugger/stencil/stencil_convert.py
Python
bsd-3-clause
9,147
0.004373
"""Takes an unrolled StencilModel and converts it to a C++ AST. The third stage in processing. Input must be processed with StencilUnrollNeighborIter first to remove neighbor loops and InputElementZeroOffset nodes. Done once per call. """ import ast import asp.codegen.cpp_ast as cpp_ast import asp.codegen.ast_tools a...
resh_var() self.dim_vars.append(dim_var) initial = cpp_ast.CNumber(self.output_grid.ghost_depth) end = cpp_ast.CNumber
(self.output_grid.shape[d]-self.output_grid.ghost_depth-1) increment = cpp_ast.CNumber(1) if d == 0: ret_node = cpp_ast.For(dim_var, add_one(initial), add_one(end), increment, cpp_ast.Block()) cur_node = ret_node elif d == dim-2: # add ...
netanelravid/screener
tests/unit/test_helpers.py
Python
apache-2.0
2,611
0
import logging import sys from logging import ( DEBUG, INFO, WARNING, CRITICAL, _loggerClass ) import pytest from future.backports.test.support import import_module from screener.helpers import ( screener_init, get_user_arguments, init_loggers, ) from screener.settings import ( ini...
, '-o', 'temp_image'), {'URL': '1
23', '--dir': 'Results', '--output': 'temp_image', '--verbose': 0}), (('', '-u', '123', '--output', 'temp_image'), {'URL': '123', '--dir': 'Results', '--output': 'temp_image', '--verbose': 0}), (('', '-u', '123', '-d', 'temp_dir', '-o', 'temp_image'), {'URL': '123',...
jonathonwalz/ansible
lib/ansible/modules/cloud/cloudstack/cs_host.py
Python
gpl-3.0
17,672
0.000792
#!/usr/bin/python # -*- coding: utf-8 -*- # # (c) 2016, René Moser <mail@renemoser.net> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Lice...
description: Name of the host. returned: success type: string sample: esx32.example.com network_kbs_read: description: Incoming network traffic on the host. returned: success type: int sample: 0 network_kbs_write: description: Outgoing network traffic on the host. returned: success type: int sam...
s type: string sample: ... out_of_band_management: description: Host out-of-band management information. returned: success type: string sample: ... pod: description: Pod name of the host. returned: success type: string sample: Pod01 removed: description: Date and time the host was removed. retur...
zatr/testassist
settings.py
Python
mit
117
0.008547
s
erver = '127.0.0.1' username = 'admin' password = 'password' diagnostic_command = 'run_diag' log_command = 'run_log'
kchard/surframble
buoy_to_json/buoy_to_json.py
Python
mit
644
0.003106
import os import zmq import json import logging logging.basicConfig(format='%(asctime)s -
%(message)s', level=logging.INFO) buoy_data_folder = os.path.join(os.environ['RESOURCE_DIR'], 'buoy') context = zmq.Context
() socket = context.socket(zmq.SUB) socket.connect ('tcp://broker:5557') socket.setsockopt(zmq.SUBSCRIBE, '') logging.info("Waiting for data") while True: surf_data = socket.recv_json() logging.info("Recieved data: %s" % surf_data) buoy_file_name = "%s.json" % str(surf_data['id']) with open(os.path.joi...
svagionitis/puzzles
adventofcode.com/2015/1/sol1.py
Python
mit
581
0.001721
if __name__ == "__main__": with open("input.txt") as f: res = 0 data = f.read() flag_basement_first = False for i, d in enumerate(data): if d == '(': res += 1 if d == ')': res -= 1 if res == -1 and flag_basemen...
flag_basement_first = True print '1. T
o what floor do the instructions take Santa? %d' % res
valentinedwv/pdfssa4met
headings.py
Python
gpl-3.0
4,413
0.006571
#!/bin/env python """ Extract and tag References from a PDF. Created on Mar 1, 2010 @author: John Harrison Usage: headings.py OPTIONS FILEPATH OPTIONS: --help, -h Print help and exit --noxml Do not tag individual headings with XML tags. Default is to include tagging. --title Only pr...
ortlist = [(v,k) for k,v in font_color_hash.iteritems()] sortlist.sort(reverse=True) main_font_color = sortlist[0][1] head_txts = [] stop = False for page_node in tree.xpath('//PAGE'): for
block_node in page_node.xpath('.//BLOCK'): if xmltag: if block_node == title_node: st = "<title>" et = "</title>" elif block_node == auth_node: st = "<author>" et = "</author>" el...
big-data-research/neuralnetworks_workshop_bucharest_2015
nn_demo/01nn_otto.py
Python
apache-2.0
11,593
0.001984
__author__ = 'alexs' import theano.tensor as T import theano import numpy as np import cPickle import pandas as pd from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import StandardScaler import numpy as np import random import json def getReferenceLabels(): referenceLabels = dict() fo...
radients[i] memory = memories[i] change = learning_rate * gradient + momentum_learning_rate * memory new_val = weight - change update_lists.append((weight, new_val)) update_lists.append((memory, change)) return update_lists class NN(): def __init__(self): self.l...
e = None self.activatwe = None self.output = None def build(self, givenWeights=None): # first: init or build the in-between weight matrixes for i in range(0, len(self.layers) - 1): n = self.layers[i].size m = self.layers[i + 1].size if givenWeigh...
jawilson/home-assistant
tests/components/wled/test_config_flow.py
Python
apache-2.0
7,451
0.000403
"""Tests for the WLED config flow.""" from unittest.mock import MagicMock from wled import WLEDConnectionError from homeassistant.components import zeroconf from homeassistant.components.wled.const import CONF_KEEP_MASTER_LIGHT, DOMAIN from homeassistant.config_entries import SOURCE_USER, SOURCE_ZEROCONF from homeass...
ssistant, init_integration: MagicMock, mock_wled_config_flow: MagicMock, ) -> None: """Test we abort zeroconf flow if WLED device already configured.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_HOST: "192.168.1.123"},...
nfigured" async def test_zeroconf_device_exists_abort( hass: HomeAssistant, init_integration: MagicMock, mock_wled_config_flow: MagicMock, ) -> None: """Test we abort zeroconf flow if WLED device already configured.""" result = await hass.config_entries.flow.async_init( DOMAIN, con...
TravisCG/SI_scripts
canpyY.py
Python
gpl-3.0
803
0.028643
#!/usr/bin/python """ Create Y matrix for Canopy. This is the connection between the SNAs and CNVs """ import sys Wm = open(sys.argv[1]) Wm.readline() cnvs = list() header = list() header.append("non-cna_region") for i in Wm: region = i.split()[0] (chrx, start, end) = region.split("_") cnvs.append((chrx, int(s...
r) for i in X: sna = i.split()[0] chrx, pos, alt = sna.split("_") pos = int(pos) out = list() out.append(sna) out.append("0") # non-cna_region ok = False for j in cnvs: if chrx == j[0] and j[1] < pos and j[2] > pos: out.append("1") ok = True else: out.append("0") if not ok: out[1] = "1" # set th...
on-cna_region to 1 print "\t".join(out) X.close()
edoburu/django-parler
parler/utils/views.py
Python
apache-2.0
2,807
0.001069
""" Internal DRY functions. """ from django.conf import settings from parler import appsettings from parler.utils import normalize_language_code, is_multilingual_project, get_language_title def get_language_parameter(request, query_language_key='language', object=None, default=None): """ Get the language para...
ated = current_language in available_languages tabs.allow_deletion = len(available_languages) > 1 return tabs class TabsList(list):
def __init__(self, seq=(), css_class=None): self.css_class = css_class self.current_is_translated = False self.allow_deletion = False super().__init__(seq)
Nitaco/ansible
contrib/inventory/scaleway.py
Python
gpl-3.0
7,193
0.000695
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' External inventory script for Scaleway ==================================== Shamelessly copied from an existing inventory script. This script generates an inventory that Ansible can understand by making API requests to Scaleway API Requires some python libraries, en...
e if config.has_option('cache', 'cache_max_age'): maxage = config.get('cache', 'cache_max_age') else: maxage = 60 if (int(time.time()) - int(existing.st_mtime)) <= int(maxage): return True return False def generate
_inv_from_api(config): try: inventory['all'] = copy.deepcopy(EMPTY_GROUP) if config.has_option('auth', 'api_token'): auth_token = config.get('auth', 'api_token') auth_token = env_or_param('SCALEWAY_TOKEN', param=auth_token) if auth_token is None: sys.stderr.w...
rcgee/oq-hazardlib
openquake/hazardlib/mfd/youngs_coppersmith_1985.py
Python
agpl-3.0
15,232
0
# coding: utf-8 # The Hazard Library # Copyright (C) 2013-2016 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 ...
n_mag) - N(char_mag)`` represents the rate of noncharacteristic, exponentially distributed earthquakes and is used to derive the cumulative a value by solving the following equation :: 10 ** (a_val - b_val * min_mag) - 10 *
* (a_val - b_val * (char_mag - 0.25)) = N(min_mag) - N(char_mag) which can be written as :: a_val = log10(N(min_mag) - N(char_mag)) / (10 ** (- b_val * min_mag) - 10 ** (- b_val * (char_mag - 0.25)) In the calculation of N(min_mag) and N(char_mag), the ...
mrramazani/mysql-replicant-python-1
lib/tests/deployment/simple.py
Python
bsd-3-clause
2,759
0.001812
# Copyright (c) 2010, Mats Kindahl, Charles Bell, and Lars Thalmann # All rights reserved. # # Use of this source code is goverened by a BSD licence that can be # found in the LICENCE file. from mysql.replicant.server import Server from mysql.replicant.common import User from mysql.replicant.machine import Linux from ...
le=Master(_repl_user), port=3307, socket='/var/run/m
ysqld/mysqld1.sock', defaults_file=_cnf("mysqld1"), config_section="mysqld1") slaves = [Server(server_id=2, name="mysqld2", sql_user=_replicant_user, ssh_user=User("mysql"), machine=Linux(), role=Final(master), port=3308...
Kasai-Code/Kinesis
settings/config.py
Python
mit
741
0.002699
model_image_path = "model.png" generate_model_image = False dataset_training_path = "data/datasets/training.csv" dataset_testing_path = "data/datasets/testing.csv"
supported_characters = [" ", "c", "e", "t", "a", "r", "i", "o", "s", "n", "c", "l", "d", "_", "u", "m", " ", "p", "f", ".", "g", "h", ",", "\"", "/", "0", "-", "b", ")", "("
, "1", "E", "*", "=", ":", ";", ">", "T", "S", "y", "2", "R", "A", "v", "w", "L", "C", "<", "N", "x", "I", "k", "'", "D", "O", "P", "3", "#", "M", "F", "U", "4", "5", "9", "V", "{", "}", "B", "8", "H", "G", "6", "+", "7", "z", "W", "$", "[", "]", "@", "&", "j", "q", "\\", "Y", "K", "X", "!", "%", "|", "5", "`", "Q", "J...
home-assistant/home-assistant
homeassistant/components/fritz/common.py
Python
apache-2.0
19,263
0.000779
"""Support for AVM FRITZ!Box classes.""" from __future__ import annotations from collections.abc import Callable, ValuesView from dataclasses import dataclass, field from datetime import datetime, timedelta import logging from types import MappingProxyType from typing import Any, TypedDict, cast from fritzconnection ...
> str: """Return device model.""" if not self._model: raise ClassSetupMissing() return self._model @property def current_firmware(self) -> str: """Return current SW version.""" if not self._current_firmware: raise ClassSetupMissing() retur...
"""Return latest SW version.""" return self._latest_firmware @property def update_available(self) -> bool: """Return if new SW version is available.""" return self._update_available @property def mac(self) -> str: """Return device Mac address.""" if not self...
mozilla/github-org-scripts
check_CoC.py
Python
mpl-2.0
195
0
##################
############################## # # file moved to own repository: # https://github.com/mozilla/Mozilla-GitHub-Standards # ##########################
######################
plotly/python-api
packages/python/plotly/plotly/validators/splom/dimension/_valuessrc.py
Python
mit
466
0
import _plotly_utils.basevalidators class ValuessrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__( self, plotly_name="valuessrc", parent_name="splom.dimension"
, **kwargs ): super(ValuessrcValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "none"), role=kwargs.pop("role", "info"), **kwargs )
tddv/readthedocs.org
readthedocs/donate/apps.py
Python
mit
202
0
from django.apps import AppConfig class DonateAppConfig(AppConfig): name
= 'readthedocs.donate' verbose_name = 'Do
nate' def ready(self): import readthedocs.donate.signals # noqa
gltn/stdm
stdm/third_party/sqlalchemy/testing/plugin/plugin_base.py
Python
gpl-2.0
20,361
0
# plugin/plugin_base.py # Copyright (C) 2005-2020 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """Testing extensions. this module is designed to work as a testing-framework...
print("%20s\t%s" % (macro, file_config.get("db", macro))) sys.exit(0) def _requirements_opt(opt_str, value, parser): _setup_requirements(value) def _exclude_tag(opt_str, value, parser): exclude_tags.add(value.replace("-", "_")) def _include_tag(opt_str, value, parser): include_tags.add(value.r...
nfigure.append(fn) return fn def post(fn): post_configure.append(fn) return fn @pre def _setup_options(opt, file_config): global options options = opt @pre def _set_nomemory(opt, file_config): if opt.nomemory: exclude_tags.add("memory_intensive") @pre def _monkeypatch_cdecimal(op...
makyo/honeycomb
usermgmt/templatetags/profile_extras.py
Python
mit
914
0
from django import template from django.template.defaultfilters import stringfilter from django.utils.html import conditional_escape from django.utils.safestring import mark_safe from usermgmt import utils register = template.Library() @register.filter(is_safe=True) @stringfilter def render_attributes(value, autoes...
etc. """ # TODO # @makyo 2016-11-06 #63 if value == '': return 'No attributes' to_return = '<dl>' for attribute in value.split('\n'): k, v = attribute.split('=', 1) if k in utils.ATTRIBUTES: to_return += '<dt>{}</dt>'.format(utils.ATTRIBUTES[k]['dt']) ...
utils.ATTRIBUTES[k]['dd'].format(value=conditional_escape(v))) to_return += '</dl>' return mark_safe(to_return)
sagiss/sardana
scripts/upgrade/upgradeCLI.py
Python
lgpl-3.0
1,360
0.013235
#!/usr/bin/env python import sys, time import PyTango from upgrade_utils import * def upgrade(serv, old_vers, new_vers): u_kcls = get_suitable_upgrade(old_vers, new_vers) u_obj = u_kcls() db = PyTango.Database() print for msg, perc in u_obj.upgrade(db, serv, old_vers, new_vers): msg = "\0...
s.argv) > 2: vers = sys.argv[2] pool_serv_list = get_server_list() while not serv in pool_serv_list: print_list(pool_serv_list) serv = raw_input("Which instance you want to upgrade? ") old_vers = get_pool_server_version(serv) print "Current version of %s is %s" % (serv, old_v...
suitable upgrade plugin for version %s.\nUpgrade FAILED" % old_vers return while not get_suitable_upgrade(old_vers, vers): print_list(possible_upgrades) vers = raw_input("To which version you want to upgrade %s (bigger than %s)? " % (serv, old_vers)) upgrade(serv, old_vers, vers) ...
catapult-project/catapult
third_party/google-endpoints/google/api/config/service_config.py
Python
bsd-3-clause
4,729
0.006344
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # #
http://www.apache.org/l
icenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations u...
csvoss/onelinerizer
tests/scope_comprehension.py
Python
mit
1,199
0.000834
x = 4 a = lambda: x # Perhaps it once made sense to someone why c and d see the inner x # but a and b do not. print(''.join( # generator expression '{}{}{} {}{}{}{}\n'.format(i, j, k, a(), b(), c(), d()) for i, b in enumerate([a, lambda: x, a]) for j, c in enumerate([b, lambda: x, b]) for k, d in...
{}{}\n'.format(i, j, k, a(), b(), c(), d()) for i, b in enumerate([a, lambda: x, a]) for j, c in enumerate([b, lambda: x, b]) for k, d in enumerate([c, lam
bda: x, c]) for x in [6]}))) print(''.join(sorted({ # dict comprehension '{}{}{} {}{}{}{}\n'.format(i, j, k, a(), b(), c(), d()): 1 for i, b in enumerate([a, lambda: x, a]) for j, c in enumerate([b, lambda: x, b]) for k, d in enumerate([c, lambda: x, c]) for x in [7]}.keys()))) # Except in...
Davidrjx/mongoengine
mongoengine/document.py
Python
mit
43,855
0.000638
import re import warnings from bson.dbref import DBRef import pymongo from pymongo.read_preferences import ReadPreference import six from mongoengine import signals from mongoengine.base import (BaseDict, BaseDocument, BaseList, DocumentMetaclass, EmbeddedDocumentList, ...
tion = cls._get_capped_collection() else: db = cls._get_db() collection_name = cls._get_collection_name()
cls._collection = db[collection_name] # Ensure indexes on the collection unless auto_create_index was # set to False. if cls._meta.get('auto_create_index', T
a25kk/newe
src/newe.sitecontent/newe/sitecontent/browser/showroom.py
Python
mit
7,487
0
# -*- coding: utf-8 -*- """Module providing views for the folderish content page type""" import json import urllib from Acquisition import aq_inner from Products.Five.browser import BrowserView from plone import api from plone.i18n.normalizer.interfaces import IIDNormalizer from zope.component import getUtility from n...
lf, request, name): if not hasattr(self, 'subpath'): self.subpath
= [] self.subpath.append(name) return self def active_filter_category(self): try: active_category = self.traverse_subpath[0] return active_category except AttributeError: return None def contained_items(self, type_interface): context...
JoaoRodrigues/pdb-tools
tests/test_pdb_intersect.py
Python
apache-2.0
5,216
0.000384
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2018 João Pedro Rodrigues # # 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 # # Unl...
text(self): """$ pdb_intersect""" sys.argv = [''] # Execute the script self.exec_module() self.assertEqual(self.retcode, 1) # ensure the program exited gracefully.
self.assertEqual(len(self.stdout), 0) # no output self.assertEqual(self.stderr, self.module.__doc__.split("\n")[:-1]) if __name__ == '__main__': from config import test_dir mpath = os.path.abspath(os.path.join(test_dir, '..')) sys.path.insert(0, mpath) # so we load dev files before any ...
liberorbis/libernext
env/lib/python2.7/site-packages/celery/utils/log.py
Python
gpl-2.0
9,145
0.000437
# -*- coding: utf-8 -*- """ celery.utils.log ~~~~~~~~~~~~~~~~ Logging utilities. """ from __future__ import absolute_import, print_function import logging import numbers import os import sys import threading import traceback from contextlib import contextmanager from billiard import current_process, uti...
ghandler', 'in_sighandler', 'get_logger', 'get_task_logger', 'mlevel', 'ensure_process_aware_logger', 'get_multiprocessing_logger', 'reset_multiprocessing_logger'] _process_aware = False PY3
= sys.version_info[0] == 3 MP_LOG = os.environ.get('MP_LOG', False) # Sets up our logging hierarchy. # # Every logger in the celery package inherits from the "celery" # logger, and every task logger inherits from the "celery.task" # logger. base_logger = logger = _get_logger('celery') mp_logger = _get_logger('multip...
dsorokin/aivika-modeler
simulation/aivika/modeler/stream_random.py
Python
bsd-3-clause
7,405
0.006212
# Copyright (c) 2017 David Sorokin <david.sorokin@gmail.com> # # Licensed under BSD3. See the LICENSE.txt file in the root of this distribution. from simulation.aivika.modeler.model import * from simulation.aivika.modeler.port import * from simulation.aivika.modeler.stream import * from simulation.aivika.modeler.data_...
scale) + ' ' + str(shape) y = StreamPort(model, transact_type.get_data_type()) y.bind_to_input() y.write(code) return y def poisson_random_stream(transact_type, mean_delay): """Return a new stream of transacts with rand
om delays having the Poisson distribution with the specified mean.""" expect_transact_type(transact_type) model = transact_type.get_model() code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ ' code += 'randomPoissonStream ' + str(mean_delay) y = StreamPort(model, transac...
timothyparez/PyBitmessage
src/class_receiveDataThread.py
Python
mit
46,068
0.006556
doTimingAttackMitigation = False import base64 import errno import math import time import threading import shared import hashlib import os import select import socket import random import ssl from struct import unpack, pack import sys import traceback from binascii import hexlify #import string #from subprocess impor...
der.size: # if so little of the data has arrived that we can't even read the checksum then wait for more data. return magic,command,payloadLength,checksum = shared.Header.unpack(self.data[:shared.Header.size])
if magic != 0xE9BEB4D9: self.data = "" return if payloadLength > 1600100: # ~1.6 MB which is the maximum possible size of an inv message. logger.info('The incoming message, which we have not yet download, is too large. Ignoring it. (unfortunately there is no way to tel...
fengzishiren/pysugar
src/pysugar.py
Python
mit
5,899
0.01242
# -*- coding: utf-8 -*- ''' Created on 2014年7月23日 @author: fengzishiren @mail: xiaoyaozi106@163.com ''' import re import MySQLdb import os import sys from settings import * __version__ = '0.1' __date__ = '2014-07-23' __updated__ = '2014-07-23' FORMAT_ARGS = {'author': 'pysugar', 'date': __date__, 'version': __versio...
_type = OP_TYPE_DICT.get(name[0:3]) if type == None: return None match = PATTERN_ARG.search(line) assert match, 'Illegal Parameters' return Token(name, _type, match.group(1).lower()) def gen_bean_name(bean): ''' eg. UserAccount, userAccount ''' set_format_args(bean_na...
e, tokens): gs = lambda table_name, token: SQL_CODE[token.type] % \ dict({'method_name': token.name, 'arg_type':token.args, 'table_name':table_name}, **FORMAT_ARGS) sqls = [gs(table_name, tok) for tok in tokens if tok] # Note: Ignore tok if tok == None set_format_args(sq...
CognizantOneDevOps/Insights
PlatformAgents/com/cognizant/devops/platformagents/agents/alm/hp/HpAlmAgent3.py
Python
apache-2.0
11,216
0.005171
#------------------------------------------------------------------------------- # Copyright 2017 Cognizant Technology Solutions # # 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:...
None, reqHeaders={}) def getDomains(self, baseEndPoint, cookieHeader): projectsEndPoint = baseEndPoint + '/qcbin/rest/domains?include-projects-info=y&alt=application/'+self.responseType.lower()
projectResponse = self.getResponse(projectsEndPoint, 'GET', None, None, None, reqHeaders=cookieHeader) return projectResponse @BaseAgent.timed def getProjectDetails(self, baseEndPoint, reqHeaders, domain, project, entityName, fields, startFrom): domainTracking = self.tracking.get(...
SpaceGroupUCL/qgisSpaceSyntaxToolkit
esstoolkit/external/networkx/drawing/tests/test_layout.py
Python
gpl-3.0
15,534
0.000515
"""Unit tests for layout functions.""" import networkx as nx from networkx.testing import almost_equal import pytest numpy = pytest.importorskip("numpy") test_smoke_empty_graphscipy = pytest.importorskip("scipy") class TestLayout: @classmethod def setup_class(cls): cls.Gi = nx.grid_2d_graph(5, 5) ...
= self.check_scale_and_center c = (4, 5) G = nx.complete_graph(9) G.add_node(9) sc(nx.random_layout(G, center=c), scale=0.5, center=(4.5, 5.5)) # rest can have 2*scale length: [-scale, scale] sc(nx.spring_layout(G, scale=2, center=c), scale=2, center=c) sc(nx.spec...
center=c), scale=2, center=c) sc(nx.circular_layout(G, scale=2, center=c), scale=2, center=c) sc(nx.shell_layout(G, scale=2, center=c), scale=2, center=c) sc(nx.spiral_layout(G, scale=2, center=c), scale=2, center=c) sc(nx.kamada_kawai_layout(G, scale=2, center=c), scale=2, center=c) ...
fae92/TSML
lexer_parser/lexer.py
Python
cc0-1.0
1,403
0.018532
# ----------------------------------------------------------------------------- # lexer.py # # A simple calculator with variables -- all in one file. # ----------------------------------------------------------------------------- reserved = { 'class':'CLASS', 'block':'BLOCK', 'event':'EVENT', 'transiti...
r'\&' t_POINT = r'\.' #t_IDENTIFIER = r'[A-Z][a-zA-Z0-9_]*' t_FLECHE = r'\->' # Ignored characters t_ignore = " \t" def t_newline(t): r'\n+'
t.lexer.lineno += t.value.count("\n") def t_IDENTIFIER(t): r'[a-zA-Z_][a-zA-Z_0-9]*' t.type = reserved.get(t.value,'IDENTIFIER') # Check for reserved words t.value = t.value return t def t_error(t): print("lexer : Illegal character '%s'" % t.value[0]) t.lexer.skip(1) # Build the lexer im...
gems-uff/noworkflow
npm/watch.py
Python
mit
2,623
0.000762
import os import subprocess from pathlib import Path from time import sleep PACKAGES = Path('packages') class Module: def __init__(self, name, path=None, files=None, dependencies=None): self.name = name if path is None: path = PACKAGES / name self.path = path self.file...
dependencies
=[utils]) nowvis = Module("nowvis", dependencies=[history, trial]) nbextension = Module("nbextension", dependencies=[history, trial]) ALL = NoFileModule("ALL", dependencies=[nowvis, nbextension]) print("Monitoring packages...") while True: visited = {} try: ALL.check(visited=visited) except Except...
hadim/pygraphml
pygraphml/graph.py
Python
bsd-3-clause
6,171
0.003889
# -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from __future__ import print_function from . import Node from . import Edge from collections import deque class Graph: """ Main class which represent a Graph :param na...
""" if n1 not in self._nodes: raise Test("fff") if n2 not in self._nodes: raise Test("fff") e = Edge(n1, n2, directed) self._edges.append(e) return e def add_edge_by_id(self, id1, id2): try: n1 = next(n for n in self._nodes...
(id1)) try: n2 = next(n for n in self._nodes if n.id == id2) except StopIteration: raise ValueError('Graph has no node with ID {}'.format(id2)) return self.add_edge(n1, n2) def add_edge_by_label(self, label1, label2): """ """ n1 = None ...
e-gob/plataforma-kioscos-autoatencion
scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/modules/cloud/vmware/vmware_vmkernel_ip_config.py
Python
bsd-3-clause
3,594
0.001948
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2015, Joseph Callen <jcallen () csc.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_version': '1.1', ...
if vnic.device == vmk_name: spec = vnic.spec if spec.ip.ipAddress != ip_address: spec.ip.dhcp = False spec.ip.ipAdd
ress = ip_address spec.ip.subnetMask = subnet_mask host_network_system.UpdateVirtualNic(vmk_name, spec) return True return False def main(): argument_spec = vmware_argument_spec() argument_spec.update(dict(vmk_name=dict(required=True, type='str'), ...
dennissv/forestvision
Python/ReadCompute.py
Python
mit
8,907
0.03166
# -*- coding: utf-8 -*- """ Created on Wed Dec 7 00:16:31 2016 @author: Dennis """ import numpy as np import transformations import utm import gmplot from geopy.distance import vincenty def readINS(filename): results = [] f = open(filename, 'r') c = 0 for line in f: if c < ...
) current.append(s[14]) results.append(current) first = False f.close() return np.float
64(results) def usefulINS(data): ''' Time (s) | North (m) | East | Altitude | Roll (radians) | Pitch | Yaw ''' results,raw = [],[] n0 = data[:,10][0] e0 = data[:,9][0] for i in data: raw.append([i[18]%86400, i[10], i[9], i[1], i[0], \ i[2], i[4...
Zardinality/TF_Deformable_Net
lib/__init__.py
Python
mit
18
0.055556
#import fast_rcnn
pikuli-project/pikuli
test/test_region.py
Python
mit
12,465
0.000481
# -*- coding: utf-8 -*- import pytest from hamcrest import assert_that, equal_to, all_of, \ instance_of, has_property, calling, raises from pikuli import Region, Location from pikuli.common_exceptions import FailExit X = 311 Y = 128 ID = 3 WIDTH = 303 HEIGHT = 201 FIND_TIMEOUT = 3.1 TITLE = 'New test region' c...
estRegion(object): test_region = Region(X, Y, WIDTH, HEIGHT, title=TITLE, id=ID) def test_str(self): assert_that(str(self.test_region), equal_to('Region "%s" (%i, %i, %i, %i)' % (TITLE, X, Y, WIDTH, HEIGHT))) @pytest.mark.parametrize("id,region,expe...
id(), equal_to(expected)) @pytest.mark.parametrize("title,region,expected", [ ("Default title", Region(X, Y, WIDTH, HEIGHT), 'New Region'), ("Custom title", test_region, 'New test region') ]) def test_title(self, title, region, expected): assert_that(region.title, equal_to(expected)...
bdelliott/wordgame
web/django/templatetags/i18n.py
Python
mit
13,319
0.003003
import re from django.template import Node, Variable, VariableNode from django.template import TemplateSyntaxError, TokenParser, Library from django.template import TOKEN_TEXT, TOKEN_VAR from django.template.base import _render_value_in_context from django.utils import translation from django.utils.encoding import for...
elf.countervar] = count plural, plural_vars = self.render_token_list(self.plural) result = translation.ungettext(singular, plural, count) vars.extend(plural_vars) else: result = translation.ugettext(singular) # Escape all isolated '%' before substituting i...
. result = re.sub(u'%(?!\()', u'%%', result) data = dict([(v, _render_value_in_context(context[v], context)) for v in vars]) context.pop() return result % data def do_get_available_languages(parser, token): """ This will store a list of available languages in the context. ...
orlenko/FBBot
src/FBBot/fbposter/management/commands/populate.py
Python
apache-2.0
412
0.002427
from django.core.management.base import BaseCommand from django.contrib.auth.models import User from fbposter.models import FacebookStatus import facebook import datetime class Command(BaseCommand): args = '' help = 'Gets fresh message
s from Reddit' def handle(self, *args, **options): if len(args) < 1: self.stdout.write('Usage: ./manage.py facebook_post ') return
255BITS/HyperGAN
tests/losses/test_least_squares_loss.py
Python
mit
966
0.005176
import tensorflow as tf import hyperchamber as hc import hypergan as hg import numpy as np from hypergan.losses.least_squares_loss import LeastSquaresLoss from hypergan.ops import TensorflowOps from unittest.mock import MagicMock from tests.mocks import mock_gan loss_config = {'test': True, 'reduce':'reduce_mean', 'l...
e): def test_config(self): with self.test_session(): loss = LeastSquaresL
oss(mock_gan(), loss_config) self.assertTrue(loss.config.test) def test_create(self): with self.test_session(): gan = mock_gan() loss = LeastSquaresLoss(gan, loss_config) d_loss, g_loss = loss.create() d_shape = gan.ops.shape(d_loss) g...
cmmorrow/sci-analysis
sci_analysis/analysis/base.py
Python
mit
5,281
0.002083
"""Module: base.py Classes: Analysis - Generic analysis root class. Test - Generic statistical test class. GroupTest - Perform a test on multiple vectors that are passed as a tuple of arbitrary length. Comparison - Perform a test on two independent vectors of equal length. NormTest - Tests for wheth...
' + str(value) return line table = list() header = '' if isinstance(results, list): header = format_header(order) for row in results: table.append(format_row(row, order)) elif isinstance(results, dict):
max_length = max([len(label) for label in results.keys()]) for key in order: table.append(format_items(key, results[key])) out = [ '', '', name, '-' * len(name), '' ] if len(header) > 0: out.extend([ header, '-' * ...
google/neural-light-transport
nlt/datasets/nlt.py
Python
apache-2.0
7,804
0.001281
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
**kwa
rgs) # Trigger init. in a main thread before starting multi-threaded work. # See http://yaqs/eng/q/6292200559345664 for details Image.init() def _glob(self): # Handle holdouts holdout_cam = self.config.get('DEFAULT', 'holdout_cam').split(',') holdout_light = self.con...
dpac-vlsi/SynchroTrace
util/ext/ply/test/yacc_literal.py
Python
bsd-3-clause
1,566
0.014687
# ----------------------------------------------------------------------------- # yacc_literal.py # # Grammar with bad literal characters # ----------------------------------------------------------------------------- import sys if ".." not in sys.path: sys.path.insert(0,"..") import ply.yacc as yacc from calclex imp...
NAME EQUALS expression' names[t[1]] = t[3] def p_
statement_expr(t): 'statement : expression' print(t[1]) def p_expression_binop(t): '''expression : expression '+' expression | expression '-' expression | expression '*' expression | expression '/' expression | expression '**' expressi...
assefay/inasafe
safe_qgis/impact_statistics/test/test_aggregator.py
Python
gpl-3.0
16,606
0.001144
# coding=utf-8 """ InaSAFE Disaster risk assessment tool developed by AusAid and World Bank - **GUI Test Cases.** Contact : ole.moller.nielsen@gmail.com .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Fre...
logging import numpy.testing from os.path import join # Add PARENT directory to path to make test aware of other modules pardir = os.path.abspath(join(os.path.dirname(__file__), '..')) sys.path.append(pardir) from qgis.core import QgsVectorLayer, QgsCoordinateReferenceSystem from safe.common.testing import get_qgi...
afe_qgis import breakdown_defaults from safe_qgis.safe_interface import ( UNITDATA, TESTDATA, BOUNDDATA, Raster, Vector) from safe_qgis.utilities.utilities_for_testing import ( set_canvas_crs, set_jakarta_extent, GEOCRS) from safe_qgis.widgets.dock import Dock from safe_qgis.impact_sta...
rtrwalker/geotecha
examples/speccon/speccon1d_vr_4layers_vert_schiffmanandstein1970_Fig2.py
Python
gpl-3.0
2,145
0.000932
# speccon1d_vr example # Vertical consolidation of four soil layers # Figure 2 from: # Schiffman, R. L, and J. R Stein. (1970) 'One-Dimensional Consolidation of # Layered Systems'. Journal of the Soil Mechanics and Foundations # Division 96, no. 4 (1970): 1499-1504. from __future__ import division, print_function im...
ues are actually kv/gamw # speccon1d_vr parameters drn = 0 neig = 60 H = np.sum(h) z2 = np.cumsum(h) / H # Normalized Z at bottom of each layer z1 = (np.cumsum(h) - h) / H # Normalized Z at top of each layer mvref = mv[0] # Choosing 1st layer as reference value kvref = kv[0] # Choo
sing 1st layer as reference value dTv = 1 / H**2 * kvref / mvref mv = PolyLine(z1, z2, mv/mvref, mv/mvref) kv = PolyLine(z1, z2, kv/kvref, kv/kvref) surcharge_vs_time = PolyLine([0,0,30000], [0,1,1]) surcharge_vs_depth = PolyLine([0,1], [1,1]) # Load is uniform with depth ppress_z = np.linspace(0,1,200) tvals = ...
saltstack/salt
tests/pytests/unit/states/postgresql/test_user.py
Python
apache-2.0
23,174
0.00082
import pytest import salt.modules.postgres as postgres import salt.states.postgres_user as postgres_user from tests.support.mock import create_autospec, patch class ScramHash: def __eq__(self, other): return other.startswith("SCRAM-SHA-256$4096:") @pytest.fixture(name="db_args") def fixture_db_args(): ...
e": "username", "result": T
rue, "changes": {"username": "Present"}, "comment": "The user username has been created", } mocks["postgres.role_get"].assert_called_once() mocks["postgres.user_create"].assert_called_once_with( username="username", createdb=None, createroles=None, encrypted=T...
markflyhigh/incubator-beam
sdks/python/apache_beam/examples/cookbook/bigtableio_it_test.py
Python
apache-2.0
7,002
0.008569
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
croseconds_from_datetime from google.cloud._helpers import UTC from google.cloud.bigtable import row, column_family, Client except ImportError: Client = None UTC =
pytz.utc _microseconds_from_datetime = lambda label_stamp: label_stamp _datetime_from_microseconds = lambda micro: micro EXISTING_INSTANCES = [] LABEL_KEY = u'python-bigtable-beam' label_stamp = datetime.datetime.utcnow().replace(tzinfo=UTC) label_stamp_micros = _microseconds_from_datetime(label_stamp) LABELS = ...
DHTC-Tools/parrot-benchmark-tools
Root/parrot-root/get_file_list.py
Python
apache-2.0
494
0.008097
#!/usr/bin/env python import sys, random if len(sys.argv) != 3: sys.stderr.write("Must provide file with list of filenames and number of files to pick\n") sys.exit(1) file_list = open(sys.argv[1]) file_array = [] for filepath in file_list: file_array.append(filepath.
strip()) try: choices = int(sys.argv[2]) except: sys.stderr.write("Can't get the number of files to pick\n") sys.exit(1) for i in range(choices): sys.stdout.write("%s\n" % random.choice(file_array))
psychopy/psychopy
psychopy/experiment/routines/_base.py
Python
gpl-3.0
27,908
0.001039
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2022 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). """Describes the Flow of an experiment """ from psychopy.constants import FOREVER from xm...
def writePreCode(self, buff): return def writePreCodeJS(self, buff): return def writeStartCode(self, buff): return def writeStartCodeJS(self, buff): return def writeRunOnceInitCode(self, buff): return def writeInitCode(self, buff): return def...
return def writeRoutineBeginCodeJS(self, buff, modular): return def writeEachFrameCodeJS(self, buff, modular): return def writeRoutineEndCode(self, buff): # reset routineTimer at the *very end* of all non-nonSlip routines code = ('# the Routine "%s" was not non-slip ...
OCA/account-analytic
mrp_analytic_sale_project/models/sale_order.py
Python
agpl-3.0
490
0.002041
# Copyright
(C) 2021 Open Source Integrators # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models class SaleOrder(models.Model): _inherit = "sale.order" def action_confirm(self): res = super(SaleOrder, self).action_confirm() for order in self: order.procur...
d} ) return res
ryanpitts/growlerbot
scrapers/__init__.py
Python
mit
45
0
from
growler_guys import scrape_growler_
guys
Azure/azure-sdk-for-python
sdk/storage/azure-storage-blob/samples/blob_samples_authentication_async.py
Python
mit
5,908
0.003047
# 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. # --------------------------------------------------------------------...
ectory_application_secret = os.getenv("ACTIVE_DIRECTORY_APPLICATION_SECRET") active_directory_tenant_id = os.getenv("ACTIVE_DIRECTORY_TENANT_ID") async def auth_connection_string_async(self): # [START auth_from_connection_string] from azure.storage.blob.aio import BlobServiceClient blob...
m_connection_string(self.connection_string) # [END auth_from_connection_string] # [START auth_from_connection_string_container] from azure.storage.blob.aio import ContainerClient container_client = ContainerClient.from_connection_string( self.connection_string, container_nam...
alaeddine10/ggrc-core
src/ggrc/app.py
Python
apache-2.0
1,435
0.007666
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: # Maintained By: from . import settings # Initialize Flask app from flask import Flask app = Flask('ggrc', instance_relative_config=True) app.co...
oescape') app.jinja_env.add_extension('jinja2.ext.with_') app.jinja_env.add_extension('hamlpy.ext.HamlPyExtension') # Initialize services import ggrc.services ggrc.services.init_all_services(app) # Initialize views import ggrc.views ggrc.views.init_all_object_views(app) # Initialize configured and default extensions...
exer = get_indexer() if settings.ENABLE_JASMINE: # Configure Flask-Jasmine, for dev mode unit testing from flask.ext.jasmine import Jasmine, Asset jasmine = Jasmine(app) jasmine.sources( Asset("dashboard-js"), Asset("dashboard-js-spec-helpers")) jasmine.specs( Asset("dashboard-js-specs"))...
ua-snap/downscale
old/old_bin/sort_files_by_rcp.py
Python
mit
1,564
0.064578
import os, glob, shutil from pathos import multiprocessing as mp import pandas as pd import numpy as np base_path = '/Data/malindgren/cru_november_final/IEM/ar5' output_base_path = '/Data/malindgren/cru_november_final/IEM/ar5' models = [ 'IPSL-CM5A-LR', 'GISS-E2-R', 'MRI-CGCM3', 'CCSM4', 'GFDL-CM3' ] # variables = [...
] def run( x, y ): import shutil return shutil.mo
ve( x, y ) pool = mp.Pool( 15 ) out = pool.map( lambda x: run(x[0], x[1]), zip( group[1], out_group ) ) pool.close()
grajasumant/ducking-octo-cyril
misctests/mandelbrot_cuda.py
Python
gpl-2.0
1,857
0.008078
#################################################### # Calculate Mandelbrot set and save it as a bmp image # # Data parallel version using Pycuda # Create string with cuda code and let the graphics # card farm out the work to each warp. # #################################################### import bmp import pycu...
float nyf = 1.0f*ny; float qif = 4.0f*rowf/nyf-2.0f; float qrf = 4.0f*jf/nxf-2.0f; iteration[i] = maxiter; zr = 0.0f; zi = 0.0f; for(int n=0;n < maxiter;n++) { float nzr = zr*zr - zi*zi + qrf; float nzi = 2.0*zr*zi + qif; zi...
eration[i] = n; break; } } """, "mandlebrot_gpu",) # allocate a numpy array iterations = nm.zeros(nx*ny).astype(nm.int32) # allocate a gpu array iterations_gpu = gpuarray.to_gpu(iterations) # perform the gpu calculation complex_gpu(nm.int16(nx), nm.int16(ny), nm...
irisliu0616/Short-text-Classification
Model/Ohsumed/ohsumed_LSTM-SVM_CV.py
Python
mit
10,500
0.013905
from __future__ import print_function import os import sys import numpy as np import time from IPython import get_ipython np.random.seed(1337) from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.utils.np_utils import to_categorical from keras.layers impor...
OP_OUT, Nb_EPOCH, BATCH_SIZE, EMBEDDING_DIM, train_accuracy, valid_accuracy, test_accuracy, time] header.append(items) f = open(fname, 'wb')
writer = csv.writer(f) writer.writerows(header) header = [] # reset header after each loop f.close() def embedding_index(GLOVE_DIR, FILENAME): global embeddings_index embeddings_index = {} fname = os.path.join(GLOVE_DIR, FILENAME) f = open(fname) for line in f: values = lin...
muddyfish/PYKE
node/ord.py
Python
mit
408
0.002451
from node.dictionary import Dictionary from nodes imp
ort Node class Ord(Node): char = ".
o" args = 1 results = 1 def ord(self, string: str): """ord(string)""" try: return ord(string) except TypeError: return [[ord(i)for i in string]] def lookup(self, word_id: int): Dictionary.setup() return Dictionary.word_list[word_id]
jettify/aiogibson
tests/test_commands.py
Python
mit
10,025
0
from ._testutil import GibsonTest, run_until_complete from aiogibson import errors class CommandsTest(GibsonTest): """Gibson high level commands. :see: http://gibson-db.in/commands/ """ @run_until_complete def test_set(self): key, value = b'test:set', b'bar' response = yield from...
lf): key, value = b'test:dec', 78 resp = yield from self.gibson.set(key, value, expire=3) resp = yield from self.gibson.get(key) self.assertEqual(resp, b'78') resp = yield from self.gibson.dec(key) self.assertEqual(resp, 77) resp = yield from self.gibson.get(key) ...
st:lock', b'zap' resp = yield from self.gibson.set(key, value, 3) self.assertEqual(resp, value) resp = yield from self.gibson.lock(key, 10) self.assertEqual(resp, True) with self.assertRaises(errors.KeyLockedError): yield from self.gibson.set(key, value, 3) y...
omf2097/pyomftools
omftools/cli/af_compile.py
Python
mit
405
0
import argparse from omftools.pyshadowdive.af import AFFile if __name__ == "__mai
n__": parser = argparse.ArgumentParser(description="Compile AF file from JSON") parser.add_argument("input_file", help="Input .json file") parser.add_argument("output_file", help="Output .AF file
") args = parser.parse_args() AFFile.load_json(args.input_file).save_native(args.output_file) exit(0)
brefsdal/sherpa
sherpa/image/pyds9_backend.py
Python
gpl-2.0
5,145
0.007191
#_PYTHON_INSERT_SAO_COPYRIGHT_HERE_(2007)_ #_PYTHON_INSERT_GPL_LICENSE_HERE_ from itertools import izip import numpy import time import ds9 from sherpa.utils import get_keyword_defaults, SherpaFloat from sherpa.utils.err import DS9Err _target = 'sherpa' def _get_win(): return ds9.ds9(_target) def doOpen(): ...
pcdelt = sky.cdelt # join together all strings with a '\n' between each phys = '\n'.join(["WCSNAMEP = 'PHYSICAL'",
"CTYPE1P = 'x '", 'CRVAL1P = %.14E' % pcrval[0], 'CRPIX1P = %.14E' % pcrpix[0], 'CDELT1P = %.14E' % pcdelt[0], "CTYPE2P = 'y '", 'CRVAL2P = %.14E' % pcrval[1], ...
cnewcome/sos
sos/plugins/networking.py
Python
gpl-2.0
14,527
0.000207
# 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, # but...
tus(version=1):
status_template = "nmcli --terse --fields RUNNING %s status" obj_table = [ "nm", # < 0.9.9 "general" # >= 0.9.9 ] status = self.call_ext_prog(status_template % obj_table[version]) return status['output'].lower().startswith(...
toshywoshy/ansible
test/lib/ansible_test/_internal/classification.py
Python
gpl-3.0
32,223
0.002234
"""Classify changes in Ansible code.""" from __future__ import (absolute_import, division, print_function) __metaclass__ = type import collections import os import re import time from . import types as t from .target import ( walk_module_targets, walk_integration_targets, walk_units_targets, walk_com...
o integration tests if verbose_command: result = '%s: %s' % (verbose_command, tests.get(verbose_command) or 'none') # identify targeted integration tests (those which only target a single integration command) if 'integration' in verbose_command and tests.get...
ation' in command for command in tests if command != verbose_command): if focused_target: result += ' (focused)' result += ' (targeted)' else: result = '%s' % tests if not tests.get(verbose_command): ...
bittorrent/needy
needy/sources/download.py
Python
mit
5,420
0.000738
from __future__ import print_function import io import os import binascii import hashlib import socket import shutil import sys import tarfile import tempfile import time import zipfile import logging try: import urllib.request as urllib2 except ImportError: import urllib2 from ..source import S
ource class Download(Source): def __init__(self, url, checksum, destination, cache_directory): Source.__init__(self) self.url = url self.checksum = checksum self.destination = destination self.cache_directory = cache_directory
self.local_download_path = os.path.join(cache_directory, checksum) @classmethod def identifier(cls): return 'download' def clean(self): if not self.checksum: raise ValueError('checksums are required for downloads') self.__fetch() logging.info('Unpacking to ...
wkretzsch/bcftools
misc/plot-roh.py
Python
gpl-3.0
13,378
0.023322
#!/usr/bin/python import glob, gzip, csv, sys, os, copy, re csv.register_dialect('tab', delimiter='\t', quoting=csv.QUOTE_NONE) def usage(msg=None): if msg==None: print 'Usage: plot.py [OPTIONS] <dir>' print 'Options:' print ' -H, --highlight +group1,-group2 Highlight calls shared ...
rgs = copy.deepcopy(rg) out = {} while True: min = next_region(rgs)
if min==None: break beg = min[0] end = min[1] smpls = [] for smpl in rgs: if len(rgs[smpl])==0: continue reg = rgs[smpl][0] if reg[0] > end: continue if reg[1] > end: rgs[smpl][0][0] = end + 1 else: ...
sunqm/pyscf
pyscf/symm/param.py
Python
apache-2.0
8,518
0.021601
#!/usr/bin/env python # Copyright 2014-2018 The PySCF Developers. 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 # # U...
1,-1), # 01 ('Au', 1, 1,-1,-1), # 10 ('Bu', 1,-1,-1, 1)), # 11 # E,C2,sx,sy # XOR 'C2v': (('A1', 1, 1, 1, 1), # 00
('A2', 1, 1,-1,-1), # 01 ('B1', 1,-1,-1, 1), # 10 ('B2', 1,-1, 1,-1)), # 11 # E,C2x,C2y,C2z # XOR 'D2' : (('A' , 1, 1, 1, 1), # 00 ('B1', 1,-1, -1, 1), # 01 ...
TsarFox/chandere2
tests/websites/test_8chan.py
Python
gpl-3.0
1,671
0
import pytest from chandere.errors import ChandereError from chandere.loader import load_scraper scraper = load_scraper("8chan") VALID_CROSSLINK_TARGETS = [ ("/tech/589254", ("tech", "589254")), ("/tech/ 589254", ("tech", "589254")), ("tech/589254", ("tech", "589254")), ("/tech 589254", ("tech", "589...
e_valid_uri_target(): for target, expected in VALID_URI_TARGETS: assert scraper.
parse_target(target) == expected def test_parse_invalid_uri_target(): for target in INVALID_URI_TARGETS: with pytest.raises(ChandereError): scraper.parse_target(target) def test_parse_valid_crosslink_target(): for target, expected in VALID_CROSSLINK_TARGETS: assert scraper.parse_...
mackjoner/peewee
playhouse/tests/test_keys.py
Python
mit
15,919
0.000314
from playhouse.tests.base import compiler from playhouse.tests.base import database_initializer from playhouse.tests.base import ModelTestCase from playhouse.tests.base import PeeweeTestCase from playhouse.tests.base import skip_if from playhouse.tests.base import test_db from playhouse.tests.models import * class Te...
Relationship.create(from_user=b, to_user=c) following = User.select().
join( Relationship, on=Relationship.to_user ).where(Relationship.from_user == a) self.assertEqual(list(following), [b]) followers = User.select().join( Relationship, on=Relationship.from_user ).where(Relationship.to_user == a.id) self.assertEqual(list(fol...
sbordt/markovmixing
markovmixing/video_util.py
Python
mit
1,631
0.043532
""" Make videos. """ def matplotlib_plots_to_video(path, ffigure, n): """ Make a video from a sequence of matplotlib figures. The function ffigure will be called subsequently to retrieve the sequence of matplotlib figures. The figure must have been create
d using 'plt.figure(figsize=(19.20, 10.80), dpi=100)'. The will video consists of n frames (or figures), where 100 frames correspond to 1 second. The video will have a resolution of 1920*1080. path: path of the video file (*.avi) ffigure: callback function that takes the frame number as a single argument n: num...
""" import cv2, io import numpy as np import matplotlib.pyplot as plt from PIL import Image print "INFO: Creating a video that lasts "+`n/100.0`+" seconds." # Define the codec and create VideoWriter object fourcc = cv2.cv.CV_FOURCC(*'FMP4') out = cv2.VideoWriter(path, fourcc, 100.0, (1920,1080)) for i in...
mscansian/SigmaWebPlus
plus/xmlparser.py
Python
gpl-3.0
4,326
0.015491
#!/usr/bin/python # -*- coding: UTF-8 -*- ''' xmlObject.py XXX Metodos publicos XXX Dependencias (dentro do projeto) ''' from lxml.etree import XML class aluno: xmlData = None alunoData = None def get(self, key): try: return self.alunoData[...
r': self._float(nota.text, True)}) elif nota.tag == "Exame": dadosMateria['Exame'] = self._float(nota.text, True)
elif nota.tag == "MediaFinal": dadosMateria['MediaFinal'] = self._float(nota.text, True) mediaParcial, somaPesos, notasPublicadas = [0, 0, 0] for nota in dadosMateria['Notas']: ...
wonderful4228/qualitybots
src/appengine/handlers/statistics_handler.py
Python
apache-2.0
4,705
0.007864
#!/usr/bin/python2.4 # # Copyright 2010 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...
f result.score < 0: continue browser_key = result.GetTestBrowser().key().name() # Only count results that are non-ignored. if not result.ignore: scores[browser_key] += result.score counts[browser_key] += 1 for test_browser in test_b
rowsers: test_browser_key = test_browser.key().name() scores[test_browser_key] /= float(counts[test_browser_key]) average_score = browser_score.GetOrInsertBrowserScore(suite, test_browser) average_score.layout_score = scores[test_browser_key] average_score.num_urls = counts[test_browser_ke...
rronen/HAF-score
mean_pairwise_diff.py
Python
gpl-2.0
2,366
0.023246
#!/usr/bin/env python ''' plotting utility for haplotype CFP peak and trough durring a selective sweep ''' import sys import os import numpy as np from scipy.spatial.distance import pdist from scipy.spatial.distance import squareform ''' internal imports, parent dir ''' sys.path.insert(1, os.path.join(sys.path[0], ...
############################################################ if __name__ == '__main__': # if len(sys.argv) != 3: # print "\n\tusage: %s '<ms-like-file.ms> <'ms'/'mpop'>'\n" % sys.argv[0] # else: # go(sys.argv[1], sys.ar
gv[2]) go_ms() # mean pairwise dist using cmd: ms 2000 1 -t 48.0 > pop.init == 25.8554 go_mpop() # mean pairwise dist using cmd: mpop -i pop.ms -o pop.mpop -N 2000 -m 0.012 -g 100 == 19.369463199103
Spiderlover/Toontown
toontown/coghq/LawbotOfficeLobby_Trap00.py
Python
mit
19,705
0.000457
from toontown.coghq.SpecImports import * GlobalEntities = {1000: {'type': 'levelMgr', 'name': 'LevelMgr', 'comment': '', 'parentEntId': 0, 'cogLevel': 0, 'farPlaneDistance': 1500, 'modelFilename': 'phase_11/models/lawbotHQ/LB_Zone04a', 'wantDoors': 1}, 1001: {'ty...
one, 'requestNewEntity': None, 'requestSave': None}, 0: {'type': 'zone', 'name': 'UberZone', 'comment': '', 'parentEntId': 0, 'scale': 1, 'description': '', 'visibility': []}, 100018: {'type': 'button', 'name': '<unnamed>', 'comment': '', 'pa...
.03896, 0), 'hpr': Vec3(0, 0, 0), 'scale': Vec3(3, 3, 3), 'color': Vec4(1, 1, 1, 1), 'isOn': 0, 'isOnEvent': 0, 'secondsOn': -1.0}, 100019: {'type': 'button', 'name': '<unnamed>', 'comment': '', 'parentEntId': 0, 'pos':...
jordant/err-chef
chef.py
Python
gpl-3.0
2,609
0.014182
#!/usr/bin/env python import chef import datetime from errbot import BotPlugin, botcmd from time import time STALE_TIME = 60 * 30 # 30 minutes class Chef(BotPlugin): def pretty_time(self, time): return datetime.datetime.fromtimestamp(int(time)).strftime('%Y-%m-%d %H:%M:%S') def search...
list = "Search results for query : %s\n" % args
for row in self.search_node(args): list += "%s\n" % row.object.name return(list) @botcmd def roles (self, mess, args): """ Search and return roles """ api = chef.autoconfigure() roles = '' for r...
DazWorrall/ansible
lib/ansible/modules/packaging/os/openbsd_pkg.py
Python
gpl-3.0
26,447
0.005067
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, Patrik Lundin <patrik@sigterm.se> # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', ...
kage']) else: install_cmd = "cd %s && make install && make clean=depends" % (port_dir) else: module.fail_json(msg="the port source directory %s does not exist" % (port_dir)) else: install_cmd = 'pkg_add -Im' ...
pkg_spec[name]['rc'], pkg_spec[name]['stdout'], pkg_spec[name]['stderr']) = module.run_command(install_cmd, module, use_unsafe_shell=True) else: (pkg_spec[name]['rc'], pkg_spec[name]['stdout'], pkg_spec[name]['stderr']) = execute_command("%s %s" % (install_cmd, name), module) # ...
rwl/PyCIM
CIM15/CDPSM/Balanced/IEC61970/Core/IdentifiedObject.py
Python
mit
3,613
0.002491
# Copyright (C) 2010-2011 Richard Lincoln # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish...
ossibly non unique text naming the object. @param aliasName: The aliasName is free text human readable name of the object alternative to IdentifiedObject.name. It may be no
n unique and may not correlate to a naming hierarchy. The attribute aliasName is put back because of backwards compatibility between CIM relases. It is however recommended to replace aliasName with the Name class as aliasName is planned for retirement at a future time. This was decided at a joint WG13/14 meeting in Min...
FluidityStokes/fluidity
libspud/diamond/diamond/sliceview.py
Python
lgpl-2.1
3,408
0.010563
# This file is part of Diamond. # # Diamond 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. # # Diamond is distribute...
): nodes.append(child.get_mixed_data()) nodes += self.get_nodes(node, child) return nodes def control(self, node): hbox = gtk.HBox() label = gtk.Label(node.get_name_path()) hbox.label = label data = datawidget.DataWidget() data.geometry_dim_tree = self.geometry_dim_tree ...
update(node) attributes = attributewidget.AttributeWidget() attributes.connect("on-store", self.on_store) attributes.connect("update-name", self.update_name) attributes.update(node) hbox.pack_start(label, True, True, 0) hbox.pack_start(data, True, True, 0) hbox.pack_start(attributes, True,...
orwa1902/code-exemples
TicTacToe.py
Python
apache-2.0
4,091
0.044977
board = [] for i in range(3): board.append(["*"] * 3) #a function that creats the board def print_board(board): for row in board: print (" ".join(row)) print("Let\'s play Tic Tac Toe! the rules are simple. you, the players, is given two choices: the row and column of your symbol. note that the numbers are between 0...
" and board[0][2] == "X": x = "winner" print("the winner is X") break; #middle row winner elif board[1][0] == "X" and board[1][1] == "X" and board[1][2] == "X": x = "winner" print("the winner is X") break; #right row winner elif board[2][0] == "X" and board[2][1] == "X" and board[2][2]=="X":
x = "winner" print("the winner is X") break; #top column winner elif board[0][0] == "X" and board[1][0] == "X" and board[2][0] == "X": x = "winner" print("the winner is X") break; #middle column winner elif board[0][1] == "X" and board[1][1] == "X" and board[2][1] == "X": x = "winner" print("...