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
datalogics/scons
test/Perforce/P4COMSTR.py
Python
mit
4,112
0.002432
#!/usr/bin/env python # # __COPYRIGHT__ # # 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, ...
ub'], 'sub') sub_Perforce = os.path.join('sub', 'Perforce') sub_SConscript = os.path.join('sub', 'SConscript') sub_all = os.path.join('sub', 'all') sub_ddd_in = os.path.join('sub', 'ddd.in') sub_ddd_out = os.path.join('sub', 'ddd.out') sub_eee_in = os.path.join('sub', 'eee.in') sub_eee_out = os.path.join('sub'
, 'eee.out') sub_fff_in = os.path.join('sub', 'fff.in') sub_fff_out = os.path.join('sub', 'fff.out') test.write('my-p4.py', """ import shutil import sys for f in sys.argv[1:]: shutil.copy('Perforce/'+f, f) """) test.write('SConstruct', """ def cat(env, source, target): target = str(target[0]) source = map...
knz/slcore
slc/tools/slc/input/parse.py
Python
gpl-3.0
6,199
0.042104
from ..msg import die from ..ast import * def unexpected(item): die("unexpected construct '%s'" % item.get('type','unknown'), item) def parse_varuse(varuse, item): #print "parse varuse %x: item %x: %r" % (id(varuse), id(item), item) varuse.loc = item['loc'] varuse.name = item['name'].strip() ...
assert isinstance(item, str) csp = item.strip(' \t') if len(csp) > 0: b += Opaque(item) #print "parse block %x: item %x -- END (len %d)" % (id(b), id(item), len(b))
if len(b) > 0: return b return None def parse_argparm(p, cat, item): #print "parse argparm %x: item %x: %r" % (id(p), id(item), item) t = item['type'].replace('_mutable','') if not t.endswith(cat): unexpected(item) p.loc = item['loc'] p.type = item['type'] ...
WaveBlocks/WaveBlocksND
WaveBlocksND/IOM_plugin_overlaplcwp.py
Python
bsd-3-clause
10,811
0.003515
"""The WaveBlocks Project IOM plugin providing functions for handling various overlap matrices of linear combinations of general wavepackets. @author: R. Bourquin @copyright: Copyright (C) 2013 R. Bourquin @license: Modified BSD License """ import numpy as np def add_overlaplcwp(self, parameters, timeslots=None, m...
rf[pathtg][:]) elif item == "ovkin": pathtg = "/" + self._prefixb + str(blockid) + "/overlaplcwp/timegridkin" tg.append(self._srf[pathtg][:]) elif item == "ovpot": pathtg = "/" + self._prefixb + str(blockid
) + "/overlaplcwp/timegridpot" tg.append(self._srf[pathtg][:]) else: raise ValueError("Unknown key value {}".format(item)) if len(tg) == 1: print(tg) return tg[0] else: return tuple(tg) def load_overlaplcwp_shape(self, blockid=0, key=("ov", "ovkin", "ov...
ArthurVal/RIDDLE_naoqi_bridge
naoqi_sensors_py/src/naoqi_sensors/naoqi_microphone.py
Python
bsd-3-clause
4,844
0.007019
#!/usr/bin/env python # Copyright (C) 2014 Aldebaran Robotics # # 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 applic...
crophones """ rospy.loginfo('reconfigure changed') if self.pub_audio_.get_num_connections(
) == 0: rospy.loginfo('Changes recorded but not applied as nobody is subscribed to the ROS topics.') self.config.update(new_config) return self.config # check if we are already subscribed if not self.isSubscribed: rospy.loginfo('subscribed to audio proxy, si...
jdekerautem/TurtleBot-Receptionist
pocketsphinx_files/notsotalkative.py
Python
mit
6,969
0.033434
#!/usr/bin/env python """ voice_nav.py allows controlling a mobile base using simple speech commands. Based on the voice_cmd_vel.py script by Michael Ferguson in the pocketsphinx ROS package. """ import roslib; #roslib.load_manifest('pi_speech_tutorial') import rospy from geometry_msgs.msg import Twist from std_...
'hello': ['hi', 'hey', 'hello'], 'help' : ['help me', 'can help', 'help'], 'name' : ['your name', 'name'], 'wash' : ['washroom', 'toilet'], '
library' : ['library', 'book', 'borrow'], 'labs' : ['labs'], 'talk': ['talk to me?', 'really talk?', 'you talk', 'you really talk?', 'talk'], 'amazing' : ['amazing', 'wonderful'], '...
Jc11235/Kekulean_Program
GUI_Version/Ubuntu_Version/DriverMethods.py
Python
gpl-2.0
39,406
0.044054
from PerfectMatchingData import * from Face import * from Vertex import * from Graph import * from VertexList import * from Output import * from KekuleanMethods import * from Checkers import * from RequiredEdgeMethods import * from Tkinter import * from AppInformation import * from random import randint import time i...
put("Would you like to view the graphs ranked by Fries
or Clars? (or quit?) ") if choice.lower() == 'clars': Graph.comparison = 'clars' elif choice.lower() == 'fries': Graph.comparison = 'fries' else: break graphs.sort() graphs.reverse() print "There are", len(graphs), "Kekulean structures" displayGraphs(graphs) else: pri...
justinjfu/chaos_theory
scripts/run_ddpg.py
Python
gpl-3.0
526
0.001901
import logging import gym import numpy as np from chaos_theory.algorithm import DDPG from chaos_theory.run.run_algorithm import run_online_algorithm logging.basicConfig(level=logging.DEBUG) logging.getLogger().setLevel(logging.DEBUG) np.random.seed(1) if __name__ == "__main__": env_name = 'HalfCheet
ah-v1' env = gym.make(env_name) algorithm = DDPG(env, track_tau=0.001, discount=0.95) run_online_algorithm(env, algorithm, max_length=1000, samples_per_update=1, verbose_trial=5, log_name='ddpg_'
+env_name)
NuChwezi/nubrain
nubrain/urls.py
Python
mit
1,184
0.000845
"""nubrain 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 import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-bas...
lpatterns: 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 patterns, include, url from django.contrib import admin from nubrain.settings import BASE_URL, APP_NAME from django.views.generic import RedirectView from django.utils.translation import ugettext_lazy urlpatterns = patterns...
invinst/ResponseBot
tests/unit_tests/models/test_user_model.py
Python
apache-2.0
824
0
from unittest.case import TestCase from dateutil.parser import parse fr
om responsebot.models import User, Tweet class UserModelTestCase(TestCase): def test_create_from_raw_data(self): created_at = 'Mon Apr 25 08:25:58 +0000 2016' raw = { 'some_key': 'some value', 'created_at': created_at, 'status': { 'created_at': c...
l(user.some_key, 'some value') self.assertEqual(user.created_at, expected_created_at) self.assertTrue(isinstance(user.tweet, Tweet)) self.assertEqual(user.tweet.created_at, expected_created_at) self.assertEqual(user.following, True)
simonolander/euler
euler-150-searching-a-triangular-array-for-a-sub-triangle-having-minimum-sum.py
Python
mit
1,906
0.001574
def triangle_sum(tri, r, c, h, memo): if (r, c, h) in memo: return memo[(r, c, h)] ans = tri[r][c] if h > 0: ans += triangle_sum(tri, r + 1, c, h - 1, memo) ans += triangle_sum(tri, r + 1, c + 1, h - 1, memo) if h > 1: ans -= triangle_sum(t
ri, r + 2, c + 1, h - 2, memo) memo[(r, c, h)] = ans return ans def min_triangle_sum(tri): memo = {} minimum = tri[0][0] for r in range(len(tri)): for c in range(r + 1): print(r, c) for h in range(len(tri) - r): print(r, c, h) s
= triangle_sum(tri, r, c, h, memo) if s < minimum: minimum = s print(r, c, h, ':', minimum) return minimum def min_triangle_sum_2(tri): memo = {} for r in range(len(tri)): s = 0 memo[(r, 0)] = 0 for c in range(0, r + 1): ...
cloudify-cosmo/cloudify-manager
rest-service/manager_rest/test/security_utils.py
Python
apache-2.0
3,245
0
######### # Copyright (c) 2019 Cloudify Platform Ltd. 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...
manager_rest.storage import user_datastore from manager_rest.constants import ( DEFAULT_TENANT_ID, DEFAULT_TENANT_ROLE, ) ADMIN_ROLE = 'sys_admin' USER_ROLE = 'default' USER_IN_TENANT_ROLE = 'user' def get_admin_user(): return { 'username': 'admin',
'password': 'admin', 'role': ADMIN_ROLE } def get_status_reporters(): return [ { 'username': MANAGER_STATUS_REPORTER, 'password': 'password', 'role': MANAGER_STATUS_REPORTER, 'id': MANAGER_STATUS_REPORTER_ID }, { ...
VU-Cog-Sci/PRF_experiment
exp_tools/Staircase.py
Python
mit
6,218
0.040849
#!/usr/bin/env python # encoding: utf-8 """ Staircase.py Created by Tomas HJ Knapen on 2009-11-26. Copyright (c) 2009 TK. All rights reserved. """ import os, sys, datetime import subprocess, logging import pickle, datetime, time import scipy as sp import numpy as np # import matplotlib.pylab as pl from math import ...
tinue_after_this_trial = False return continue_after_this_trial class ThreeUpOneDownStaircase(TwoUpOneDownStaircase): def answer( self, correct ): continue_aft
er_this_trial = True self.nr_trials = self.nr_trials + 1 self.past_answers.append(correct) nr_corrects_in_last_3_trials = np.array(self.past_answers, dtype = float)[-3:].sum() if nr_corrects_in_last_3_trials == 3: # this subject is too good for this stimulus value self.test_value = self.test_value - se...
pklaus/brother_ql
brother_ql/__init__.py
Python
gpl-3.0
110
0.009091
from .exceptions import * from .raster import BrotherQLRaster from .brother_ql_create import c
reate_
label
franziz/arcrawler
lib/factory/writer.py
Python
gpl-3.0
940
0.03617
from ..w
riter.crawler import CrawlerWriter from ..writer.run import RunConfigWriter from ..writer.sentry import SentryConfigWriter from ..writer.route import RouteConfigWriter from ..writer.monitor import Mo
nitorConfigWriter class WriterFactory: CRAWLER = 0 RUN_CONFIG = 1 SENTRY_CONFIG = 2 ROUTE_CONFIG = 3 MONITOR_CONFIG = 4 def __init__(self): pass @classmethod def get_writer(self, writer_name=None): """ Exceptions: - AssertionError """ assert writer_name is not None, "writer_name is...
Lincoln-Cybernetics/Explore-
mapgen.py
Python
unlicense
7,161
0.012847
import pygame import random import item import mob import tile class Mapgen(object): def __init__(self, level): self.xsiz = 10 self.ysiz = 10 self.biome = "random" self.procedure = 0 self.zone = [] self.level = level self.sizefactor = 2 #self.items = ...
elf.zone) or b+ha-1 >= len(self.zone[0]): pass else:
place.neighbors.add(self.zone[a+wa-1][b+ha-1]) return self.zone #causes deserts to expand def desertify(self): for place in self.level.terrain: place.desert_check() #causes forests to grow def grow_forest(self): for place in self.lev...
david672orford/pykarta
pykarta/geometry/from_text.py
Python
gpl-2.0
2,761
0.030215
# encoding=utf-8 # pykarta/geometry/from_text.py # Copyright 2013--2020, Trinity College # Last modified: 9 February 2020 import re from . import Point # Create a Point() from a text string describing a latitude and longitude
# # E
xample from Wikipedia article Whitehouse: 38° 53′ 51.61″ N, 77° 2′ 11.58″ W # \u2032 -- prime (minutes sign) # \u2033 -- double prime (seconds sign) # \u2019 -- single closing quote # \u201d -- double closing quote def PointFromText(coords_text): if not re.search(u'^[\(\-0-9\.°\'\u2019\u2032"\u201d\u2033NSEW, \)]+$', ...
jacobajit/ion
intranet/apps/announcements/migrations/0009_announcement_expiration_date.py
Python
gpl-2.0
432
0.002315
# -*- co
ding: utf-8 -*- import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [('announcements', '0008_auto_20150603_1401')] operations = [migrations.AddField(model_name='announcement', name='expiration_date', ...
Linaro/lava-dispatcher
lava_dispatcher/job.py
Python
gpl-2.0
10,777
0.001299
# Copyright (C) 2014 Linaro Limited # # Author: Neil Williams <neil.williams@linaro.org> # # This file is part of LAVA Dispatcher. # # LAVA Dispatcher 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 ver...
rings to the run a diagnostic self.diagnostics = [ DiagnoseNetwork, ] self.timeout = None self.protocols = [] self.compatibility = 2 # Was the job cleaned self.cleaned = False # Root directory for the job tempfiles self.tmp_dir = None ...
return self.__context__.pipeline_data @context.setter def context(self, data): self.__context__.pipeline_data.update(data) def diagnose(self, trigger): """ Looks up the class to execute to diagnose the problem described by the specified trigger. """ ...
av8ramit/tensorflow
tensorflow/python/ops/linalg/linear_operator_full_matrix.py
Python
apache-2.0
6,505
0.001845
# 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...
s, suppose `operator` is a `LinearOperatorFullMatrix` of shape `[M, N]`, and `x.shape = [N, R]`. Then * `operator.matmul(x)` is `O(M * N * R)`. * If `M=N`, `operator.solve(x)` is `O(N^3 * R)`. * If `M=N`, `operator.determinant()` is `O(N^3)`. If instead `operator` and `x` have shape `[B1,...,Bb, M, N]` and...
#### Matrix property hints This `LinearOperator` is initialized with boolean flags of the form `is_X`, for `X = non_singular, self_adjoint, positive_definite, square`. These have the following meaning: * If `is_X == True`, callers should expect the operator to have the property `X`. This is a promise th...
dhinakg/BitSTAR
plugins/srcutils.py
Python
apache-2.0
1,479
0.008114
# Copyright 2017 Starbot Discord Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compl
iance 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...
s or implied. # See the License for the specific language governing permissions and # limitations under the License. from api import command, message, plugin def onInit(plugin_in): gitsrc_command = command.Command(plugin_in, 'source', shortdesc='Get the git repo for the bot!') docs_command = command.Com...
UManPychron/pychron
pychron/pipeline/nodes/audit.py
Python
apache-2.0
1,164
0
# ==========================================================
===================== # Copyright 2018 ross # # 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 i...
IS, # 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. # =============================================================================== from pychron.pipeline.editors.audit_editor import AuditE...
comedate/VolumeRendering
test_mpr.py
Python
mit
580
0.003448
import v
tk from vtk.util.misc import vtkGetDataRoot import render_mpr reader = vtk.vtkMetaImageReader() read
er.SetFileName("C:\\Users\\fei.wang\\PycharmProjects\\Rendering\\data\\org.mha") reader.Update() render_mpr = render_mpr.RendererMPR() render_mpr.set_volume(reader) render_mpr.set_output_image_size(1024, 1024) render_mpr.set_lut_property("") render_mpr.render() render_mpr.get_output_png_image("1.png") # tes...
asedunov/intellij-community
python/testData/formatter/noBlankLinesAfterLocalImports_after.py
Python
apache-2.0
182
0.005495
from pprint i
mport pprint VAR = 42 def foo(): import sys import ast, tokenize pass class C: from textwrap import dedent pass import code
cs as C pass
fxia22/ASM_xf
PythonD/site_python/OpenGL/GL/SUN/convolution_border_modes.py
Python
gpl-2.0
585
0.011966
import
string _
_version__ = string.split('$Revision: 1.6 $')[1] __date__ = string.join(string.split('$Date: 2001/11/17 14:12:34 $')[1:3], ' ') __author__ = 'Tarn Weisner Burton <twburton@users.sourceforge.net>' __doc__ = 'http://oss.sgi.com/projects/ogl-sample/registry/SUN/convolution_border_modes.txt' __api_version__ = 0x103 ...
luzfcb/django-autocomplete-light
test_project/select2_one_to_one/urls.py
Python
mit
547
0.001828
from dal import autocomplete from django.conf.urls import url from django.views import generic from .forms import TestForm from .models import TestModel urlpatterns = [ url(
'test-autocomplete/$', autocomplete.Select2QuerySetView.as_view( model=TestModel, cre
ate_field='name', ), name='select2_one_to_one_autocomplete', ), url( 'test/(?P<pk>\d+)/$', generic.UpdateView.as_view( model=TestModel, form_class=TestForm, ) ), ]
saudisproject/saudi-bots
bots/spa.py
Python
gpl-3.0
4,254
0.002367
from urllib.request import urlopen from urllib.parse import urlparse, parse_qs from socket import error as SocketError import errno from bs4 import BeautifulSoup MAX_PAGES_TO_SEARCH = 3 def parse_news(item): '''Parse news item return is a tuple(id, title, url) ''' url = 'http://www.spa.gov.sa' + item[...
غادر')[1]) item = tuple(_list) leave_news.append(item) return leave_news if __name__ == "__main__": # just for testin
g news = cabinet_decision() print(news)
cjwfuller/python-challenge
level6.py
Python
mit
250
0
nothing = '90
052' while True: f = open('channel/' + nothing + '.txt', 'r') line = f.readline() splits = line.split('Next nothing is ', 1) if(len(splits) == 2): nothing = splits[1]
print nothing else: break
cklb/pyinduct
pyinduct/core.py
Python
gpl-3.0
100,888
0.000545
""" In the Core module you can find all basic classes and functions which form the backbone of the toolbox. """ import warnings import numbers import numpy as np import numpy.ma as ma import collections from copy import copy, deepcopy from numbers import Number from scipy import integrate from scipy.linalg import blo...
""" Basic implementation of derive function. Empty implementation, overwr
ite to use this functionality. For an example implementation see :py:class:`.Function` Args: order (:class:`numbers.Number`): derivative order Return: :py:class:`.BaseFraction`: derived object """ if order == 0: return self else: ...
confluentinc/examples
clients/cloud/python/ccloud_lib.py
Python
apache-2.0
5,500
0.001273
#!/usr/bin/env python # # Copyright 2020 Confluent 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...
help="path to Confluent Cloud configuration file", required=True) required.add_argument('-t', dest="topic", help="topic name", required=True) args = parser.parse_args() return args
def read_ccloud_config(config_file): """Read Confluent Cloud configuration for librdkafka clients""" conf = {} with open(config_file) as fh: for line in fh: line = line.strip() if len(line) != 0 and line[0] != "#": parameter, value = line.strip().split('=', ...
dangoldin/pyproducthunt
analyze.py
Python
mit
168
0.005952
from phapi import ProductHuntApi import settings import json pha = ProductHuntApi(settings.DEVELOP
ER_TOKEN) posts = pha.get_posts() print json.dumps(p
osts, indent=2)
udragon/pybrctl
pybrctl/pybrctl.py
Python
gpl-2.0
5,254
0.007423
import subprocess from distutils import spawn brctlexe = spawn.find_executable("brctl") ipexe = spawn.find_executable("ip") class BridgeException(Exception): pass class Bridge(object): def __init__(self, name): """ Initialize a bridge object. """ self.name = name def __str__(self): ...
ot set path cost in port %s in %s." % (port, self.name)) def setportprio(self, port, prio): """ Set port priority value. """ _runshell([brctlexe, 'setportprio', self.name, port, str(prio)], "Could not set priority in port %s in %s." % (port, self.name)) def _show(self): ""...
return p.stdout.read().split()[7:] def getid(self): """ Return the bridge id value. """ return self._show()[1] def getifs(self): """ Return a list of bridge interfaces. """ return self._show()[3:] def getstp(self): """ Return if STP protocol is enabled. """ ...
statsmodels/statsmodels
statsmodels/stats/rates.py
Python
bsd-3-clause
12,513
0
'''Test for ratio of Poisson intensities in two independent samples Author: Josef Perktold License: BSD-3 ''' import numpy as np import warnings from scipy import stats from statsmodels.stats.base import HolderTuple from statsmodels.stats.weightstats import _zstat_generic2 def test_poisson_2indep(count1, exposu...
def stat_func(x1, x2): return (x1 - x2 * r_d) / np.sqrt((x1 + x2) * r_d + eps) # TODO: do I need these? return_results ? # rate2_cmle = (y1 + y2) / n2 / (1 + r_d) # rate1_cmle = rate
2_cmle * r # rate1 = rate1_cmle # rate2 = rate2_cmle elif method in ['wald']: def stat_func(x1, x2): return (x1 - x2 * r_d) / np.sqrt(x1 + x2 * r_d**2 + eps) # rate2_mle = y2 / n2 # rate1_mle = y1 / n1 # rate1 = rate1_mle # rate2 = rate2_mle el...
jamescarignan/Flask-User
example_apps/user_auth_app.py
Python
bsd-2-clause
6,986
0.006298
import os from flask import Flask, render_template_string, request from flask_mail import Mail from flask_sqlalchemy import SQLAlchemy from flask_user import login_required, SQLAlchemyAdapter, UserManager, UserMixin from flask_user import roles_required # Use a Class-based config to avoid needing a 2nd file # os.gete...
members_page') }}>Members page</a> (login required)</p> <p><a href={{ url_for('special_page') }}>Special page</a> (login with username 'user007' and password 'Password1')</p> {% endblock %} """) # The Special page requires a user with 'special' and 'sauce' roles or with 'spe...
']) # Use of @roles_required decorator def special_page(): return render_template_string(""" {% extends "base.html" %} {% block content %} <h2>Special Page</h2> <p>This page can only be accessed by user007.</p><br/> <p><a href={{ url_...
robin1885/algorithms-exercises-using-python
source-code-from-author-book/Listings-for-Second-Edition/listing_8_14.py
Python
mit
65
0
class SkipList: de
f __init__(self): self.head = N
one
lifeinoppo/littlefishlet-scode
SRC/Server/Components/input/python/keyInput.py
Python
gpl-2.0
175
0.034014
# replace all key events in # js files and htmls #
to our standard key input event # more details see in DOC dir # Key 事件进行全局替换, 统一
处理。
tylercal/dragonfly
dragonfly/accessibility/__init__.py
Python
lgpl-3.0
949
0.004215
from contextlib import contextmanager import sys from . import controller from .utils import (CursorPosition, TextQuery) if sys.platform.startswith("win"): from . import ia2 os_controller_class = ia2.Controller else: # TODO Support Linux. pass controller_instance = None def get_accessibility_contro...
dependent accessibility controller which is the gateway to all accessibility functionality.""" global controller_instance if not controller_instance or controller_instance.stopped: os_controller = os_controller_class()
controller_instance = controller.AccessibilityController(os_controller) return controller_instance @contextmanager def get_stopping_accessibility_controller(): """Same as :func:`get_accessibility_controller`, but automatically stops when used in a `with` context.""" yield get_accessibility_cont...
oh6hay/refworks-bibtex-postprocess
textutil.py
Python
mit
943
0.004242
#!/usr/bin/env python # http://stackoverflow.com/questions/517
923/what-is-the-best-way-to-remove-accents-in-a-python-unicode-string import re import unicodedata def strip_accents(text): """ Strip accents from input String. :param text: The input string. :type text: String. :returns: The processed String. :rtype: String. """ try: text =...
ameError: # unicode is a default on python 3 pass text = unicodedata.normalize('NFD', text) text = text.encode('ascii', 'ignore') text = text.decode("utf-8") return str(text) def text_to_id(text): """ Convert input text to id. :param text: The input string. :type text: String....
salv-orlando/MyRepo
nova/scheduler/filters/json_filter.py
Python
apache-2.0
5,243
0.000572
# Copyright (c) 2011 Openstack, LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
result, list): # If any succeeded, include the host result = any(result) if result: filtered_hosts.app
end((host, hostinfo)) return filtered_hosts
oesteban/niworkflows
niworkflows/utils/tests/test_misc.py
Python
bsd-3-clause
2,459
0.001627
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: # # Copyright 2021 The NiPreps Developers <nipreps@gmail.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may...
mocked_run.return_value.returncode = rc assert check_valid_fs_license() is valid @pytest.mark.skipif(not os.getenv("FS_LICENSE"), reason="No FS license found") def test_fs_license_check2(monkeypatch): """Execute the canary itself.""" assert check_valid_fs_license() is True @pytest.mark.skipif(sh...
ENSE", raising=False) m.delenv("FREESURFER_HOME", raising=False) assert check_valid_fs_license() is False
wfxiang08/ansible
lib/ansible/plugins/callback/__init__.py
Python
gpl-3.0
6,672
0.002998
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # 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 License, or # (at your option) an...
Make coding more python3-ish from __future__ import (absolute_import, division) __metaclass__ = type import json from ansible import constants as C __all__ = ["CallbackBase"] class CallbackBase: ''' This is a base ansible callback class that does nothing. New callbacks should use this class as a base...
e list of callback methods used in the default callback def __init__(self, display): self._display = display if self._display.verbosity >= 4: name = getattr(self, 'CALLBACK_NAME', 'with no defined name') ctype = getattr(self, 'CALLBACK_TYPE', 'unknwon') version =...
tensorflow/tensorflow
tensorflow/core/platform/ram_file_system_test.py
Python
apache-2.0
5,699
0.006492
# Copyright 2020 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...
bdir1') file_io.create_dir_v2('ram://testdirectory/subdir2') file_io.create_dir_v2('ram://testdirectory/subdir1/subdir3') with gfile.GFile('ram://testdirectory/subdir1/subdir3/a.txt', 'w') as f: f.write('Hello, world.') file_io.delete_recursively_v2('ram://testdirectory') self.assertEqual(gfil...
f.write('Hello, world.') with gfile.GFile('ram://a.txt', 'r') as f: self.assertEqual(f.read(), 'Hello, world.' * 2) def test_append_file_with_seek(self): with gfile.GFile('ram://c.txt', 'w') as f: f.write('Hello, world.') with gfile.GFile('ram://c.txt', 'w+') as f: f.seek(offse...
cookbrite/ebs-deploy
ebs_deploy/__init__.py
Python
mit
26,434
0.002951
from boto.exception import S3ResponseError, BotoServerError from boto.s3.connection import S3Connection from boto.ec2.autoscale import AutoScaleConnection from boto.beanstalk import connect_to_region from boto.s3.key import Key from datetime import datetime from time import time, sleep import zipfile import os import ...
Creates an archive from a directory and returns the file that was created. """ with zipfile.ZipFile(filename, 'w', compression=zipfile.ZIP_DEFLATED) as zip_file: root_len = len(os.path.abspath(directory)) # create it out("Creating archive: " + str(filename)) for root, dirs, ...
h.join(root, f) archive_name = os.path.join(archive_root, f) # ignore the file we're creating if filename in fullpath: continue # ignored files if ignored_files is not None: for name in ignored_file...
maybelinot/bellring
bellring/_version.py
Python
gpl-3.0
305
0
#!/usr/bin/env python
# -*- coding: utf-8 -*- # @Author: Eduard Trott # @Date: 2015-09-15 08:57:35 # @Email: etrott@redhat.com # @Last modified by: etrott # @Last Modified time: 201
5-12-17 16:53:17 version_info = ('0', '0', '1') __version__ = '.'.join(version_info[0:3]) # + '-' + version_info[3]
amwelch/a10sdk-python
a10sdk/core/cgnv6/cgnv6_ds_lite_port_reservation.py
Python
apache-2.0
2,890
0.010035
from a10sdk.common.A10BaseClass import A10BaseClass class PortReservation(A10BaseClass): """Class Description:: DS-Lite Static Port Reservation. Class port-reservation supports CRUD Operations and inherits from `common/A10BaseClass`. This class is the `"PARENT"` class for
this module.` :param nat_end_port: {"description": "NAT End Port
", "format": "number", "type": "number", "maximum": 65535, "minimum": 1, "optional": false} :param uuid: {"description": "uuid of the object", "format": "string", "minLength": 1, "modify-not-allowed": 1, "optional": true, "maxLength": 64, "type": "string"} :param inside: {"optional": false, "type": "string", "d...
dhuang/incubator-airflow
airflow/providers/tableau/example_dags/example_tableau_refresh_workbook.py
Python
apache-2.0
2,507
0.002792
# # 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...
om datetime import timedelta from airflow import DAG from airflow.providers.tableau.operators.tableau_refresh_workbook import TableauRefreshWorkbookOperator from airflow.providers.tableau.sensors.tableau_job_status import TableauJobStatusSensor from airflow.utils.dates import days_ago with DAG( dag_id='exa
mple_tableau_refresh_workbook', dagrun_timeout=timedelta(hours=2), schedule_interval=None, start_date=days_ago(2), tags=['example'], ) as dag: # Refreshes a workbook and waits until it succeeds. task_refresh_workbook_blocking = TableauRefreshWorkbookOperator( site_id='my_site', w...
gochist/horizon
openstack_dashboard/dashboards/project/access_and_security/keypairs/views.py
Python
apache-2.0
3,012
0.000332
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # no...
s.generic import View # noqa from horizon import exceptions from horizon import forms from openstack_dashboard import api from openstack_dashboard.dashboards.project.access_and_security.keypairs \
import forms as project_forms class CreateView(forms.ModalFormView): form_class = project_forms.CreateKeypair template_name = 'project/access_and_security/keypairs/create.html' success_url = 'horizon:project:access_and_security:keypairs:download' def get_success_url(self): return reverse(...
robwarm/gpaw-symm
gpaw/test/test.py
Python
gpl-3.0
5,364
0.001119
import os import gc import platform import sys import time import tempfile import warnings from optparse import OptionParser import gpaw.mpi as mpi from gpaw.hooks import hooks from gpaw import debug from gpaw.version import version def run(): description = ('Run the GPAW test suite. The test suite can be run i...
' + ' '.join(platform.architecture()) if mpi.rank == 0: print('python %s on %s' % (python, operating_system)) print('Running tests in %s' % tmpdir) print('Jobs: %d, Cores: %d, debug-mode: %r' % (opt.jobs, mpi.size, debug)) failed = ...
ailed) > 0: open('failed-tests.txt', 'w').write('\n'.join(failed) + '\n') elif not opt.keep_tmpdir: os.system('rm -rf ' + tmpdir) hooks.update(old_hooks.items()) return len(failed) if __name__ == '__main__': run()
fedarko/CAIP
Code/LevelReader.py
Python
gpl-3.0
1,886
0.003181
""" Copyright 2011 Marcus Fedarko Contact Email: marcus.fedarko@gmail.com This file is part of CAIP. CAIP 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) ...
later version. CAIP is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERC
HANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CAIP. If not, see <http://www.gnu.org/licenses/>. ==== LevelReader.py ----- class LevelReader: reads through a level and creates cells, w...
zleap/python-qrcode
qrreadfromfile.py
Python
gpl-3.0
1,039
0.008662
#!/usr/bin/env python # -*- coding: utf-8 -*- # # qrgen1.py # # Copyright 2013 psutton <zleap@zleap.net> # # 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 Licens...
ILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA....
qrtools import QR myCode = QR(filename=u"/home/psutton/Documents/Python/qrcodes/qrcode.png") if myCode.decode(): print myCode.data print myCode.data_type print myCode.data_to_string()
JamesPavek/payroll
timesheet.py
Python
mit
2,615
0.047419
import xml.etree.ElementTree as ET import datetime import sys import openpyxl import re import dateutil def main(): print 'Number of arguments:', len(sys.argv), 'arguments.' #DEBUG print 'Argument List:', str(sys.argv) #DEBUG Payrate = raw_input("Enter your pay rate: ") #DEBUG sNumber = raw_input("Enter 900#: ...
[0].text sheet['4D'] = re.match('.*?([0-9]+)$', num).group(1) def writeStudentNum(num): sheet['8S']=num def writePayRate(num): sheet['6k']=num def char_range(c1, c2): """Generates the characters from `c1` to `c2
`, inclusive.""" """Courtesy http://stackoverflow.com/questions/7001144/range-over-character-in-python""" for c in xrange(ord(c1), ord(c2)+1): yield chr(c) main()
hasadna/OpenTrain
webserver/opentrain/timetable/migrations/0013_auto__add_field_tttrip_shape.py
Python
bsd-3-clause
2,893
0.005876
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'TtTrip.shape' db.add_column(u'timetable_tttrip', 'shape',...
ated.ForeignKey')(to=orm['timetable.TtShape'], null=True), keep_default=False) def backwards(self, orm): # Deleting field 'TtTrip.shape' db.delete_column(u'timetable_tttrip', 'shape_id') models = { u'timetable.ttshape': { 'Meta': {'object_name': 'TtS...
0', 'db_index': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'points': ('django.db.models.fields.TextField', [], {}) }, u'timetable.ttstop': { 'Meta': {'object_name': 'TtStop'}, 'gtfs_stop_id': ('django.db.models.fie...
HKUST-SING/tensorflow
tensorflow/python/debug/wrappers/local_cli_wrapper.py
Python
apache-2.0
20,594
0.004079
# 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...
empty directory. If the directory does not exist, it will be created by the debugger core during debug `run()` calls and removed afterwards. log_usage: (`bool`) whether the usage of this class is to be logged. ui_type: (`str`) requested UI type. Currently supported: (curses | readli...
dump_root is a file. """ if log_usage: pass # No logging for open-source. framework.BaseDebugWrapperSession.__init__(self, sess) if dump_root is None: self._dump_root = tempfile.mktemp(prefix=_DUMP_ROOT_PREFIX) else: if os.path.isfile(dump_root): raise ValueError("dum...
torbjoernk/pySDC
examples/spiraling_particle/HookClass.py
Python
bsd-2-clause
1,411
0.008505
from __future__ import division from pySDC.Hooks import hooks from pySDC.Stats import stats import matplotlib.pyplot as plt import numpy as np class particles_output(hooks): def __init__(self): """ Initialization of particles output """ super(particles_output,self).__init__() ...
= L.uend R = np.linalg.norm(u.pos.values) H = 1/2*np.dot(u.vel.values,u.vel.values)+0.02/R stats.add_to_stats(step=status.step, time=status.time, type='energy', value=H) oldcol = self.sframe # self.sframe = self.ax.scatter(L.uend.pos.values[0],L.uend.pos.values[1],L.uend.pos....
ax.collections.remove(oldcol) plt.pause(0.00001) return None
flashingpumpkin/filerotate
filerotate/__version__.py
Python
mit
21
0.047619
__version__ = "1.0
.3"
flyapen/UgFlu
flumotion/test/test_admin_multi.py
Python
gpl-2.0
3,725
0
# -*- Mode: Python; test-case-name: flumotion.test.test_admin_multi -*- # vi:si:et:sw=4:sts=4:ts=4 # # Flumot
ion - a streaming media server # Copyright (C) 2004,2005,2006,2007 Fluendo, S.L. (www.fluendo.com). # All rights reserved. # This file
may be distributed and/or modified under the terms of # the GNU General Public License version 2 as published by # the Free Software Foundation. # This file is distributed without any warranty; without even the implied # warranty of merchantability or fitness for a particular purpose. # See "LICENSE.GPL" in the source...
jfmorcillo/mss
mss/agent/__init__.py
Python
gpl-3.0
844
0
# -*- coding: UTF-8 -*- # # (c) 2010 Mandriva, http://www.mandriva.com/ # # This file is part of Mandriva Server Setup # # MSS 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. # # MSS is distributed in the hope that it will be useful, # but WITHOUT ANY W
ARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with MSS; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, F...
codenote/chromium-test
tools/telemetry/telemetry/core/tab.py
Python
bsd-3-clause
3,230
0.005263
# Copyright (c) 2012 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. from telemetry.core import web_contents DEFAULT_TAB_TIMEOUT = 60 class Tab(web_contents.WebContents): """Represents a tab in the browser The import...
ckend.Navigate(url, script_to_evaluate_on_commit, timeout) def GetCookieByName(self, name, timeout=DEFAULT_TAB_TIMEOUT): "
""Returns the value of the cookie by the given |name|.""" return self._inspector_backend.GetCookieByName(name, timeout)
afaheem88/rally
tests/unit/deployment/engines/test_devstack.py
Python
apache-2.0
4,402
0
# Copyright 2013: Mirantis
Inc. # All Rights Reserved. # # Licensed
under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed und...
Klaminite1337/Paragon
inc/VOCAL/translate.py
Python
mit
12,795
0.005784
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
, _buckets, FLAGS.size, FLAGS.num_layers, FLAGS.max_gradient_norm, FLAGS.batch_size, FLAGS.learning_rate, FLAGS.learning_rate_decay_factor, forward_only=forward_only, dtype=dtype) ckpt = tf.train.get_checkpoint_state(FLAGS.train_dir) if ckpt and tf.gfile.Exists(...
nt("Reading model parameters from %s" % ckpt.model_checkpoint_path) model.saver.restore(session, ckpt.model_checkpoint_path) else: print("Created model with fresh parameters.") session.run(tf.initialize_all_variables()) return model def train(): """Train a en->fr translation model using WMT data."""...
LudovicRousseau/pyscard
smartcard/CardType.py
Python
lgpl-2.1
3,695
0
"""Abstract CarType. __author__ = "http://www.gemalto.com" Copyright 2001-2012 gemalto Author: Jean-Daniel Aussel, mailto:jean-daniel.aussel@gemalto.com This file is part of pyscard. pyscard is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as publis...
to chek for matching @param reader: the reader (optional); default is None When atr is compared to the CardType ATR, matches returns true if and only if CardType.atr & CardType.mask = atr & CardType.mask, where & is the bitwise logical AND.""" if len(atr) != len(self.atr): ...
maskedatr = atr return self.maskedatr == maskedatr if __name__ == '__main__': """Small sample illustrating the use of CardType.py.""" r = readers() print(r) connection = r[0].createConnection() connection.connect() atrct = ATRCardType([0x3B, 0x16, 0x94, 0x20, 0x02, 0x01, 0x00...
Juniper/ceilometer
ceilometer/network/notifications.py
Python
apache-2.0
8,892
0
# # Copyright 2012 New Dream Network, LLC (DreamHost) # # 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...
update.*|exists} notification
s from neutron. """ resource_name = 'firewall_rule' counter_name = 'network.services.firewall.rule' class VPNService(NetworkNotificationBase): """Listen for Neutron notifications. Handle vpnservice.{create.end|update.*|exists} notifications from neutron. """ resource_name = 'vpnservic...
flake123p/ProjectH
Python/_Basics2_/A02_for_while/for_while.py
Python
gpl-3.0
238
0.016807
scores = [60, 73, 81, 95, 34] n = 0 total = 0 for x in scores: n += 1 total += x avg = total/n pr
int("f
or loop print") print(total) print(avg) i = 1 x = 0 while i <= 50: x += 1 i += 1 print("while loop print") print(x) print(i)
starnes/Python
guessnameclass.py
Python
mit
1,452
0.006887
# A program that has a list of six colors and chooses one by random. The user can then has three chances to quess the right color. After the third attepmt the program outputs "Nope. The color I was thinking of was..." import random # this is the function that will execute the program def program(): # These are the ...
N = 'green' ORANGE = 'orange' PURPLE = 'purple' PINK = 'pink' class Color:
pass c1 = Color() c2 = Color() c3 = Color() guesses_made = 0 # This input causes the program to refer to you as your name. c1.name = input('Hello! What is your name?\n') c2.color = [BLUE, GREEN, RED, ORANGE, PURPLE, PINK] # This randomizes what color is chosen c2.color = random.choi...
erikgrinaker/BOUT-dev
tools/pylib/boututils/watch.py
Python
gpl-3.0
2,197
0.004096
""" Routines for watching files for changes """ from __future__ import print_function from builtins import zip import time import os def watch(files, timeout=None, poll=2): """ Watch a given file or collection of files until one changes. Uses polling. Inputs ====== files - Name of one or mo...
Get modification time of file(s) try: if hasattr(files, '__iter__'): # Iterable lastmod = [ os.stat(f).st_mtime for f in files ] iterable = True else: # Not iterable -> just one file lastmod = os.stat(files).st_mtime iterable = ...
sleepfor = poll if timeout: # Check if timeout will be reached before next poll if time.time() - start_time + sleepfor > timeout: # Adjust time so that finish at timeout sleepfor = timeout - (time.time() - start_time) running = False # S...
mhbu50/erpnext
erpnext/education/doctype/quiz_result/test_quiz_result.py
Python
gpl-3.0
153
0.006536
# Copyright
(c) 2018, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt import unittest class TestQuizResult(unittest.TestCase): pas
s
shinglyu/servo
tests/wpt/web-platform-tests/mathml/tools/limits.py
Python
mpl-2.0
2,284
0.000438
#!/usr/bin/python from utils import mathfont import fontforge nArySumCodePoint = 0x2211 # largeop operator v = 3 * mathfont.em f = mathfont.create("limits-lowerlimitbaselinedropmin%d" % v) mathfont.createSquareGlyph(f, nArySumCodePoint) f.math.LowerLimitBaselineDropMin = v f.math.LowerLimitGapMin = 0 f.math.OverbarE...
SumCodePoint) f.math.LowerLimitBaselineDropMin = 0 f.math.LowerLimitGapMin = 0 f.math.OverbarExtraAscender = 0 f.math.OverbarVerticalGap = 0 f.math.StretchStackBottomShiftDown = 0 f.math.StretchStackGapAboveMin = 0 f.math.StretchStackGapBelowMin = 0 f.
math.StretchStackTopShiftUp = 0 f.math.UnderbarExtraDescender = 0 f.math.UnderbarVerticalGap = 0 f.math.UpperLimitBaselineRiseMin = v f.math.UpperLimitGapMin = 0 mathfont.save(f) v = 7 * mathfont.em f = mathfont.create("limits-upperlimitgapmin%d" % v) mathfont.createSquareGlyph(f, nArySumCodePoint) f.math.LowerLimitBa...
gnott/elife-bot
activity/activity_VersionDateLookup.py
Python
mit
3,787
0.004489
import json from zipfile import ZipFile import uuid import activity import re import os from os.path import isfile, join from os import listdir, makedirs from os import path import datetime from S3utility.s3_notification_info import S3NotificationInfo from provider.execution_context import Session import requests from...
self.logger.exception("Exception when trying to Lookup next version") self.emit_monitor_event(self.settings, article_structure.article_id, version, data['run'], self.pretty_name, "error", " ".join(("Error looking up version for article", ...
"message:", str(e)))) return activity.activity.ACTIVITY_PERMANENT_FAILURE def get_version(self, settings, article_structure, article_id, version): try: version_date = article_structure.get_update_date_from_zip_filename() if version_date: return version_d...
openhumanoids/exotica
exotations/dynamics_solvers/exotica_cartpole_dynamics_solver/scripts/gen_second_order_dynamics.py
Python
bsd-3-clause
2,089
0.004787
from sympy import Symbol, sin, cos, diff from pprint import pprint theta = Symbol('theta') tdot = Symbol('tdot') xdot = Symbol('xdot') u = Symbol('u') m_p_ = Symbol('m_p_') m_c_ = Symbol('m_c_') g_ = Symbol('g_') l_ = Symbol('l_') xddot = (u + m_p_ * sin(theta) * (l_ * (tdot * tdot) + g_ * cos(theta))) / (m_c_ + m_p_...
] fxx = [ [ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0] ], # fx_x [ [0, 0, 0, 0], [0, 0, 0, 0], [0, diff(diff(xddot, theta), theta), 0, diff(diff(xddot, tdot), theta)], [0,
diff(diff(tddot, theta), theta), 0, diff(diff(tddot, tdot), theta)] ], # fx_theta [ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0] ], # fx_xdot [ [0, 0, 0, 0], [0, 0, 0, 0], [0, diff(diff(xddot, theta), tdot), 0, diff(diff(xddot, tdot), td...
opensemanticsearch/open-semantic-etl
src/opensemanticetl/enhance_xmp.py
Python
gpl-3.0
4,568
0.001751
import xml.etree.ElementTree as ElementTree import os.path import sys # # is there a xmp sidecar file? # def get_xmp_filename(filename): xmpfilename = False # some xmp sidecar filenames are based on the original filename without extensions like .jpg or .jpeg filenamewithoutextension = '.' . join(filena...
file (= xml + rdf) # if xmpfilename: creator = False headline = False creator = False location = False tags = [] if verbose: print("Reading xmp sidecar file {}".format(xmpfilename)) try: ...
et.getroot() # get author try: creator = root.findtext( ".//{http://purl.org/dc/elements/1.1/}creator") if creator: data['author_ss'] = creator except BaseException as e: ...
emsi/hackoort
python/oorthap/bulb.py
Python
gpl-3.0
4,950
0.000606
import colorsys import logging from pyhap.accessory import Accessory from pyhap.const import CATEGORY_LIGHTBULB, CATEGORY_FAN from hackoort.bulb import Bulb def hls2rgb(h, l, s): """Convert h, l, s in 0-1 range to rgb in 0-255 :param h: hue :param l: luminance :param s: saturation :return: red,...
lass OortColorBulb(Accessory): category = CATEGORY_LIGHTBULB def __init__(self, driver, name, bulb: Bulb): """ :param driver: pyhap driver :param name: descriptive name
:param bulb: it has to be connected oort bulb """ super().__init__(driver, name) self.status = bulb.status self.hue, _, self.saturation = rgb2hls( self.status.red, self.status.green, self.status.blue) serv_light = self.add_preload_service( 'Light...
glenn-edgar/local_controller_3
redis_graph_py3/redis_graph_functions.py
Python
mit
10,886
0.054106
import redis import copy import json def basic_init(self): self.sep = "[" self.rel_sep = ":" self.label_sep = "]" self.namespace = [] class Build_Configuration(object): def __init__( self, redis_handle): self.redis_handle = redis_handle self.delete_all()...
def match_relationship( self, relationship, label= None , starting_set = None ): return_value = None if s
tarting_set == None: starting_set = self.redis_handle.smembers("@GRAPH_KEYS") #print("starting set",starting_set)# if label == None: #print("made it here") if self.redis_handle.sismember( "@RELATIONSHIPS", relationship) == True: #print("made it here #2") ...
mmdg-oxford/papers
Schlipf-PRL-2018/model/step.py
Python
gpl-3.0
830
0.012048
from __future__ import print_function from bose_einstein import bose_einstein from constant import htr_to_K, htr_to_meV, htr_to_eV import argparser import norm_k import numpy as np import scf import system args = argparser.read_argument(
'Evaluate step-like feature in electron-phonon coupling') thres = args.thres / htr_to_meV beta = htr_to_K / args.temp Sigma = system.make_data(args.dft, args.vb) Sigma.bose_einstein = bose_einstein(Sigma.freq, beta) for energy_meV in np.arange(0.0, args.energy, 0.5): energy = energy_meV / htr_to_meV kk = norm_k....
thres, Sigma, kk, Sigma_in) if args.vb: real_energy = -energy else: real_energy = energy print(real_energy * htr_to_meV, -Sigma_out.imag * htr_to_meV, it)
fake-name/ReadableWebProxy
Misc/install_vmprof.py
Python
bsd-3-clause
616
0.021104
# From https://gist.github.com/destan/554070
2#file-text2png-py # coding=utf8 import multiprocessing import threading import time import atexit import os import vmprof def install_vmprof(name="thread"): cpid = multiprocessing.current_process().name ctid = threading.current_thread().name fname = "vmprof-{}-{}-{}-{}.dat".format(name, cpid, ctid, time.time()...
close_profile_file(): print("Closing VMProf!") vmprof.disable() print("VMProf closed!")
roypur/python-bitcoin-accounting
new.py
Python
gpl-3.0
797
0.015056
#!/bin/python from urllib import request from pymongo import Connection import argparse import json import pymongo req = request.urlopen('https://blockchain.info/no/api/receive?method=create&address=19J9J4QHDun5YgUTfEU1qb3fSHTbCwcjGj') encoding = req.headers.get_content_charse
t() obj = json.loads(req.read().decode(encoding)) print(obj['input_address']) parser = argparse.ArgumentParser() parser.add_argument("--price") parser.ad
d_argument("--name") parser.add_argument("--description") args = parser.parse_args() price = float(args.price) * 100000000 connection=Connection() database=connection['bitcoin'] mycollection=database.entries post={"Address":(obj['input_address']), "Price":price, "Name":args.name, "Description":args.description, "Con...
mosen/commandment
commandment/mdm/response_schema.py
Python
mit
10,132
0.00227
from marshmallow import Schema, fields, post_load from marshmallow_enum import EnumField from enum import IntFlag from .. import models from commandment.inventory import models as inventory_models class ErrorChainItem(Schema): LocalizedDescription = fields.String() USEnglishDescription = fields.String() E...
Network = fields.String(attribute='current_carrier_network') SIMCarrierNetwork = fields.String(attribute='sim_carrier_network') SubscriberCarrierNetwork = fields.String(attribute='subscriber_carrier_network') CarrierSettingsVersion = fields.String(attribute=
'carrier_settings_version') PhoneNumber = fields.String(attribute='phone_number') VoiceRoamingEnabled = fields.Boolean(attribute='voice_roaming_enabled') DataRoamingEnabled = fields.Boolean(attribute='data_roaming_enabled') IsRoaming = fields.Boolean(attribute='is_roaming') PersonalHotspotEnabled = ...
andrius-preimantas/purchase-workflow
purchase_request_to_requisition/tests/test_purchase_request_to_requisition.py
Python
agpl-3.0
3,251
0
# -*- coding: utf-8 -*- # Copyright 2016 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp.tests import common from openerp.tools import SUPERUSER_ID class TestPurchaseRequestToRequisition(common.TransactionCase): def setUp(self): super(Te...
self.env.ref('product.product_product_13').id, 'product_uom_id': self.env.ref('product.product_uom_unit').id, 'product_qty': 5.0, } purchase_request_line = self.purchase_request_line.create(vals) wiz_id = self.wiz.with_context( active_model="purchase.request.l...
self.assertTrue( len(purchase_request_line.requisition_lines.ids) == 1, 'Should have one purchase requisition line created') requisition_id = purchase_request_line.requisition_lines.requisition_id self.assertEquals( len(purchase_request.line_ids), len(r...
saturnast/python-learning
tempCodeRunnerFile.py
Python
mit
441
0.006803
#!/usr/bin python3 # -*- coding:utf-8 -*- # File Name: fact.py # Author: Lipsu
m # Mail: niuleipeng@gmail.com # Created Time: 2016-0
5-11 17:27:38 # def fact(n): # if n == 1: # return 1 # return fact(n-1) * n def fact(n): return fact_iter(n, 1) def fact_iter(num, product): if num == 1: return product return fact_iter(num - 1, num * product) num = int(input('input a number plz:')) print(fact(num));
laurentb/weboob
modules/caissedepargne/cenet/browser.py
Python
lgpl-3.0
12,250
0.002857
# -*- coding: utf-8 -*- # Copyright(C) 2012 Romain Bignon # # This file is part of a weboob module. # # This weboob module is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the Licens...
ps://www.cenet.caisse-epargne.fr" STATE_DURATION = 5 login = URL( r'https://(?P<domain>[^/]+)/authentification/manage\?step=identification&identifiant=(?P<login>.*)', r'https://.*/authentification/manage\?step=identification&identifiant=.*', r'https://.*/login.aspx', LoginPage,...
URL(r'https://(?P<domain>[^/]+)/authentification/manage\?step=account&identifiant=(?P<login>.*)&account=(?P<accountType>.*)', LoginPage) cenet_vk = URL(r'https://www.cenet.caisse-epargne.fr/Web/Api/ApiAuthentification.asmx/ChargerClavierVirtuel') cenet_home = URL(r'/Default.aspx$', CenetHomePage) cenet_acco...
kenshay/ImageScript
ProgramData/SystemFiles/Python/Lib/site-packages/networkx/algorithms/smetric.py
Python
gpl-3.0
1,194
0.000838
import networkx as nx #from networkx.generators.smax import li_smax_graph def s_metric(G, normalized=True): """Return the s-metric of graph. The s-metric is defined as the sum of the products deg(u)*deg(v) for every edge (u,v) in G. If norm is provided construct the s-max graph and compute it's s_met...
bs/cond-mat/0501169 """ if normalized: raise nx.NetworkXError("Normalization not implemented") #
Gmax = li_smax_graph(list(G.degree().values())) # return s_metric(G,normalized=False)/s_metric(Gmax,normalized=False) # else: return float(sum([G.degree(u) * G.degree(v) for (u, v) in G.edges()]))
semanticbits/survey_stats
src/survey_stats/survey.py
Python
bsd-2-clause
5,498
0.002001
import pandas as pd from rpy2.robjects import pandas2ri from rpy2.robjects.packages import importr from rpy2.robjects import Formula from rpy2 import robjects as ro from survey_stats.helpr import svyciprop_xlogit, svybyci_xlogit, factor_summary from survey_stats.helpr import filter_survey_var, rm_nan_survey_var, svyby_...
rbase.gc() gc.collect()
if fpc and design=='cluster': fix_lonely_psus() rdf = rfeather.read_feather(fthr_file) logger.info('creating survey design from data and annotations', cols=list(rbase.colnames(rdf))) strata = '~strata' if denovo: strata = '~year+strata' res = rsvy.svydesign( ...
nachoplus/cronoStamper
tools/cameraSimulator.py
Python
gpl-2.0
1,376
0.021076
#!/usr/bin/python ''' Cronostamper test suit: Simple trigger simulator. Open a socket and execute /oneShot when someone get connected and exit. "oneshot" activate the GPIO 7 just one time. Nacho Mas Junary-2017 ''' import socket import commands import sys import time import datetime from thread import * HOST = '' ...
rbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print 'Starting CronoStamper Sockets Server.' print 'Socket created' #Bind socket to local host and port try: s.bind((HOST, PORT)) except socket.error as msg: print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + m...
getoutput('./oneShot') d = str(datetime.datetime.fromtimestamp(float(rst))) conn.sendall(d+'\r\n') print d conn.close() #now keep talking with the client while 1: #wait to accept a connection - blocking call conn, addr = s.accept() print 'Connected with ' + addr[0] + ':' + str(addr[1]) ...
dropbox/changes-lxc-wrapper
tests/cli/test_wrapper.py
Python
apache-2.0
3,544
0.000564
import threading from mock import patch from uuid import uuid4 from changes_lxc_wrapper.cli.wrapper import WrapperCommand def generate_jobstep_data(): # this must generic a *valid* dataset that should result in a full # run return { 'status': {'id': 'queued'}, 'data': {}, 'expect...
d_job(mock_run, mock_api_cls): jobstep_id = uuid4() jobstep_data = generate_jobstep_da
ta() jobstep_data['status']['id'] = 'finished' mock_api = mock_api_cls.return_value mock_api.get_jobstep.return_value = jobstep_data command = WrapperCommand([ '--jobstep-id', jobstep_id.hex, '--api-url', 'http://changes.example.com', ]) command.run() assert not mock_run.c...
googlefonts/statmake
statmake/lib.py
Python
mit
7,470
0.002142
import collections import copy from typing import Dict, Mapping, Optional, Set import fontTools.misc.py23 import fontTools.ttLib import fontTools.ttLib.tables.otTables as otTables import statmake.classes def apply_stylespace_to_variable_font( stylespace: statmake.classes.Stylespace, varfont: fontTools.ttLib...
ariable( stylespace, varfont, additional_locations ) varfont["name"] = name_table varfont["STAT"] = stat_table def generate_name_and_STAT_variable( stylespace: statmake.classes.Stylespace, varfont: fontTools.ttLib.TTFont, additional_loc
ations: Mapping[str, float], ): """Generate a new name and STAT table ready for insertion.""" if "fvar" not in varfont: raise ValueError( "Need a variable font with the fvar table to determine which instances " "are present." ) stylespace_name_to_axis = {a.name.defa...
rec/BiblioPixel
bibliopixel/layout/geometry/segment.py
Python
mit
1,539
0.00065
from . import strip class Segment(strip.Strip): """Represents an offset, length segment within a strip.""" def __init__(self, strip, length, offset=0): if offset < 0 or length < 0: raise ValueError('Segment indices are non-negative.') if offset + length > len(strip): ...
x_index(index)] = value def __len__(self): retur
n self.length def next(self, length): """Return a new segment starting right after self in the same buffer.""" return Segment(self.strip, length, self.offset + self.length) def _fix_index(self, index): if isinstance(index, slice): raise ValueError('Slicing segments not impl...
slack-sqlbot/slack-sqlbot
slack_sqlbot/urls.py
Python
mit
164
0
from django.conf.urls import patterns, url urlpatterns = patterns('',
url(r'^sql/$', 'sqlparser.views.parse_sql'), )
Aerolyzer/Aerolyzer
aerolyzer/location.py
Python
apache-2.0
3,932
0.007121
import urllib2 import json import sys import os import wunderData def get_coord(exifdict): ''' Purpose: The purpose of this script is to extract the Latitude and Longitude from the EXIF data Inputs: exifdict: structure storing the image's EXIF data. Outputs: coords: A tuple of the...
e to a Latitude and Longitude Inputs: zipcode: 5 digit long ZIP code. Outputs: coord: tuple holding latitude and longitude Returns: (lat,lon) Assumptions: The EXIF data is valid. ''' try: url = 'https://maps.googleapis.com/maps/api/geocode/json?address='+zipcode+...
okey c = urllib2.urlopen(url) results = c.read() parsedResults = json.loads(results) lat = float(parsedResults['results'][0]['geometry']['location']['lat']) lon = float(parsedResults['results'][0]['geometry']['location']['lng']) except Exception: print "Unable to retrieve d...
analogue/bravado
bravado/swagger_model.py
Python
bsd-3-clause
5,223
0.000191
# -*- coding: utf-8 -*- import contextlib import logging import os import os.path import yaml from bravado_core.spec import is_yaml from six.moves import urllib from six.moves.urllib import parse as urlparse from bravado.compat import json from bravado.requests_client import RequestsClient log = logging.getLogger(__...
__init__(self, path): self.path = path self.is_yaml = is_yaml(path) def get_path(self): if not self.path.endswith('.json') and not self.is_yaml: return self.path + '.json' return self.path def wait(self, timeout=None): with contextlib.closing(urllib.request....
= fp.read() return self.FileResponse(content) def result(self, *args, **kwargs): return self.wait(*args, **kwargs) def cancel(self): pass def request(http_client, url, headers): """Download and parse JSON from a URL. :param http_client: a :class:`bravado.http_client.Http...
Tigge/trello-to-web
zip.py
Python
mit
659
0.007587
#! /usr/bin/env python3 import os import zipfile import sys import settings __author__ = 'tigge' def main(): zipfilename = os.path.join(settings.get("folder"), settings.get("basename") + ".zip") zip = zipfile.ZipFile(zipfilename, mode="w", ) for filename in os.listdir(settings.get("folder")):
print(filename, os.path.basename(zipfilename),filename == os.path.basenam
e(zipfilename)) if not filename.startswith(".t2w-temp-") and filename != os.path.basename(zipfilename): zip.write(os.path.join(settings.get("folder"), filename), arcname=filename) zip.close() if __name__ == "__main__": sys.exit(main())
yanchen036/tensorflow
tensorflow/contrib/tpu/python/tpu/tpu_estimator.py
Python
apache-2.0
121,921
0.006389
# Copyright 2017 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...
import tpu_feed from tensorflow.contrib.tpu.python.tpu import training_loop from tensorflow.contrib.tpu.python.tpu import util as util_lib from tensorflow.contrib.training
.python.training import hparam from tensorflow.core.framework import variable_pb2 from tensorflow.core.framework.summary_pb2 import Summary from tensorflow.core.protobuf import config_pb2 from tensorflow.python.data.ops import dataset_ops from tensorflow.python.estimator import estimator as estimator_lib from tensorflo...
sivel/ansible-modules-core
network/dellos9/dellos9_command.py
Python
gpl-3.0
6,997
0.001143
#!/usr/bin/python # # (c) 2015 Peter Sprygada, <psprygada@ansible.com> # # Copyright (c) 2016 Dell Inc. # # 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 versi...
sample: ['...', '...'] stdout_lines: description: The value of stdout split into a list returned: always type: list sample: [['...', '...'], ['...'], ['...']] failed_conditions: description: The list of conditionals that have failed returned: failed type: list sample: [
'...', '...'] warnings: description: The list of warnings (if any) generated by module based on arguments returned: always type: list sample: ['...', '...'] """ from ansible.module_utils.basic import get_exception from ansible.module_utils.netcli import CommandRunner, FailedConditionsError from ansible.module...
Goodly/TextThresher
thresher/migrations/0002_auto_20170607_1544.py
Python
apache-2.0
473
0
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-06-07 15:44 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dep
endencies = [ ('thresher', '0001_initial'), ] operations = [ migrations.AlterField( model_name='project', name='pybossa_url', field=models.CharField(blank=True, default=b'', max_length=200), ),
]
ubiquitypress/rua
src/core/util.py
Python
gpl-2.0
1,313
0
from bs4 import BeautifulSoup from urllib.parse import quote from core import models def get_setting(setting_name, setting_group_name, default=None): try: setting = models.Setting.o
bjects.get( name=setting_name, group__name=setting_group_name, ) return setting
.value except models.Setting.DoesNotExist: if default: return default return '' def strip_html_tags(raw_html): return BeautifulSoup(raw_html, "html.parser").get_text() def add_content_disposition_header( response, filename, disposition='attachment' ): ...
smarr/mxtool
mx.mx/suite.py
Python
gpl-2.0
4,144
0.021477
suite = { "name" : "mx", "libraries" : { # ------------- Libraries ------------- "JACOCOAGENT" : { "urls" : ["https://lafo.ssw.uni-linz.ac.at/pub/jacoco/jacocoagent-0.7.1-1.jar"], "sha1" : "2f73a645b02e39290e577ce555f00b02004650b0", }, "JACOCOREPORT" : { "urls" : ["https://lafo....
7a1efd2", }, "FINDBUGS_DIST" : { "urls" : [ "https://lafo.ssw.uni-linz.ac.at/pub/graal-external-deps/findbugs-3.0
.0.zip", "http://sourceforge.net/projects/findbugs/files/findbugs/3.0.0/findbugs-3.0.0.zip/download", ], "sha1" : "6e56d67f238dbcd60acb88a81655749aa6419c5b", }, "SIGTEST" : { "urls" : [ "http://hg.netbeans.org/binaries/A7674A6D78B7FEA58AF76B357DAE6EA5E3FDFBE9-apitest.jar", ...
karban/agros2d
data/scripts/dc_motor_dynamic.py
Python
gpl-2.0
3,460
0.010116
import numpy as np import pylab as pl from scipy.integrate import odeint from scipy.interpolate import interp1d phi = [0.0, 4.0, 8.0, 12.0, 16.0, 20.0, 24.0, 28.0, 32.0, 36.0, 40.0, 44.0, 48.0, 52.0, 56.0, 60.0, 64.0, 68.0, 72.0, 76.0, 80.0, 84.0, 88.0, 92.0, 96.0, 100.0, 104.0, 108.0, 112.0, 116.0, 120.0, 124.0, 128....
, 'b', label="$\mathrm{0.0~A$") pl.plot(phi, T_torque, 'r', label="$\mathrm{0.8~A$") pl.plot([0, 180], [0, 0], '--k') pl.xlabel("$\\phi~\mathrm{(deg.)}$") pl.ylabel("$T~
\mathrm{(Nm)}$") pl.legend(loc="lower right") fn_chart_static = pythonlab.tempname("png") pl.savefig(fn_chart_static, dpi=60) pl.close() # show in console pythonlab.image(fn_chart_static) J = 7.5e-5; k = 2e-4 T_f = interp1d(phi, T_torque, kind = "linear") def func(x, t): dx = [0., 0.] dx[0] = x[1] dx...
eklitzke/icfp08
src/constants.py
Python
isc
491
0.004073
# The docs say the processing time is less than 20 milliseconds #PROCESSING_TIME = 0.015 PROCESSING_TIME = 0.010 INTERVAL_SCALE = 0.95 # Number o
f degrees for a small angle... if the angle is smaller than this then # the rover won't try to turn, to help keep the path straight SMALL_ANGLE = 7.0 # E
nsure that the rover isn't in a hard turn for this kind of angle SOFT_ANGLE = 15.0 FORCE_TURN_DIST = 40.0 FORCE_TURN_SQ = FORCE_TURN_DIST ** 2 BLOAT = 1.3 # make things 30 percent bigger
anhstudios/swganh
data/scripts/templates/object/draft_schematic/food/shared_drink_charde.py
Python
mit
446
0.047085
#### NOTICE: THI
S FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Intangible() result.template = "object/draft_schematic/food/shared_drink_charde.iff" result.attribute_template_id = -1 result.st...
return result
iulian787/spack
var/spack/repos/builtin/packages/perl-io-socket-ssl/package.py
Python
lgpl-2.1
1,217
0.003287
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * import inspect class PerlIoSocketSsl(PerlPackage): """SSL sockets with IO::Socket interface""" ...
ers_filename = 'spack-config.in' with open(co
nfig_answers_filename, 'w') as f: f.writelines(config_answers) with open(config_answers_filename, 'r') as f: inspect.getmodule(self).perl('Makefile.PL', 'INSTALL_BASE={0}'. format(prefix), input=f)
MrCreosote/kb_read_library_to_file
lib/kb_read_library_to_file/kb_read_library_to_fileServer.py
Python
mit
23,263
0.00129
#!/usr/bin/env python from wsgiref.simple_server import make_server import sys import json import traceback import datetime from multiprocessing import Process from getopt import getopt, GetoptError from jsonrpcbase import JSONRPCService, InvalidParamsError, KeywordError,\ JSONRPCError, InvalidRequestError from jso...
ServiceCustom(JSONRPCService): def call(self, ctx, jsondata): """ Calls jsonrpc service's method and returns its return value in a JSON string or None if there is none.
Arguments: jsondata -- remote method call in jsonrpc format """ result = self.call_py(ctx, jsondata) if result is not None: return json.dumps(result, cls=JSONObjectEncoder) return None def _call_method(self, ctx, request): """Calls given method with g...
divio/django-cms
cms/utils/compat/__init__.py
Python
bsd-3-clause
545
0.00367
from platform import python_vers
ion from django import get_version from distutils.version import LooseVersion DJANGO_VERSION = get_version() PYTHON_VERSION = python_version() # These means "less than or equal to DJANGO_FOO_BAR" DJANGO_2_2 = LooseVersion(DJANGO_VERSION) < LooseVersion('3.0') DJANGO_3_0 = LooseVersion(DJANGO_VERSION) < LooseVersion...
ersion('3.3')
blakedewey/nipype
nipype/interfaces/fsl/tests/test_auto_ErodeImage.py
Python
bsd-3-clause
1,597
0.028178
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from nipype.testing import assert_equal from nipype.interfaces.fsl.maths import ErodeImage def test_ErodeImage_inputs(): input_map = dict(args=dict(argstr='%s', ), environ=dict(nohash=True, usedefault=True, ), ignore_exception=dict(nohash=Tr...
ct(argstr='-odt %s', position=-1, ), output_type=dict(), terminal_output=dict(nohash=True, ), ) inputs = ErodeImage.input_spec() for key, metadata in input_map.items(): for metakey, value in metadata.items(): yield assert_equal, getattr(inputs.traits()[key], metakey)...
ts(): output_map = dict(out_file=dict(), ) outputs = ErodeImage.output_spec() for key, metadata in output_map.items(): for metakey, value in metadata.items(): yield assert_equal, getattr(outputs.traits()[key], metakey), value