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
AASHE/hub
hub/apps/content/types/academic.py
Python
mit
2,754
0
from django.db import models from model_utils import Choices from ...metadata.models import ProgramType, SustainabilityTopic from ..models import ContentType, ContentTypeManager from ..search import BaseIndex class AcademicProgram(ContentType): DISTANCE_CHOICES = Choices( ('local', 'Local Only'), ...
arFi
eld( 'Commitment', max_length=20, choices=COMMITMENT_CHOICES, blank=True, null=True) objects = ContentTypeManager() class Meta: verbose_name = 'Academic Program' verbose_name_plural = 'Academic Programs' @classmethod def label_overrides(cls): return { ...
lsaffre/djangosite
djangosite/models.py
Python
bsd-2-clause
1,293
0.001547
# -*- coding: UTF-8 -*- # Copyright 2013-2014 by Luc Saffre. # License: BSD, see LICENSE for more details. """This module is based on Ross McFarland idea to simply send the server startup signal "at the end of your last app's models.py file" in his post `Django Startup Signal (Sun
24 June 2012) <http://www.xormedia.com/django-startup-signal/>`_. This adds a subtle hack to also cope with postponed imports. If there are postponed apps, then :mod:`djangosite.models` must itself raise an `ImportError` so that it get
s itself postponed and imported another time. Note that `loading.cache.postponed` contains all postponed imports even if they succeeded at the second attempt. """ # cannot use logging here because it causes duplicate logger setup # in certain situations. # import logging # logger = logging.getLogger(__name__) # imp...
nomuna/opencv_tesseract
ocr_on_cropped.py
Python
mit
780
0.010256
import cv2 import cv2.cv as cv import tesseract cv.NamedWindow("win") img = cv2.imread("GBIAe.jpg") # numpy.ndarray height, width, channels = img.shape # crop the image crop = (2*height/3, width/3) roi = img[crop
[0]:height, crop[1]:2*width/3] # Convert the cropped area, which is a numpy.ndarray, to cv2.cv.iplimage bitmap = cv.CreateImageHeader((roi.shape[1], roi.shape[0]), cv.IPL_DEPTH_8U, 3) cv.SetData(bitmap, roi.tostring(), roi.dtype.itemsize * 3 * roi.shape[1] ) # Extract the text with te
sseract api = tesseract.TessBaseAPI() api.Init(".","eng", tesseract.OEM_DEFAULT) api.SetPageSegMode(tesseract.PSM_AUTO) tesseract.SetCvImage( bitmap, api) text=api.GetUTF8Text() conf=api.MeanTextConf() print("text %s" % text) api.End() cv.ShowImage("win", bitmap) cv.WaitKey()
depboy/p2pool-depboy
p2pool/bitcoin/networks/myriad_groestl.py
Python
gpl-3.0
1,216
0.006579
import os import platform from twisted.internet import defer from .. import data, helper from p2pool.util import pack P2P_PREFIX = 'af4576ee'.decode('hex') P2P_PORT = 10888 ADDRESS_VERSION = 50 RPC_PORT = 10889 RPC_CHECK = defer.inlineCallbacks(lambda bitcoind: defer.returnValue( 'myriadcoinaddress' in ...
= lambda height: 1000*100000000 >> (height + 1)//967680 POW_FUNC = lambda data: pack.IntType(256).unpack(__import__('groestl_hash').getPoWHash(data)) BLOCK_PERIOD = 150 # s SYMBOL = 'MYR' CONF_FILE_FUNC=lambda: os.path.join(os.path.join(os.environ['APPDATA'], 'myriadcoin') if platform.system() == 'Windows' else os.pat...
/Application Support/myriadcoin/') if platform.system() == 'Darwin' else os.path.expanduser('~/.myriadcoin'), 'myriadcoin.conf') BLOCK_EXPLORER_URL_PREFIX = 'http://birdonwheels5.no-ip.org/block/' ADDRESS_EXPLORER_URL_PREFIX = 'http://birdonwheels5.no-ip.org/address/' TX_EXPLORER_URL_PREFIX = 'http://birdonwheels5.no-i...
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractOrtatranslationsBlogspotCom.py
Python
bsd-3-clause
570
0.033333
def extractOrtatranslationsBlogspotCom(item): ''' Parser for 'ortatranslations.blogspot.
com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPos
tfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessage...
MauHernandez/cyclope
cyclope/widgets.py
Python
gpl-3.0
7,445
0.002284
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2010-2013 Código Sur Sociedad Civil. # All rights reserved. # # This file is part of Cyclope. # # Cyclope 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 Foundat...
['Cut','Copy','Paste','PasteText'], ['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'], ['BidiLtr', 'BidiRtl'], '/', ['Bold','Italic','Underline','Strike','-','Subsc...
yCenter','JustifyRight','JustifyBlock'], ['Link','Unlink'], ['Image','Flash','Table','HorizontalRule'], '/', ['Styles','Format','Font','FontSize'], ['TextColor','BGColor'] ...
caioserra/apiAdwords
examples/adspygoogle/dfp/v201308/update_teams.py
Python
apache-2.0
2,513
0.006367
#!/usr/bin/python # # Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
= ad_unit_ids # Update teams on the server. teams = team_service.UpdateTeams(teams) # Display results. if teams: for team
in teams: print ('Team with id \'%s\' and name \'%s\' was updated.' % (team['id'], team['name'])) else: print 'No teams were updated.' else: print 'No teams found to update.'
dpazel/music_rep
tests/transformation_tests/functions_tests/pitchfunctions_tests/test_general_pitch_function.py
Python
mit
1,586
0.000631
import logging import sys import unittest from tonalmodel.diatonic_pitch import DiatonicPitch from transformation.functions.pitchfunctions.general_
pitch_function import GeneralPitchFunction class TestGeneralPitchFunction(unittest.TestCase): logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) def setUp(self): pass def tearDown
(self): pass def test_simple_pitch_function(self): p_map = {'A:7': 'Ab:7', 'Bb:6': 'B:6', 'Db:5': 'D:5'} gpf = GeneralPitchFunction(p_map) assert DiatonicPitch.parse('Ab:7') == gpf['A:7'] assert DiatonicPitch.parse('B:6') == gpf['Bb:6'] assert DiatonicPitch.parse(...
thiagopena/djangoSIGE
djangosige/apps/financeiro/models/__init__.py
Python
mit
72
0
# -*- coding: utf-8 -*-
from .lancamen
to import * from .plano import *
utarsuno/urbtek
universal_code/debugging.py
Python
apache-2.0
2,265
0.026932
#!/usr/bin/env python3 # coding=utf-8 """ This module, debugging.py, will contain code related to debugging (such as printing error messages). """ #import sys #sys.path.insert(0, '/home/dev_usr/urbtek') #from universal_code import system_operations as so class MyException(Exception): """ Just something useful to ...
end=None): if end is None: print(color + text + TextColors.ENDC + '\n') else: print(color + text + TextColors.ENDC, end='') def terminate(termination_message=''): if termination_message is '': print_text_with_color('Program termination has been initiated, good bye!', TextColors.FAIL) else: print_text_with...
print_text_with_color(' The program will now terminate.', TextColors.FAIL) exit()
messente/messente-python
messente/api/sms/api/delivery.py
Python
apache-2.0
1,647
0
# -*- coding: utf-8 -*- # Copyright 2016 Messente Communications OÜ # # 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 ...
eport yet, try again in 5 seconds" ]), }) class DeliveryResponse(Response): def __init__(self, *args, **kwargs): Response.__init__(self, *args, **kwargs) def _get_error_map(self): return error_map def get_result(self): return self.status_text class DeliveryAPI(api.API): ...
rt """ def __init__(self, **kwargs): api.API.__init__(self, "delivery", **kwargs) def get_dlr_response(self, sms_id): r = DeliveryResponse( self.call_api("get_dlr_response", dict(sms_unique_id=sms_id)) ) self.log_response(r) return r def get_report(...
hivesolutions/netius
src/netius/middleware/annoyer.py
Python
apache-2.0
2,721
0.004781
#!/usr/bin/python # -*- coding: utf-8 -*- # Hive Netius System # Copyright (c) 2008-2020 Hive Solutions Lda. # # This file is part of Hive Netius System. # # Hive Netius System is free software: you can redistribute it and/or modify # it under the terms of the Apache License as published by the Apache # Foun...
a simple diagnostics strategy. """ def __init__(self, owner, period = 10.0): Middleware.__init__(self, owner) self.period = period self._initial = None self._thread = None
self._running = False def start(self): Middleware.start(self) self.period = netius.conf("ANNOYER_PERIOD", self.period, cast = float) self._thread = threading.Thread(target = self._run) self._thread.start() def stop(self): Middleware.stop(self) if sel...
Shaswat27/sympy
sympy/core/compatibility.py
Python
bsd-3-clause
31,587
0.001646
""" Reimplementations of constructs introduced in later versions of Python than we support. Also some functions that are needed SymPy-wide and are located here for easy import. """ from __future__ import print_function, division import operator from collections import defaultdict from sympy.external import import_modu...
exclude multiple items, pass them as a tuple. You can
also set the _iterable attribute to True or False on your class, which will override the checks here, including the exclude test. As a rule of thumb, some SymPy functions use this to check if they should recursively map over an object. If an object is technically iterable in the Python sense but does ...
8acs2016/All-Terrain-Life-Vest
code.py
Python
apache-2.0
762
0.018373
# All-Te
rrain-Life-Vest All Terrain Life Vest- IEA Raspverry Pi Competition Entry # Description import RPi.GPIO as GPIO import time import os GPIO.setmode (GPIO.BCM) GPIO.cleanup() GPIO.setwarnings(False) GPIO.setup(17,GPIO.OUT) GPIO.setup(04,GPIO.OUT) GPIO.setup(22, GPIO.IN) print("---------------") print("Button+GPIO") ...
print("air bag activated") os.system('date') print GPIO.input(22) time.sleep(1) GPIO.output(17,GPIO.LOW) GPIO.output(04,GPIO.LOW) else: os.system('clear') print("air bag NOT activated") time.sleep(1)
arkharin/OpenCool
scr/logic/components/expansion_valve/theoretical.py
Python
mpl-2.0
1,392
0.001437
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. """ Define the Expansion Valve component. """ from scr.logic.components.component import Component as Cmp from scr.logi...
a): super().__init__(id_, inlet_nodes_id, outlet_nodes_id, component_data) """ Fundamental properties equations """ @fundamental_equation() # function name can be arbitrary. Return a single vector with each side of the equation evaluated. def _eval_intrinsic_equations(self): id_inlet_no...
de(id_inlet_node) id_outlet_node = self.get_id_outlet_nodes()[0] outlet_node = self.get_outlet_node(id_outlet_node) h_in = inlet_node.enthalpy() h_out = outlet_node.enthalpy() return [h_in / 1000.0, h_out / 1000.0]
antont/tundra
src/Application/PythonScriptModule/pymodules_old/webserver/webcontroller.py
Python
apache-2.0
5,782
0.008302
"""a non-blocking, non-threaded non-multiprocessing circuits web server""" import time #timestamping images import datetime #showing human readable time on render page import os import rexviewer as r import naali try: import circuits except ImportError: #not running within the viewer, but testing outside it ...
ubmit" name="rotate" value="10"/> <input type="submit" name="rotate" value="-10"/> </p> <p>move:<br/ <input type="submit" name="move" value="+1"/><br> <input type="submit" name="move" value="-1"/> </p> </form> <img src="%s"/> </body> </html>""" #second version where webui gives absolute pos&ort ...
so each user has own on client side abshtml = open(OWNPATH + "webui.html").read() def save_screenshot(): rend = naali.renderer rend.HideCurrentWorldView() rend.Render() imgname = "image-%s.png" % time.time() r.takeScreenshot(SHOTPATH, imgname) rend.ShowCurrentWorldView() baseurl = "/" #...
geradcoles/random-name
randomname/lists/names_male.py
Python
apache-2.0
28,040
0.094009
WORDS = ( 'Aaron', 'Abdul', 'Abe', 'Abel', 'Abraham', 'Abram', 'Adalberto', 'Adam', 'Adan', 'Adolfo', 'Adolph', 'Adrian', 'Agustin', 'Ahmad', 'Ahmed', 'Al', 'Alan', 'Albert', 'Alberto', 'Alden', 'Aldo', 'Alec', 'Alejandro', 'Alex', 'Alexander', 'Alexis', 'Alfonso', 'Alfonzo', 'Alfred', 'Al...
'Gaston', 'Gavin', 'Gayle', 'Gaylord', 'Genaro', 'Gene', 'Geoffrey', 'George', 'Gerald', 'Geraldo', 'Gerard', 'Gerardo', 'German', 'Gerry', 'Gil', 'Gilbert', 'Gilberto', 'Gino
', 'Giovanni', 'Giuseppe', 'Glen', 'Glenn', 'Gonzalo', 'Gordon', 'Grady', 'Graham', 'Graig', 'Grant', 'Granville', 'Greg', 'Gregg', 'Gregorio', 'Gregory', 'Grover', 'Guadalupe', 'Guillermo', 'Gus', 'Gustavo', 'Guy', 'Hai', 'Hal', 'Hank', 'Hans', 'Harlan', 'Harland', 'Harley', 'Harold', 'Ha...
FirstDraftGIS/firstdraft
projfd/appfd/forms.py
Python
apache-2.0
726
0.012397
# In forms.py... from appfd.models import Basemap from django.forms import CharField, FileField, Form, ModelChoiceField, URLField from timezone_field import TimeZoneFormField class
BasemapForm(Form): basemap = ModelChoiceField(to_field_name="name", queryset=Basemap.objects.all()) class LinkForm(Form): data = URLField() class TextForm(Form): data = CharField() class FileForm(Form): data = FileField() class RequestPossibleAdditionsForm(Form): name = CharField() # no
t validating whether token is in correct tokens bc that would slow # things down too much token = CharField() class TimezoneForm(Form): timezone = TimeZoneFormField() class TweetForm(Form): text = CharField()
puttarajubr/commcare-hq
corehq/apps/orgs/decorators.py
Python
bsd-3-clause
1,343
0.005957
from django.core.urlresolvers import reverse from django.http import HttpResponse, HttpResponseRedirect, Http404 def no_permissions_redirect(request): np_page = reverse('no_permissions') return HttpResponseRedirect(np_page) if request.method == 'GET' else HttpResponse("Missing qualifications") def check_and_...
uest, org, *args, **kwargs): check_and_set_org(request, org) if not hasattr(request, 'couch_user') or not \ (request.couch_user.is_org_admin(org) or request.couch_user.is_superuser):
return no_permissions_redirect(request) else: return view_func(request, org, *args, **kwargs) return shim def org_member_required(view_func): def shim(request, org, *args, **kwargs): check_and_set_org(request, org) if not hasattr(request, 'couch_user') or not\ ...
google-research/google-research
generalization_representations_rl_aistats22/minigrid/rl_basics.py
Python
apache-2.0
3,853
0.008305
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # 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 applicab...
epsilon: float in [0, 1] Returns: Numpy array S \times A: policy followed by the agent """ return epsilon * policy_random(env) + (1 - epsilon) * optimal_policy def policy_iteration(env, gamma=0.99, tolerance=1e-5, verbose=False): """Run policy iteration on env. Args: env: a MiniGrid environment,...
tolerance: float, evaluation stops when the value function change is less than the tolerance. verbose: bool, whether to print verbose messages. Returns: Numpy array with V* """ values = np.zeros(env.num_states) # Random policy policy = np.ones((env.num_states, env.num_actions)) / env.num_actio...
hjanime/VisTrails
scripts/get_usersguide.py
Python
bsd-3-clause
3,866
0.008795
#!/usr/bin/env python ############################################################################### ## ## Copyright (C) 2014-2015, New York University. ## Copyright (C) 2011-2014, NYU-Poly. ## Copyright (C) 2006-2011, University of Utah. ## All rights reserved. ## Contact: [email protected] ## ## This file is par...
: ## ## - Redistributions of source code must retain the above copyright n
otice, ## 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 disclaimer in the ## documentation and/or other materials provided with the distribution. ## - Neither the name of the Ne...
lilleswing/deepchem
examples/multiclass/multiclass_sklearn.py
Python
mit
605
0.001653
import deepchem as dc import numpy as np import sklearn from sklearn.ensemble import RandomForestClassifier N = 100 n_feat = 5 n_classes = 3 X = np.random.rand(N, n_feat) y = np.random.randint(3, size=(N,)) dataset = dc.data.NumpyDataset(X, y) sklearn_model = RandomFo
restClassifier(class_weight="balanced", n_estimators=50) model = dc.models.SklearnModel(sklearn_model) # Fit trained model print("About to fit model") model.fit(dataset) model.save() print("About to evaluate model") train_scores =
model.evaluate(dataset, sklearn.metrics.roc_auc_score, []) print("Train scores") print(train_scores)
cysuncn/python
spark/crm/PROC_A_SUBJECT_D003025.py
Python
gpl-3.0
2,560
0.012851
#coding=UTF-8 from pyspark import SparkContext, SparkConf, SQLContext, Row, HiveContext from pyspark.sql.types import * from datetime import date, datetime, timedelta import sys, re, os st = datetime.now() conf = SparkConf().setAppName('PROC_A_SUBJECT_D003025').setMaster(sys.argv[2]) sc = SparkContext(conf = conf) sc....
+V_DT+".parquet" ACRM_A_TARGET_D003025.cache() nrows = ACRM_A_TARGET_D003025.count() ACRM_A_TARGET_D003025.write.save(path=hdfs + '/' + dfn, mode='overwrite') ACRM_A_TARGET_D003025.unpersist() ACRM_F_CI_ASSET_BUSI_PROTO.unpersist() ret = os.system("hdfs dfs -rm -r /"+dbname+"/ACRM_A_TARGET_D003025/"+V_DT_LD+".parquet")...
d start[%s] end[%s] use %d seconds, insert ACRM_A_TARGET_D003025 lines %d") % (V_STEP, st.strftime("%H:%M:%S"), et.strftime("%H:%M:%S"), (et-st).seconds, nrows)
peter8472/GSM_SMS
gsm7.py
Python
apache-2.0
1,043
0.009
#! /usr/bin/python # coding=utf-8 """Another gsm lookup class. This one should actually work""" b= [u"@∆ 0¡P¿p"] b.append(u"£_!1AQaq") b.append(u'$Φ"2BRbr') b.append(u"¥Γ#3CScs") b.append(u"èΛ¤4DTdt") b.append(u"éΩ%5EUeu") b.append(u"ùΠ&6FVfv") b.append(u"ìΨ'7GWgw") b.append(u"òΣ(8HXhx") b.append(u"ÇΘ)9IYiy") b....
col == 1: raise Exception("gsm escape char found") try: return b[row][col] except IndexError(e): print e exit(1) if __name__ == "__main__": mygsm = G
sm7() for x in range(0,3): print mygsm.look(x) print b[7][6]
sjsucohort6/openstack
python/venv/lib/python2.7/site-packages/openstack/tests/unit/orchestration/v1/test_stack.py
Python
mit
3,804
0
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
sot = stack.Stack() self.assertEqual('stack', sot.resource_key) self.assertEqual('stacks', sot.resources_key) self.assertEqual('/stacks', sot.base_path) self.assertEqual('orchestration', sot.service.service_type) self.assertTrue(sot.allow_create) self.assertTrue(sot...
t.allow_update) self.assertTrue(sot.allow_delete) self.assertTrue(sot.allow_list) def test_make_it(self): sot = stack.Stack(FAKE) self.assertEqual(FAKE['capabilities'], sot.capabilities) self.assertEqual(FAKE['creation_time'], sot.created_at) self.assertEqual(FAKE['d...
t-wissmann/qutebrowser
tests/unit/utils/test_qtutils.py
Python
gpl-3.0
33,751
0.000089
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2014-2020 Florian Bruhin (The Compiler) <[email protected]> # # This file is part of qutebrowser. # # qutebrowser 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 S...
tGui import QColor from qutebrowser.utils import qtutils, utils, usertypes import overflow_test_cases if utils.is_linux: # Those are not run on macOS because that seems to cause a hang sometimes. # On Windows, we don't run them either because of # https://github.com/pytest-dev/pytest/issues/3650 try: ...
rt test_file # pylint: enable=no-name-in-module,useless-suppression except ImportError: # Debian patches Python to remove the tests... test_file = None else: test_file = None # pylint: disable=bad-continuation @pytest.mark.parametrize(['qversion', 'compiled', 'pyqt', 'version', 'exact'...
bronycub/sugarcub
sugarcub/settings.py
Python
gpl-3.0
7,848
0.002548
''' Django settings for sugarcub project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ ''' from django.conf.global_settings import AUTHENTICATION_BACKENDS, STATICFI...
9/0'.format(REDIS_HOST), 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', } }, } # Session SESSION_ENGINE = 'django.contrib.se
ssions.backends.cache' SESSION_CACHE_ALIAS = 'default' # Admin DAB_FIELD_RENDERER = 'django_admin_bootstrapped.renderers.BootstrapFieldRenderer' # Bootstrap BOOTSTRAP3 = { 'horizontal_label_class': 'col-md-2', 'horizontal_field_class': 'col-md-10' } # Logging LOGGING = { 'version': 1, 'disable_...
rhdedgar/openshift-tools
ansible/roles/lib_gcloud/library/gcloud_dm_resource_reconciler.py
Python
apache-2.0
25,410
0.002676
#!/usr/bin/env python # ___ ___ _ _ ___ ___ _ _____ ___ ___ # / __| __| \| | __| _ \ /_\_ _| __| \ # | (_ | _|| .` | _|| / / _ \| | | _|| |) | # \___|___|_|\_|___|_|_\/_/_\_\_|_|___|___/_ _____ # | \ / _ \ | \| |/ _ \_ _| | __| \_ _|_ _| # | |) | (_) | | .` | (_) || | | _|| |) | | ...
.extend([name]) if zone: cmd.extend(['--zone', zone]) data = None if metadata_from_file: cmd.append('--metadata-from-file') data = metadata_from_file else: cmd.append('--metadata') data = metada
ta cmd.append(','.join(['%s=%s' % (key, val) for key, val in data.items()])) return self.gcloud_cmd(cmd, output=True, output_type='raw') def _list_service_accounts(self, sa_name=None): '''return service accounts ''' cmd = ['iam', 'service-accounts'] if sa_name: ...
pombredanne/https-git.fedorahosted.org-git-kobo
tests/test_http.py
Python
lgpl-2.1
1,375
0.002909
#!/usr/bin/python # -*- coding: utf-8 -*- import unittest import run_tests # set sys.path import tempfile import os from kobo.http import * class TestPOSTTransport(unittest.TestCase): def setUp(self): self.postt = POSTTransport() def test_get_content_type(self): tf0 = tempfile.mkstemp()[1...
uffix=".avi")[1] self.assertEqual(self.postt.get_content_type(tf0), "application/octet-stream") self.assertEqual(self.postt.get_content_type(tf1), "text/plain") # *.rtf: py2.7 returns 'application/rtf'; py2.4 returns 'text/rtf' self.assertEqual(self.postt.get_content_type(tf2).split("/")...
eo/x-msvideo") def test_add_file(self): tf1 = tempfile.mkstemp()[1] tf2 = tempfile.mkstemp()[1] tf3 = open(tempfile.mkstemp()[1]) os.unlink(tf1) self.assertRaises(OSError, self.postt.add_file, "file", tf1) self.assertEqual(self.postt.add_file("file", tf2), None) ...
onecodex/onecodex
onecodex/vendored/potion_client/__init__.py
Python
mit
6,097
0.002788
# flake8: noqa from functools import partial from operator import getitem, delitem, setitem from six.moves.urllib.parse import urlparse, urljoin from weakref import WeakValueDictionary import requests try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping # ...
cls._links = links = {} for link_schema in schema['links']: link = Link(self, rel=link_schema['rel'], href=link_schema['href'], method=link_schema['method'], schema=link_schema.get('schema', None)...
if link.rel in ('self', 'instances', 'create', 'update', 'destroy'): setattr(cls, '_{}'.format(link.rel), link) links[link.rel] = link if link.rel != 'update': # 'update' is a special case because of MutableMapping.update() setattr(cls, snake_case(link....
texit/texit
graph.py
Python
mit
2,827
0.020516
import os import json from subprocess import check_output, Calle
dProcessError #Constants _TREE_PATH="data/graph/" def renderGraph(query): """ Returns the path to a svg file that contains the grap
h render of the query. Creates the svg file itself if it does not already exist. """ #Compute the hash of the query string qhash = hashFunc(query) if (not os.path.exists(_TREE_PATH+str(qhash))): #Create bucket if it doesn't already exist. os.makedirs(_TREE_PATH+str(qha...
lolosk/microblog
app/__init__.py
Python
gpl-2.0
71
0.028169
fr
om flask import Flask app = Flask(__name__) from app import views
endlessm/chromium-browser
third_party/depot_tools/recipes/recipe_modules/bot_update/__init__.py
Python
bsd-3-clause
1,081
0.00185
DEPS = [ 'depot_tools', 'gclient', 'gerrit', 'gitiles', 'recipe_engine/buildbucket', 'recipe_engine/context', 'recipe_engine/commit_position', 'recipe_engine/cq', 'recipe_engine/json', 'recipe_engine/path', 'recipe_engine/platform', 'recipe_engine/properties', 'recipe...
, 'recipe_engine/step', 'tryserver', ] from recipe_engine.recipe_api import Property from recipe_engine.config import ConfigGroup, Single PROPERTIES = { # Gerrit patches will have all properties about them prefixed with patch_. 'deps_revision_overrides': Property(default={}), 'fail_patch': Property(defa...
le.', param_name='properties', kind=ConfigGroup( # Whether we should do the patching in gclient instead of bot_update apply_patch_on_gclient=Single(bool), ), default={}, ), }
tbodt/v8py
tests/test_context.py
Python
lgpl-3.0
3,108
0.004505
import pytest import time from v8py import JavaScriptTerminated, current_context, new def test_glob(context): context.eval('foo = "bar"') assert context.glob.foo == 'bar' def test_getattr(context): context.foo = 'bar' assert context.foo == 'bar' assert context.glob.foo == 'bar' assert context...
; }, deleteProperty(target, phrase) { if (phrase == "testC") while(true); return false; }
}); """) proxy = context_with_timeout.glob.proxy with pytest.raises(JavaScriptTerminated): testA = proxy.testA with pytest.raises(JavaScriptTerminated): proxy.testB = 5 with pytest.raises(JavaScriptTerminated): del proxy.testC def test_expose(context): def f():...
m-rossi/matplotlib2tikz
test/test_text_overlay.py
Python
mit
2,420
0.00124
import matplotlib.pyplot as plt import numpy from helpers import assert_equality def plot(): fig = plt.figure() xxx = numpy.linspace(0, 5) yyy = xxx ** 2 plt.text( 1, 5, "test1", size=50, rotation=30.0, ha="center", va="bottom", color="r...
ad=0.2", ec=(1.0, 0.5, 0.5), fc=(1.0, 0.8, 0.8), ls="dashdot", ), ) plt.text( 3, 6, "test2", size=50, rotation=-30.0, ha="center", va="center", color="b", weight="bold", bbox=dict(boxstyle...
="center", va="center", color="b", weight="demi", bbox=dict( boxstyle="rarrow", ls="dashed", ec=(1.0, 0.5, 0.5), fc=(1.0, 0.8, 0.8) ), ) plt.text( 4, 16, "test4", size=20, rotation=90.0, ha="center", va="...
luosch/leetcode
python/Find Minimum in Rotated Sorted Array.py
Python
mit
428
0.002336
class Solution(object): def findMin(s
elf, nums): left = 0 right = len(nums) - 1 mid = (left + right) / 2 while left <= right: if nums[left] <= nums[
right]: return nums[left] mid = (left + right) / 2 if (nums[mid] >= nums[left]): left = mid + 1 else: right = mid return nums[mid]
Shiwin/LiteNote
noties/urls.py
Python
gpl-2.0
1,648
0.016383
from django.conf.urls import patterns, include, url from django.contrib import admin from django.contrib.auth import views admin.autodiscover() urlpatterns = patterns('', url(r'^$',
'lite_note.views.home', name='home'), url(r'^test','lite_note.views.new_home',name='new_home'), url(r'^admin/', include(admin.site.urls)), url(r'^login/', views.login, name='login'), url(r'^logout/', views.logout, {'next_pag...
='logout'), url(r'^register/', 'regsiter.views.registration', name='registration_register'), url(r'^create/', 'lite_note.views.create_note', name='create_note'), url(r'^unknown/', 'lite_note.views.enter_anonymous_user', name='enter_anonymous'), ...
jdhenke/ally
core.py
Python
mit
4,087
0.005872
#!/bin/python ''' Library for formulating and solving game trees as linear programs. ''' class Node(object): '''Abstract class to represent a node in the game tree.''' def solve(self): ''' Should populate the solutions dictionary. solutions: TerminalNode ==> list of lists of inequali...
for leftLeaf i
n leftLeaves: for rightLeaf in rightLeaves: yield (leftLeaf, rightLeaf, leftChild, rightChild, ) # functions which maintain CDF form of inequalities def And(a, b): output = [] for x in a: for y in b: output.append(x+y) # must be tuple to be a...
pawkoz/dyplom
blender/doc/python_api/examples/bpy.props.4.py
Python
gpl-2.0
495
0.00202
""" Update Example ++++++++++++++ It can be useful to perform an action when a property is changed and
can be used to update other properties or synchronize with exte
rnal data. All properties define update functions except for CollectionProperty. """ import bpy def update_func(self, context): print("my test function", self) bpy.types.Scene.testprop = bpy.props.FloatProperty(update=update_func) bpy.context.scene.testprop = 11.0 # >>> my test function <bpy_struct, Scene("S...
androomerrill/scikit-nano
sknano/apps/nanogen_gui/_pyqt4_ui_mwnt_Ch_list_item_dialog.py
Python
bsd-2-clause
5,271
0.001897
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'mwnt_Ch_list_item_dialog.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: de...
self.m_spin_box.setMinimumSize(QtCore.QSize(90, 36)) font = QtGui.QFont() font.setFamily(_fromUtf8("Arial")) font.setPointSize(16) self.m_spin_box.setFont(font) self.m_spin_box.setMaximum(100) self.m_spin_box.setProperty("value", 10) self.m_spin_box.setObjectNam...
x) self.horizontalLayout_3.addLayout(self.horizontalLayout_4) self.horizontalLayout_5.addLayout(self.horizontalLayout_3) self.verticalLayout.addLayout(self.horizontalLayout_5) self.horizontalLayout = QtGui.QHBoxLayout() self.horizontalLayout.setObjectName(_fromUtf8("horizontalLay...
google/lasr
third_party/chamfer3D/dist_chamfer_3D.py
Python
apache-2.0
2,341
0.002136
from torch import nn from torch.autograd import Function import torch import importlib import os chamfer_found = importlib.find_loader("chamfer_3D") is not None if not chamfer_found: ## Cool trick from https://github.com/chrdiller print("Jitting Chamfer 3D") from torch.utils.cpp_extension import load c...
e module @thibaultgroueix # GPU tensors only class chamfer_3DFunction(Function): @staticmethod def forward(ctx, xyz1, xyz2): batchsize, n, _ = xyz1.size() _, m, _ = xyz2.size() device = xyz1.device
dist1 = torch.zeros(batchsize, n) dist2 = torch.zeros(batchsize, m) idx1 = torch.zeros(batchsize, n).type(torch.IntTensor) idx2 = torch.zeros(batchsize, m).type(torch.IntTensor) dist1 = dist1.to(device) dist2 = dist2.to(device) idx1 = idx1.to(device) idx2 = idx...
geotagx/geotagx-pybossa-archive
pybossa/util.py
Python
agpl-3.0
11,505
0.000782
# -*- coding: utf8 -*- # This file is part of PyBossa. # # Copyright (C) 2013 SF Isle of Man Limited # # PyBossa is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at...
ACEBOOK_APP_ID'], consumer_secret=c_s, # app.config['FACEBOOK_APP_SECRET'] request_token_params={'scope': 'email'}
) def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs): # This code is taken from http://docs.python.org/library/csv.html#examples # csv.py doesn't do Unicode; encode temporarily as UTF-8: csv_reader = csv.reader(utf_8_encoder(unicode_csv_data), dialect=dialect...
alexandreferreira/groovedowndl
djangogroovedown/servicos/views.py
Python
apache-2.0
2,206
0.002267
# Create your views here. import json import os from django.http.response import HttpResponse, Http404 from django.shortcuts import render_to_response from django.template import RequestContext from django.views.decorators.csrf import csrf_exempt from djangogroovedown.utils import download_music_temp_file, search_for_m...
leWrapper def index(request): return render_to_respons
e('index.html', {}, context_instance=RequestContext(request)) def get_list_popular_music(request): perido = request.GET.get('period') client = Client() client.init() if perido == '1': popular_music = client.popular(period=Client.DAILY) else: popular_music = client.popular(period=Cl...
Danielhiversen/home-assistant
tests/components/directv/test_init.py
Python
apache-2.0
1,186
0
"""Tests for the DirecTV integration.""" from homeassistant.components.directv.const import DOMAIN from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant from tests.components.directv import setup_integration from tests.test_util.aiohttp import AiohttpClientMocker # pyl...
lientMocker ) -> None: """Test the DirecTV configuration entry not ready.""" entry = await setup_integration(hass, aioclient_mock, setup_error=True) assert entry.state is ConfigEntryState.SETUP_RETRY async def test_unload_config_entry( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker ) -> Non...
"""Test the DirecTV configuration entry unloading.""" entry = await setup_integration(hass, aioclient_mock) assert entry.entry_id in hass.data[DOMAIN] assert entry.state is ConfigEntryState.LOADED await hass.config_entries.async_unload(entry.entry_id) await hass.async_block_till_done() a...
orientechnologies/pyorient
pyorient/messages/commands.py
Python
apache-2.0
19,879
0.000755
# -*- coding: utf-8 -*- from .database import BaseMessage from .records import RecordUpdateMessage, RecordDeleteMessage, RecordCreateMessage from ..exceptions import PyOrientBadMethodCallException from ..constants import COMMAND_OP, FIELD_BOOLEAN, FIELD_BYTE, FIELD_CHAR, \ FIELD_INT, FIELD_LONG, FIELD_SHORT, FIELD_...
def _read_sync(self): # type of response # decode body char with flag continue ( Header already read ) response_type = self._decode_field(FIELD_CHAR) if not isinstance(response_type, str): response_type = response_type.decode() res = [] if response_type =...
ndMessage, self).fetch_response(True) # end Line \x00 return None elif response_type == 'r' or response_type == 'w': res = [self._read_record()] self._append(FIELD_CHAR) # end Line \x00 _res = super(CommandMessage, self).fetch_response(True...
CaliOpen/CaliOpen
src/backend/components/py.pgp/caliopen_pgp/keys/__init__.py
Python
gpl-3.0
552
0
# -*- coding: utf-8 -*- """ PGP public keys management """ from __future__ import absolute_import, unicode_literals from .rfc7929 import DNSDiscovery from .hkp import HKPDiscovery from .keybase import KeybaseDiscovery from .base import PGPPublicKey, PG
PUserId, DiscoveryResult from .discoverer import PublicKeyDi
scoverer from .contact import ContactPublicKeyManager __all__ = ['DNSDiscovery', 'HKPDiscovery', 'KeybaseDiscovery', 'PGPPublicKey', 'PGPUserId', 'DiscoveryResult', 'PublicKeyDiscoverer', 'ContactPublicKeyManager']
xpharry/Udacity-DLFoudation
tutorials/reinforcement/gym/gym/envs/classic_control/mountain_car.py
Python
mit
4,262
0.0061
""" https://webdocs.cs.ualberta.ca/~sutton/MountainCar/MountainCar1.cp """ import math import gym from gym import spaces from gym.utils import seeding import numpy as np class MountainCarEnv(gym.Env): metadata = { 'render.modes': ['human', 'rgb_array'], 'video.frames_per_second': 30 } def...
ans)
backwheel.set_color(.5, .5, .5) self.viewer.add_geom(backwheel) flagx = (self.goal_position-self.min_position)*scale flagy1 = self._height(self.goal_position)*scale flagy2 = flagy1 + 50 flagpole = rendering.Line((flagx, flagy1), (flagx, flagy2)) ...
benoitsteiner/tensorflow-opencl
tensorflow/contrib/kfac/python/ops/utils_lib.py
Python
apache-2.0
1,520
0
# 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...
mport * from tensorflow.python.util.all_util import remove_undocumented # pylint: enable=unused-import,line-too-long,wildcard-import _allowed_symbols = [ "SequenceDict", "setdefault", "tensors_to_column", "column_to_tensors", "kronecker_product", "layer_params_to_mat2d", "mat2d_to_layer_par...
rate_random_signs", "fwd_gradients", ] remove_undocumented(__name__, allowed_exception_list=_allowed_symbols)
alienlike/courier
courier/scripts/create_tables.py
Python
gpl-3.0
816
0.003676
import logging from sqlalchemy import engine_from_config from courier.scripts import settings from courier.models import Declarativ
eBase, DBSession, db_views, populate_lookups LOG = False def main(DBSession, engine): # set up logging if LOG: logging.basicConfig()
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO) # build tables & views db_views.drop_views(engine) DeclarativeBase.metadata.bind = engine DeclarativeBase.metadata.drop_all() DeclarativeBase.metadata.create_all(engine) db_views.build_views(engine) # populate lookups ...
isobelsv/nyu-python
while_loop.py
Python
mit
249
0.012048
#!/usr/bin/env python3 import sys if __name
__ == '__main__': a_str = sys.argv[1] b_str = sys.argv[2] a = int(sys.argv[1]) b = int(sys.argv[2]) while (a <= b): print("a ="
+ str(a) + str(b) + ")") a = a+1
kpech21/Greek-Stemmer
tests/tools/test_text_tools.py
Python
lgpl-3.0
2,368
0
# -*- coding: utf-8 -*- import pytest from greek_stemmer.tools.text_tools import * class TestParseText: def test_parse_word_receives_no_string(self): assert parse_word(None) == '' # check accents removal and uppercase letters parse_word_testdata = [ (' $', '$'), (' foo ', 'FOO...
ek(None) is False # check accents removal and uppercase letters parse_is_greek_testdata = [ (' $', False), ('0.5', False), ('foo', False), ('(25%)', False), (u'\u2167 ί', False), ("Greek's", False), ('κ', True), ('eλληνικά', False), ('EΛΛΗ...
t.mark.parametrize('word, output', parse_is_greek_testdata) def test_is_greek_with_various_inputs(self, word, output): assert is_greek(word) == output
PeterWangIntel/crosswalk-webdriver-python
third_party/atoms.py
Python
bsd-3-clause
417,522
0.000091
__all__ = ["GET_FIRST_CLIENT_RECT", \ "GET_LOCATION_IN_VIEW", \ "GET_PAGE_ZOOM", \ "IS_ELEMENT_CLICKABLE", \ "TOUCH_SINGLE_TAP", \ "CLEAR", \ "CLEAR_LOCAL_STORAGE", \ "CLEAR_SESSION_STORAGE", \ "CLICK", \ "EXECUTE_ASYNC_S...
this.left+\", "\ "\"+this.top+\" - \"+this.width+\"w x \"+this.height+\"h)\"};function s("\ "a){var b;a:{b=m(a);if(b.defaultView&&b.defaultView.getComputedStyle&&(b"\ "=b.defaultView.getComputedStyle(a,null))){b=b.position||b.getPropertyVa"\ "lue(\"position\")||\"\";break a}b=\"\"}return b||(a.currentSt...
on}function t(a){var b;"\ "try{b=a.getBoundingClientRect()}catch(e){return{left:0,top:0,right:0,bo"\ "ttom:0}}return b}\nfunction u(a){var b=m(a),e=s(a),d=\"fixed\"==e||\"ab"\ "solute\"==e;for(a=a.parentNode;a&&a!=b;a=a.parentNode)if(e=s(a),d=d&&\""\ "static\"==e&&a!=b.documentElement&&a!=b.body,!d&&(a....
dhermes/google-cloud-python
dns/tests/unit/test__http.py
Python
apache-2.0
2,719
0.000736
# Copyright 2015 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
"Accept-Encoding": "gzip", base_http.CLIENT_INFO_HEADER: MUT._CLIENT_INFO, "User-Agent": conn.USER_AGENT, } expected_uri = conn.build_api_url("/rainbow") http.request.assert_called_once_with( data=req_data, headers=expected_headers, method="GET"
, url=expected_uri )
chgans/django-google-dork
django_google_dork/migrations/0001_initial.py
Python
bsd-2-clause
4,143
0.003621
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django_google_dork.models import model_utils.fields import django.utils.timezone class Migration(migrations.Migration): replaces = [('django_google_dork', '0001_initial'), ('django_google_dork', '0002...
ango_google_dork.models.CampaignNameField(unique=True, max_length=32)), ], options={ 'abstract': False, }, bases=(models.Model,), ), migrations.CreateModel( name='Dork', fields=[ ('id', models.AutoFie...
ango.utils.timezone.now, verbose_name='created', editable=False)), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, verbose_name='modified', editable=False)), ('query', django_google_dork.models.DorkQueryField(max_length=256)), ('ca...
noamraph/dreampie
dreampielib/data/subp_main.py
Python
gpl-3.0
1,566
0.005109
# Copyright 2009 Noam Yorav-Raphael # # This file is part of DreamPie. # # DreamPie 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. # ...
etails. # # You should have received a copy of the GNU General Public License # along with DreamPie. If not, see <http://www.gnu.org/licenses/>. # This file is a script (not a module) run by the DreamPie GUI. # It expects one argument: the port to connect to. # It creates a package called dreampielib from subp-py2.z...
, # and runs dreampielib.subprocess.main(port). import sys from os.path import abspath, join, dirname def main(): port = int(sys.argv[1]) py_ver = sys.version_info[0] lib_name = abspath(join(dirname(__file__), 'subp-py%d' % py_ver)) sys.path.insert(0, lib_name) from dreampielib.subprocess im...
D4wN/brickv
src/build_data/windows/OpenGL/GL/ARB/texture_border_clamp.py
Python
gpl-2.0
1,249
0.015212
'''OpenGL extension ARB.texture_border_clamp This module customises the behaviour of the OpenGL.raw.GL.ARB.texture_border_clamp to provide a more Python-friendly API Overview (from the spec) The base OpenGL provides clamping such that the texture coordinates are limited to exactly the ran
ge [0,1]. When a texture coordinate is clamped using this algorithm, the tex
ture sampling filter straddles the edge of the texture image, taking 1/2 its sample values from within the texture image, and the other 1/2 from the texture border. It is sometimes desirable for a texture to be clamped to the border color, rather than to an average of the border and edge colors. This extension ...
scott-s-douglas/SWAPR
sqlite1.py
Python
gpl-2.0
12,933
0.03232
import sqlite3 import os.path import sys import random def makeDatabase(databaseName): if databaseName[-3:] != ".db": databaseName = databaseName + ".db" conn = sqlite3.connect(databaseName) conn.commit() conn.close() def listToString(list): string = "" for i in list: string += str(i)+"\t" return string[:-...
d self.conn.commit() #adds a person into the database, works for both new users and existing ones def addEntry(self, wID, URL, labNumber, metadata = None): if self.databaseName != None and self.conn != None and self.cursor !=None: #If the student did not submit a URL (aka the inputted URL is '') if URL ==...
ts URL into the uniqueStudentURL database to check if the URL is unique else: try: self.cursor.execute("INSERT INTO uniqueStudentURL VALUES (?,?,?)", [labNumber, wID, URL]) #if there is no error in inserting to a table where URL has to be unique, put it in the actual student database self.cursor....
datawire/quark
quarkc/test/ffi/expected/py/package/package_md/__init__.py
Python
apache-2.0
3,603
0.006939
from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from __future__ import print_function from builtins import str as unicode from quark_runtime import * _lazyImport.plug("package_md.test_Test_go_Method") import quark.reflect class test_Test_go_Method(quark.r...
ass class test_Test
(quark.reflect.Class): def _init(self): quark.reflect.Class._init(self) def __init__(self): super(test_Test, self).__init__(u"test.Test"); (self).name = u"test.Test" (self).parameters = _List([]) (self).fields = _List([quark.reflect.Field(u"quark.String", u"name")]) ...
ric2b/Vivaldi-browser
chromium/build/skia_gold_common/skia_gold_properties.py
Python
bsd-3-clause
4,742
0.011177
# Copyright 2020 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. """Class for storing Skia Gold comparison properties. Examples: * git revision being tested * Whether the test is being run locally or on a bot * What the co...
kia Gold. Args: args: The parsed arguments from an argparse.ArgumentParser. """ self._git_revision = None self._issue = None self._patchset = None self._job_id = None self._local_pixel_tests = None self._no_luci_auth = None self._bypass_skia_gold_functionality = None self....
elf): return self.issue is not None @property def continuous_integration_system(self): return self._continuous_integration_system or 'buildbucket' @property def code_review_system(self): return self._code_review_system or 'gerrit' @property def git_revision(self): return self._GetGitRevis...
codedstructure/rpcpdb
rpcpdb/cli_pyro.py
Python
mit
250
0.004
#!/
usr/bin/env python -u import Pyro.core from rpcpdb import cli def get_api_connection(): return Pyro.core.getProxyForURI("PYROLOC://localhost:7766/rpc") cli.get_api_connection = get_api_connectio
n if __name__ == '__main__': cli.main()
brian-rose/climlab
climlab/radiation/rrtm/_rrtmg_lw/setup.py
Python
mit
3,492
0.0063
from __future__ import print_function from os.path import join, abspath modules = ['parkind.f90', 'parrrtm.f90', 'rrlw_cld.f90', 'rrlw_con.f90', 'rrlw_kg01.f90', 'rrlw_kg02.f90', 'rrlw_kg03.f90', 'rrlw_kg04.f90', 'rrlw_kg05.f90', ...
w_gen_source(ext, build_dir): '''Add RRTMG_LW fortran source if Fortran 90 compiler available, if no compiler is found do not try to build the extension.''' thispath = config.local_path module_src = [] for item in modules: fullname = join(thispath,'rrtmg_lw_v4.85','gcm_model','modules',item)...
fullname = join(thispath,'sourcemods',item) else: fullname = join(thispath,'rrtmg_lw_v4.85','gcm_model','src',item) module_src.append(fullname) sourcelist = [join(thispath, '_rrtmg_lw.pyf'), join(thispath, 'Driver.f90')] try: config.have_f90c() ...
dslab-epfl/bugbase
lib/installer/dependency_installer.py
Python
bsd-3-clause
4,885
0.002252
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ This scripts is a script to use to install dependencies of programs """ from abc import abstractmethod, ABCMeta import logging import platform import subprocess from lib.helper import launch_and_log_as_root from lib.exceptions import DistributionNotSupportedExceptio...
"-y"] + packages launch_and_log_as_root(cmd) @staticmethod def update_sources() -> None: """ Updates the repository sources, as on some OS, having
it out of sync may lead to error on installation :raise subprocess.CalledProcessError if process fails """ logging.info("Updating apt repositories") launch_and_log_as_root(["apt-get", "update"])
desavera/bicraft
dockerbuild/superset_config.py
Python
gpl-3.0
1,331
0.012772
#--------------------------------------------------------- # Superset specific config #--------------------------------------------------------- ROW_LIMIT = 5000 SUPERSET_WORKERS = 4 SUPERSET_WEBSERVER_PORT = 8080 CACHE_CONFIG={'CACHE_TYPE':'filesystem', 'CACHE_DEFAULT_TIMEOUT': 50000, 'CACHE_DIR': '/opt/superset/fsc...
#--------------------------------------------------------- #--------------------------------------------------------- # Flask App Builder configuration #--------------------------------------------------------- # Your App secret key SECRET_KEY = '\2\1thisismyscretkey\1\2\e\y\y\h' # The SQLAlchemy connection string to...
ction defines the path to the database that stores your # superset metadata (slices, connections, tables, dashboards, ...). # Note that the connection information to connect to the datasources # you want to explore are managed directly in the web UI #SQLALCHEMY_DATABASE_URI = 'sqlite:////root/.superset/superset.db' SQL...
111pontes/ydk-py
cisco-ios-xe/ydk/models/cisco_ios_xe/CISCO_ETHERLIKE_EXT_MIB.py
Python
apache-2.0
17,254
0.013272
""" CISCO_ETHERLIKE_EXT_MIB The MIB module to describe generic objects for ethernet\-like network interfaces. This MIB provides ethernet\-like network interfaces information that are either excluded by EtherLike\-MIB or specific to Cisco products. """ import re import collections from enum import Enum from y...
ot3Pauseextadminmode>` .. attribute:: ceedot3pauseextopermode Provides additional information about the flow control operational status on this interface. txDisagree(0) \- the transmit pause function on this interface is disabled due to ...
isagree(1) \- the receive pause function on this interface is disabled due to disagreement from the far end on negotiation. txDesired(2) \- the transmit pause function on this interface is desired. rxDesired(3) \- the receive pause function on ...
tellesnobrega/storm_plugin
sahara/tests/unit/utils/test_edp.py
Python
apache-2.0
1,793
0
# Copyright (c) 2014 Red Hat 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 writi...
E_JAVA, edp.JOB_TYPE_MAPREDUCE, strict=True)) self.assertFalse(edp.compare_j
ob_type( edp.JOB_TYPE_MAPREDUCE_STREAMING, edp.JOB_TYPE_JAVA, edp.JOB_TYPE_MAPREDUCE, strict=True)) self.assertTrue(edp.compare_job_type( edp.JOB_TYPE_MAPREDUCE_STREAMING, edp.JOB_TYPE_JAVA, edp.JOB_TYPE_MAPREDUCE)) self...
aaronkurtz/gourmand
gourmand/subscriptions/migrations/0002_make_unique_per_user.py
Python
gpl-2.0
516
0
# -*- coding: utf-8 -*- from __future__ import un
icode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('subscriptions', '0001_initial'), ] operations = [ migrations.AlterUniqueTogether(
name='personalarticle', unique_together=set([('sub', 'article')]), ), migrations.AlterUniqueTogether( name='subscription', unique_together=set([('owner', 'feed')]), ), ]
ytsapras/robonet_site
events/management/commands/remove_old_events.py
Python
gpl-2.0
985
0.012183
# -*- coding: utf-8 -*- """ Created on Wed Jul 12 11:31:48 2017 @author: rstreet """ from django.core.management.base import BaseCommand from django.contrib.auth.models import User from events.models import EventName, Event from sys import exit class Command(BaseCommand): help = '' def _remove_old_e...
t '+event.name+', ID='+str(event.event_id)) for event in ogle_events: Event.objects.filter(id=event.event_id).delete() print('Removed event '+event.name+', ID='+str(event.event_id)) def handle(self,*args, **options): self._remove_old_events(*args,
**options)
e-gob/plataforma-kioscos-autoatencion
scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/modules/network/ovs/openvswitch_bridge.py
Python
bsd-3-clause
8,968
0.001227
#!/usr/bin/python #coding: utf-8 -*- # (c) 2013, David Stygstra <[email protected]> # Portions copyright @ 2015 VMware, Inc. # 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 ANSIB...
mplatized_command % module.params if want['parent']: templatized_command = "%(parent)s %(vlan)s" command += " " + templatized_command % module.params if want['set']: templatized_command = " -- set %(set)s" command +=
templatized_command % module.params commands.append(command) if want['fail_mode']: templatized_command = ("%(ovs-vsctl)s -t %(timeout)s" " set-fail-mode %(bridge)s" " %(fail_mode)s") c...
PoplarYang/oneinstack-odm
include/get_public_ipaddr.py
Python
apache-2.0
536
0.044776
#!/usr/bin/env python import re,urllib2 class Get_public_ip: def getip(self): try: myip = self.visit("http://ip.chinaz.com/getip.aspx") except: try: myip = self.visit("http://ipv4.icanhazip.com/") except:
myip = "So sorry!!!" return myip def visit(self,url): opener = urllib2.urlopen(url)
if url == opener.geturl(): str = opener.read() return re.search('\d+\.\d+\.\d+\.\d+',str).group(0) if __name__ == "__main__": getmyip = Get_public_ip() print getmyip.getip()
adsworth/ldp3
ldp/trip/models.py
Python
mit
2,583
0.007356
from django.conf import settings from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from django.db import models from django.db.models.signals import post_save from django.utils.translation import ugettext as _ from django.utils.timezone import localtime from actstream impo...
Choices(( ('push', 'PUSH', _('pushed')), ('pump', 'PUMP', _('pumped')), ('paddle', 'PADDLE', _('paddled')), )) skater = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='trips') type = models.CharField(verbose_name=_('Type')...
e=_('End time'), editable=False) distance = models.DecimalField(verbose_name=_('Distance'), max_digits=5, decimal_places=2) notes = models.TextField(verbose_name=_('Notes'), default='', blank=True) duration = TimedeltaField(verbose_name=_('Duration')) avg_speed = models.DecimalField(_('Avg. Speed...
jiobert/python
Velez_Felipe/Asignments/draw_stars.py
Python
mit
300
0.066667
x = [4,6,1,3,5,7,25] y = [4, "Tom", 1, "Michael", 5, 7, "Jimmy Smith"] def draw_stars(x): index = 0 while index < len(x): if type(x[index])is str: first_letter = x[index].lower() print first_letter[0] * len(first_l
etter) else: print "*" * x[index] index = index + 1 dr
aw_stars(y)
Kupoman/yggdrasil
docs/ext/breathe/renderer/rst/doxygen/domain.py
Python
apache-2.0
6,928
0.003897
class DomainHelper(object): pass class NullDomainHelper(DomainHelper): pass class CppDomainHelper(DomainHelper): def __init__(self, definition_parser, substitute): self.definition_parser = definition_parser self.substitute = substitute self.duplicates = {} def check_cache...
(target,) = self.target_handler.create_target(name)
inv = self.env.domaindata['c']['objects'] if name in inv: self.env.warn( self.env.docname, 'duplicate C object description of %s, ' % name + 'other instance in ' + self.env.doc2path(inv[name][0]), self.lineno) inv[name] = (s...
reviewboard/reviewboard
reviewboard/hostingsvcs/tests/test_client.py
Python
mit
29,598
0
"""Test cases for the hosting service client support.""" from kgb import SpyAgency from reviewboard.hostingsvcs.models import HostingServiceAccount from reviewboard.hostingsvcs.service import (HostingService, HostingServiceClient, ...
ed_message): HostingServiceHTTPRequest( url='http://example.com?z=1&z=2&baz=true', method='POST', body=123, hosting_service=service) def test_init_with_header_key_not_unicode(self): """Testing HostingServiceHTTPRequest construction...
tingService(account) expected_message = ( 'Received non-Unicode header %r (value=%r) for the HTTP request ' 'for %r. This is likely an implementation problem. Please make ' 'sure only Unicode strings are sent in request headers.' % (b'My-Header', 'abc', HostingSe...
live4thee/zstack-utility
cephbackupstorage/cephbackupstorage/cephagent.py
Python
apache-2.0
33,834
0.00269
__author__ = 'frank' import os import os.path import pprint import re import traceback import urllib2 import zstacklib.utils.daemon as daemon import zstacklib.utils.http as http import zstacklib.utils.jsonobject as jsonobject from zstacklib.utils import lock from zstacklib.utils import linux from zstacklib.utils impo...
# on the Content-type line" ib = entity.content_type.params['boundary'].strip('"') if not re.match("^[ -~]{0,200}[!-~]$", ib): raise ValueError('Invalid boundary in multipart form: %r' % (ib,)) ib = ('--' + ib).encode('ascii') # Find the first marker while True: b = entity....
line() if not b: return b = b.strip() if b == ib: break return ib def stream_body(task, fpath, entity, boundary): def _progress_consumer(total): task.downloadedSize = total @thread.AsyncThread def _do_import(task, fpath): shell.check_ru...
CloCkWeRX/rabbitvcs-svn-mirror
rabbitvcs/ui/property_page.py
Python
gpl-2.0
7,016
0.009407
# # This is an extension to the Nautilus file manager to allow better # integration with the Subversion source control system. # # Copyright (C) 2010 by Jason Heeris <[email protected]> # # RabbitVCS is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
WidgetWrapper.__init__(self, claim_domain=claim_domain) self.path = path self.vcs = vcs or rabbitvcs.vcs.VCS() self.checker = StatusChecker() self.get_widget("file_name").set_text(os.path.basename(path)) ...
invalidate = False, summary = False) self.get_widget("vcs_type").set_text(self.status.vcs_type) self.get_widget("content_status").set_text(unicode(self.status.simple_content_status())) self.get_widget("prop_statu...
Ernti/GG
gg/GGobjectlist.py
Python
gpl-2.0
491
0
''' Created on 17 Dec 2013 @author:
tore ''' class ObjectList(object): def __init__(self): self.objectlist = [] self.windowlist = [] def addObject(self, listobject): self.objectlist.append(listobject) def removeObject(self, listobject): self.objectlist.remove(listobject) def addWindow(self, listobj...
lf.windowlist.remove(listobject)
bollu/polymage
sandbox/apps/python/img_proc/lens_blur/main.py
Python
apache-2.0
632
0.007911
import numpy as np import time import sys from __init__ i
mport * from i
nit import init_all from printer import print_header, print_config, print_line from builder import create_lib,build_lensblur from exec_pipe import lensblur #from app_tuner import auto_tune app = "lens_blur" def main(): print_header() app_data = {} app_data['app'] = app app_data['ROOT'] = ROOT in...
baroquehq/baroque
baroque/datastructures/counters.py
Python
mit
1,120
0.002679
from baroque.entities.event import Event class EventCounter: """A counter of events.""" def __init__(self): self.events_count = 0 self.events_count_by_type = dict() def increment_counting(self, event): """Counts an event Args: event (:obj:`baroque.entities.ev...
+= 1 else: self.events_count_by_type[t] = 1 def count_all(self): """Tells how many events have been counted globally Returns: int """ return self.events_count def count(self, eventtype): """Tells how many events have been counted of th...
t """ return self.events_count_by_type.get(type(eventtype), 0)
greglandrum/rdkit
rdkit/VLib/NodeLib/SmilesOutput.py
Python
bsd-3-clause
2,131
0
# $Id$ # # Copyright (C) 2003 Rational Discovery LLC # All Rights Reserved # from rdkit import Chem from rdkit.VLib.Output import OutputNode as BaseOutputNode class OutputNode(BaseOutputNode): """ dumps smiles output Assumptions: - destination supports a write() method - inputs (parents) ...
StringIO >>> sio = StringIO() >>> node = OutputNode(dest=sio,delim=', ') >>> node.AddParent(suppl) >>> ms = [x for x in node] >>> len(ms) 4 >>> txt = sio.getvalue() >>> repr(txt) "'1, C1CCC1\\\\n2, C1CC1\\\\n3, C=O\\\\n4, CCN\\\\n'" """ def __init__(self, ...
BaseOutputNode.__init__(self, dest=dest, strFunc=self.smilesOut) self._dest = dest self._idField = idField self._delim = delim self._nDumped = 0 def reset(self): BaseOutputNode.reset(self) self._nDumped = 0 def smilesOut(self, mol): self._nDumped += 1 ...
summanlp/textrank
test/test_keywords.py
Python
mit
7,150
0.003776
import unittest from summa.keywords import keywords from summa.preprocessing.textcleaner import deaccent from numpy import isclose from .utils import get_text_from_test_data class TestKeywords(unittest.TestCase): def test_text_keywords(self): text = get_text_from_test_data("mihalcea_tarau.txt") ...
racters. text = get_text_from_test_data("spanish.txt") kwds = keywords(text, language="spanish", deaccent=False, split=True) # Verifies that there are some keywords are retrieved with accents. self.assertTrue(any(deaccent(keyword) != keyword for keyword in kwds)) def test_text_as_by...
word extraction for a text that is not a unicode object # (Python 3 str). text = get_text_from_test_data("spanish.txt") bytes = text.encode(encoding="utf-8") with self.assertRaises(ValueError): keywords(bytes, language="spanish") if __name__ == '__main__': unittest.main...
waterponey/scikit-learn
sklearn/ensemble/tests/test_gradient_boosting.py
Python
bsd-3-clause
40,529
0.000099
""" Testing for the gradient boosting module (sklearn.ensemble.gradient_boosting). """ import warnings import numpy as np from itertools import product from scipy.sparse import csr_matrix from scipy.sparse import csc_matrix from scipy.sparse import coo_matrix from sklearn import datasets from sklearn.base import clo...
assert_raises(ValueError, lambda X, y: Gradie
ntBoostingClassifier( loss='deviance').fit(X, y), X, [0, 0, 0, 0]) def test_loss_function(): assert_raises(ValueError, GradientBoostingClassifier(loss='ls').fit, X, y) assert_raises(ValueError, GradientBoostingClassifier(loss='lad').f...
andybondar/CloudFerry
cloudferrylib/os/network/neutron.py
Python
apache-2.0
47,578
0.000504
# Copyright (c) 2014 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the License); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, so...
'lb_monitor': NeutronNetwork.convert_lb_monitors, 'lb_vip': NeutronNetwork.convert_lb_vips } return obj_map[obj_name](neutron_object, cloud) @staticmethod def con
vert_networks(net, cloud): identity_res = cloud.resources[utl.IDENTITY_RESOURCE] net_res = cloud.resources[utl.NETWORK_RESOURCE] get_tenant_name = identity_res.get_tenants_func() subnet_names = [] for subnet in net['subnets']: name = net_res.neutron_client.show_subne...
hexlism/css_platform
sleepyenv/bin/pilfont.py
Python
apache-2.0
209
0
#!/home/firlism/tools/css_platform/sleepyenv/bin/python # EASY-INSTALL-SCRIPT: 'Pillow==2.8.2','pil
font.py' __requires__ = 'Pillow==2.8.2' __import__('pkg_resources').run_script('Pillow=
=2.8.2', 'pilfont.py')
Physiolution-Polska/MoDDiss
gui/__init__.py
Python
gpl-2.0
52
0
""" Package for graphics user interface
meth
ods """
sevaivanov/various
python/server/twisted/purely-twisted.py
Python
mit
887
0.00451
import sys from twisted.python import log from twisted.internet import reactor from twisted.internet.protocol import ServerFactory, ClientFactory, Protocol class EchoServerProtocol(Protocol): def dataReceived(self, data): log.msg('Data received %s' % data) self.transport.write(b'Server push back: %...
f connectionMade(self): log.msg('Client connection from %s' % self.transport.getPeer()) def connectionLost(self, reason): log.msg('Lost connection because %s' % reason) class EchoServerFactory(ServerFactory): def buildProtocol(self, addr): return EchoServerProtocol() if __name__ == '_...
ng(sys.stdout) log.msg('Starting twisted engines...') server = EchoServerFactory() reactor.listenTCP(8080, server) log.msg('Listening on http://127.0.0.1:8080') reactor.run()
Eleyvie/wreck
integrated/headers/header_items.py
Python
mit
14,843
0.019605
################################################### # header items.py # This file contains declarations for items # DO NOT EDIT THIS FILE! ################################################### #item flags itp_type_horse = 0x0000000000000001 itp_type_one_handed_wpn = 0x0000000000000002 itp_type_two_ha...
e_bits = 58 iwf_thrust_damage_bits = 60 iwf_thrust_damage_type_bits = 68 iwf_weapon_length_bits = 70 iwf_speed_rating_bits = 80 iwf_shoot_speed_bits = 90 iwf_max_ammo_bits = 100 # use this for shield endurance too? iwf_abundance_bits = 110 iwf_accuracy_bits ...
_armor_mask return 0.25 * a def get_head_armor(y): return (y >> ibf_head_armor_bits) & ibf_armor_mask def get_body_armor(y): return (y >> ibf_body_armor_bits) & ibf_armor_mask def get_leg_armor(y): return (y >> ibf_leg_armor_bits) & ibf_armor_mask def get_difficulty(y): return (y >> ibf_diff...
shsingh/ansible
lib/ansible/modules/network/aci/aci_l3out_route_tag_policy.py
Python
gpl-3.0
6,992
0.001573
#!/usr/bin/python # -*- coding: utf-8 -*- # 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__ = ty
pe ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'certified'} DOC
UMENTATION = r''' --- module: aci_l3out_route_tag_policy short_description: Manage route tag policies (l3ext:RouteTagPol) description: - Manage route tag policies on Cisco ACI fabrics. version_added: '2.4' options: rtp: description: - The name of the route tag policy. type: str required: yes alias...
Davidhw/WikipediaEditScrapingAndAnalysis
scraping_wikipedia_links/popular_articles/popular_articles/items.py
Python
gpl-2.0
276
0.003623
# Define here
the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html from scrapy.item import Item, Field class PopularArticlesItem(Item): # define the fields
for your item here like: # name = Field() pass
3dinfluence/opensprinklerlib
opensprinklerlib/controller/gpio_compatible.py
Python
mit
1,943
0.002059
#!/usr/bin/env python try: # Attempt to load RPi Module import RPi.GPIO as GPIO except: try: # Attempt to load Beagle Bone Module import Adafruit_BBIO.GPIO as GPIO except: pass from controller import * class GPIOCompatible(Controller): """GPIO interface compatible Control...
ass__ = abc.ABCMeta def __init__(se
lf): """GPIO Compatible Class Initializer """ super(GPIOCompatible, self).__init__() def __del__(self): self._shiftOut() GPIO.cleanup() def _init_hardware(self): self._setup_pins() self._init_gpio() @abc.abstractmethod def _setup_pins(self): ...
ancho85/pylint-playero-plugin
tests/input/func_noerror_query_heir.py
Python
gpl-2.0
522
0.011494
# pylint:disable=R0201 from OpenOrange import * from User import User from RetroactiveAccounts import RetroactiveAccounts class
HeirFinder(RetroactiveAccounts): def doReplacements(self, txt): d = {1:"ONE", 2:"TWO"} us = User.bring("USER") txt = txt.replace(":1", us.Name + d[1]) return txt def run(self): query8 = self.getQuery() query8.sql = self.doReplacements(query8.sql) #pylin...
6601 query8.open() #there will be missing tables here
mmnelemane/nova
nova/tests/unit/api/ec2/test_ec2_validate.py
Python
apache-2.0
11,301
0.001327
# Copyright 2012 Cloudscaling, Inc. # All Rights Reserved. # Copyright 2013 Red Hat, 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/L...
fake_network.set_stub_network_methods(self.stubs) # set up our cloud self.cloud = cloud.CloudController() # Short-circuit the conductor service self.flags(use_local=True, group='conductor') # Stub out the notification service so we use the no-op serializer # an...
notifier.stub_notifier(self.stubs) self.addCleanup(fake_notifier.reset) # set up services self.conductor = self.start_service('conductor', manager=CONF.conductor.manager) self.compute = self.start_service('compute') self.scheduter = self.start_service('scheduler'...
erdavila/git-svn-diff
tests/impl/git.py
Python
mit
1,477
0.024374
import os.path import subprocess import shutil class GitImpl(object): def __init__(self): from svn import SvnImpl svn_impl = SvnImpl(suffix='-git') shutil.rmtree(svn_impl.client_path) self.temp_path = svn_impl.temp_path self.server_path = svn_impl.server_path self.client_path = os.path.join(self.temp_p...
t.strip() assert commit != '' revisions = [commit] diff_file = os.path.join(self.temp_path, 'git.diff') with open(diff_file, 'w') as f: cmd = ['git', 'diff', '--
no-prefix'] + revisions subprocess.check_call(cmd, cwd=self.client_path, stdout=f) return diff_file
irdan/marionette
marionette_tg/__init__.py
Python
apache-2.0
6,400
0.001563
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import random sys.path.append('.') from twisted.internet import reactor import marionette_tg.driver import marionette_tg.multiplexer import marionette_tg.record_layer import marionette_tg.updater EVENT_LOOP_FREQUENCY_S = 0.01 AUTOUPDATE_DELAY = 5 class Mari...
factory = None def __init__(self, format_name): self.multiplexer_outgoing_ = marionette_tg.multiplexer.BufferOutgoing() self.multiplexer_incoming_ = marionette_tg.multiplexer.BufferIncoming() self.multiplexer_incoming_
.addCallback(self.process_cell) self.factory_instances = {} if self.check_for_update(): self.do_update() self.set_driver(format_name) self.reload_ = False def set_driver(self, format_name): self.format_name_ = format_name self.driver_ = marionette_tg.d...
djpine/pyman
Book/chap7/Supporting Materials/daysBtwnDates.py
Python
cc0-1.0
740
0.02027
import numpy as np def leapyear(year): if year%4 != 0: return False elif year%400 == 0: return True elif year%100 == 0: return False else: return True def leapyearcount(years): a = np.where(years%4==0, 1, 0) b = np.where(years%100==0, -1, 0) c = np.where(yea...
eapyear(year))) print(leapyearcount(np.arange(1899,1999))) out = daysBtwnDates("2012-Sep-21", "2
013-Jan-15") print(out)
marrow/WebCore
web/core/__init__.py
Python
mit
424
0.004717
# encoding: utf-8 # ## Imports from threading import local
as __local # Expose these
as importable from the top-level `web.core` namespace. from .application import Application from .util import lazy # ## Module Globals __all__ = ['local', 'Application', 'lazy'] # Symbols exported by this package. # This is to support the web.ext.local extension, and allow for early importing of the variable. lo...
master-q/ATS-Postiats-contrib
contrib/libatscc/libatscc2py/CATS/string_cats.py
Python
mit
791
0.007585
###### # # HX-20
14-08: # for Python code translated from ATS # ###### ###### #beg of [string_cats.py] ###### ###### from ats2pypre_basics_cats import * ###### ############################################ def atspre_strlen(x): return (x.__len__()) ############################################ def ats2pypre_string_get_at(x, i): ret...
###### def ats2pypre_string_isalnum(x): return (x.isalnum()) def ats2pypre_string_isalpha(x): return (x.isalpha()) def ats2pypre_string_isdecimal(x): return (x.isdecimal()) ############################################ def ats2pypre_string_lower(x): return (x.lower()) def ats2pypre_string_upper(x): return (x.upper())...
stryder199/RyarkAssignments
Assignment2/web2py/gluon/storage.py
Python
mit
5,788
0.002592
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <[email protected]> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) Provides: - List; like list but returns None instead of IndexOutOfBounds - Storage; like dictionary allowi...
f[key] = [] return self[key] def load_sto
rage(filename): fp = open(filename, 'rb') portalocker.lock(fp, portalocker.LOCK_EX) storage = cPickle.load(fp) portalocker.unlock(fp) fp.close() return Storage(storage) def save_storage(storage, filename): fp = open(filename, 'wb') portalocker.lock(fp, portalocker.LOCK_EX) cPickle....
biosustain/marsi
marsi/cli/app.py
Python
apache-2.0
1,357
0.000737
# Copyright 2016 Chr. Hansen A/S and The Novo Nordisk Foundation Center for Biosustainability, DTU. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the Licen
se 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 governing ...
import ChemistryController from marsi.cli.controllers.database import DatabaseController from marsi.cli.controllers.modeling import OptimizationController class MarsiApp(CementApp): class Meta: label = 'marsi' base_controller = 'base' handlers = [ MarsiBaseController, ...
ArchAssault-Project/archassaultweb
todolists/migrations/0005_add_slugs.py
Python
gpl-2.0
9,702
0.007833
# -*- coding: utf-8 -*- from south.db import db from south.v2 import DataMigration from django.db import models from django.template.defaultfilters import slugify class Migration(DataMigration): def forwards(self, orm): existing = list(orm.Todolist.objects.values_list( 'slug', flat=True).dist...
lds.CharField', [], {'max_length': '255'}), 'repo': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'packages'", 'on_delete': 'models.PROTECT', 'to': "orm['main.Repo']"}), 'url': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}) }, ...
'Meta': {'ordering': "('name',)", 'object_name': 'Repo', 'db_table': "'repos'"}, 'bugs_category': ('django.db.models.fields.SmallIntegerField', [], {'default': '2'}), 'bugs_project': ('django.db.models.fields.SmallIntegerField', [], {'default': '1'}), 'id': ('django.db.models.fields...
rajpushkar83/pbs
cloudmesh_pbs/DbPBS.py
Python
apache-2.0
4,729
0.000846
from __future__ import print_function import os import abc import shelve from pprint import pprint from cloudmesh_base.tables import dict_printer from cloudmesh_base.Shell import Shell from cloudmesh_base.util import banner from cloudmesh_base.util import path_expand from cloudmesh_pbs.OpenPBS import OpenPBS class...
tput) return None def qsub(self, name, host, script, template=None, kind="dict"): r = self.pbs.qsub(name, host, script, template=template, kind=kind) pprint(r) return dict(r) if __name__ == "__main__": qsub = False db = DbPBS() db.clear() db.info
() db.update(host="india", user=False) print(db.list(output="table")) print(db.list(output="csv")) print(db.list(output="dict")) print(db.list(output="yaml")) banner("user") db.clear() db.update(host="india") print(db.list(output="table")) if qsub: banner('qsub') ...