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
mountaindust/Parasitoids
tests/test_ParsitoidModel.py
Python
gpl-3.0
14,934
0.014062
""" Test suite for ParasitoidModel, for use with py.test Created on Fri May 08 12:12:19 2015 Author: Christopher Strickland Email: wcstrick@live.unc.edu """ import pytest import numpy as np import math from scipy import sparse, signal import ParasitoidModel as PM import globalvars ##################################...
rt_time == '00:30': assert all(wind_data[days[0]][0,:] == wind_data_raw[days[0]][0,:]) assert all(wind_data[days[0]][interp_num-1,:] == wind_data_raw[days[0]][0,:]) for ii in range(wind_data_raw[days[0]].shape[0]-1): assert all(wind_data[days[0]][interp_num*(1+ii),:] == ...
data[days[-1]][-1,:] == wind_data_raw[days[-1]][-1,:]) assert all(wind_data[days[-1]][-interp_num+1,:] == wind_data_raw[days[-1]][-1,:]) for ii in range(wind_data_raw[days[0]].shape[0]-1): assert all(wind_data[days[0]][interp_num*(ii),:] == wind_data_raw[days[0]][...
pyfa-org/Pyfa
service/conversions/releaseOct2021.py
Python
gpl-3.0
225
0.004444
""" Conversion pack for October 2021 release """ CONVERSIO
NS = { # Renamed items "Quafe Zero": "Quafe Zero Classic", "Exigent Sentry Drone Navigation Mutapla
smid": "Exigent Sentry Drone Precision Mutaplasmid", }
ChainBoy/init_python_project
utils/environment.py
Python
apache-2.0
5,907
0.000727
# -*- coding:utf-8 -*- # @version: 1.0 # @author: # @date: '14-4-10' import os import logging import threading from ConfigParser import ConfigParser from ConfigParser import NoSectionError, InterpolationMissingOptionError, Error import simplejson as json from utils.logger import Logger _lock = ...
工作目录的一级子文件夹下,深度为2, 以此类推。 """ self._working_path, self._app_name = self._parse_start_file_name( start_file_name, start_file_depth) self._set_working_path(self._working_path) self._init_logger() self._configure_parser = ConfigParser() self._is_confi...
return self.get_configure_value(db_setting_section_name, "host"), \ self.get_configure_value(db_setting_section_name, "db"), \ self.get_configure_value(db_setting_section_name, "user"), \ self.get_configure_value(db_setting_section_name, "passwd") def get_app_name(self):...
nkgilley/home-assistant
homeassistant/components/homekit_controller/storage.py
Python
apache-2.0
2,471
0.000405
"""Helpers for HomeKit data stored in HA storage.""" from homeassistant.core import callback from homeassistant.helpers.storage import Store from .const import DOMAIN ENTITY_MAP_STORAGE_KEY = f"{DOMAIN}-entity-map" ENTITY_MAP_STORAGE_VERSION = 1 ENTITY_MAP_SAVE_DELAY = 10 class EntityMapStorage: """ Holds ...
HomeKit has a cacheable entity map that describes how an IP or BLE endpoint is structured. This object holds the latest copy of that data. An endpoint is made of accessories, services and characteristics. It is safe to cache this data until the c# discovery data changes. Caching thi
s data means we can add HomeKit devices to HA immediately at start even if discovery hasn't seen them yet or they are out of range. It is also important for BLE devices - accessing the entity structure is very slow for these devices. """ def __init__(self, hass): """Create a new entity map ...
jianajavier/pnc-cli
test/unit/test_productreleases.py
Python
apache-2.0
4,762
0.0021
__author__ = 'thauser' from mock import patch, MagicMock from pnc_cli import productreleases from pnc_cli.swagger_client.models import ProductReleaseRest def test_create_product_release_object(): compare = ProductReleaseRest() compare.version = '1.0.1.DR1' compare.support_level = 'EOL' result = produc...
sult @patch('pnc_cli.productreleases.create_product_release_object', return_value='created release') @patch('pnc_cli.productreleases.releases_api.create_new', return_value=MagicMock(content='created release')) @patch('pnc_cli.productreleases.productversions_api.get_specific', r
eturn_value=MagicMock(content=MagicMock(version='1.0'))) def test_create_release(mock_get_specific, mock_create_new, mock_create_object): result = productreleases.create_release(version='0.DR1', release_date='2016-01-01', downlo...
zac11/AutomateThingsWithPython
Lists/list_concat.py
Python
mit
155
0.058065
list2=['tom','jerry','mickey'] list1=['hardy','bob','minnie'] print(list1+lis
t2) print(list2+list1) p
rint(list1*3) print(list2+['disney','nick','pogo'])
scalingdata/Impala
thirdparty/hive-1.2.1.2.3.0.0-2557/lib/py/thrift/reflection/__init__.py
Python
apache-2.0
807
0.001239
# Licensed to the Apache Software Foundation (ASF) und
er 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 use this file except in compliance # with the License. ...
in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __all__ = ['limited']
TunnelBlanket/Houdini
Houdini/Data/Ban.py
Python
mit
936
0.007479
# coding: utf-8 from sqlalchemy import Column, DateTime, ForeignKey, Integer, Text, text from sqlalchemy.orm import relationship from Houdini.Data import Base metadata = Base.metadata class Ban(Base):
__tablename__ = 'ban' PenguinID = Column(ForeignKey(u'penguin.ID', ondelete=u'CASCADE', onupdate=u'CASCADE'), primary_key=True, nullable=False) Issued = Column(DateTime, primary_key=True, nullable=False, server_default=text("current_timestamp()")) Expires = Column(DateTime, primary_key=True, nullable=Fals...
teger, nullable=False) Comment = Column(Text) penguin = relationship(u'Penguin', primaryjoin='Ban.ModeratorID == Penguin.ID') penguin1 = relationship(u'Penguin', primaryjoin='Ban.PenguinID == Penguin.ID')
kraziegent/mysql-5.6
xtrabackup/test/python/subunit/tests/test_subunit_tags.py
Python
gpl-2.0
2,267
0.000882
# # subunit: extensions to python unit
test to get test results from subprocesses. # Copyright (C) 2005 Robert Collins <robertc@robertcollins.net> # # Licensed under either the Apache License, Version 2.0 or the BSD 3-clause # license at the users choice. A copy of both licenses are available in the # project source as Apache-2.0 and BSD. You may not u...
Unless required by applicable law or agreed to in writing, software # distributed under these licenses is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # license you chose for the specific language governing permissions and # limitations under...
wangzheng0822/algo
python/23_binarytree/binary_tree.py
Python
apache-2.0
2,175
0.001839
""" Pre-order, in-order and post-order traversal of binary
trees. Aut
hor: Wenru Dong """ from typing import TypeVar, Generic, Generator, Optional T = TypeVar("T") class TreeNode(Generic[T]): def __init__(self, value: T): self.val = value self.left = None self.right = None # Pre-order traversal def pre_order(root: Optional[TreeNode[T]]) -> Generator[T,...
TimBuckley/effective_django
django/test/signals.py
Python
bsd-3-clause
4,520
0
import os import time import threading import warnings from django.conf import settings from django.db import connections from django.dispatch import receiver, Signal from django.utils import timezone from django.utils.functional import empty template_rendered = Signal(providing_args=["template", "context"]) setting...
here the receiver is related to a contrib app. # Settings that may not work well when using 'override_settings' (#19031) COMPLEX_OVERRIDE_SETTINGS = set(['DATABASES']) @receiver(setting_changed) def clear_cache_handlers(**kwargs): if kwargs[
'setting'] == 'CACHES': from django.core.cache import caches caches._caches = threading.local() @receiver(setting_changed) def update_installed_apps(**kwargs): if kwargs['setting'] == 'INSTALLED_APPS': # Rebuild any AppDirectoriesFinder instance. from django.contrib.staticfiles.fin...
youtube/cobalt
third_party/skia_next/third_party/skia/infra/bots/assets/ccache_mac/create.py
Python
bsd-3-clause
1,385
0.01083
#!/usr/bin/env python # # Copyright 2016 Google Inc. # # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Create a ccache binary for mac hosts.""" import argparse import os import subprocess import sys FILE_DIR = os.path.dirname(os.path.abspath(__file__)) INFRA...
heck_call(["make" ,"install"]) def main(): parser = argparse.ArgumentParser() parser.add_argumen
t('--target_dir', '-t', required=True) args = parser.parse_args() create_asset(args.target_dir) if __name__ == '__main__': main()
jeroenk/artisanConvert
odl/odl_extract.py
Python
bsd-3-clause
30,114
0.005678
# Copyright (c) 2011, 2012, Jeroen Ketema, University of Twente # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice,...
sion def GetId(data): for item in data: if item[0] == "Attribute" \ and item[1] == "_Art1_Id": return item[2][0] raise OdlExtractException("No model identifier found") def GetModel(odl_data): for ident in odl_data: if odl_data[ident][0] == "_Art1_Model": ...
odel_id = GetId(odl_data[ident][1]) name = ident.replace(' ', '_').replace('-', '_').replace('&', "and") return (model_id, name) raise OdlExtractException("No model name found") def GetName(data): version = GetVersion(data) return version[1][6:].replace(' ', '_') \ .replace...
jessamynsmith/my_project
my_project/urls.py
Python
mit
837
0
"""my_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-ba...
name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import include,
path from app1 import urls as app1_urls urlpatterns = [ path('admin/', admin.site.urls), path('app1/', include(app1_urls)), ]
homecoded/radioberry
radio/TextRenderer.py
Python
mit
779
0.002567
import pygame fonts = [] is_initialized = False FONT_TINY = 0 FONT_SMALL = 1 FONT_BIG = 2 CENTER_X = 'center_x' def render(text, x, y, font_id, surface, render_mode=0): global is_initialized global fonts if not is_initialized: fonts = [ pygame.font.Font('gfx/MunroSmall.ttf', 10), ...
mall.ttf', 20), pygame.font.Font('gfx/MunroSmall.ttf', 40) ] is_initialized = True temp_surface = fonts[font
_id].render(text, 0, (255, 0, 0)) if render_mode == CENTER_X: text_rect = temp_surface.get_rect() text_rect.x = x - tuple(text_rect)[2]/2 text_rect.y = y surface.blit(temp_surface, text_rect) else: surface.blit(temp_surface, (x, y))
shweta97/pyta
examples/pylint/E0203_access_member_before_definition.py
Python
gpl-3.0
121
0
class MyClass: def __
init__(self): p
rint(self.a) # Haven't defined self.a yet, can't use self.a = 5
zuun77/givemegoogletshirts
leetcode/python/739_daily-temperatures.py
Python
apache-2.0
367
0.002725
class Solution: def dailyTemperatures(self, T): ans = []
m = [None]*101 for i in range(len(T)-1, -1, -1): x = T[i] m[x] = i ans.append(min([x for x in m[x+1:] if x is not None], default=i)-i) ans.reverse() return ans print(Soluti
on().dailyTemperatures([73, 74, 75, 71, 69, 72, 76, 73]))
therealjumbo/python_summer
py31eg/average2_ans.py
Python
gpl-3.0
1,820
0
#!/usr/bin/env python3 # Copyright (c) 2008-11 Qtrac Ltd. All rights reserved. # This program or module 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...
nt("numbers:", numbers) if numbers: print("count =", len(numbers), "total =", total, "lowest =", lowest
, "highest =", highest, "mean =", total / len(numbers), "median =", median)
mcallaghan/tmv
BasicBrowser/tmv_app/migrations/0081_auto_20180216_1308.py
Python
gpl-3.0
767
0
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2018-02-16 13:
08 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tmv_app', '0080_auto_20180214_1234'), ] operations = [ migrations.AddField( model_name='dynamictopic', name='ipcc_score',...
name='ipcc_share', field=models.FloatField(null=True), ), migrations.AddField( model_name='dynamictopic', name='share', field=models.FloatField(null=True), ), ]
brainwane/zulip
zerver/lib/bulk_create.py
Python
apache-2.0
6,975
0.004301
from typing import Any, Dict, Iterable, List, Optional, Set, Tuple, Union from django.db.models import Model from zerver.lib.create_user import create_user_profile, get_display_email_address from zerver.lib.initial_password import initial_password from zerver.lib.streams import render_stream_description from zerver.m...
= recipient objects_to_update.add(result) model.objects.bulk_update(objects_to_update, ['recipient']) # This is only sed in populate_db, so doesn't really need tests def bulk_create_streams(realm: Realm, stream_dict: Dict[str, Dict[str, Any]]) -> None: # nocoverage exis
ting_streams = frozenset([name.lower() for name in Stream.objects.filter(realm=realm) .values_list('name', flat=True)]) streams_to_create: List[Stream] = [] for name, options in stream_dict.items(): if 'history_public_to_subscribers' no...
asceth/sinan
support/support.py
Python
mit
1,629
0.003683
"""Support for building sinan, bootstraping it on a new version of erlang""" import sys import os import commands from optparse import OptionParser class BuildError(Exception): def __init__(self, value): self.value = v
alue def __str__(self): return repr(self.value) ERTS_VERSION = "5.6.3" BUILD_PATH = "_build/development/apps/%s/ebin" ERLWARE_PATH = "/usr/local/erlware" ERLC = "erlc +debug_info " LOCAL_APPS = [("etask", "0.5.0"), ("sinan", "0.11.0.2"), ("sinan_web_api", "0.1.0.5")] ERLWAR...
"eunit-2.0", "cryptographic-0.2.1", "ewlib-0.8.2.0", "ewrepo-0.19.0.0", "gas-6.1.1", "kernel-2.12.3", "ibrowse-1.4", "uri-0.2.0", "sgte-0.7.1", "gtime-0.9.4", ...
laurenrevere/osf.io
api_tests/reviews/mixins/filter_mixins.py
Python
apache-2.0
9,384
0.001492
from datetime import timedelta import pytest from furl import furl from api.preprint_providers.permissions import GroupHelper from osf_tests.factories import ( ReviewActionFactory, AuthUserFactory, PreprintFactory, PreprintProviderFactory, ProjectFactory, ) def get_actual(app, url, user=None, so...
ect=ProjectFactory(is_public=True) ) for _ in range(5): actions.append(ReviewActionFactory(target=preprint)) return actions @pytest.fixture() def allowed_providers(self, providers): return providers @pytest.fixture() def expected_actions(self, al...
all_actions if a.target.provider_id in provider_ids] @pytest.fixture() def user(self, allowed_providers): user = AuthUserFactory() for provider in allowed_providers: user.groups.add(GroupHelper(provider).get_group('moderator')) return user def test_filter_actions(self,...
Timidger/mackup
mackup/constants.py
Python
gpl-3.0
677
0
"""Constants used in Mackup.""" # Current version VERSION = '0.8.7' # Support platforms PLATFORM_DARWIN = 'Darwin' PLATFORM_LINUX = 'Linux' # Directory containing the application configs APPS_DIR = 'applications' # Mackup application name MACKUP_APP_NAME = 'mackup' # Default Mackup
backup path where it stores its files in Dropbox MACKUP_BACKUP_PATH = 'Mackup' # Mackup config file MACKUP_CONFIG_FILE = '.mackup.cfg' # Di
rectory that can contains user defined app configs CUSTOM_APPS_DIR = '.mackup' # Supported engines ENGINE_DROPBOX = 'dropbox' ENGINE_GDRIVE = 'google_drive' ENGINE_BOX = 'box' ENGINE_COPY = 'copy' ENGINE_ICLOUD = 'icloud' ENGINE_FS = 'file_system'
mohlerm/hotspot
evaluation/eval_octane.py
Python
gpl-2.0
763
0.011796
import os import re import glob import sys #print(str(sys.argv[1])) files = glob.glob(r'/disk2/octane_node160/'+str(sys.argv[1])+'/*.*') files.sort() #print(files) result = [] for infile in files: linestring = infile[28:] f = open(infile) file = f.read() f.close() m = re.search(r"Score \(version 9\)...
"Warmup (120s): " + m.group(1)) linestring = linestring + (m.group(1)) m = re.search(r"DEOPT COUNTER\: (\d*)", file) linestring = linestring +(";") if(m is not None): # print("DEOPT Counter: " + m.group(1)) linestring = linestring +(m.grou
p(1)) result.append(linestring) result.sort() for b in result: print(b);
adityahase/frappe
frappe/website/doctype/website_settings/test_website_settings.py
Python
mit
227
0.008811
# -*- coding: utf-8 -*- # Copyright (c) 2020, Frappe Technologies and Co
ntributors # See license.txt from __future__ import unicode_literals # import frappe impor
t unittest class TestWebsiteSettings(unittest.TestCase): pass
Elfhir/apero-imac
product/views.py
Python
mpl-2.0
671
0.026826
from product.models import * from django.shortcuts import render_to_response from django.views.generic import ListView, DetailView from datetime import datetime class ListDrink(ListView): model = Drink context_object_name = "product_list" template_name = "product_list.html" paginate_by = 5 class DetailDrink(Deta...
uct.html" class ListAppetizer(ListView): model = Appetizer context_object_name = "product_list" template_name = "product_list.html"
paginate_by = 5 class DetailAppetizer(DetailView): model = Appetizer context_object_name = "product" template_name = "product.html"
JeroenZegers/Nabu-MSSS
nabu/postprocessing/scorers/bss_eval.py
Python
mit
57,733
0.001472
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Source separation algorithms attempt to extract recordings of individual sources from a recording of a mixture of sources. Evaluation methods for source separation compare the extracted sources from reference sources and attempt to measure the perceptual quality of th...
le number of sources (prevents insane computational load) MAX_SOURCES = 100 def filter_kwargs(_function, *args, **kwargs): """Given a function and args and keyword args to pass to it, call the function but using only the keyword arguments which it accep
ts. This is equivalent to redefining the function with an additional \*\*kwargs to accept slop keyword args. If the target function already accepts \*\*kwargs parameters, no filtering is performed. Parameters ---------- _function : callable Function to call. Can take in any numbe...
CZ-NIC/knot
tests-extra/tests/modules/onlinesign/test.py
Python
gpl-3.0
2,463
0.001624
#!/usr/bin/env python3 '''Check online DNSSEC signing module (just basic checks).''' import dns.rdatatype from dnstest.test import Test from dnstest.utils import * from dnstest.module import ModOnlineSign t = Test(stress=False) ModOnlineSign.check() knot = t.server("knot") zones = t.zone_rnd(4, dnssec=False, recor...
4", key_size="384")) knot.dnssec(zones[2]).enable = True knot.dnssec(zones[3]).enable = True knot.dnssec(zones[3]).nsec3 = True def check_zone(zone, dnskey_rdata_start): # Check SOA record. soa1 = knot.dig(zone.name, "SOA", dnssec=True) soa1.check(rcode="NOERROR", flags="QR AA")
soa1.check_count(1, "RRSIG") t.sleep(1) # Ensure different RRSIGs. soa2 = knot.dig(zone.name, "SOA", dnssec=True) soa2.check(rcode="NOERROR", flags="QR AA") soa2.check_count(1, "RRSIG") for rrset in soa1.resp.answer: if rrset.rdtype == dns.rdatatype.SOA: if rrset not in soa...
orientechnologies/pyorient
tests/test_record_contents.py
Python
apache-2.0
12,906
0.000852
# -*- coding: utf-8 -*- __author__ = 'Ostico <ostico@gmail.com>' import unittest import os os.environ['DEBUG'] = "1" os.environ['DEBUG_VERBOSE'] = "0" import pyorient class CommandTestCase(unittest.TestCase): def __init__(self, *args, **kwargs): super(CommandTestCase, self).__init__(*args, **kwargs) ...
\ "" + res[0].oRecordData['b'] + \ " equals '{}" res = self.client.c
ommand( 'create vertex v content {"b":{},"a":1,"d":{}}' ) # print(res[0]) assert res[0].oRecordData['b'] == {}, "Failed to asert that received " \ "" + res[0].oRecordData['b'] + \ " equals '{...
ruchee/vimrc
vimfiles/bundle/vim-python/submodules/pylint/pylint/utils/ast_walker.py
Python
mit
3,263
0.000306
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html # For details: https://github.com/PyCQA/pylint/blob/master/LICENSE import collections from astroid import nodes class ASTWalker: def __init__(self, linter): # callbacks per node types self.nbstatements = 0 s...
isit_events = collections.defaultdict(list) self.leave_events = collections.default
dict(list) self.linter = linter self.exception_msg = False def _is_method_enabled(self, method): if not hasattr(method, "checks_msgs"): return True for msg_desc in method.checks_msgs: if self.linter.is_message_enabled(msg_desc): return True ...
realriot/KinderThek.bundle
Contents/Code/mod_sesamstrasse.py
Python
bsd-3-clause
3,151
0.047287
import datetime, re from mod_helper import * debug = True def sesamstrasseShow(): mediaList = ObjectContainer(no_cache=True) if debug == True: Log("Running sesamstrasseShow()...") try: urlMain = "http://www.sesamstrasse.de" content = getURL(urlMain+"/home/homepage1077.html") spl = content.split('<div class=...
key = Callback(sesamstrasseCreateVideoObject, item = item, container = True), title = item['title'], thumb = item['thumb'], duration = item['duration'], rating_key
= item['url'], items = [] ) # Lookup URL and create MediaObject. mo = MediaObject(parts = [PartObject(key = Callback(sesamstrasseGetStreamingUrl, url = item['url']))]) # Append mediaobject to clipobject. vo.items.append(mo) if container: return ObjectContainer(objects = [vo]) else: return vo ...
rafaduran/python-mcollective
tests/integration/test_with_rabbitmq.py
Python
bsd-3-clause
1,771
0
import os from pymco.test import ctxt from . import base class RabbitMQTestCase(base.IntegrationTestCase): '''RabbitMQ integration test case.''' CTXT = { 'connector': 'rabbitmq', 'plugin.rabbitmq.vhost': '/mcollective', 'plugin.rabbitmq.pool.size': '1', 'plugin.rabbitmq.pool....
integration test case.""" CTXT = { 'connector': 'ra
bbitmq', 'plugin.rabbitmq.vhost': '/mcollective', 'plugin.rabbitmq.pool.size': '1', 'plugin.rabbitmq.pool.1.host': 'localhost', 'plugin.rabbitmq.pool.1.port': 61612, 'plugin.rabbitmq.pool.1.user': 'mcollective', 'plugin.rabbitmq.pool.1.password': 'marionette', 'pl...
emidln/django_roa
env/lib/python2.7/site-packages/socketpool/backend_eventlet.py
Python
bsd-3-clause
1,213
0.002473
# -*- coding: utf-8 - # # This file is part of socketpool. # See the NOTICE for more information. import eventlet from eventlet.green import select from eventlet.green import socket from eventlet import queue from socketpool.pool import ConnectionPool sleep = eventlet.sleep Socket = socket.socket Select = select.sel...
unning = False def __init__(self, pool, delay=150): self.pool = pool self.delay = delay def start(self): self.running = True g = eventlet.spawn(self._exec) g.link(self._exit) def _exit(self, g): try
: g.wait() except: pass self.running = False def _exec(self): while True: eventlet.sleep(self.delay) self.pool.murder_connections() def ensure_started(self): if not self.running: self.start()
karan259/PivotPi
Software/Python/Control_Panel/pivot_control_with_sliders.py
Python
mit
7,313
0.008615
from __future__ import print_function from __future__ import division from builtins import input import subprocess from time import sleep from pivotpi import * try: import wx except ImportError: raise ImportError,"The wxPython module is required to run this program" total_servos = 8 horizontal_spacer = 20 v...
20) self.vsizer.Add(title_sizer, 1, wx.ALIGN_CENTER_HORIZONTAL, 20) for i in range(total_servos): self.fields.append(wx.BoxSizer(wx.HORIZONTAL)) txt = wx.StaticText(self, label="Servo/Pivot {}:".format(i+1)) txt.SetFont(wx.Font( 14, ...
STYLE_NORMAL, wx.FONTWEIGHT_BOLD)) self.servo.append(txt) self.fields[i].AddSpacer(horizontal_spacer) self.fields[i].Add(self.servo[i]) self.slider.append(wx.Slider(self, id=i*total_ids_per_line, minValue=0, maxValue=180, size=(180,20))) ...
eldie1984/Scripts
pg/para.py
Python
gpl-2.0
262
0.007634
import paramiko ssh = paramiko.SSHClient() ssh.set_missing_host_key_polic
y( paramiko.AutoAddPolicy()) ssh.connect('127.0.0.1', username='xxxxxxx', password='xxxxxxxxxxx') stdin, stdout, stderr = ssh.exec_command("uptime") type(stdin) stdout.readlines(
)
geowurster/fio-plugin-example
fio_metasay/scripts/cli.py
Python
mit
575
0
# Moothedata command. import click import fiona as fio from fiona.fio.cli import cli from fio_metasay import moothedata @cli.command(short_help="Cowsay some dataset metadata.") @click.argument( 'inputfile', type=click.Path(resolve_path=True), required=True, metavar="INPUT") @click.option('--
item', default=None, help="Select a metadata item.") @click.pass_context def metasay(ctx
, inputfile, item): """Moo some dataset metadata to stdout.""" with fio.open(inputfile) as src: meta = src.meta click.echo(moothedata(meta, key=item))
FranzSchubert92/cw
python/powers_of_3.py
Python
bsd-3-clause
908
0.007709
""" Powers of Three: Given a positive in
teger N, return the largest integer k such that 3**k < N. For example, >>> largestPower(3) 0 >>> largestPower(4) 1 >>> largestPower(28) 3 >>> largestPower(80) 3 >>> largestPower(82)
4 >>> largestPower(20700) 9 >>> largestPower(10**7) 14 >>> largestPower(10**8) 16 """ from math import ceil, log def largestPower_v1(n): k = -1 while 3**k < n: if 3**(k+1) >= n: break k += 1 return k def largestPower_v2(n): return int(ceil(log(n, 3)) - 1) if __name__ ==...
toslunar/chainerrl
tests/agents_tests/basetest_pgt.py
Python
mit
3,966
0
from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from builtins import * # NOQA from future import standard_library standard_library.install_aliases() # NOQA import chainer from chainer import functions as F from chain...
_TestPGTOnABC): def make_model(self, env): n_dim_obs = env.observation_space.low.size n_dim_action = env.action_space.low.size n_hidden_channels = 50 policy = Sequence( L.Linear(n_dim_obs, n_hidden_channels), F.relu
, L.Linear(n_hidden_channels, n_hidden_channels), F.relu, L.LSTM(n_hidden_channels, n_hidden_channels), policies.FCGaussianPolicy( n_input_channels=n_hidden_channels, action_size=n_dim_action, min_action=env.action_space.low...
algorythmic/bash-completion
test/t/test_dmypy.py
Python
gpl-2.0
423
0
import pytest class TestDmypy: @pytest.mark.complete( "dmypy ", require_cmd=True, xfail="! dmypy --help
&>/dev/null" ) def test_commands(self, completion): assert "help" in completion
assert not any("," in x for x in completion) @pytest.mark.complete("dmypy -", require_cmd=True, require_longopt=True) def test_options(self, completion): assert "--help" in completion
qrizan/moopy
moopy/genres/migrations/0001_initial.py
Python
mit
1,137
0.001759
# -*- coding: utf-8 -*- # Generat
ed by Django 1.10 on 2016-08-26 04:44 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AU...
operations = [ migrations.CreateModel( name='Genre', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('slug', models.SlugField(blank=True...
fhqgfss/MoHa
moha/modelsystem/sites.py
Python
mit
7,169
0.02176
import numpy as np class Site(object): """A class for general single site Use this class to create a single site object. The site comes with identity operator for a given dimension. To build specific site, additional operators need be add with add_operator method. """ def __init__(sel...
t z of spin, -
s_p, raises the component z of spin, - s_m, lowers the component z of spin, - n_up, number of electrons with spin up, - n_down, number of electrons with spin down, - n, number of electrons, i.e. n_up+n_down, and - u, number of double occupancies, i.e. n_up*n_down. """ def __init__(self): ...
applied-mixnetworks/txmix
txmix/client.py
Python
gpl-3.0
6,459
0.002322
import attr import types import binascii from eliot import start_action from eliot.twisted import DeferredContext from zope.interface import implementer from sphinxmixcrypto import SphinxParams, SphinxPacket, ReplyBlock from sphinxmixcrypto import IMixPKI, IReader, SECURITY_PARAMETER from txmix import IMixTranspor...
self.protocol = ClientProtocol(self.params, self.pki, self.client_id, self.rand_reader, packet_received_handler=lambda x: self.message_received(x))
d = self.protocol.make_connection(self.transport) self.pki.set_client_addr("onion", self.protocol.client_id, self.transport.addr) return d def message_received(self, message): """ receive a message """ action = start_action( action_type=u"mix client:mess...
django-blog-zinnia/zinnia-url-shortener-hashids
zinnia_hashids/backend.py
Python
bsd-3-clause
501
0
"""URL Shortener backend for Zinnia Hashids""" from django.contrib.sites.models import Site from django.core.urlresolvers import
reverse from zinnia.settings import PROTOCOL from zinnia_hashids.factory import hashids def backend(entry): """ Hashids URL shortener backend for Zinnia. """ hashed_pk = hashids.encode(entry.pk) url = '%s://%s%s' % ( PROTOCOL, Site.objects.get_current().domain, reverse('entry_ha...
wargs={'token': hashed_pk})) return url
mathiasuhlenbrock/sedatar
astronomical_database/scripts/python/test_query.py
Python
gpl-3.0
1,551
0
import rdflib g = rdflib.Graph() g.parse('astronomical_database/data/rdf/astronomical_database.rdf') result = g.query(""" PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX ontology: <urn://sedatar.org/astronomical_database#> # All cla...
WHERE { # ?x0 rdfs:subClassOf* ontology:Thing. # ?x1 rdf:type ?x0. # ?x1 rdfs:label ?x2. # } # Number of planets. # SELECT DISTINCT ?x1 WHERE { # ?x0 rdfs:label 'planet'. #
?x0 ontology:numberOfInstances ?x1. # } # Size of Earth. # SELECT DISTINCT ?x2 WHERE { # ?x0 rdfs:label 'Earth'. # ?x0 ?x1 ?x2. # ?x1 rdfs:subPropertyOf* ontology:size. # } """) for row in sorted(result): print('%s' % row)
lilsweetcaligula/Online-Judges
hackerrank/algorithms/implementation/medium/extra_long_factorials/py/solution.py
Python
mit
134
0.022388
#!/bin/p
ython3 import sys fact = lambda n: 1 if n <= 1 else n * fact(n - 1) n = int(input().strip()) fct = fact
(n) print(fct)
jkloo/fff
setup.py
Python
mit
718
0.001393
''' Setup script for FuzzyFileFinder. ''' import setuptools from fff import __project_
_, __version__, CLI README = 'README.md' setuptools.setup(name='fff', version=__version__, description='Fuzzy File Finder.', url="https://github.com/jkloo/fff", author='Jeff Kloosterman', author_email='kloosterman.jeff...
ages=setuptools.find_packages(), entry_points={'console_scripts': [CLI + ' = fff.fffind:main']}, license='MIT', long_description=open(README).read(), install_requires=[] )
shuaizi/leetcode
leetcode-python/num179.py
Python
apache-2.0
685
0.00146
__author__ = 'shuai' class Solution: # @param {integer[]} nums # @return {string} def largestNumber(self, nums): ret = "" for i in range(len(nums)): for j in range(i + 1, len(nums)):
str_i = str(nums[i]) str_j = str(nums[j]) if str_i + str_j < str_j + str_i: tmp = nums[i] nums[i] = nums[j] nums[j] = tmp # to check if ma
x equals 0 ,return '0' if i == 0 and nums[i] == 0: return '0' ret += str(nums[i]) return ret sol = Solution() print sol.largestNumber([3, 30, 34, 5, 9])
gr4viton/gr4Dalek
spine/dd/spine/dcmotor.py
Python
gpl-3.0
3,260
0.009202
import pyb #from pyb import I2C, SPI, UART #import staccel import math #import os #import gc # garbage collection for writing? #import microsnake #from microsnake import MicroSnakeGame as Game #from microsnake import move_arrow_pressed import shared_globals #from shared_globals import move_arrow_pressed as move_ar...
q.in1.value(to_set_in[0]) q.in2.value(to_set_in[1]) q.velocity = vel q.set_in = to_set_in def __str__(q): txt = ( 'DCm[{nam}] in1,in2[{in1},{in2}]={set_in}' ' tim,dir_en[{tim},{en}],' ' vel={vel}').format( nam=q.name, ...
q.in2.value()] return txt
rjhd2/HadISD_v2
qc_tests/clouds.py
Python
bsd-3-clause
8,787
0.019119
#!/usr/local/sci/bin/python #***************************** # # Cloud Coverage Logical Check (CCC) # # #************************************************************************ # SVN Info #$Rev:: 67 $: Revision of last commit #$Author:: rdunn ...
lagged_obs_number(logfile, "Mid full cloud", "cloud", len(flag_locs[0]), noWrite = True) else: utils.print_flagged_obs_number(logfile, "Mid full cloud", "cloud", len(flag_locs[0])) # copy flags into attribute high.flags[flag_locs] = 1 return # mid_full #******************************...
aram obj station: station object :returns: ''' cloud_base = getattr(station, "cloud_base") bad_cb = np.where(cloud_base.data == 22000) # no flag set on purpose - just set to missing (unobservable) cloud_base.data[bad_cb] = cloud_base.mdi cloud_base.data.mask[bad_cb] = True ret...
watchsky126/jumpserver
connect.py
Python
gpl-2.0
12,846
0.002802
# coding: utf-8 import sys reload(sys) sys.setdefaultencoding('utf8') import socket import os import re import select import time import paramiko import struct import fcntl import signal import textwrap import getpass import fnmatch import readline import datetime from multiprocessing import Pool os.environ['DJANGO...
Login. ### \033[0m 1) Type \033[32mIP or Part IP, Host Alias or Comments \033[0m To Login. 2) Type \033[32mP/p\033[0m To Print The Servers You Available. 3) Type \033[32mG/g\033[0m To Print The Server Groups You Available. 4) Typ
e \033[32mG/g(1-N)\033[0m To Print The Server Group Hosts You Available. 5) Type \033[32mE/e\033[0m To Execute Command On Several Servers. 6) Type \033[32mQ/q\033[0m To Quit. """ print textwrap.dedent(msg) def print_user_host(username): try: hosts_attr = get_user_host(username) except ...
jeancochrane/learning
linear-algebra/tests/test_vector_operations.py
Python
mit
5,540
0.000181
import unittest import env from linalg.vector import Vector class TestVectorOperations(unittest.TestCase): def test_vector_equality(self): a = Vector([1, 2, 3]) b = Vector([1, 2, 3]) self.assertEqual(a, b) def test_vector_inequality(self): a = Vector([1, 2, 3]) b = V...
[6.404, -9.144, 2.759, 8.718]) v_decomposed = (v.project(b) + v.orthogonal_component(b)) self.assertEqual(v, v_decomposed.round(3)) def test_cross_product(self): """ Testing the calculation of cross products, as well as the areas of parallelograms and
triangles spanned by different vectors. """ v = Vector([8.462, 7.893, -8.187]) w = Vector([6.984, -5.975, 4.778]) cross = v.cross(w) self.assertEqual(cross.round(3), Vector([-11.205, -97.609, ...
vmuriart/pythonnet
setup.py
Python
mit
15,375
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Setup script for building clr.pyd and dependencies using mono and into an egg or wheel. """ import collections import fnmatch import glob import os import subprocess import sys import sysconfig from distutils import spawn from distutils.command import build_ext, insta...
s part of the build. For common windows platforms pre-generated files are included as most windows users won't have Clang installed, which is required to generate the file. """ interop_filename = "interop{0}{1}{2}.cs".format( PY_MAJOR, PY_MINOR, getattr(sys, "abiflags", "")) return os.pa...
"" for ext in (".sln", ): for path in glob.glob("*" + ext): yield path for root, dirnames, filenames in os.walk("src"): for ext in (".cs", ".csproj", ".snk", ".config", ".py", ".c", ".h", ".ico"): for filename in fnmatch.filter(filenames, "*" + ext): ...
evandrix/Splat
code/demo/quixey/bucket_sort.py
Python
mit
471
0
def bucketsort(arr, k): "
"" Input: arr: A list of small ints k: Upper bound of the size of the ints in arr (not inclusive) Precondition: all(isinstance(x, int) and 0 <= x < k for x in arr) Output: The elements of arr in sorted order """ counts = [0] * k for x in arr: counts[x] += ...
n sorted_arr
bigswitch/neutron
neutron/tests/unit/extensions/test_agent.py
Python
apache-2.0
7,074
0
# Copyright (c) 2013 OpenStack Foundation. # 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...
ALANCER} lbaas_hostb = copy.deepcopy(lbaas_hosta) lbaas_hostb['host'] = LBAAS_HOSTB callback = agents_db.AgentExtRpcCallback() callback.report_state( self.adminContext,
agent_state={'agent_state': lbaas_hosta}, time=datetime.utcnow().strftime(constants.ISO8601_TIME_FORMAT)) callback.report_state( self.adminContext, agent_state={'agent_state': lbaas_hostb}, time=datetime.utcnow().strftime(constants...
tylertian/Openstack
openstack F/nova/nova/tests/api/openstack/compute/contrib/test_server_diagnostics.py
Python
apache-2.0
2,735
0
# Copyright 2011 Eldar Nugaev # 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 ...
ack.common import jsonutils from nova import test from nova.tests.api.openstack import fakes import nova.utils UUID = 'abc' def fake_get_diagnostics(self, _context, instance_uuid): return {'data': 'Some diagnostic info'}
def fake_instance_get(self, _context, instance_uuid): if instance_uuid != UUID: raise Exception("Invalid UUID") return {'uuid': instance_uuid} class ServerDiagnosticsTest(test.TestCase): def setUp(self): super(ServerDiagnosticsTest, self).setUp() self.flags(verbose=True) s...
stilobique/Icon-Header
views/header.py
Python
gpl-3.0
1,454
0.002063
import bpy # ----------------------------------------------------------------------------- # Draw UI, use an function to be append into 3D View Header # --------------------------------------------------
--------------------------- def u
i_3D(self, context): layout = self.layout row = layout.row(align=True) row.operator("view.grid_control", text='', icon='GRID') icon = 'CURSOR' row.operator("object.center_pivot_mesh_obj", text='', icon=icon) icon = 'SMOOTH' row.operator("object.smooth_shading", text='', icon=icon) row ...
bountyfunding/bountyfunding
test/integration_test/email_test.py
Python
agpl-3.0
1,266
0.006319
import bountyfunding from bountyfunding.core.const import * from bountyfunding.core.data import clean_database from test import to_object from nose.tools import * USER = "bountyfunding" class Email_Test: def setup(self): self.app = bountyfunding.app.test_client() clean_database() def ...
title='Title', link='/issue/1')) eq_(r.status_code, 200) r = self.app.post('/issue/1/sponsorships', data=dict(user=USER, amount=10)) eq_(r.status_code, 200) r = self.app.get("/issue/1") eq_(r.status_code, 200)
r = self.app.put('/issue/1', data=dict( status=IssueStatus.to_string(IssueStatus.STARTED))) eq_(r.status_code, 200) emails = self.get_emails() eq_(len(emails), 1) email = emails[0] eq_(email.recipient, USER) ok_(email.issue_id) ok_(email.body) ...
romansalin/testrail-reporting
testrail_reporting/auth/models.py
Python
apache-2.0
1,147
0
import logging from mongoengine import * from flask.ext.security import RoleMixin from flask.ext.security import UserMixin log = logging.getLogger(__name__) class AuthRole(Document, RoleMixin): name = StringField(max_length=80, unique=True) description = StringField(max_length=255) def __str__(self): ...
return user def __str__(self): return '{0} {0} ({1})'.format(self.name, self.family_na
me, self.email)
ZhangAustin/deepy
deepy/layers/conv.py
Python
mit
2,682
0.001491
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging as loggers import numpy as np import theano.tensor as T from theano.tensor.nnet import conv from theano.tensor.signal import downsample from deepy.utils import build_activation, UniformInitializer from deepy.layers.layer import NeuralLayer logging = log...
._activation_func(pooled_out + self.B_conv.dimshuffle('x', 0, 'x', 'x')) if self.flatten_output: output = output.flatten(2) return output def _setup_functions(self):
self._activation_func = build_activation(self.activation) def _setup_params(self): self.W_conv = self.create_weight(suffix="conv", initializer=self.initializer, shape=self.filter_shape) self.B_conv = self.create_bias(self.filter_shape[0], suffix="conv") self.register_parameters(sel...
citrix-openstack-build/trove
trove/openstack/common/rpc/impl_qpid.py
Python
apache-2.0
26,203
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack Foundation # Copyright 2011 - 2012, 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 # # ...
"type": "topic", "x-declare": { "durable": True, "auto-delete": True, }, }, "link": { "name": link_name, "durable": True, "x-declare": { "durable": ...
de"]["x-declare"].update(node_opts) addr_opts["link"]["x-declare"].update(link_opts) self.address = "%s ; %s" % (node_name, jsonutils.dumps(addr_opts)) self.connect(session) def connect(self, session): """Declare the reciever on connect.""" self._declare_receiver(session) ...
ixtabinnovations/USB_Cryptor
USB.py
Python
gpl-3.0
993
0.021148
from os import path from collections import namedtuple from subprocess import Popen,
PIPE def sys(cmd): return Popen(cmd, stdout=PIPE, shell=True).stdout.read() class USB: ''' Depends on findmnt to find source from target and extra information like fs type ''' def __init__(self, target): try: assert path.exists(target) and not path.isfile(target) # do i even exist? ex...
lf._get_info(target, 'T') else: self.data = self._get_info(target, 'S') def _get_info(self, d, v, splitchar='|'): for i, x in enumerate(sys("findmnt -%s \"%s\"" % (v, d)).split('\n')): if i > 0: return namedtuple('USB_info', 'target source fstype options')(*splitchar.join(x.split())...
AlienStudio/jpsp_python
jpsp/jpspapp/tests.py
Python
mit
3,241
0.00779
from django.test import TestCase, Client from jpspapp.models import Club, Activity,UserProfile from django.contrib.auth.models import User from django.contrib.auth import authenticate, login import datetime # Create your tests here. class ClubTestCase(TestCase): def setUp(self): User.objects.create_user(...
ShezhangName="社长", ShezhangQq="12345678", ShezhangGrade='1', ShezhangClass='1', IfRecruit=True, EnrollGroupQq='12345678') def test_club_update(self): club = Club.objects.get(ClubName="测试社团") club.ShezhangName = "社长姓名" club.save() self.assertEqu
al(club.ShezhangName, "社长姓名") def test_club_del(selfs): club = Club.objects.get(ClubName="测试社团") club.delete() user = User.objects.get(username="clubtest") user.delete() class ActivityModelTest(TestCase): def setUp(self): User.objects.create_user(username="clubtest", e...
c-oreills/before_after
before_after/tests/test_before_after.py
Python
gpl-2.0
2,890
0.000346
#!/usr/bin/env python from unittest import TestCase from before_after import before, after, before_after from before_after.tests import test_functions class TestBeforeAfter(TestCase): def setUp(self): test_functions.reset_test_list() super(TestBeforeAfter, self).setUp() def test_before(self...
test_functions.sample_fn(1) test_functions.sample_fn(3) self.assertEqual(test_functions.test_list, [1, 2, 3]) def test_before_and_after_once(self): def befo
re_fn(*a): test_functions.test_list.append(1) def after_fn(*a): test_functions.test_list.append(3) with before_after( 'before_after.tests.test_functions.sample_fn', before_fn=before_fn, after_fn=after_fn, once=True): test_functions.sa...
reidlindsay/wins
sandbox/experiments/dsr/icc/test.py
Python
apache-2.0
15,846
0.011612
#! /usr/bin/env python """ Simulate DSR over a network of nodes. Revision Info ============= * $LastChangedBy: mandke $ * $LastChangedDate: 2011-10-26 21:51:40 -0500 (Wed, 26 Oct 2011) $ * $LastChangedRevision: 5314 $ :author: Ketan Mandke <kmandke@mail.utexas.edu> :copyright: Copyright 2009-2011 The Universit...
ort * from wins.mac import RBAR, ARF from wins.net import DSR from wins.traffic import Agent import sys from optparse import OptionParser import numpy as np import struct import gc import time RNG_INIT = 1 EXIT_WITH_TRACE = 1 class Node(Element): name = "node" tracename = "NODE" def __init__(self, **k...
it__(self, **kwargs) def configure(self, pos=None, # motion \ useshared=False, # arp \ cfocorrection=True, # phy \ usecsma=False, # mac \ ...
gppezzi/easybuild-framework
easybuild/toolchains/mpi/psmpi.py
Python
gpl-2.0
1,693
0.001772
# # # Copyright 2012-2019 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Research Foundation (...
ful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Pub
lic License # along with EasyBuild. If not, see <http://www.gnu.org/licenses/>. # # """ Support for Parastation MPI as toolchain MPI library. :author: Kenneth Hoste (Ghent University) """ from easybuild.toolchains.mpi.mpich import Mpich class Psmpi(Mpich): """Parastation MPI class""" MPI_MODULE_NAME = ['ps...
rhndg/openedx
lms/djangoapps/courseware/testutils.py
Python
agpl-3.0
7,021
0.002564
""" Common test utilities for courseware functionality """ from abc import ABCMeta, abstractmethod from datetime import datetime import ddt from mock import patch from lms.djangoapps.courseware.url_helpers import get_redirect_url from student.tests.factories import AdminFactory, UserFactory, CourseEnrollmentFactory f...
rtContains(response, chrome_element) @ddt.data( (ModuleStoreEnum.Type.mongo, 5), (ModuleStoreEnum.Type.split, 5), ) @ddt.unpack def test_success_enrolled_staff(self, default_store, mongo_calls): with self.store.default_store(default_store): self.setup_course(default_...
r(admin=True, enroll=True, login=True) # The 5 mongoDB calls include calls for # Old Mongo: # (1) fill_in_run # (2) get_course in get_course_with_access # (3) get_item for HTML block in get_module_by_usage_id # (4) get_parent when loading ...
Firefly-Automation/Firefly
Firefly/components/nest/thermostat.py
Python
apache-2.0
7,969
0.010415
from uuid import uuid4 from Firefly import logging, scheduler from Firefly.components.virtual_devices import AUTHOR from Firefly.const import (COMMAND_UPDATE, DEVICE_TYPE_THERMOSTAT, LEVEL) from Firefly.helpers.action import Command from Firefly.helpers.device.device import Device from Firefly.helpers.metadata.metadat...
f.away = away def set_home(self, **kwargs): self.away = 'home' def set_temperature(self, **kwargs): t = kwargs.get('temperature') if t is None: return try: t = int(t) except: return self.temperature = t def set_mode(self, **kwargs): m = kwargs.get('mode
') if m is None: logging.error('no mode provided') return m = m.lower() if m not in MODE_LIST: logging.error('Invalid Mode') return self.mode = m def update_thermostat(self, **kwargs): thermostat = kwargs.get('thermostat') logging.info('[NEST] updating thermostat: %s' ...
achernet/cython
Cython/Compiler/Pipeline.py
Python
apache-2.0
13,086
0.003897
from __future__ import absolute_import import itertools from time import time from . import Errors from . import DebugFlags from . import Options from .Visitor import CythonTransform from .Errors import CompileError, InternalError, AbortError from . import Naming # # Really small pipeline stages # def dumptree(t): ...
t_from_pyx tree = context.parse(source_desc, scope, pxd = 0, full_module_name = full_module_name) tree.compilation_source = compsrc tree.scope = scope tree.is_pxd = False return tree return parse def parse_pxd_stage_factory(context, scope, module_name): def parse(source_...
tree.is_pxd = True return tree return parse def generate_pyx_code_stage_factory(options, result): def generate_pyx_code_stage(module_node): module_node.process_implementation(options, result) result.compilation_source = module_node.compilation_source return result re...
minorua/QGIS
tests/src/python/qgis_wrapped_server.py
Python
gpl-2.0
19,452
0.00257
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ QGIS Server HTTP wrapper for testing purposes ================================================================================ This script launches a QGIS Server listening on port 8081 or on the port specified on the environment variable QGIS_SERVER_PORT. Hostname is ...
.parse from http.server import BaseHTTPRequestHandler, HTTPServer from qgis.core import QgsApplication from qgis.server import (QgsBufferServerRequest, QgsBufferServerResponse, QgsServer, QgsServerRequest) __author__ = 'Alessandro Pasotti' __date__ = '05/15/2016' __copyright__ = 'Copyright 20...
nt among all # executions os.environ['QT_HASH_SEED'] = '1' import sys import signal import ssl import math import copy import urllib.parse from http.server import BaseHTTPRequestHandler, HTTPServer from socketserver import ThreadingMixIn import threading from qgis.core import QgsApplication, QgsCoordinateTransform, Q...
saga-project/bliss
test/compliance/file/03_copy_local_remote_etc.py
Python
mit
2,709
0.014766
# -*- coding: utf-8 -*- # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 __author__ = "Ole Christian Weidner" __copyright__ = "Copyright 2012, Ole Christian Weidner" __license__ = "MIT" import sys, time, uuid import getpass import bliss.saga as saga def run(remote_base_url, local_file_to_copy): """Test...
) mylocalfile.copy("%s/%s/bh-copy" % (remote_base_url, tmpdirname)) remote_tdir = saga.filesystem.Directory("%s/%s/" % (remote_base_url, tmpdirname)) remote_tdir.make_dir("A") remote_tdir.make_dir("B") print remote_tdir.list() print "
Size: %s" %str(remote_tdir.get_size()) remote_tdir.remove("A") remote_tdir.remove("B") print remote_tdir.list() print "Size: %s" %str(remote_tdir.get_size()) remote_tdir.remove() remote_tdir.close() except saga.Exception, ex: failed = True ...
valsson/MD-MC-Codes-2016
LJ7-2D_MD-sampling/DataTools.py
Python
mit
3,140
0.014013
#! /usr/bin/env python import numpy as np def writeDataToFile(filename, data, fieldNames=[], constantsNames=[], constantsValues=[], appendFile=False, addTimeField=False, dataFormat='%10.5f'): commentsStr = '#! ' delimiterStr =' ' if(a...
ames)==len(data): fieldsStr += 'FIELDS ' for f in fieldNames: fieldsStr += f + ' ' for i in range(len(constantsNames)): str1 = '\nSET {0:} {1:'+dataFormat[1:]+'}
' fieldsStr += str1.format(constantsNames[i],constantsValues[i]) data2 = np.column_stack(data) if appendFile: file = open(filename,'a') else: file = open(filename,'w') np.savetxt(file, data2 , header=fieldsStr, delimiter=delimiterStr, fmt=dataFormat, comments=commentsStr) fil...
edigiacomo/django-statusboard
statusboard/migrations/0016_service_position.py
Python
gpl-2.0
464
0
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-22 21:06 from __future__ import unicode_literals from django.db import migrations, models class Migra
tion(migrations.Migration): dependencies = [ ('statusboard', '0015_merge_20170222_2058'), ] operations = [ migrations.AddField( model_name='service', name='position
', field=models.PositiveIntegerField(default=0), ), ]
pkimber/booking
booking/models.py
Python
apache-2.0
10,565
0.000947
# -*- encoding: utf-8 -*- from dateutil.relativedelta import relativedelta from django.core.exceptions import ValidationError from django.db import models from django.db.models import Q from django.utils import timezone from reversion import revisions as reversion from base.model_utils import TimeStampedModel from bas...
ter_by_date( self._current(), timezone.now().date(), self._two_months() ) def _staff_month(self, month, year): return self._filter_by_month(self._current(), month, year) def _user(self): return self._current().filter( permission__slug__in
=(Permission.PUBLIC, Permission.USER), ) def _user_calendar(self): return self._filter_by_date( self._user(), timezone.now().date(), self._two_months() ) def _user_month(self, month, year): return self._filter_by_month(self._user(), month, year) def calendar(se...
drjova/cds-demosite
cds/modules/ffmpeg/ffmpeg.py
Python
gpl-2.0
3,735
0.002677
# -*- coding: utf-8 -*- # # This file is part of CERN Document Server. # Copyright (C) 2016 CERN. # # CERN Document Server 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 ...
307, USA. # # In applying this license, CERN does not # waive the privileges and immunities granted to it by virtue of its status # as an Intergovernmental Organization or submit itself to any jurisdiction. """Python wrap
pers for the ffmpeg command-line utility.""" from __future__ import absolute_import from subprocess import check_output import pexpect def ff_probe(input_filename, field): """Retrieve requested field from the output of ffprobe. **OPTIONS** * *-v error* show all errors * *-select_streams v:0* sele...
Ignoramuss/LDERP
LDERPdjango/login/views.py
Python
apache-2.0
8,998
0.002223
from django.shortcuts import render from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required from django.contrib.auth import views as auth_views from django.contrib.auth import logout from django.views.decorators.csrf import csrf_protect from django.shortcuts import render_...
orm = RegistrationForm() return render(request, 'home.html', {'form':LoginForm(),'signup_form':form}) # def register_success(request): # return render( request, 'home.html', {'message': 'Registered successfully'} ) # def logout_page(request): # logout(request) # return HttpResponseRedirect('
/logout') class LoginSignupView(auth_views.LoginView): def get_context_data(self, **kwargs): context = super(LoginSignupView, self).get_context_data(**kwargs) context.update({ 'signup_form': RegistrationForm(), 'message':'' }) return context # def change_pas...
liangcun/ConceptsOfSpatialInformation
CoreConceptsPy/GdalPy/examples/events/earthquake/EarthquakeRdfWriter2.py
Python
apache-2.0
3,451
0.010207
# -*- coding: utf-8 -*- """ Abstract: Creates RDF for earthquake objects. Gets an Array of Python Earthquake objects and turns them to RDF using RDFlib. The RDF can either be outputted or written to a file. This class does not inherit from RDFWriter! """ __author__ = "Marc Tim Thiemann" __copyright__ = "Copyright ...
None: print self.g.serialize(format=format) else: self.g.serialize(destination = destination +
'.' + self.getExtension(format), format=format) def add(self, earthquake, uri): """ Add RDF for this earthquake to the graph. @param earthquake The earthquake object @param uri The uri for that earthquake """ randomId = os.urandom(16).encode('hex') eq = URI...
andreav/swgit
core/ObjMail.py
Python
gpl-3.0
5,260
0.028897
#!/usr/bin/env python # Copyright (C) 2012 Andrea Valle # # This file is part of swgit. # # swgit 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 lat...
efaults for mail delivery # # Please run # swgit --tutorial-mailcfg # for more informations # #[%s] #mailserver-sshuser = #mailserver-sshaddr = #from = #to = #to-1 = #to-2 = #cc
= #cc-1 = #cc-2 = #bcc = #bcc-1 = #bcc-2 = #subject = #body-header = #body-footer = # #[%s] #mailserver-sshuser = #mailserver-sshaddr = #from = #to = #to-1 = #to-...
codegooglecom/jaikuengine
common/test/throttle.py
Python
apache-2.0
1,689
0.003552
# Copyright 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
il as test_util class ThrottleTest(base.FixturesTestCase): def setUp(self): super(ThrottleTest, self).setUp() self.popular = api.actor_get(api.ROOT, 'popular@example.com') def test_basic(self): # lather # succeed the first two times, fail the third throttle.throttle(self.popular, 'test', ...
def _failPants(): throttle.throttle(self.popular, 'test', minute=2) self.assertRaises(exception.ApiThrottled, _failPants) # rinse # magically advance time by a couple minutes o = test_util.override_clock(clock, seconds=120) # repeat # succeed the first two times, fail the thir...
SujaySKumar/django
django/utils/termcolors.py
Python
bsd-3-clause
7,479
0.000669
""" termcolors.py """ from django.utils import six color_names = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white') foreground = {color_names[x]: '3%s' % x for x in range(8)} background = {color_names[x]: '4%s' % x for x in range(8)} RESET = '0' opt_dict = {'bold': '1', 'underscore': '4', 'blink...
ld',)}, 'WARNING': {'fg': 'yellow', 'opts': ('bold',)}, 'NOTICE': {'fg': 'red'}, 'SQL_FIELD': {'fg': 'green', 'opts': ('bold',)}, 'SQL_COLTYPE': {'fg': 'green'}, 'SQL_KEYWORD': {'fg': 'blue'}, 'SQL_TABLE': {'opts': ('bold',)}, 'HTTP_INFO': {'opts': ('bold',)}, ...
}, 'HTTP_BAD_REQUEST': {'fg': 'red', 'opts': ('bold',)}, 'HTTP_NOT_FOUND': {'fg': 'red'}, 'HTTP_SERVER_ERROR': {'fg': 'magenta', 'opts': ('bold',)}, 'MIGRATE_HEADING': {'fg': 'cyan', 'opts': ('bold',)}, 'MIGRATE_LABEL': {'opts': ('bold',)}, 'MIGRATE_SUCCESS': {'fg': 'gree...
vicky2135/lucious
oscar/lib/python2.7/site-packages/phonenumbers/timezone.py
Python
bsd-3-clause
4,947
0.001819
"""Phone number to time zone mapping functionality >>> import phonenumbers >>> from phonenumbers.timezone import time_zones_for_number >>> ro_number = phonenumbers.parse("+40721234567", "RO") >>> tzlist = time_zones_for_number(ro_number) >>> len(tzlist) 1 >>> str(tzlist[0]) 'Europe/Bucharest' >>> mx_number = phonenumb...
a # Copyright (C) 2013 The Libphonenumber 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 applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ...
pyblish/pyblish-standalone
pyblish_standalone/version.py
Python
lgpl-3.0
229
0
VERSION_MAJOR = 0 VERSION_MIN
OR = 2 VERSION_PATCH = 0 version_info = (VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH) version = '%i.%i.%i' % version_info __version__ = version __all__ = ['version', 'ver
sion_info', '__version__']
SINGROUP/pycp2k
pycp2k/classes/_print26.py
Python
lgpl-3.0
526
0.003802
from pycp2k.inputsection import InputSe
ction from ._neighbor_lists3 import _neighbor_lists3 from ._subcell1 import _subcell1 from ._ewald_info1 import _ewald_info1 class _print26(InputSection): def __init__(self): InputSection.__init__(self) self.NEIGHBOR_LISTS = _neighbor_lists3() self.SUBCELL = _subcell1() self.EWALD_...
self._name = "PRINT" self._subsections = {'EWALD_INFO': 'EWALD_INFO', 'SUBCELL': 'SUBCELL', 'NEIGHBOR_LISTS': 'NEIGHBOR_LISTS'}
jmerdich/django-natural-duration
natural_duration/fields.py
Python
bsd-3-clause
4,597
0.000218
# vim: set fileencoding=UTF-8 import re from datetime import timedelta from django.forms import Field from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from django.utils.dateparse import parse_duration from django.utils.duration import duration_string from .uti...
MICRO = timedelta(microseconds=1) MILLIS = timedelta(milliseconds=1) SECOND = timedelta(seconds=1) MINUTE = timedelta(minutes=1) HOUR = timedelta(hours=1) DAY = timedelta(days=1) WEEK = timedelta(days=7) MONTH = timedelta(days=30) YEAR = timedelta(days=365) # a mapping of regexes to timedeltas UNITS = { 'moment':...
'millisecond': MILLIS, 'mil': MILLIS, 'ms': MILLIS, 'second': SECOND, 'sec': SECOND, 's': SECOND, 'minute': MINUTE, 'min': MINUTE, 'm(?!s)': MINUTE, 'hour': HOUR, 'hr': HOUR, 'h': HOUR, 'day': DAY, 'dy': DAY, 'd': DAY, 'week': WEEK, 'wk': WEEK, 'w': WE...
murgatroid99/grpc
src/python/grpcio_tests/tests/interop/_insecure_intraop_test.py
Python
apache-2.0
1,452
0
# Copyright 2015 gRPC 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 applicable law or agreed to in writing...
server() test_pb2_grpc.add_TestServiceServicer_to_server(methods.TestService(), self.server) port = self.server.add_insecure_port('[::]:0') self.server.start() self.stub = test_pb2_
grpc.TestServiceStub( grpc.insecure_channel('localhost:{}'.format(port))) if __name__ == '__main__': unittest.main(verbosity=2)
abrenaut/waybackscraper
setup.py
Python
mit
608
0.001645
from setuptools import setup, find_packages import sys if sys.version_info[0] < 3 or sys.version_info[1] < 5: sys.exit('Sorry,
Python < 3.5 is not supported') setup(name='waybackscraper', version='0.5', description='Scrapes a website archives on the wayback machine using asyncio.', author='Arthur Brenaut', author_email='arthur.brenaut@gmail.com', packages=find_packages(), entry_points={ 'console_s...
=False)
slivingston/btsynth
btsynth/__init__.py
Python
bsd-3-clause
89
0.022472
""" SCL; 2011, 201
2. """ version = "0.2" from btsynth import * from gridworld import *
rupfw/rup1.0
RUP1.0/Server/Badnet/BadNet2.py
Python
gpl-2.0
905
0.060773
# FALL 2014 Computer Networks SEECS NUST # BESE 3 # Dr Nadeem Ahmed # BadNet2: Errors every 5th Packet # Usage: BadNet.transmit instead of sendto from soc
ket import * class BadNet: dummy=' ' counter = 1 @staticmethod def transmit(csocket,message,serverName,serverPort): # print 'Got a packet' + str(BadNet.counter) if (BadNet.counter % 5) != 0: csocket.sendto(message,(serverName,serverPort)) print 'BadNet Sends properly packet No ' + str(BadNet.counter) ...
ist(message) # get last char of the string x=ord(mylist[-1]) if (x&1)==1: #if first bit set, unset it x &= ~(1) else: #if first bit not set, set it x |= 1 mylist[-1]=chr(x) dummy=''.join(mylist) csocket.sendto(dummy,(serverName,serverPort)) BadNet.counter=BadNet.counter+...
nii-cloud/dodai-compute
nova/scheduler/driver.py
Python
apache-2.0
14,688
0.000204
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2010 Openstack, LLC. # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # ...
self.service_is_up(services[0]): raise exception.ComputeServiceUnavailable(host=src) def _live_migration_dest_check(self, context, instance_ref, dest, block_migration): """Live migration check routine (for destination host). :param context: security c...
stination host """ # Checking dest exists and compute node. dservice_refs = db.service_get_all_compute_by_host(context, dest) dservice_ref = dservice_refs[0] # Checking dest host is alive. if not self.service_is_up(dservice_ref): raise exception.ComputeServ...
manqala/erpnext
erpnext/utilities/transaction_base.py
Python
gpl-3.0
5,360
0.024254
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe import frappe.share from frappe import _ from frappe.utils import cstr, now_datetime, cint, flt from erpnext.controllers.status_updater im...
r(self._prev.contact_by) or \ cstr(self.contact_date) != cstr(self._prev.contact_date) or force: self.delete_events() self._add_calendar_event(opts) def delete_events(self): events = frappe.db.sql_list("""select name from `tabEvent` where ref_type=%s and ref_name=%s""", (self.doctype, self.name)) if...
events))), tuple(events)) def _add_calendar_event(self, opts): opts = frappe._dict(opts) if self.contact_date: event = frappe.get_doc({ "doctype": "Event", "owner": opts.owner or self.owner, "subject": opts.subject, "description": opts.description, "starts_on": self.contact_date, "eve...
AutorestCI/azure-sdk-for-python
azure-mgmt-compute/azure/mgmt/compute/v2016_04_30_preview/models/api_error.py
Python
mit
1,621
0.000617
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
Error(Model): """Api error. :param details: The Api error details :type details: list[~azure.mgmt.compute.v2016_04_30_preview.models.ApiErrorBase] :param innererror: The Api inner error :type innererror: ~azure.mgmt.compute.v2016_04_30_preview.models.InnerError :param code: The error ...
ge: The error message. :type message: str """ _attribute_map = { 'details': {'key': 'details', 'type': '[ApiErrorBase]'}, 'innererror': {'key': 'innererror', 'type': 'InnerError'}, 'code': {'key': 'code', 'type': 'str'}, 'target': {'key': 'target', 'type': 'str'}, 'm...
xapi-project/sm
drivers/mpath_cli.py
Python
lgpl-2.1
3,107
0.001931
#!/usr/bin/python # # Copyright (C) Citrix Systems Inc. # # This program 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; version 2.1 only. # # This program is distributed in the hope that it will be use...
def __init__(self): return def __str__(self): print("", "MPath CLI failed
") mpathcmd = ["/usr/sbin/multipathd", "-k"] def mpexec(cmd): util.SMlog("mpath cmd: %s" % cmd) (rc, stdout, stderr) = util.doexec(mpathcmd, cmd) if stdout != "multipathd> ok\nmultipathd> " \ and stdout != "multipathd> " + cmd + "\nok\nmultipathd> ": raise MPathCLIFail def add_path(...
home-assistant/home-assistant
homeassistant/components/octoprint/sensor.py
Python
apache-2.0
7,576
0.000396
"""Support for monitoring OctoPrint sensors.""" from __future__ import annotations from datetime import datetime, timedelta import logging from pyoctoprintapi import OctoprintJobInfo, OctoprintPrinterInfo from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorStateClass, ) f...
"""Ret
urn sensor state.""" printer: OctoprintPrinterInfo = self.coordinator.data["printer"] if not printer: return None for temp in printer.temperatures: if temp.name == self._api_tool: val = ( temp.actual_temp if self._t...
mmgen/mmgen
test/unit_tests_d/ut_daemon.py
Python
gpl-3.0
4,118
0.043468
#!/usr/bin/env python3 """ test/unit_tests_d/ut_daemon.py: unit test for the MMGen suite's Daemon class """ from subprocess import run,DEVNULL from mmgen.common import * from mmgen.daemon import * from mmgen.protocol import init_proto def test_flags(): d = CoinDaemon('eth') vmsg(f'Available opts: {fmt_list(d.avail...
p.returncode: die(2,f'Unable to execute {d.exec_fn}') else: vmsg('{:16} {}'.format( d.exec_fn+':', cp.stdout.decode().splitlines()[0] )) else: if opt.quiet: msg_r('.') if op == 'stop' and hasattr(d,'rpc'): run_session(d.rpc.stop_daemon(quiet=opt.quiet))...
class unit_tests: win_skip = ('start','status','stop') def flags(self,name,ut): qmsg_r('Testing flags and opts...') vmsg('') daemons = test_flags() qmsg('OK') qmsg_r('Testing error handling for flags and opts...') vmsg('') test_flags_err(ut,daemons) qmsg('OK') return True def cmds(self,name,u...
rollbar/pyrollbar
setup.py
Python
mit
3,249
0.000308
import re import os.path from setuptools import setup, find_packages HERE = os.path.abspath(os.path.dirname(__file__)) README_PATH = os.path.join(HERE, 'README.md') try: with open(README_PATH) as fd: README = fd.read() except IOError: README = '' INIT_PATH = os.path.join(HERE, 'rollbar/__init__.py') ...
Software Development :: Bug Tracking", "Topic :: Software Development :: Testing", "Topic :: Software Development :: Quality Assurance", "Topic :: System :: Logging", "Topic :: System :: Monitoring", ], install_requires=[ # The currently used version of `setuptools` h...
ests>= 0.12.1` # always installs the latest version of the package. 'requests>=0.12.1; python_version == "2.7"', 'requests>=0.12.1; python_version >= "3.6"', 'requests<2.26,>=0.12.1; python_version == "3.5"', 'requests<2.22,>=0.12.1; python_version == "3.4"', 'six>=1.9.0'...
jumoconnect/openjumo
jumodjango/lib/suds/sax/parser.py
Python
mit
4,435
0.000676
# This program is free software; you can redistribute it and/or modify # it under the terms of the (LGPL) GNU Lesser General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will b...
copy o
f the GNU Lesser General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # written by: Jeff Ortel ( jortel@redhat.com ) """ The sax module contains a collection of classes that provide a (D)ocument (O)bject (M)ode...
ericshawlinux/bitcoin
test/functional/interface_zmq.py
Python
mit
4,763
0.00189
#!/usr/bin/env python3 # Copyright (c) 2015-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the ZMQ notification interface.""" import struct from test_framework.address import ADDRESS_BCRT1...
receive the broadcasted txid. txid = self.hashtx.receive() assert_equal(payment_txid, bytes_to_hex_str(txid)) # Should receive the broadcasted raw transacti
on. hex = self.rawtx.receive() assert_equal(payment_txid, bytes_to_hex_str(hash256(hex))) self.log.info("Test the getzmqnotifications RPC") assert_equal(self.nodes[0].getzmqnotifications(), [ {"type": "pubhashblock", "address": ADDRESS}, {"type": "pubhas...
tleonhardt/CodingPlayground
python/prompt-toolkit/auto_suggestion.py
Python
mit
410
0
#!/usr/bin/env python from prompt_toolkit.history import InMemoryHistory from prompt_toolkit import prompt from prompt_toolkit.auto_suggest import AutoSugges
tFromHistory history = InMemoryHistory() wh
ile True: text = prompt("> ", history=history, auto_suggest=AutoSuggestFromHistory()) if text == 'quit': print("Goodbye...") break else: print('You said: {}'.format(text))
abhikumar22/MYBLOG
blg/Lib/site-packages/social_core/backends/eventbrite.py
Python
gpl-3.0
1,055
0.000948
from .oauth import BaseOAuth2 class EventbriteOAuth2(BaseOAuth2): """Eventbrite OAuth2 authentication backend""" name = 'eventbrite' AUTHORIZATION_URL = 'https://www.eventbrite.com/oauth/authorize' ACCESS_TOKEN_URL = 'https://www.eventbrite.com/oauth/token' METADATA_URL = 'https://www.eventbriteap...
['emails']))['email'] return { '
username': email, 'email': email, 'first_name': response['first_name'], 'last_name': response['last_name'] } def user_data(self, access_token, *args, **kwargs): """Loads user data and datacenter information from service""" return self.get_json(self.METADA...
gem/oq-engine
openquake/engine/tools/viewlog.py
Python
agpl-3.0
1,703
0
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2015-2022 GEM Foundation # # OpenQuake 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 Licen...
b import sap def viewlog(calc_id, host='localhost', port=8000): """ Extract the log of the given calculation ID from the WebUI """ base_url = 'http://%s:%s/v1/calc/' % (host, port) start = 0 psize = 10 # page size try: while True: url = base_url + '%d
/log/%d:%d' % (calc_id, start, start + psize) rows = json.load(urlopen(url)) for row in rows: print(' '.join(row)) start += len(rows) time.sleep(1) except BaseException: pass if __name__ == '__main__': viewlog.calc_id = 'calculation ID' ...
semiautomaticgit/SemiAutomaticClassificationPlugin
maininterface/editraster.py
Python
gpl-3.0
15,191
0.032585
# -*- coding: utf-8 -*- ''' /************************************************************************************************************************** SemiAutomaticClassificationPlugin The Semi-Automatic Classification Plugin for QGIS allows for the supervised classification of remote sensing images, provid...
def __init__(self): pass # set raster value def setRasterValueAction(self): self.setRasterValue() # set raster value def setRasterValue(self, batch = 'No', rasterInput = None, vectorInput = None, vecto
rFieldName = None): if cfg.ui.edit_val_use_ROI_radioButton.isChecked() and cfg.lstROI is None: cfg.mx.msg22() return else: if batch == 'No': self.rstrNm = cfg.ui.edit_raster_name_combo.currentText() b = cfg.utls.selectLayerbyName(self.rstrNm, 'Yes') else: b = 'No' if b is not No...