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
ioam/topographica
topo/learningfn/som.py
Python
bsd-3-clause
5,130
0.009747
""" SOM-based learning functions for CFProjections. """ from math import ceil import param from imagen import PatternGenerator, Gaussian from holoviews import BoundingBox from topo.base.arrayutil import L2norm, array_argmax from topo.base.cf import CFPLearningFn ### JABHACKALERT: This class will be removed once th...
= BoundingBox(points=((-rbound,-rbound), (rbound,rbound))) # Print parameters designed to match fm2d's output #print "%d rad= %d std= %f alpha= %f" % (topo.sim._time, radius_int, radius, single_connection_learning_rate
) neighborhood_matrix = nk_generator(bounds=bb,xdensity=1,ydensity=1, size=2*radius) for r in range(rmin,rmax): for c in range(cmin,cmax): cwc = c - wc rwr = r - wr lattice_dist = L2norm((cwc,rwr)) ...
cliffe/SecGen
modules/utilities/unix/ctf/metactf/files/repository/src_angr/dist/scaffold10.py
Python
gpl-3.0
4,519
0.011286
# This challenge is similar to the previous one. It operates under the same # premise that you will have to replace the check_equals_ function. In this # case, however, check_equals_ is called so many times that it wouldn't make # sense to hook where each one was called. Instead, use a SimProcedure to write # your ow...
the # correct symbol, disassemble the binary. # (!) check_equals_symbol = ??? # :string project.hook_symbol(check_equals_symbol, ReplacementCheckEquals()) simulation = project.factory.simgr(initial_state) def is_successful(state): stdou
t_output = state.posix.dumps(sys.stdout.fileno()) return ??? def should_abort(state): stdout_output = state.posix.dumps(sys.stdout.fileno()) return ??? simulation.explore(find=is_successful, avoid=should_abort) if simulation.found: solution_state = simulation.found[0] solution = ??? pr...
woddx/privacyidea
privacyidea/lib/utils.py
Python
agpl-3.0
5,349
0.002243
from .log import log_with import logging log = logging.getLogger(__name__) import binascii from .crypto import geturandom import qrcode import StringIO import urllib from privacyidea.lib.crypto import urandom import string import re def generate_otpkey(key_size=20): """ generates the HMAC key of keysize. Shoul...
enerate :type key_size: int :return: hexlified key :rtype: string """ log.debug("generating key of size %s" % key_size) return binascii.hexlify(geturandom(key_size)) def create_png(data, alt=None): im
g = qrcode.make(data) output = StringIO.StringIO() img.save(output) o_data = output.getvalue() output.close() return o_data def create_img(data, width=0, alt=None): """ create the qr image data :param data: input data that will be munched into the qrcode :type data: string ...
gsnyder206/synthetic-image-morph
congrid.py
Python
gpl-2.0
3,937
0.018542
import numpy as n import scipy.interpolate import scipy.ndimage def congrid(a, newdims, method='linear', centre=False, minusone=False): '''Arbitrary resampling of source array to new dimension sizes. Currently only supports maintaining the same number of dimensions. To use 1-D arrays, first promote them to...
(see Numerical Recipes for validity of use of n 1-D interpolations) spline - uses ndimage.map_coordinates centre: True - interpolation points are at the centres of the bins F
alse - points are at the front edge of the bin minusone: For example- inarray.shape = (i,j) & new dimensions = (x,y) False - inarray is resampled by factors of (i/x) * (j/y) True - inarray is resampled by(i-1)/(x-1) * (j-1)/(y-1) This prevents extrapolation one element beyond bounds of input array....
davidthaler/Kaggle_Avito-2015
val_run0.py
Python
mit
1,259
0.01668
''' This script gets log loss on the validation set from full_val_set.pkl, (generated by the full_validation_set.py script) for some simple, no-learning models like the HistCTR, all 0's, or mean-value benchmark. author: David Thaler date: July 2015 ''' import avito2_io from datetime import datetime from eval import ...
tCTR']} search_etl = {'cat' : lambda l
: l['CategoryID']} # validation run input = avito2_io.rolling_join(True, train_etl, search_etl, do_validation=True, val_ids=val_ids) loss = 0.0 for (k, (x, y)) in enumerate(input): #loss +=...
rika/precip
precip/experiment.py
Python
apache-2.0
62,853
0.008146
#!/usr/bin/python2.7 -tt """ Copyright 2012 University Of Southern California 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 ...
h.join(self._conf_dir, "precip_"+uid+".pub") self._ssh_privkey = os.path.join(self._conf_dir, "precip_"+uid) if not os.path.exists(self._ssh_privkey): logger.info("Creating new ssh key in " + self._conf_dir) logger.info("You don't need to
enter a passphrase, just leave it blank and press enter!") cmd = "ssh-keygen -q -t rsa -f " + self._ssh_privkey + " </dev/null" p = subprocess.Popen(cmd, shell=True) stdoutdata, stderrdata = p.communicate() rc = p.returncode if rc != 0: raise ...
jitka/weblate
weblate/trans/admin_views.py
Python
gpl-3.0
7,747
0
# -*- coding: utf-8 -*- # # Copyright © 2012 - 2016 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.org/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, eith...
Site from django.shortcuts import render from django.contrib.admin.
views.decorators import staff_member_required from django.contrib import admin from django.utils.translation import ugettext as _ from django.conf import settings import django import six from weblate.trans.models import SubProject, IndexUpdate from weblate import settings_example from weblate import appsettings from...
huertatipografica/huertatipografica-fl-scripts
AT_Outlines/AT-RoundCorners.py
Python
apache-2.0
2,230
0.045291
#FLM: AT ChrisCorner """Round selected corners: RADIUS
is a Point instance that represents the x and y radius of the corner HAND
LELENGTH is a number between 0. and 1. that determines how long the bezier handles should be, affecting the steepness of the curve """ import math def getContourRange(nid,g): cID = g.FindContour(nid) cStart = g.GetContourBegin(cID) cEnd = cStart + g.GetContourLength(cID) - 1 return cStart,cEnd def getNextNode(...
gregdek/ansible
lib/ansible/cli/adhoc.py
Python
gpl-3.0
7,375
0.002847
# Copyright: (c) 2012, Michael DeHaan <michael.dehaan@gmail.com> # Copyright: (c) 2018, Ansible Project # 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 from ansible import constants as ...
text.CLIARGS['module_args']: err = "No argument passed to %s module" % context.CLIARGS['module_name'] if pattern.endswith(".yml"): err = err + ' (did you mean to run ansible-playbook?)' raise AnsibleOptionsError(err) # Avoid modules that don't work with ad-ho...
ad-hoc commands" % context.CLIARGS['module_name']) play_ds = self._play_ds(pattern, context.CLIARGS['seconds'], context.CLIARGS['poll_interval']) play = Play().load(play_ds, variable_manager=variable_manager, loader=loader) # used in start callback ...
rendermotion/RMPY
Tools/QT4/ui/FormRigDisplay.py
Python
lgpl-3.0
1,331
0.003005
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'UI_RigDisplay.ui' # # Created: Wed Mar 21 21:43:33 2018 # by: pyside-uic 0.2.14 running on PySide 1.2.0 # # WARNING! All changes made in this file will be lost! from PySide import QtCore, QtGui class Ui_Form(object): def setupUi(s...
drawStyle) self.verticalLayout.addLayout(self.horizontalLayout) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): Form.setWindowTitle(QtGui.QApplication.translate("Form", "Form", None, QtGui.QApplication.UnicodeUTF8)) self.C...
nt DrawStyle", None, QtGui.QApplication.UnicodeUTF8))
InsulaCoworking/MusicCity
bands/migrations/0049_band_hidden_in_catalog.py
Python
gpl-2.0
567
0.001764
# Generated by Django 2.2.13 on 2021-09-28 11:02 from django.db import mi
grations, models class Migration(migrations.Migration): dependencies = [ ('bands', '0048_band_profile_thumb'), ] operations = [ migrations.AddField( model_name='band', name='
hidden_in_catalog', field=models.BooleanField(default=False, help_text='Ocultar el perfil del listado, para bandas que no son de Alcala pero se crea su perfil para ciclos y festivales', verbose_name='Oculto en el listado principal'), ), ]
murven/malmo
Malmo/samples/Python_examples/tutorial_5_solved.py
Python
mit
7,626
0.011671
# ------------------------------------------------------------------------------------------------ # Copyright (c) 2016 Microsoft Corporation # # 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 ...
--------------------------------------------------------------------------------- # Tutorial sample #5: Observations import MalmoPython import os import sys import time import json sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) # flush print output immediately def Menger(xorg, yorg, zorg, size, blocktype, var...
ant, holetype): #draw solid chunk genstring = GenCuboidWithVariant(xorg,yorg,zorg,xorg+size-1,yorg+size-1,zorg+size-1,blocktype,variant) + "\n" #now remove holes unit = size while (unit >= 3): w=unit/3 for i in xrange(0, size, unit): for j in xrange(0, size, unit): ...
ArneBab/video-splitter
ffmpeg-split.py
Python
apache-2.0
2,871
0.019157
#!/usr/bin/env python import subprocess import re import math from optparse import OptionParser length_regexp = 'Duration: (\d{2}):(\d{2}):(\d{2})\.\d+,' re_length = re.compile(length_regexp) def main(): (filename, split_length) = parse_options() if split_length <= 0: print "Split length can't be 0...
shell = True, stdout = subprocess.PIPE ).stdout.read() print output matches = re_length.search(output) if matches: video_length = int(matches.group(1)) * 3600 + \ int(matches.group(2)) * 60 + \ ...
eo length." raise SystemExit split_count = int(math.ceil(video_length/float(split_length))) if(split_count == 1): print "Video length is less then the target split length." raise SystemExit split_cmd = "ffmpeg -i '"+filename+"' -vcodec copy " try: filebase = ".".join(fi...
persandstrom/home-assistant
homeassistant/components/huawei_lte.py
Python
apache-2.0
3,730
0
""" Support for Huawei LTE routers. For more details about this component, please refer to the documentation at https://home-assistant.io/components/huawei_lte/ """ from datetime import timedelta from functools import reduce import logging import operator import voluptuous as vol import attr from homeassistant.const...
10) DOMAIN = 'huawei_lte' DATA_KEY = 'huawei_lte' CONFIG_SCHEMA = vol.Schema({ DOMAIN: vol.All(cv.ensure_list, [vol.Schema({ vol.Required(CONF_URL): cv.url, vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, })]) }, extra=vol.ALLOW_EXTRA) @attr.s class Ro...
se, factory=dict) traffic_statistics = attr.ib(init=False, factory=dict) wlan_host_list = attr.ib(init=False, factory=dict) def __getitem__(self, path: str): """ Get value corresponding to a dotted path. The first path component designates a member of this class such as dev...
PyCQA/pylint
tests/functional/u/use/use_implicit_booleaness_not_comparison.py
Python
gpl-2.0
5,576
0.009146
# pylint: disable=missing-docstring, missing-module-docstring, invalid-name # pylint: disable=too-few-public-methods, line-too-long, dangerous-default-value # pylint: disable=wrong-import-order # https://github.com/PyCQA/pylint/issues/4774 def github_issue_4774(): # Test literals # https://github.com/PyCQA/pyl...
s = MyClassWithProxy() assert my_class.parent_function == {} # [use-implicit
-booleaness-not-comparison] assert my_class.my_property == {} # [use-implicit-booleaness-not-comparison] # If the return value is not always implicit boolean, don't raise assert my_class.my_difficult_property == {} # Uninferable does not raise assert AnotherClassWithProperty().my_property == {}
mamchecker/mamchecker
mamchecker/conf.py
Python
gpl-3.0
1,452
0.004132
# -*- coding: utf-8 -*- ''' Sphinx setting. ''' import os.path import sys sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) extensions = [ 'mamchecker.inl', 'sphinx.ext.mathjax', 'sphinxcontrib.tikz', 'sphinxcontrib.texfigure'] # i.e. same as conf.py and with page.html containing only {...
t,calc,shadows,plotmarks' latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'a4paper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', 'preamble': '''\\usepackage{amsfonts}\\usepackage{amssymb}\\usepackage{amsmath}\\usepackage{siunitx}\\u
sepackage{tikz}''' + ''' \\usetikzlibrary{''' + tikz_tikzlibraries + '''}''' } # latex # sphinx-build[2] -b latex -c . -D master_doc=<rst-file> -D project=<rst-file> <src-dir> <build-dir> # sphinx-build2 -b latex -c . -D master_doc=vector -D project=vector r/b _build # html # sphinx-build[2] -b html -c . -D m...
kennyledet/Algorithm-Implementations
10_Harshad_Number/Python/wasi0013/HarshadNumber.py
Python
mit
856
0.026869
""" Harshad Number implementation See: http://en.wikipedia.org/wiki/Harshad_number """ def is_harshad(n): result=0 while n: result+=n%10 n//=10 return n%result == 0 # Return if the remainder of n/result is 0 else return False de
f main(): # test contains a set of harshad numbers test=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42, 45, 48, 50, 54, 60, 63, 70, 72, 80, 81, 84, 90, 100, 102, 108, 110, 111, 112, 114, 117, 120, 126, 132, 133, 135, 140, 144, 150, ...
1] flag=True for i in test: if not is_harshad(i): flag=False break print("The test was", "Successful"if flag else "Unsuccessful!"); if __name__ == '__main__': main()
cmjatai/cmj
cmj/core/migrations/0013_auto_20180516_1559.py
Python
gpl-3.0
1,070
0.000939
# -*- coding: utf-8 -*- # Generated by D
jango 1.11.13 on 2018-05-16 18:59 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0012_auto_201
80227_0858'), ] operations = [ migrations.AlterModelOptions( name='user', options={'ordering': ('first_name', 'last_name'), 'permissions': (('menu_dados_auxiliares', 'Mostrar Menu Dados Auxiliares'), ('menu_tabelas_auxiliares', 'Mostrar Menu de Tabelas Auxiliares'), ('menu_conta...
pseudonym117/Riot-Watcher
src/riotwatcher/_apis/legends_of_runeterra/MatchApi.py
Python
mit
1,097
0.000912
from .. import BaseApi, NamedEndpoint from .urls import MatchApiUrls class MatchApi(NamedEndpoint): """ This class wraps the LoR-Match-V1 Api calls provided by the Riot API. See https://developer.riotgames.com/apis#lor-match-v1 for more detailed information """ def __init__(self, base_api: B...
""" Initialize a new MatchApi which uses the provided base_api :param BaseApi base_api: the root API object to use for making all requests. """ super(
).__init__(base_api, self.__class__.__name__) def by_puuid(self, region: str, puuid: str): """ Get a list of match ids by PUUID. :returns: List[string] """ return self._request_endpoint( self.by_puuid.__name__, region, MatchApiUrls.by_puuid, puuid=puuid ...
jnadro/pybgfx
pybgfx/__init__.py
Python
bsd-2-clause
96
0
from .bgfx import * from .
bgfx_ex import * from .bgfx_utils impor
t * from .bgfxdefines import *
mattjml/wood_cylinder_cut
cut.py
Python
apache-2.0
5,717
0.009271
import numpy as np from math import pi, tan, cos, sin, sqrt import sys import argparse render = True try: from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt except: render = False parser = argparse.ArgumentParser(description=\ "Calculates cutting path around cylinder for certain an...
trix for a theta radian rotation around the axis given.''' axis = axis/sqrt(np.dot(axis,axis)) a = cos(theta/2) b,c,d = -axis*sin(theta/2)
return np.array([[a*a+b*b-c*c-d*d, 2*(b*c-a*d), 2*(b*d+a*c)], [2*(b*c+a*d), a*a+c*c-b*b-d*d, 2*(c*d-a*b)], [2*(b*d-a*c), 2*(c*d+a*b), a*a+d*d-b*b-c*c]]) def vertical_plane_normal(p1,p2): '''Compute a normal to the cutting plane''' p3 = p1 + [0,0,1] return np.cross...
KelSolaar/Foundations
foundations/globals/constants.py
Python
gpl-3.0
3,184
0.000942
#!/usr/bin/env python # -*- coding: utf-8 -*- """ **constants.py** **Platform:** Windows, Linux, Mac Os X. **Description:** Defines **Foundations** package default constants through the :class:`Constants` class. **Others:** """ from __future__ import unicode_literals import os import platform import fou...
tory: unicode """ if platform.system() == "Windows" or platform.system() == "Microsoft" or platform.system() == "Darwin": provider_directory = "HDRLabs" """ :param provider_directory: Package provider directory. :type provider_directory: unicode """ elif platform.syst...
r directory. :type provider_directory: unicode """ null_object = "None" """ :param null_object: Default null object string. :type null_object: unicode """
jpwbernardi/Computacao-Distribuida
Trabalho1/main.py
Python
gpl-3.0
816
0.011029
# -*- coding: utf-8 -*- from bottle import run, get, post, view, request, redirect, route, static_file, template import bottle import json import threading import requests import time import sys messages = set([]) @bottle.route('/static/<path:path>') def server_static(path): return static_file(p
ath, root='static') @get('/chat') @view('chat') def chat(): name = request.query.name return dict(msg=list(messages), name=name) @route('/') def index(): redirect('chat') @post('/send') def sendmsg(): name = request.forms.getunicode('name') msg = request.forms.getunicode('msg') global message...
g != None: messages.add((name, msg)) redirect('chat?name=' + name) else: redirect('chat') run(host='localhost', port=int(sys.argv[1]))
8devices/IoTPy
IoTPy/sandbox/ledstrip.py
Python
mit
5,948
0.000841
from math import exp from colorsys import hls_to_rgb import random import struct import threading from time import sleep class Wire: def __init__(self, board, pin): self.board = board self.pin = pin def __enter__(self): self.board.uper_io(0, self.board.encode_sfp(100, [1])) r...
def get_value(self): r, g, b =
hls_to_rgb(self.value, 0.3, 1.0) return (int(r*255) << 16) | (int(g*255) << 8) | int(b*255) class SawHueColorEvolver(SawNumberEvolver): def get_value(self): r, g, b = hls_to_rgb(self.value, 0.3, 1.0) return (int(r*255) << 16) | (int(g*255) << 8) | int(b*255) class LedEffect(object): d...
kyoren/https-github.com-h2oai-h2o-3
h2o-py/tests/testdir_algos/rf/pyunit_swpredsRF.py
Python
apache-2.0
1,272
0.015723
import sys sys.path.insert(1, "../../../") import h2o, tests def swpredsRF(): # Training set has two predictor columns # X1: 10 categorical levels, 100 observations per level; X2: Unif(0,1) noise # Ratio of y = 1 per Level: cat01 = 1.0 (strong predictor), cat02 to cat10 = 0.5 (weak predictors) ...
"y"] = swpreds["y"].asfactor() #Log.info("Summary of swpreds_1000x3.csv from H2O:\n") #swpreds.summary() # Train H2O DRF without Noise Column #Log.info("Distributed Random Forest with only Predictor Column") model1 = h2o.random_forest(x=swpreds[["X1"]], y=swpreds["y"], ntrees=50, max_depth=20, nbi...
print(perf1.auc()) # Train H2O DRF Model including Noise Column: #Log.info("Distributed Random Forest including Noise Column") model2 = h2o.random_forest(x=swpreds[["X1","X2"]], y=swpreds["y"], ntrees=50, max_depth=20, nbins=500) model2.show() perf2 = model2.model_performance(swpreds) print(p...
N402/NoahsArk
ark/app.py
Python
mit
3,309
0.000302
import os from flask import Flask from ark.utils._time import friendly_time from ark.master.views import master_app from ark.account.views import account_app from ark.goal.vi
ews import goal_app from ark.oauth.views import oauth_app from ark.dashboard.views import dashboard_app from ark.goal.models import Goal from ark.exts import (setup_babel, setup_bcrypt, setup_cache,
setup_collect, setup_database, setup_login_manager, setup_oauth, setup_csrf) def create_app(name=None, config=None): app = Flask(name or __name__) app.config.from_object('ark.settings') init_config(app) if isinstance(config, dict): app.config.updat...
pepitogithub/PythonScripts
Dados.py
Python
gpl-2.0
1,284
0.043614
from Probabilidades import Probabilidad from validador import * a = Probabilidad() a.cargarDatos("1","2","3","4","5","6") uno = [" ------- ","| |","| # |","| |"," ------- "] dos = [" ------- ","| # |","| |","| # |"," ------- "] tres = [" ------- ","| # |","| # |","|...
:seis} def dado(*repeticiones): tiradas = 1 if (len(repeticiones) > 0): tiradas = repeticiones[0] else: tiradas = 1 for i in range(0,tiradas): numero =
a.generar() resultado = diccio[numero] for fila in resultado: print fila seguir = True while (seguir): print "indique la cantidad de tiradas:" ingreso = validador.ingresar(int,validador.entre,0,20) if(ingreso == 0): print "KeepRollingDi...
stphivos/django-angular2-fullstack-devops
backend/api/migrations/0001_initial.py
Python
mit
955
0.002094
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-05-09 12:57 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migration...
CADE, to=settings.AUTH_USER_MODEL)), ], options={ 'abstract': False,
}, ), ]
bishnucit/Python-Preludes
6.py
Python
mit
286
0.003497
from selenium import webdriver from selenium.webdriver.common.keys import
Keys # clicking on Welcome link. driver = webdriver.Firefox() driver.get("http://www.practiceselenium.com/") driver.find_element_by_link_text("Check Out").clic
k() assert "Check Out" in driver.title driver.close()
Ayrx/cryptography
tests/conftest.py
Python
bsd-3-clause
1,721
0
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. from __future__ import absolute_import, division, print_function import pytest from cryptography.hazmat.backends import _available_backen...
untest_setup(item): check_backend_support(item) def pytest_addoption(parser): parser.addoption( "--backend", action="store", metavar="NAM
E", help="Only run tests matching the backend NAME." )
pjxiao/yum-s3-plugin
s3.py
Python
apache-2.0
9,268
0.006798
""" Yum plugin for Amazon S3 access. This plugin provides access to a protected Amazon S3 bucket using either boto or Amazon's REST authentication scheme. On CentOS this file goes into /usr/lib/yum-plugins/s3.py You will also need two configuration files. See s3.conf and s3test.repo for examples on how to deploy t...
self.baseurl.path # See http://docs.python.org/library/urlparse.html self.baseurl = urlparse(baseurl) self.bucket_name = re.match('(.*)\.s3.*\.amazonaws\.com', self.baseurl[1]).group(1) self.key_prefix = self.baseurl[2][1:] def _handle_s3(self, awsAccessKey, awsS...
def _dump_attributes(self): self.logger.debug("baseurl: %s" % str(self.baseurl)) self.logger.debug("bucket: %s" % self.bucket_name) self.logger.debug("key_prefix: %s" % self.key_prefix) def _key_name(self,url): self.logger.debug("_key_name url=%s, key_prefix=...
persandstrom/home-assistant
tests/components/binary_sensor/test_threshold.py
Python
apache-2.0
13,704
0
"""The test for the threshold sensor platform.""" import unittest from homeassistant.setup import setup_component from homeassistant.const import ( ATTR_UNIT_OF_MEASUREMENT, STATE_UNKNOWN, TEMP_CELSIUS) from tests.common import get_test_home_assistant class TestThresholdSensor(unittest.TestCase): """Tes...
self.assertEqual('range', state.attributes.get('type')) assert state.state == 'on' self.hass.states.set('sensor.test_monitored', 9) self.hass.block_till_done() state = self.hass.states.get('binary_sensor.threshold') self.assertEqual('below', state.attributes.get('pos...
ates.set('sensor.test_monitored', 21) self.hass.block_till_done() state = self.hass.states.get('binary_sensor.threshold') self.assertEqual('above', state.attributes.get('position')) assert state.state == 'off' def test_sensor_in_range_with_hysteresis(self): """Test if sour...
NuclearTalent/NuclearStructure
doc/Programs/cython_examples/matvec/setup.py
Python
cc0-1.0
119
0
from
distutils.core import setup from Cython.Build import cythonize setup( ext_modules=cythonize("matvec.pyx"), )
Onager/plaso
plaso/parsers/interface.py
Python
apache-2.0
8,018
0.008855
# -*- coding: utf-8 -*- """The parsers and plugins interface classes.""" import abc import os from plaso.lib import errors class BaseFileEntryFilter(object): """File entry filter interface.""" # pylint: disable=redundant-returns-doc @abc.abstractmethod def Match(self, file_entry): """Determines if a fi...
ique # for all plugins/parsers, such as 'Chrome', 'Safari' or 'UserAssist'. NAME = 'base_parser' # Data format supported by the parser plugin. This information is used by # the parser manager to generate
parser and plugin information. DATA_FORMAT = '' # List of filters that should match for the parser to be applied. FILTERS = frozenset() # Every derived parser class that implements plugins should define # its own _plugin_classes dict: # _plugin_classes = {} # We deliberately don't define it here to ma...
mozilla-iam/cis
python-modules/cis_change_service/cis_change_service/__init__.py
Python
mpl-2.0
349
0
# -*- coding: utf-8 -*- """Flask application for publishing changes.""" __version__ = "0.0.1
" from cis_change_service import api from cis_change_service import common
from cis_change_service import exceptions from cis_change_service import idp from cis_change_service import profile __all__ = [api, common, exceptions, idp, profile, __version__]
indera/olass-client
olass/run.py
Python
mit
1,316
0
#!/usr/bin/env python """ Goal: Implement the application entry point. @authors: Andrei Sura <sura.andrei@gmail.com> """ import argparse from olass.olass_client import OlassClient from olass.version import __version__ DEFAULT_SETTINGS_FILE = 'config/settings.py' def main(): """ Read args """ parser = arg...
onfirmation") parser.add_argument('--rows', default=100, help="Number of rows/batch sent to the server") args = parse
r.parse_args() if args.version: import sys print("olass, version {}".format(__version__)) sys.exit() app = OlassClient(config_file=args.config, interactive=args.interactive, rows_per_batch=args.rows) app.run() if __name__ == "__main__":...
ziposoft/godiva
src/zs/view_dt.py
Python
mit
582
0.015464
import django_tables2 as tables from django_tables2 import RequestConfig from django_tables2.utils import A # alias for Accessor from django.shortcuts import render import inspect class DtTemplate(tables.Table): #name_first = tables.Column(verbose_name="First Name") #name_last = tables.LinkColumn('track:...
count',or
derable=False,verbose_name="Number of results") class Meta: #model = Runner attrs = {"class": "paleblue"}
ernw/dizzy
dizzy/tests/test_field.py
Python
bsd-3-clause
3,596
0.003615
# test_field.
py # # Copyright 2017 Daniel Mende <mail@c0decafe.de> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following condit
ions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaim...
jfillmore/Omega-API-Engine
clients/python/omega/dbg.py
Python
mit
8,885
0.008216
#!/usr/bin/env python # omega - python client # https://github.com/jfillmore/Omega-API-Engine # # Copyright 2011, Jonathon Fillmore # Licensed under the MIT license. See LICENSE file. # http://www.opensource.org/licenses/mit-license.php """Uses python introspection to provide PHP-like "var_dump" functionality for de...
obj_info['modules'] = {} obj_info['modules'][key] = unicode(item.__doc__)[0:64].strip() elif inspect.isclass(item): if not 'classes' in obj_info: obj_info['classes'] = {}
obj_info['classes'][key] = unicode(item.__doc__)[0:64].strip() else: if not 'properties' in obj_info: obj_info['properties'] = {} obj_info['properties'][key] = obj2str(item, short_form = True) return obj_info def print_tb(): import traceba...
CornellProjects/hlthpal
web/project/main/permissions.py
Python
apache-2.0
624
0.008013
from rest_framework import permissions from rest_framework.permissions import BasePermission cla
ss IsAuthenticatedOrCreate(permissions.IsAuthenticated): def has_permission(self, request
, view): if request.method == 'POST': return True return super(IsAuthenticatedOrCreate, self).has_permission(request, view) class IsOwner(BasePermission): message = "You must be the owner of this object." def has_object_permission(self, request, view, obj): my_safe_methods =...
atilag/qiskit-sdk-py
qiskit/qasm/_node/_gatebody.py
Python
apache-2.0
1,570
0
# -*- coding: utf-8 -*- # Copyright 2017 IBM RESEARCH. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
SM custom gate bod
y. children is a list of gate operation nodes. These are one of barrier, custom_unitary, U, or CX. """ def __init__(self, children): """Create the gatebody node.""" Node.__init__(self, 'gate_body', children, None) def qasm(self, prec=15): """Return the corresponding OPENQA...
zejn/prometapi
prometapi/sos112/management/commands/update_sos112.py
Python
agpl-3.0
707
0.008487
from django.core.management.base import BaseCommand
, CommandError from optparse import make_option import os import sys class Command(BaseCommand): help = 'Update SPIN SOS112 feed.' def handle(self, *args, **options): from prometapi.sos112.models import SOS112, fetch_sos112, parse_sos112 import simplejson timestamp, data =...
obj = SOS112( timestamp=timestamp, original_data=data, json_data=simplejson.dumps(json_data)) obj.save()
gunan/tensorflow
tensorflow/python/framework/meta_graph_test.py
Python
apache-2.0
43,142
0.007
# Copyright 2016 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...
ate a minimal graph with zero variables. input_tensor = array_ops.placeholder(
dtypes.float32, shape=[], name="input") offset = constant_op.constant(42, dtype=dtypes.float32, name="offset") output_tensor = math_ops.add(input_tensor, offset, name="add_offset") # Add input and output tensors to graph collections. ops.add_to_collection("input_tensor", input_tensor) ...
aelaguiz/pyvotune
pyvotune/theano/rbm.py
Python
mit
13,636
0.00066
# -*- coding: utf-8 -*- import numpy as np class RBM(object): """Restricted Boltzmann Machine (RBM) """ def __init__(self, theano, T, input=None, n_visible=784, n_hidden=500, W=None, hbias=None, vbias=None, np_rng=None, theano_rng=None): """ RBM constructor....
sample_v_given_h(self, h0_sample): ''' This function infers state of visible units given hidden unit
s ''' # compute the activation of the visible given the hidden sample pre_sigmoid_v1, v1_mean = self.propdown(h0_sample) # get a sample of the visible given their activation # Note that theano_rng.binomial returns a symbolic sample of dtype # int64 by default. If we want to kee...
gento/dionaea
modules/python/scripts/store.py
Python
gpl-2.0
2,119
0.032091
#**********************************************
************
********************** #* Dionaea #* - catches bugs - #* #* #* #* Copyright (C) 2009 Paul Baecher & Markus Koetter #* #* This program is free software; you can redistribute it and/or #* modify it under the terms of the GNU General Public License #* as published ...
xlqian/navitia
source/jormungandr/jormungandr/scenarios/helper_classes/streetnetwork_path.py
Python
agpl-3.0
8,235
0.002186
# Copyright (c) 2001-2017, Canal TP and/or its affiliates. All rights reserved. # # This file is part of Navitia, # the software to build cool stuff with public transport. # # Hope you'll enjoy and contribute to this project, # powered by Canal TP (www.canaltp.fr). # Help us simplify mobility and open public tr...
Exception':{}\n".format(str(e))) return None def _do_request(self): self._logger.debug( "requesting %s direct path from %s to %s by %s", self._path_type, self._orig_obj.uri, self._dest_obj.uri, self._mode, ) dp = ...
()) self._logger.debug( "finish %s direct path from %s to %s by %s", self._path_type, self._orig_obj.uri, self._dest_obj.uri, self._mode, ) return dp def _async_request(self): self._value = self._future_manager.create_futu...
gkc1000/pyscf
pyscf/pbc/df/mdf_ao2mo.py
Python
apache-2.0
6,690
0.003737
#!/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...
i
jslice_list[ji], tao, ao_loc) zij *= coulG[p0:p1,None] fswap['zij/'+str(ji)][p0:p1] = zij mokl_list = [] klslice_list = [] for kk in range(nkpts): kl = kconserv[ki, kj, kk] mokl, klslice = _conc_mos(mo_coeff_kpts[2][kk], mo_coeff_kpts[3][k...
catapult-project/catapult-csm
telemetry/telemetry/timeline/inspector_importer.py
Python
bsd-3-clause
2,689
0.008553
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Imports event data obtained from the inspector's timeline.""" from telemetry.timeline import importer import telemetry.timeline.slice as tracing_slice imp...
def FinalizeImport(self): pass @staticmethod def AddRawEventToThreadRecursive(thread, raw_inspector_event): pending_slice = None if ('startTime' in
raw_inspector_event and 'type' in raw_inspector_event): args = {} for x in raw_inspector_event: if x in ('startTime', 'endTime', 'children'): continue args[x] = raw_inspector_event[x] if len(args) == 0: args = None start_time = raw_inspector_event['start...
Gailbear/dots-editor
tests/test_core.py
Python
mit
2,462
0.005686
from dots_editor import core, utf8_braille import os, pygame, pytest TEST_STRING = u'\u2801\u2803\u2809\u2819\u2811' TEST_FILENAME = 'test.txt' def test_setenv(): assert os.environ["SDL_VIDEODRIVER"] == "dummy" def test_key_to_dot(game): assert game.key_to_dot(pygame.K_f) == 1 assert game.key_to_dot(pyga...
tmpdir): assert game.savemode == 'ascii' game.save_sentences() f = tmpdir.join(TEST_FILENAME) assert f.check() assert f.read() == 'ABCDE' def test_save_sentences_unicode(game, tmpdir): game.savemode = 'unicode' game
.save_sentences() f = tmpdir.join(TEST_FILENAME) assert f.check() assert f.read_text('utf8') == TEST_STRING def test_save_sentences_ascii_2_sentences(game_2lines, tmpdir): assert game_2lines.savemode == 'ascii' game_2lines.save_sentences() f = tmpdir.join(TEST_FILENAME) assert f.check() ...
mick-d/nipype_source
nipype/interfaces/fsl/tests/test_auto_EPIDeWarp.py
Python
bsd-3-clause
1,781
0.03032
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from nipype.testing import assert_equal from nipype.interfaces.fsl.epi import EPIDeWarp def test_EPIDeWarp_inputs(): input_map = dict(args=dict(argstr='%s', ), cleanup=dict(argstr='--cleanup', ), dph_file=dict(argstr='--dph %s', mandatory=Tr...
ignore_exception=dict(nohash=True, usedefault=True, ), mag_file=dict(argstr='--mag %s', mandatory=True, position=0, ), nocleanup=dict(argstr='--nocleanup', usedefault=True, ), output_type=dict(), sigma=dict(argstr='--sigma %s', usedefault=True, ), tediff=dict(a...
), tmpdir=dict(argstr='--tmpdir %s', genfile=True, ), vsm=dict(argstr='--vsm %s', genfile=True, ), ) inputs = EPIDeWarp.input_spec() for key, metadata in input_map.items(): for metakey, value in metadata.items(): yield assert_equal, getattr(inputs.traits()[key...
jj0hns0n/geonode
geonode/upload/urls.py
Python
gpl-3.0
1,501
0.002665
# -*- coding: utf-8 -*- ########################################################################
# #
# Copyright (C) 2016 OSGeo # # 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 hop...
peter1010/my_vim
vimfiles/py_scripts/snippet.py
Python
gpl-2.0
569
0.010545
import vim def func_header_snippet(row): cmt = "//!" cb = vim.current.buffer start = row
while start >= 0: line = cb[start-1].strip() if not line.startswith(cmt): break start -= 1 print("HDR") def select_snippet(line): line = line.strip() if line.startswith("//!"): return func_header_snippet def main(): row, col = vim.current.window.curs...
func = select_snippet(cline) if func: func(row) #! @brief #! @details main()
popdynamics/popdynamics
basepop.py
Python
mit
40,337
0.001289
# -*- coding: utf-8 -*- """ Base Population Model to handle different type of models """ from __future__ import print_function from __future__ import division from builtins import range from builtins import object from past.utils import old_div import os import sys import math import random import platform import glo...
compartment. In order to handle all the connections without putting too much of a burden on the programmer the differential equations are built up from the individual connections rather than being specified straight up. Basic concepts: self.target_times: time steps where model values are stor...
tween values in self.target_times self.time: current time of simulation self.compartments: dictionary that holds current compartment populations self.init_compartments: dictionary of initial compartment values self.flows: dictionary that holds current compartment flows self.p...
thomashuang/Fukei
setup.py
Python
mit
865
0.020809
from setuptools import setup with open('README.rst') as f: long_description = f.read(
) setup( name = "fukei", version = "0.1", license = 'MIT', description = "A Python Tornado port of shadowsocks and socks proxy", author = 'Thomas Huang', url = 'https://github.com/thomashuang/Fukei', packages = ['fukei', 'fukei.connection', 'fukei.upstream'], package_data={
'fukei': ['README.rst', 'LICENSE', 'config/config.json'] }, install_requires = ['setuptools', ], scripts=['bin/ss-local', 'bin/ss-server', 'bin/ss-default'], classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.6', ...
anyweez/regis
face/util/exceptions.py
Python
gpl-2.0
2,294
0.012642
''' Thrown when a user doesn't have an available question. There may be questions that haven't been answered, but none of them are in the 'ready' state, meaning that they've been parsed but their answer hasn't been computed. ''' class NoQuestionReadyException(Exception): def __init__(self, user): self.user...
ists. ''' class DuplicateNameException(Exception): def __init__(self, uname): self.uname = uname def __str__(self): return 'The username %s already exists.' % self.uname ''' [Deprecated] This exception is thrown when a user tries to hack the URL or POST parameters to view data that isn...
self.qid = qid def __str__(self): return '%s made an authorized guess attempt on question ID #%d' % (self.user.username, self.qid) ''' This exception is thrown when a new user tries to create an account but no QuestionSet is available to pair them to. New QuestionSets are supposed to be ge...
won0089/oppia
core/tests/test_utils.py
Python
apache-2.0
26,631
0.000263
# coding: utf-8 # # Copyright 2014 The Oppia 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 requi...
self.stashed_user_env = { 'USER_EMAIL': os.environ['USER_EMAIL'], 'USER_ID': os.environ['USER_ID'], 'USER_IS_ADMIN': os.environ['USER_IS_ADMIN'] } def _restore_stashed_user_env(self): """Restores a stashed set of use
r-specific env variables. Developers: please don't use this method outside this class -- it makes the individual tests harder to follow. """ if not self.stashed_user_env: raise Exception('No stashed user env to restore.') for key in self.stashed_user_env: ...
LowResourceLanguages/hltdi-l3
l3xdg/morphology/internals.py
Python
gpl-3.0
16,052
0.002803
""" This file is part of L3Morpho. Author: Michael Gasser <gasser@cs.indiana.edu> ----------------------------------------------------------------- internals.py is part of Natural Language Toolkit: Internal utility functions Copyright (C) 2001-2008 University of Pennsylvania Author: Steven Bird <sb@csse.unimelb.edu....
java when it is run. @param bin: The full path to the C{java} binary. If not specified, then nltk will search the system for a C{java} binary; and if one is not found, it will raise a C{LookupError} exception. @type bin: C{string} @param options: A list of options that should be passed to...
the maximum heap size to 512 megabytes. If no options are specified, then do not modify the options list. @type options: C{list} of C{string} """ global _java_bin, _java_options if bin is not None: if not os.path.exists(bin): raise ValueError('Could not find java binary at ...
thenenadx/forseti-security
google/cloud/security/common/gcp_api/iam.py
Python
apache-2.0
1,047
0
# Copyright 2017 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 or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS,...
IES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Wrapper for IAM API client.""" from google.cloud.security.common.gcp_api import _base_client # TODO: The next editor must remove this disable and correc...
nagyistoce/netzob
test/src/test_netzob/test_Common/test_Type/test_Endianess.py
Python
gpl-3.0
2,233
0.010767
# -*- coding: utf-8 -*- #+---------------------------------------------------------------------------+ #| 01001110 01100101 01110100 01111010 01101111 01100010 | #| | #| Netzob : Inferring communication protocol...
s. | #| | #| You should have received a copy of the GNU General Public License | #| along with this program. If not, see <http://www.gnu.org/licenses/>. | #+-----------------------------------------------...
----------------+ #| @url : http://www.netzob.org | #| @contact : contact@netzob.org | #| @sponsors : Amossys, http://www.amossys.fr | #| Supélec, http://www.rennes.supelec.fr/ren/rd/cidre...
kimegitee/python-koans
python3/koans/about_scoring_project.py
Python
mit
2,731
0.014647
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 100...
# number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # scor...
examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def score(dice): ''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items())) ...
carthach/essentia
test/src/unittests/all_tests.py
Python
agpl-3.0
8,953
0.006143
#!/usr/bin/env python # Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra # # This file is part of Essentia # # Essentia 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 (FSF), e...
ing of the data in the pools due to the fact # that we run the network twice. def runResetRun(gen, *args, **kwargs): # 0. Find networks which contain algorithms who do not play nice with
our # little trick. In particular, we have a test for multiplexer that runs # multiple generators... def isValid(algo): if isinstance(algo, essentia.streaming.VectorInput) and not list(algo.connections.values())[0]: # non-connected VectorInput, we don't want to get too fancy here.....
abelboldu/nagpy-pushover
nagpy/util/pushover.py
Python
epl-1.0
690
0.007246
#!/usr/bin/env python import urllib import urllib2 import urlparse import json import os PUSHOVER_API = "https://api.pushover.net/1/" class PushoverError(Exception): pass def pushover(**kwargs): assert 'message' in kwargs if not 'token' in kwargs: kwargs['token'] = os.environ['PUSHOVER_TOKEN'] ...
kwargs: kwargs['user'] = os.environ['PUSHOVER_USER'] url = urlparse.
urljoin(PUSHOVER_API, "messages.json") data = urllib.urlencode(kwargs) req = urllib2.Request(url, data) response = urllib2.urlopen(req) output = response.read() data = json.loads(output) if data['status'] != 1: raise PushoverError(output)
willybh11/python
projectEuler/problems/e7.py
Python
gpl-3.0
287
0.020906
print ''' By listing the first six
prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10,001st prime number? ''' def problem(): x,limit = 1,0 while limit != 10001: x += 1 if
isprime(x): limit += 1 print x problem()
DavidNorman/tensorflow
tensorflow/python/keras/engine/training_dataset_test.py
Python
apache-2.0
22,565
0.004254
# Copyright 2018 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...
.float32) output_e_np = np.random.random((10, 4)).astype(dtype=np.float32) # Test
with tuples dataset_tuple = dataset_ops.Dataset.from_tensor_slices(( (input_a_np, input_b_np), (output_d_np, output_e_np))) dataset_tuple = dataset_tuple.repeat(100) dataset_tuple = dataset_tuple.batch(10) model.fit(dataset_tuple, epochs=1, steps_per_epoch=2, verbose=1) model.evaluate(data...
socialplanning/opencore
opencore/project/browser/base.py
Python
gpl-3.0
3,338
0.000899
from Acquisition import aq_inner from Products.Five.browser.pagetemplatefile import ZopeTwoPageTemplateFile from opencore.browser.base import BaseView, view from opencore.project import LATEST_ACTIVITY from opencore.project import P
ROJ_HOME from opencore.project.utils import get_featurelets from plone.memoize.instance import memoizedproperty from topp.featurelets.interfaces import IFeatureletSupporter, IFeaturelet from topp.utils import text from zope.component import queryAdapter class ProjectBaseView(BaseV
iew): # XXX to move to project @memoizedproperty def has_mailing_lists(self): return self._has_featurelet('listen') @memoizedproperty def has_task_tracker(self): return self._has_featurelet('tasks') @memoizedproperty def has_blog(self): return self._has_featurelet...
svanschalkwyk/datafari
windows/python/Lib/test/test_pdb.py
Python
apache-2.0
11,281
0.002748
# A test suite for pdb; at the moment, this only validates skipping of # specified test modules (RFE #5142). import imp import sys import os import unittest import subprocess import textwrap from test import test_support # This little helper class is essential for testing pdb under doctest. from test_doctest import _...
() > <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>(3)test_function() -> print(1) (Pdb) break 3 Breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3 (Pdb) disable 1 (Pdb) ignore 1 10 W
ill ignore next 10 crossings of breakpoint 1. (Pdb) condition 1 1 < 2 (Pdb) break 4 Breakpoint 2 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4 (Pdb) break 4 Breakpoint 3 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4 (Pdb) break Num Type Disp Enb Where ...
pri22296/beautifultable
docs/conf.py
Python
mit
5,447
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # BeautifulTable documentation build configuration file, created by # sphinx-quickstart on Sun Dec 18 15:59:32 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in th...
utodoc", "sphinx.ext.intersphinx", "sphinx.e
xt.todo", "sphinx.ext.coverage", "sphinx.ext.ifconfig", "sphinx.ext.viewcode", "sphinx.ext.napoleon", ] napoleon_google_docstring = False napoleon_include_special_with_doc = False # napoleon_use_param = False # napoleon_use_ivar = True autodoc_member_order = "bysource" # Add any paths that contain te...
mattdm/dnf
dnf/base.py
Python
gpl-2.0
113,956
0.001667
# Copyright 2005 Duke University # Copyright (C) 2012-2018 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later versio...
load_other"] = True try: self._sack.load_repo(repo._repo, build_c
ache=True, **mdload_flags) except hawkey.Exception as e: logger.debug(_("loading repo '{}' failure: {}").format(repo.id, e)) raise dnf.exceptions.RepoError( _("Loading repository '{}' has failed").format(repo.id)) @staticmethod def _setup_default_conf(): ...
vinni-au/vega-strike
data/bases/frigid_mud.py
Python
gpl-2.0
4,436
0.018034
import Base import VS import dynamic_mission import vsrandom import fixers shipsize = VS.getPlayer().rSize()/35 #print "Ship Size: " + str(VS.getPlayer().rSize()) #debug dynamic_mission.CreateMissions() time_of_day='_day' # ROOMS landing = Base.Room ('Landing Pad') if (VS.getPlayer().rSize()<=100): Base.Texture (...
10, 0.30, 0.22, 'Computer', 'Upgrades Info') Base.Comp (entrance, 'my_comp_id', -0.90, -0.30, 0.30, 0.22, 'Computer', 'News Missions Upgra
des Info Cargo ShipDealer') Base.Comp (exit, 'my_comp_id', 0.20, -0.30, 0.30, 0.22, 'Computer', 'News Missions Upgrades Info Cargo ShipDealer') # FIXERS bartender = vsrandom.randrange(0,19) Base.Texture (bar1,'bartender','bases/generic/bartender%d.spr' % (bartender), -0.47, 0.15) Base.Python (bar1, 'talk', -0.67, ...
Sabayon/anaconda
pyanaconda/installclasses/awesome.py
Python
gpl-2.0
1,507
0.000664
# # awesome.py # # Copyright (C) 2014 Fabio Erculiani # # 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...
S FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should h
ave received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # from pyanaconda.installclass import BaseInstallClass from pyanaconda.i18n import N_ from pyanaconda.sabayon import Entropy class InstallClass(BaseInstallClass): id = "sabayon_awesome" ...
amol9/wallp
wallp/desktop/desktop_factory.py
Python
mit
1,362
0.022761
import os from redlib.api.system import sys_command, CronDBus, CronDBusError, is_linux, is_windows from ..util.logger import log from . import Desktop, DesktopError from . import gnome_desktop from . import feh_desktop if is_windows(): from .windows_desktop import WindowsDesktop def load_optional_module(module, pa...
t_module(module, package=package) except ImportError as e: print(e) if err_msg is not None: print(err_msg) load_optional_module('.kde_plasma_desktop', package='wallp.desktop', err_msg='KDE Plasma will not be supported.') def get_desktop(): if is_linux(): crondbus = CronDBus
(vars=['GDMSESSION', 'DISPLAY', 'XDG_CURRENT_DESKTOP']) crondbus.setup() gdmsession = os.environ.get('GDMSESSION', None) xdg_current_desktop = os.environ.get('XDG_CURRENT_DESKTOP', None) if gdmsession is None and xdg_current_desktop is None: log.error('could not read environment variables: GDMSESSION or XD...
UCSC-MedBook/MedBook_
tools/old-external-tools/shazam/abiFG.py
Python
bsd-3-clause
14,508
0.010408
#!/usr/bin/python2.6 import sys, string, os, time, fnmatch, imgFG, markup, re from markup import oneliner as o from numpy import * import pdb abi = ["DTB-004", "DTB-009", "DTB-024Pro", "DTB-030", "DTB-034", "DTB-036", "DTB-046", "DTB-049", "DTB-053", "DTB-064", "DTB-073"] naive = ["DTB-003", "DTB-005", "DTB-011", ...
bels": continue vals = data["sample"][d] p.tr() #name of gene geneUrl = 'http://www.genecards.org/cgi-bin/carddisp.pl?gene='+d tsv.write('<a href=%s target="_blank">%s</a>\t' % (geneUrl, d)) p.td(o.a(d, href=geneUrl, target="_blank")) tmp = [round(v, 3...
i = f.find("pid") if i == -1: print "string 'pid' not found in file name", f sys.exit(0) tmp = f[i:-3].split('_') pid = tmp[0] + '_' + tmp[1] pid = re.sub("\.","", pid) print "pid:",pid return pid, getPathwayName(pid) def summarizePathway(samples, data, e...
streeter/autoliker
main.py
Python
mit
617
0
#!/usr/bin/env python from autoliker.services.instagram import InstagramUserPhotoService from autoliker.servi
ces.twitter import TwitterUserMentionService if __name__ == '__main__': services = [InstagramUserPhotoService, TwitterUserMentionService] for service_cls in services: service = service_cls() print("Fetching the latest {} posts...".format(service.SERVICE_NAME)) posts = service.latest_p...
ts) print("Liked {} posts, skipped {} posts".format(liked, skipped))
mretegan/crispy
crispy/utils.py
Python
mit
2,446
0
# coding: utf-8 ################################################################### # Copyright (c) 2016-2022 European Synchrotron Radiation Facility # # # # Author: Marius Retegan # # ...
if sys.platform == "darwin": font.setPointSize(font.pointSize() + 2) return font
sukeesh/Jarvis
jarviscli/plugins/evaluator.py
Python
mit
9,968
0.000401
# -*- coding: utf-8 -*- import re import sympy from colorama import Fore from plugin import alias, plugin @alias('calc', 'evaluate') @plugin('calculate') def calculate(jarvis, s): """ Jarvis will get your calculations done! -- Example: calculate 3 + 5 """ tempt = s.replace(" ", "") i...
it = equation.split('=') if len(split) == 1: return equation if len(split) != 2: jarvis
.say("Warning! More than one = detected!", Fore.RED) return equation return "{} - ({})".format(split[0], split[1]) def format_expression(s): s = str.lower(s) s = s.replace("power", "**") s = s.replace("plus", "+") s = s.replace("minus", "-") s = s.replace("dividedby", "/") s = s.r...
xZise/pywikibot-core
scripts/interwiki.py
Python
mit
111,420
0.000701
#!/usr/bin/python # -*- coding: utf-8 -*- """ Script to check language links for general pages. Uses existing translations of a page, plus hints from the command line, to download the equivalent pages from other languages. All of such pages are downloaded as well and checked for interwiki links recursively until ther...
ll be subsequently removed. If restoring process interrupts again, it saves all unprocessed pages in one new dump file of the given site. -continue: like restore, but after having gone through the dumped pages, continue alphabetically starting at the las...
e subsequently removed. -warnfile: used as -warnfile:filename, reads all warnings from the given file that apply to the home wiki language, and read the rest of the warning as a hint. Then treats all the mentioned pages. A quicker way to ...
nttks/edx-platform
openedx/core/djangoapps/ga_task/migrations/0001_initial.py
Python
agpl-3.0
1,256
0.000796
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings class Migration(migrations.Migration): dependencies = [ migra
tions.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Task', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('task_type', models.CharField(...
db_index=True)), ('task_input', models.CharField(max_length=255)), ('task_id', models.CharField(max_length=255, db_index=True)), ('task_state', models.CharField(max_length=50, db_index=True)), ('task_output', models.CharField(max_length=1024, null=True)),...
splotz90/urh
misc/IQGenerator.py
Python
gpl-3.0
6,115
0.003598
import numpy as np from misc.Plotter import Plotter class IQGenerator(object): def __init__(self, f_baseband=10, f_s=1000, bits=[True, False, True, True, False, False]): self.f_baseband = f_baseband self.f_s = f_s self.t_s = 1 / f_s self.bits = bits self.samples_per_cycle ...
# Plotter.generic_plot(np.arange(0, len(iq
_data.real)), iq_data.real, iqg.modulation) carrier_plot = np.arange(0, len(iqg.carrier_samples)), iqg.carrier_samples.real, "Carrier" demod_plot = np.arange(0, len(demod)), demod, "Demod" # plot = carrier_plot + demod_plot plot = demod_plot Plotter.generic_plot(*plot) iq_data.tofile("../tests/...
twisted/quotient
xquotient/test/historic/test_composer4to5.py
Python
mit
598
0.001672
from axiom.test.historic.stubloader import StubbedTest from xquotient.compos
e import Composer, Drafts class ComposerUpgradeTestCase(StubbedTest): """ Test that the Composer no longer has a 'drafts' attribute, that no Drafts items have been created and that the other attributes have been copied. """ def test_upgrade(self): composer = self.store.findUnique(Composer...
ore.count(Drafts), 0)
unicefuganda/edtrac
edtrac_project/rapidsms_uganda_common/setup.py
Python
bsd-3-clause
845
0.002367
from setuptools import setup setup( name='uganda_common', version='0.1', license="BSD", install_requires = ["rapidsms"], description='A suite of utility functions for Uganda RSMS deployments.', long_description='', author='UNICEF Uganda T4D', author_email='mossplix@gmail.com', ur...
- Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent',
'Programming Language :: Python', 'Framework :: Django', ] )
ckan/ckanext-archiver
ckanext/archiver/plugin.py
Python
mit
8,644
0.000231
import logging from ckan import model from ckan import plugins as p from ckanext.report.interfaces import IReport from ckanext.archiver.interfaces import IPipe from ckanext.archiver.logic import action, auth from ckanext.archiver import helpers from ckanext.archiver import lib from ckanext.archiver.model import Archi...
# IAuthFunctions def get_auth_functions(self): return { 'archiver_resource_show': auth.archiver_resource_show, 'archiver_dataset_show': auth.archiver_dataset_show, } #
ITemplateHelpers def get_helpers(self): return dict((name, function) for name, function in list(helpers.__dict__.items()) if callable(function) and name[0] != '_') # IPackageController def after_show(self, context, pkg_dict): # Insert the archival i...
ericlink/adms-server
playframework-dist/play-1.1/framework/pym/play/commands/javadoc.py
Python
mit
1,459
0.004798
import os, os.path import shutil import subprocess from play.utils import * COMMANDS = ['javadoc', 'jd'] HELP = { 'javadoc': 'Generate your application Javadoc' } def execute(**kargs): command = kargs.get("command") app = kargs.get("app") args = kargs.get("args") play_env = kargs.get("env") ...
in(root, file)) add_java_files(app.path) for module in m
odules: add_java_files(os.path.normpath(module)) outdir = os.path.join(app.path, 'javadoc') sout = open(os.path.join(app.log_path(), 'javadoc.log'), 'w') serr = open(os.path.join(app.log_path(), 'javadoc.err'), 'w') if (os.path.isdir(outdir)): shutil.rmtree(outdir) javadoc_cmd = [jav...
NNBlocks/NNBlocks
nnb/activation.py
Python
gpl-3.0
1,375
0.007273
# NNBlocks is a Deep Learning framework for computational linguistics. # # Copyright (C) 2015 Frederico Tommasi Caroli # # NNBlocks 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 t...
#The ReLU functions are a copy of theano's recommended way to implement ReLU. #theano.tensor.nnet.relu is not used her
e because it is only available in #version 0.7.2 of theano def ReLU(a): return 0.5 * (a + abs(a)) def leaky_ReLU(alpha): def r(a): f1 = 0.5 * (a + alpha) f2 = 0.5 * (a - alpha) return f1 * a + f2 * abs(a) return r
petervo/cockpit
pkg/lib/inotify.py
Python
lgpl-2.1
2,629
0.004184
# # This file is part of Cockpit. # # Copyright (C) 2017 Red Hat, Inc. # # Cockpit is free software; you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation; either version 2.1 of the License, or # (at your option) any later vers...
es.get_errno
self._libc.inotify_init.argtypes = [] self._libc.inotify_init.restype = ctypes.c_int self._libc.inotify_add_watch.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_uint32] self._libc.inotify_add_watch.restype = ctypes.c_int sel...
mF2C/COMPSs
compss/programming_model/bindings/python/src/exaqute/ExaquteTaskPyCOMPSs.py
Python
apache-2.0
1,613
0
#!/usr/bin/python # # Copyright 2002-2019 Barcelona Supercomputing Center (www.bsc.es) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at
# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under 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 gove...
pss.api.task import task from pycompss.api.api import compss_wait_on from pycompss.api.api import compss_barrier from pycompss.api.api import compss_delete_object from pycompss.api.api import compss_delete_file from pycompss.api.parameter import * from pycompss.api.implement import implement from pycompss.api.constr...
tripleee/gmail-oauth2-tools
python/oauth2.py
Python
apache-2.0
12,198
0.00705
#!/usr/bin/python # # Copyright 2012 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 or a...
ms.iteritems(), key=lambda x: x[0]): param_fragments.append('%s=%s' % (param[0], UrlEscape(param[1]))) return '&'.join(param_fragments) def GeneratePermissionUrl(client_id, scope='https://mail.google.com/'): """Generates the URL fo
r authorizing access. This uses the "OAuth2 for Installed Applications" flow described at https://developers.google.com/accounts/docs/OAuth2InstalledApp Args: client_id: Client ID obtained by registering your app. scope: scope for access token, e.g. 'https://mail.google.com' Returns: A URL that th...
jkonecny12/anaconda
pyanaconda/ui/tui/spokes/user.py
Python
gpl-2.0
11,266
0.00142
# User creation text spoke # # Copyright (C) 2013-2014 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distrib...
put) def _set_create_user(self, args): self._create_user = not self._create_user def _set_fullname(self, dialog): self.user.gecos = dialog.run() def _set_username(self, dialog): self.user.name = dialog.run(
) def _set_use_password(self, args): self._use_password = not self._use_password def _set_password(self, password_dialog): password = password_dialog.run() while password is None: password = password_dialog.run() self.user.password = password def _set_adminis...
matokeotz/matokeo-api
app/app/urls.py
Python
mit
1,219
0
"""app URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based ...
blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin from rest_framework.documentation impo
rt include_docs_urls urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^docs/', include_docs_urls(title='Matokeo API')), url(r'^api/', include('api.urls.student_urls')), url(r'^api/', include('api.urls.subject_urls')), url(r'^...
anybox/anybox.recipe.openerp
anybox/recipe/openerp/tests/oerp70/setup.py
Python
agpl-3.0
3,751
0.018128
#!/usr/bin/env python # -*- coding: utf-8 -*- # flake8: noqa # # setup.py from openobject-server 7.0, included as is, except for the # dependency list # ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL ...
ee <http://www.gnu.org/licenses/>. # ############################################################################## import glob, os, re, setuptools, sys from os.path import join, isfile # List all data files def data(): files = [] for root, dirnames, filenames in os.walk('openerp'): for filename in fi...
pend(os.path.join(root, filename)) d = {} for v in files: k=os.path.dirname(v) if k in d: d[k].append(v) else: d[k]=[v] r = d.items() if os.name == 'nt': r.append(("Microsoft.VC90.CRT", glob.glob('C:\Microsoft.VC90.CRT\*.*'))) import babel ...
kohr-h/odl
odl/contrib/solvers/spdhg/examples/get_started.py
Python
mpl-2.0
2,277
0
# Copyright 2014-2018 The ODL contributors # # This file is part of ODL. # # 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 https://mozilla.org/MPL/2.0/. """A simple example to get started with SPDH...
.-B. Schoenlieb, *Stochastic Primal-Dual Hybrid Gradient Algorithm with Arbitrary Sampling and Imaging Ap
plications*. ArXiv: http://arxiv.org/abs/1706.04957 (2017). """ from __future__ import division, print_function import odl import odl.contrib.solvers.spdhg as spdhg import odl.contrib.datasets.images as images import numpy as np # set ground truth and data image_gray = images.building(gray=True) X = odl.uniform_discr...
quantumlib/ReCirq
recirq/hfvqe/analysis_test.py
Python
apache-2.0
6,819
0
# Copyright 2020 Google # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, soft...
0.9]) initial_opdm = np.diag([1] * 3 + [0] * 3) final_opdm = unitary(parameters) @ initial_opdm @ unitary( parameters).conj().T test_energy = energy_from_opdm(final_opdm, constant=molecule.nuclear_repulsion, one_body_tensor=obi, ...
"Build test assuming sampling functions work""" rhf_objective, molecule, parameters, obi, tbi = make_h3_2_5() unitary, energy, _ = rhf_func_generator(rhf_objective) parameters = np.array([0.1, 0.2]) initial_opdm = np.diag([1] * 1 + [0] * 2) print(initial_opdm) final_opdm = unitary(parameters) ...
nanaze/pystitch
pystitch/dmc_colors.py
Python
apache-2.0
1,790
0.027374
import csv import os import color def _GetDataDirPath(): return os.path.join(os.path.dirname(__file__), 'data') def _GetCsvPath(): return os.path.join(_GetDataDirPath(), 'dmccolors.csv') def _GetCsvString(): with open(_GetCsvPath()) as f: return f.read().strip() def _CreateDmcColorFromRow(row): number =...
tlines() # Skip first line lines = lines[1:] reader = csv.reader(lines, delimiter='\t') dmc_colors = set() for row in reader: dmc_colors.a
dd(_CreateDmcColorFromRow(row)) return dmc_colors def GetDMCColors(): global _dmc_colors if not _dmc_colors: _dmc_colors = frozenset(_CreateDMCColors()) return _dmc_colors def GetClosestDMCColorsPairs(rgb_color): pairs = list() for dcolor in GetDMCColors(): pairs.append((dcolor, color.RGBC...
Azure/azure-sdk-for-python
sdk/databoxedge/azure-mgmt-databoxedge/azure/mgmt/databoxedge/v2019_07_01/models/__init__.py
Python
mit
10,249
0.000195
# 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 cause incorrect behavior and will be lost if the c...
from ._models_py3 import Address from ._models_py3 import Alert from ._models_py3 import AlertErrorDetails from ._models_py3 import AlertList from ._models_py3 import AsymmetricEncryptedSecret from ._models_py3 import Authentication from ._models_py3 import AzureContainerInfo from ._models_...
grilo/pyaccurev
tests/test_client.py
Python
gpl-3.0
19,204
0.00125
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import os import collections import mock import accurev.client import accurev.depot class TestAccuRevClient(unittest.TestCase): def setUp(self): self.client = accurev.client.Client() def test_cmd(self): self.client.chdir('somed...
_user(self): with mock.patch.object(self.client, "cmd") as mocked: mocked.return_value = '', '' self.client.group_show('user') mocked.assert_called_once_with('show -fx -u user groups') def test_member_sh
ow(self): with mock.patch.object(self.client, "cmd") as mocked: mocked.return_value = '', '' self.client.member_show('group') mocked.assert_called_once_with('show -fx -g group members') def test_cpkdescribe(self): query = "<AcRequest>\n" query += "\t<cpk...
bravelittlescientist/kdd-particle-physics-ml-fall13
src/adaboost.py
Python
gpl-2.0
1,625
0.002462
#!/usr/bin/python2 # This is an Adaboost classifier import sys from util import get_split_training_dataset from metrics import suite import feature_selection_trees as fclassify from sklearn.grid_search import GridSearchCV from sklearn.ensemble import AdaBoostClassifier from sklearn.tree import DecisionTreeClassifi...
lassifier if __name__ == "__main__": # Let's take our training data and train a decision tree # on a subset. Scikit-learn provides a good module for cross- # validation. Xt, Xv, Yt, Yv = get_split_training_dataset() Classifier = train(Xt, Yt) pri
nt "Adaboost Classifier" suite(Yv, Classifier.predict(Xv)) # smaller feature set Xtimp, features = fclassify.get_important_data_features(Xt, Yt, max_features=25) Xvimp = fclassify.compress_data_to_important_features(Xv, features) ClassifierImp = train(Xtimp,Yt) print "Adaboosts Classiifer, 25 i...
mateusz-blaszkowski/PerfKitBenchmarker
perfkitbenchmarker/providers/azure/provider_info.py
Python
apache-2.0
872
0.002294
# Copyright 2015 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
to in writing, software # distrib
uted under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Provider info for Azure """ from perfkitbenchmarker import provider_info fro...
gmt/kernel-ng-util
kernelng/config.py
Python
gpl-2.0
46,364
0.005133
#!/usr/bin/env python #-*- coding:utf-8 -*- # vim:ai:sta:et:ts=4:sw=4:sts=4 """kernelng 0.x Tool for maintaining customized overlays of kernel-ng.eclass-based ebuilds Copyright 2005-2014 Gentoo Foundation Copyright (C) 2014 Gregory M. Turner <gmt@be-evil.net> Distributed under the terms of the GNU General ...
standard configuration-file # line-item (i.e.: key=value). # # We use the OrderedDict so that we can round-trip the
configuration file without re-ordering # the sections. Initially this will be fairly broken, but the enhancements to achieve full # .conf => OO => .conf round-trip capabilities are simply to saving off some formatting metadata # at the KNGConfigItem level during "deserialization" -- aka parsing, what-have-you. First,...
deepmind/dm_robotics
cpp/setup.py
Python
apache-2.0
4,478
0.00335
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
}".format(build_type), "-DDM_ROBOTICS_BUILD_TESTS=OFF", "-DDM_ROBOTICS_BUILD_WHEEL=True", "--log-level=VERBOSE", ] version_script = os.environ.get("DM_ROBOTICS_VERSION_SCRIPT", None) if version_script: cmake_args.append(f"-DDM_ROBOTICS_VERSION_SCRIPT={version_scr
ipt}",) build_args = [] if "CMAKE_BUILD_PARALLEL_LEVEL" not in os.environ: build_args += ["-j4"] if not os.path.exists(self.build_temp): os.makedirs(self.build_temp) # Generate build files: subprocess.check_call( [ext.cmake] + cmake_args + ["-S", ext.sourcedir], cwd=self.build...
endlos99/xdt99
test/as-checkobj.py
Python
gpl-3.0
4,385
0.00114
#!/usr/bin/
env python3 import os from config import Dirs, Disks, Files, XAS99_CONFIG from utils import (xas, xdm, sinc, error, clear_env, delfile, check_obj_code_eq, check_image_set_eq, check_imag
e_files_eq, read_stderr, get_source_markers, check_errors) # Main test def runtest(): """check cross-generated output against native reference files""" clear_env(XAS99_CONFIG) # object code for inp_file, opts, ref_file, compr_file in [ ('asdirs.asm', [], 'ASDIRS-O', 'ASDIRS-C'), ('a...
JDrosdeck/xml-builder-0.9
xmlbuilder/tests/__init__.py
Python
mit
3,828
0.025078
#!/usr/bin/env python from __future__ import with_statement #------------------------------------------------------------------------------- import unittest from xml.etree.ElementTree import fromstring #------------------------------------------------------------------------------- from xmlbuilder import XMLBuild...
): xml << "text1" << "text2" << ('some_node',) self.assertEqual(str(xml),"<root>text1text2<some_node /></root>") #------------------------------------------------
--------------------------- def testFormat(self): x = XMLBuilder('utf-8',format = True) with x.root(): x << ('array',) with x.array(len = 10): with x.el(val = 0): pass with x.el('xyz',val = 1): p...