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
hvy/chainer-mnist
models/simplecnn.py
Python
mit
995
0.009045
import chainer import chainer.links as L import chainer.functions as F class SimpleCNN(chainer.Chain): """ Simple Convolutional Neural Network for training the MNIST dataset. Input dimensions are 28, 28, 1 where 1 represent the single grayscale channel. """
def __init__(self): super(SimpleC
NN, self).__init__( conv1 = L.Convolution2D(1, 8, 5, stride=1, pad=2), conv2 = L.Convolution2D(8, 16, 3, stride=1, pad=2), fc1 = L.Linear(576, 10) ) self.train = True def __call__(self, x, t): h = F.relu(self.conv1(x)) h = F.max_poolin...
KivApple/mcu-info-util
mcu_info_util/svd_utils.py
Python
mit
6,803
0.003234
import os from re import match, sub from datetime import datetime from pkg_resources import resource_listdir from cmsis_svd.parser import SVDParser from functools import reduce def find_for_mcu(mcu): mcu = mcu.lower() vendors = resource_listdir("cmsis_svd", "data") for vendor in vendors: fnames = ...
, periph.name, reg.address_offset)) f.write("\n") for field in reg.fields: f.write("/* %s_%s_%s: %s */\n" % (periph.name, sub(r"[\[\]]", "", reg.name), field.name, field.description)) if field.bit_width == 1: f.write("#define %s_%s_%s (1 << %s)...
("#define %s_%s_%s_OFFSET %s\n" % (periph.name, sub(r"[\[\]]", "", reg.name), field.name, field.bit_offset)) f.write("#define %s_%s_%s_WIDTH %s\n" % (periph.name, sub(r"[\[\]]", "", reg.name), ...
SavenR/Bingether
jsframework/api/views.py
Python
artistic-2.0
286
0.006993
from rest_framework import viewsets from jsframework.api.serializers import
exampleSerializer from jsframework.models import modelName class
ExampleViewSet(viewsets.ModelViewSet): queryset = modelName.objects.all() serializer_class = exampleSerializer lookup_field = 'name'
googleapis/python-datacatalog
samples/generated_samples/datacatalog_v1beta1_generated_data_catalog_test_iam_permissions_async.py
Python
apache-2.0
1,610
0.000621
# -*- coding: utf-8 -*- # Copyright 2022 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...
d 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. # # Generated code. DO NOT EDIT! # # Snippet for...
may require modifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-cloud-datacatalog # [START datacatalog_v1beta1_generated_DataCatalog_TestIamPermissions_async] from google.cloud import datacatalog_v1beta1 async def...
zmathe/WebAppDIRAC
Core/ConfMgr.py
Python
gpl-3.0
2,674
0.055348
import imp import os from DIRAC import gConfig, gLogger from DIRAC.Core.Utilities.CFG import CFG from DIRAC.ConfigurationSystem.Client.Helpers import CSGlobals BASECS = "WebApp" def loadWebAppCFGFiles(): """ Load WebApp/web.cfg definitions """ exts = [] for ext in CSGlobals.getCSExtensions(): if ext ==...
nition" % ( modName, current ) ) try: webCFG.deleteKey( current ) except: pass modCFG.deleteKey( "%s/AbsoluteDefinition" % current ) else: for sec in modCFG[ current ].listSect
ions(): expl.append( "%s/%s" % ( current, sec ) ) #Add the modCFG webCFG = webCFG.mergeWith( modCFG ) gConfig.loadCFG( webCFG ) def getRawSchema(): """ Load the schema from the CS """ base = "%s/Schema" % ( BASECS ) schema = [] explore = [ ( "", schema ) ] while len( explore ): pa...
drawquest/drawquest-web
website/drawquest/apps/brushes/migrations/0009_add_iphone_fields_to_paintbrush.py
Python
bsd-3-clause
5,409
0.00721
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import DataMigration from django.db import models class Migration(DataMigration): def forwards(self, orm): brush = orm.Brush.objects.get(canonical_name='paintbrush') brush.description = "Billy is perfect for that painter...
eld', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('d
jango.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_le...
mdrio/pydoop
pydoop/__init__.py
Python
apache-2.0
5,061
0.001383
# BEGIN_COPYRIGHT # # Copyright 2009-2015 CRS4. # # 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 agree...
ER.hadoop_native(hadoop_home) def hadoop_classpath(hadoop_home=None): return _PATH_FINDER.hadoop_classpath(hadoop_home) def package_dir(): return os.path.dirname(os.path.abspath(__file__)) ############################## # Since Pydoop 1.0, we've stopped supporting installations for multiple # Hadoop versi...
of the Hadoop version. ############################## def jar_name(hadoop_vinfo=None): return "pydoop.jar" def jar_path(hadoop_vinfo=None): path = os.path.join(package_dir(), jar_name()) if os.path.exists(path): return path else: return None def complete_mod_name(module, hadoop_vinf...
bleepr/bleepr-relay
socket_server/socket_server.py
Python
mit
1,009
0.004955
#!/usr/bin/python import json import redis from ws4py.client.threadedclient import WebSocketClient r = redis.StrictRedis(host="localhost", port=6379, db=0) class SocketClient(WebSocketClient): def opened(self): # Subscribe to channel - JSON inside JSON, WTF is this library Snowden! print("opening"...
: print("Socket closed: {}, {}".format(code, reason)) def received_message(self, message): message = str(message) data = json.loads(message) data["device"] = "20:C3:8F:F6:5E:CE" # Temp hack, MAC should come from server mac_address = data["device"] r.append(mac_addre...
f run_socket(): ws = SocketClient("ws://burger.bleepr.io/websocket") ws.connect() ws.run_forever() if __name__ == "__main__": run_socket()
pplu/botocore
tests/unit/retries/test_standard.py
Python
apache-2.0
26,658
0
from tests import unittest import mock from nose.tools import assert_equal, assert_is_instance from botocore.retries import standard from botocore.retries import quota from botocore import model from botocore.awsrequest import AWSResponse from botocore.exceptions import HTTPClientError, ConnectionError from botocore....
'members': {}, }, 'ModeledThrottlingError': { 'type': 'structure', 'members': { 'message': { 'shape': 'ErrorMessage', } }, 'exception': True, 'retryable': {'throttling': True} }, ...
'shape': 'ErrorMessage', } }, 'exception': True, 'retryable': {} }, 'ModeledRetryableErrorWithCode': { 'type': 'structure', 'members': { 'message': { 'shape': 'ErrorMessage', ...
google-research/seed_rl
mujoco/toy_env.py
Python
apache-2.0
4,588
0.005449
# coding=utf-8 # Copyright 2019 The SEED 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 agre...
loat(0.) else: reward = -float(sum((action-self.memory[self.t - self.horizon])**2)) self.t += 1 return self._get_obs(), reward, False, None def reset(self): self.memory = np.random.uniform( -1, 1, size=(self.horizon, self.n_actions)).astype(np.float32) self.t = 0 return self._ge...
v): """Goal-based environment in which actions correspond to switching bits. Based on https://arxiv.org/pdf/1707.01495.pdf. """ def __init__(self, n_bits=10, horizon=20): self._n_bits = n_bits self._horizon = horizon self.observation_space = gym.spaces.Dict( achieved_goal=gym.spaces.Box(lo...
armab/st2contrib
packs/openstack/actions/lib/openstack.py
Python
apache-2.0
2,933
0
import os import re import yaml import types from keystoneclient.auth.identity import v2 from keystoneclient import session from keystoneclient.v2_0.client import Client as keyclient class OpenStack(object): def __init__(self, conf): config_file = os.path.join(os.
path.dirname(__file__), conf) try: fh = open(config_file) config = yaml.load(fh) fh.clo
se() except Exception as e: print("Error reading config file %s: %s" % (conf, e)) self.username = config['username'] self.password = config['password'] self.tenant = config['tenant'] self.auth_url = config['auth_url'] self.endpoints = config['endpoints'] ...
samuelmaudo/yepes
yepes/contrib/standards/migrations/0001_initial.py
Python
bsd-3-clause
16,430
0.005356
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import yepes.contrib.standards.model_mixins import mptt.fields import yepes.fields class Migration(migrations.Migration): dependencies = [ ] initial = True operations = [ migrations.Cre...
ian Name', blank=True)), ('name_zh', yepes.contrib.standards.model_mixins.LocalizedNameField(db_index=True, max_length=127, verbose_name='Chinese Name', blank=True)), ('region', models.ForeignKey(related_name='countries', verbose_name='Region', to='standards.Region')), ('...
ple "ES".', unique=True, verbose_name='Code')), ('long_code', yepes.fields.CharField(min_length=3, force_upper=True, charset='A-Z', max_length=3, help_text='Specify 3-letter country code, for example "ESP".', unique=True, verbose_name='Long Code')), ('number', yepes.fields.CharField(min_...
ubiqx-org/Carnaval
carnaval/smb/SMB2_Header.py
Python
agpl-3.0
40,520
0.017794
# -*- coding: utf-8 -*- # ============================================================================ # # SMB2_Header.py # # Copyright: # Copyright (C) 2016 by Christopher R. Hertel # # $Id: SMB2_Header.py; 2019-06-18 17:56:20 -0500; crh$ # # -------------------------------------------...
handle ULONG field values. That # ensures that unsigned 32-bit field values are handled correctly. # The <long> type can be used to store UINT32 and UINT64 values, as # well as shorter integer types. # See: https://docs.python.org/2/library/stdtypes.html#typesnumeric # # - This project, overall, is ...
it easy to do protocol testing, # these protections can be easily bypassed. # # References: # # [MS-SMB2] Microsoft Corporation, "Server Message Block (SMB) # Protocol Versions 2 and 3", # http://msdn.microsoft.com/en-us/library/cc246482.aspx # # ToDo: # - Add more unit tests. # ...
DaisukeMiyamoto/ivbpf_manager
ivbpf_manager/pfmanager.py
Python
apache-2.0
5,659
0.002474
# -*- coding: utf-8 -*- import requests import BeautifulSoup import csv class PfManager: """ Data management tool for IVBPF and CNSPF """ PASSWORD_FILE = 'password.txt' LOGIN_URL = 'user.php' REGISTER_URL = 'register.php' DETAIL_URL = 'detail.php' DELETE_URL = 'config.php' def __...
filename, 'wb') as f: raw = self.session.get(record.get('src')).content f.write(raw) return data def del_record(self, id): data = { 'lid': id, 'mode': 'do_ddel' } r = self.session.post(self.base
_url + 'modules/' + self.db_name + self.DELETE_URL, data=data) if self.show_result: print r.text def get_keywordtree(self): pass def make_archive(self, name, filepath): pass # archive = zipfile.ZipFile('./'.name+'.tar.gz', 'w', filepath, zipfile.ZIP_DEFLATED) ...
mheap/ansible
lib/ansible/plugins/cache/jsonfile.py
Python
gpl-3.0
2,046
0.002933
# (c) 2014, Brian Coca, Josh Drake, et al # (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = ''' cache: jsonfi...
description: User defined prefix to use when creating the JSON files env: - name: ANSIBLE_CACHE_PLUGIN_PREFIX ini: - key: fact_caching_prefix section: defaults _timeout: default: 86400 description: Expiration timeout for the cache plugin data ...
integer ''' import codecs try: import simplejson as json except ImportError: import json from ansible.parsing.ajson import AnsibleJSONEncoder, AnsibleJSONDecoder from ansible.plugins.cache import BaseFileCacheModule class CacheModule(BaseFileCacheModule): """ A caching module backed by json files. ...
libvirt/libvirt-test-API
libvirttestapi/repos/network/network_dhcp_leases.py
Python
gpl-2.0
6,408
0.000936
# Copyright (C) 2010-2012 Red Hat, Inc. # This work is licensed under the GNU GPLv2 or later. #test DHCPLeases() API for libvirt import os import json from libvirt import libvirtError from libvirttestapi.utils import utils from libvirttestapi.src import sharedmod required_params = ('networkname',) optional_params = ...
expirytime']: if dnsmasq[j]['mac-address'] == api['mac']: if dnsmasq[j]['ip-address'] == api['ipaddr']: logger.info("PASS: mac: %s" % api['mac']) logger.info("PASS: ip: %s" % api['ipaddr']) logger.info("PASS: expiry-time: %s" % api[...
']) return False break else: if j == len(dnsmasq) - 1: logger.error("Last loop %d, FAIL: mac: %s" % (j, api['mac'])) return False else: if j == len(dnsmasq) - 1: logger.error("Las...
assamite/creamas
creamas/domains/image/gp/artifact.py
Python
gpl-2.0
8,831
0.002718
import numpy as np import deap.gp import cv2 from creamas.core.artifact import Artifact class GPImageArtifact(Artifact): """An artifact implementation for the images created using genetic programming, :class:`GPImageArtifact` requiring ``pip install creamas[extras]``. The artifact implementation is coupled w...
turn black image if any errors occur. import traceback print(traceback.format_exc()
) return np.zeros(img.shape, dtype=np.uint8) # Clip values in range [0, 255] img = np.clip(img, 0, 255, out=img) return np.uint8(img) @staticmethod def max_distance(shape, bw=True): """Maximum distance between two images is calculated as the euclidean distan...
moodpulse/l2
appconf/models.py
Python
mit
902
0.003413
from django.db import models from django.template.defaultfilters import truncatechars class Setting(models.Model): name = models.CharField(max_length=100, unique=True, db_index=True) value = models.TextField(blank=True, default='') value_type = models.CharField(max_length=1, choices=(('s', 'string'), ('i'...
hide_value_in_list = models.BooleanField(default=False) def __str__(self): return "%s = %s (%s)" % (self.name, "**скрыто**" if self.hide_value_in_list else truncatechars(self.value, 150), self.get_value_type_display()) def get_
value(self): val = self.value types = {'s': str, 'i': int, 'b': (lambda v: v.lower() == "true"), 'f': float} return types[self.value_type](val) class Meta: verbose_name = 'Параметр' verbose_name_plural = 'Параметры'
softak/webfaction_demo
vendor-local/lib/python/selenium/webdriver/firefox/firefox_binary.py
Python
bsd-3-clause
5,982
0.002173
# Copyright 2008-2011 WebDriver committers # Copyright 2008-2011 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 requ...
s import WebDriverException from selenium.webdriver.common import utils import time class FirefoxBinary(object): NO_FOCUS_LIBRARY_NAME = "x_ignore_nofocus.so" def __init__(self, firefox_path=None): self._start_cmd = firefox_path if self._start_cmd is None: self._start_cmd = self....
her than modifying the environment of the calling Python process # copy it and modify as needed. self._firefox_env = os.environ.copy() def launch_browser(self, profile): """Launches the browser for the given profile name. It is assumed the profile already exists. """ ...
ardinor/scrutiny
scrutiny/handlers/file.py
Python
mit
7,753
0.006578
from datetime import timedelta, datetime """ Instead of parsing log files, perhaps it would be better to basically tail them, subscribe to changes and when we see an entry that matches our regex, add it. Or, scan through the log files on startup, then set the datetime of the last entry we see as some 'last checked' va...
d+1 if ns >= 60: ns = 0 log_date = log_date.replace(second=ns) matches[log_date] = (m.group('ip_add'), m.group('user')) return matches def read_sshd_logs(self): matches = {} for l...
h.log' in log_file or 'secure' in log_file: modified_time = datetime.strptime(time.ctime(os.path.getmtime( os.path.join(log_dir, log_file))), "%a %b %d %H:%M:%S %Y") if modified_time > self.last_run(): content = self.get_file_content(lo...
blueray45/GSRT
test01_validity_test_SH-PSV_input_S.py
Python
gpl-2.0
1,502
0.01265
# -*- coding: utf-8 -*- """ Created on Thu Jan 21 04:00:41 2016 @author: irnakat """ # test IOfile import IOfile from TFCalculator import TFCalculator as TFC import TFDisplayTools # validity test for SH PSV case using S wave as an input # filename fname = 'sampleinput_linear_elastic_1layer_halfspace....
# kennet sh print 'TF calculation using kennet sh method' th
eclass5 = TFC(datash) theclass5.tf_kennet_sh() print 'calculation has been finished!' TFDisplayTools.TFPlot(theclass1,theclass3,theclass5,theclass4, \ label=['Kramer SH','Knopoff SH','Kennet SH','Knopoff PSV']) TFDisplayTools.PhasePlot(theclass1,theclass3,theclass5,theclass4, \ label=['Kramer SH',...
davebridges/Lab-Website
communication/tests.py
Python
mit
14,526
0.01783
""" This file contains the unit tests for the :mod:`communication` app. Since this app has no models there is model and view tests: * :class:`~communication.tests.CommunicationModelTes
ts` * :class:`~communication.tests.CommunicationViewTests` """ from lab_website.tests import BasicTests from communication.models import LabAddress,LabLocation,Post from perso
nnel.models import Address, Person from papers.models import Publication from projects.models import Project class CommunicationModelTests(BasicTests): '''This class tests the views associated with models in the :mod:`communication` app.''' fixtures = ['test_address',] def test_create_new_lab_add...
hunch/hunch-gift-app
django/__init__.py
Python
mit
565
0.00177
VERSION = (1, 3, 0, 'alpha', 1) def get_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version = '%s.%s' % (version, VERSION[2]) if VERSION[3:]
== ('alpha', 0): version = '%s pre-alpha' % version else: if VERSION[3] != 'final': version = '%s %s %s' % (version, VERSION[3], VERS
ION[4]) from django.utils.version import get_svn_revision svn_rev = get_svn_revision() if svn_rev != u'SVN-unknown': version = "%s %s" % (version, svn_rev) return version
rtx3/Microburst
ray/messager.py
Python
mit
6,218
0.003699
# -*- coding: utf-8 -*- from __future__ import unicode_literals from flask import json from collections import OrderedDict #from event import RayEvents from app import msg_event import models import utils import six class Message(object): def __init__(self, msg_content=None, msg_title='Messages from System', msg_...
message_id=self.msg_id, message_type=self.msg_type, message_from=self.msg_from, message_to=self.msg_to, message_tag=self.msg_tag, message_content=self.ms
g_content, message_title=self.msg_title, message_sent=True) new_msg.save() self.id = new_msg.message_id return self.id def send(self, trace='0000'): self.save() msg_event.on_event('on_send', msg_id=str(self.msg_id), ...
tmelz/reddit_api
reddit/reddit_test.py
Python
gpl-3.0
32,366
0.000247
#!/usr/bin/env python # This file is part of reddit_api. # # reddit_api 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. # # reddit_api...
if self.r.config.is_reddit: url = self.url('/r/programming/comments/bn2wi/') else: url = self.url('/r/reddit_test9/comments/1a/') comments = self.r.get_submission(url=url).comments self.assertFalse([item for item in comments if not (isinst...
len(list(self.r.get_all_comments(limit=num)))) def test_get_front_page(self): num = 50 self.assertEqual(num, len(list(self.r.get_front_page(limit=num)))) def test_info_by_known_url_returns_known_id_link_post(self): if self.r.config.is_reddit: url = 'http://imgur.com/Vr8ZZ'...
Rdbaker/Mealbound
migrations/versions/af956d77be6a_.py
Python
bsd-3-clause
1,726
0
"""Changes the location <-> meal m2m table to user <-> meal m2m table. Revision ID: af956d77be6a Revises: 9628d0303d10 Create Date: 2017-05-24 00:18:02.563617 """ import sqlalchemy as sa from alembic import op from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = 'af956d77be6...
user_id', 'meal_guid') ) op.drop_table('location_meal') # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( 'location_meal', sa.Column('location_guid', postgresql.UUID(), autoincrement=Fals...
utoincrement=False, nullable=False), sa.ForeignKeyConstraint(['location_guid'], ['location.id'], name='location_meal_location_guid_fkey'), sa.ForeignKeyConstraint(['meal_guid'], ['meal.id'], name='location_meal_meal_guid_fkey'), sa....
codedsk/hubcheck
hubcheck/pageobjects/widgets/search_results.py
Python
mit
1,807
0.010515
from hubcheck.pageobjects.widgets.item_list import ItemList from hubcheck.pageobjects.basepageelement import TextReadOnly import re class SearchResults(ItemList): """Specific type of ItemList used to iterate through lists that result from searches. Provides a header_counts() function, that returns t...
t__(owner,locatordict,row_class,row_class_locator
dict) # update the locators with those from the owner self.update_locators_from_owner() # setup page object's components self.counts = TextReadOnly(self,{'base':'counts'}) # update the component's locators with this objects overrides self._updateLocators() #FIXME:...
ccwang002/biocloud-server-kai
src/manage.py
Python
mit
454
0
#!/usr/bin/env python import os import sys if
__name__ == "__main__": # CHANGED manage.py will use development settings by # default. Change the DJANGO_SETTINGS_MODULE environment variable # for using the environment specific settings file. os.environ.setdefault(
'DJANGO_SETTINGS_MODULE', 'biocloud.settings.local' ) from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
geo-poland/frappe
frappe/utils/data.py
Python
mit
16,930
0.032073
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals # IMPORTANT: only import safe functions as this module will be included in jinja environment import frappe import operator import re, urllib, datetime, math import babel.dates...
ttr(frappe.local, "current_date", None): return getdate(frappe.local.current_date).strftime("%Y-%m-%d") + " " + \ now_datetime().strftime('%H:%M:%S.%f') else: return now_datetime().strftime('%Y-%m-%d %H:%M:%S.%f') def nowdate(): """return current date as yyyy-mm-dd""" return now_d
atetime().strftime('%Y-%m-%d') def today(): return nowdate() def nowtime(): """return current time in hh:mm""" return now_datetime().strftime('%H:%M:%S.%f') def get_first_day(dt, d_years=0, d_months=0): """ Returns the first day of the month for the date specified by date object Also adds `d_years` and `d_mo...
Osmose/kitsune
kitsune/search/views.py
Python
bsd-3-clause
23,529
0.000935
import json import logging import time from datetime import datetime, timedelta from itertools import chain from django.conf import settings from django.http import ( HttpResponse, HttpResponseBadRequest, HttpResponseRedirect) from django.shortcuts import render from django.utils.html import escape from django.uti...
mary = bleach.clean(doc['question_content'], strip=True)[:500] result = { 'title': doc['question_title'], 'type': 'question', 'is_solved': doc['question_is_solved'], 'num_answers': doc['question_num_answers'], 'num_votes': doc[...
t_week']} elif doc['model'] == 'forums_thread': summary = _build_es_excerpt(doc, first_only=True) result = { 'title': doc['post_title'], 'type': 'thread'} else: raise UnknownDocType('%s is an unknown doctype' % doc['model']) ...
gwpy/seismon
bin/seismon_epics_client.py
Python
gpl-3.0
11,084
0.027066
#!/usr/bin/env python # # code to read the output from seismon_info and write # the data as epics channels to an EPICS IOC via # channel access # # Data file consists on several lines, one per LIGO site. # each line is space delimited and has the format # Earthquake-GPS Magnitude P-wave-arrival S-wave-arrival R3.5-wave...
N_EQ_LATITUDE_DEG', lat_f) caput(cds.IFO + ':CDS-SEISMON_EQ_LONGITUDE_DEG', long_f) caput(cds.IFO + ':CDS
-SEISMON_EQ_' + cds.SITE + '_DISTANCE_M', dist_f) caput(cds.IFO + ':CDS-SEISMON_' + cds.SITE + '_P_ARRIVALTIME_GPS', p_arr_f) # TESTING #p_arr_f = caput(cds.IFO + ':CDS-SEISMON_' + cds.SITE + '_P_ARRIVALTIME_GPS'] # TESTING #p_arr_i = int(p_arr_f) # TESTING ...
LandRegistry/ownership-alpha
migrations/versions/2e5fec09053_.py
Python
mit
849
0.015312
"""empty message
Revision ID: 2e5fec09053 Revises: None Create Date: 2014-09-01 16:06:13.655715 """ # revision identifiers, used by Alembic. revision = '2e5fec09053' down_revision = None from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql def upgrade():
### commands auto generated by Alembic - please adjust! ### op.create_table('owners', sa.Column('id', sa.Integer(), nullable=False), sa.Column('title_number', sa.String(), nullable=False), sa.Column('lrid', postgresql.UUID(as_uuid=True), nullable=False), sa.Column('owner_index', sa.Integer(), nulla...
waveform80/gpio-zero
docs/examples/led_remote_5.py
Python
bsd-3-clause
476
0
from gpiozero import
LED from gp
iozero.pins.pigpio import PiGPIOFactory from time import sleep factory3 = PiGPIOFactory(host='192.168.1.3') factory4 = PiGPIOFactory(host='192.168.1.4') led_1 = LED(17) # local pin led_2 = LED(17, pin_factory=factory3) # remote pin on one pi led_3 = LED(17, pin_factory=factory4) # remote pin on another pi while T...
alerta/python-alerta-client
alertaclient/commands/cmd_config.py
Python
apache-2.0
298
0
import click @click.command('config', short_help='Display remote client config') @click.pass_obj
def cli(obj): """Display client config downloaded from API server.""" for k, v in obj.items(): if isinstance(v, list): v = ', '.join(v) click.
echo(f'{k:20}: {v}')
kubeflow/pipelines
components/contrib/CatBoost/Train_classifier/from_CSV/component.py
Python
apache-2.0
3,545
0.002539
from kfp.components import InputPath, OutputPath, create_component_from_func def catboost_train_classifier( training_data_path: InputPath('CSV'), model_path: OutputPath('CatBoostModel'), starting_model_path: InputPath('CatBoostModel') = None, label_column: int = 0, loss_function: str = 'Logloss', ...
descriptions = {label_column: 'Label'} column_description_path = tempfile.NamedTemporaryFile(dele
te=False).name with open(column_description_path, 'w') as column_description_file: for idx, kind in column_descriptions.items(): column_description_file.write('{}\t{}\n'.format(idx, kind)) train_data = Pool( training_data_path, column_description=column_description_path, ...
aurelieladier/openturns
python/test/t_DickeyFullerTest_std.py
Python
lgpl-3.0
1,164
0.000859
#! /usr/bin/env python from __future__ import print_function import openturns as ot size = 100 # ARMA parameters arcoefficients = ot.ARMACoefficients([0.3]) macoefficients = ot.ARMACoefficients(0) timeGrid = ot.RegularGrid(0.0, 0.1, size) # White noise ==> gaussian whiteNoise = ot.WhiteNoise(ot.Normal(), timeGrid) ...
e ARMA process # The realization is supposed to be of a stationnary process realization = ot.TimeSeries(myARMA.getRealization()) # In the strategy of tests, one has to detect a trend tendency # We check if the time series writes as x_t = a +b * t + c * x_{t-1} # H0 = c is equal to one and thus # p-value threshold : pr...
= True <=> p-value > p-value threshold test = ot.DickeyFullerTest(realization) print("Drift and linear trend model=", test.testUnitRootInDriftAndLinearTrendModel(0.95)) print("Drift model=", test.testUnitRootInDriftModel(0.95)) print("AR1 model=", test.testUnitRootInAR1Model(0.95))
mkeilman/sirepo
sirepo/template/template_common.py
Python
apache-2.0
23,341
0.001157
# -*- coding: utf-8 -*- u"""Common execution template. :copyright: Copyright (c) 2015 RadiaSoft LLC. All Rights Reserved. :license: http://www.apache.org/licenses/LICENSE-2.0.html """ from __future__ import absolute_import, division, print_function from pykern import pkcompat from pykern import pkio from pykern impor...
import math import numpy import os
import pykern.pkrunpy import re import sirepo.http_reply import sirepo.http_request import sirepo.sim_data import sirepo.template import sirepo.util import subprocess import types DEFAULT_INTENSITY_DISTANCE = 20 #: Input json file INPUT_BASE_NAME = 'in' #: Test if value is numeric text NUMERIC_RE = re.compile(r'^\...
callowayproject/django-app-skeleton
create_pkg.py
Python
gpl-3.0
9,890
0
#!/usr/bin/env python # -*- coding: utf-8 -*- import ConfigParser import os import random import sys import subprocess import platform IS_WINDOWS = False win32api = None if platform.system() == 'Windows': IS_WINDOWS = True try: import win32api except (ImportError, ): pass CONFIG_FILE =...
te()[0]) if not has_venv_wrapper: print 'virtualenvwrapper is required to run this script. Please' \ 'install it with\n easy_install virtualenvwrapper\n\nor\n\n' \ 'pip virtualenvwrapper' sys.exit(1) def mk_virtual_env(name, dest): """Creates a virtualenv using vi...
ng the virtual environment (%s)...' % name if not dest.startswith('/'): dest = os.path.realpath(dest) create_env_cmds = [ 'source virtualenvwrapper.sh', 'cd %s' % dest, 'mkvirtualenv --no-site-packages --distribute %s' % name, 'easy_install pip' ] create_pa_cmd = ...
Yanel85/GAEphotos
lang/ccgettext.py
Python
gpl-2.0
1,569
0.011472
# -*- coding: utf-8 -*- import os,sys import stat,fnmatch import re from pprint import pformat def get_file_list(path, ext, subdir = True ): if os.path.exists(path): dirlist = [] for name in os.listdir(path): fullname = os.path.join(path, name) st = os.lstat(fullname) ...
th.abspath("..") def main(): print(project_path) pyFiles = get_file_list(project_path, '*.py', True) htmlFiles = get_file_list(project_path, '*.html', True) words = [] for fname in pyFiles+htmlFiles: f = open(fname, 'r') conte
nt = f.read() f.close() iterator = re_gettext.finditer(content) matches = list(iterator) iterator = re_gettext2.finditer(content) matches += list(iterator) for match in matches: words.append(unicode(match.group('word'))) words = list(set(words)) print...
Tayamarn/socorro
webapp-django/crashstats/monitoring/tests/test_views.py
Python
mpl-2.0
6,622
0
import datetime import json import mock import pytest from django.core.urlresolvers import reverse from django.conf import settings from django.utils import timezone from crashstats.crashstats.tests.test_views import BaseTestViews, Response from crashstats.crashstats.models import CrontabberState from crashstats.sup...
ettings.DEFAULT_PRODUCT] assert params['_results_number'] == 1 assert params['_columns'] == ['uuid'] return { 'hits': [ {'uuid': '12345'}, ], 'facets': [], 'total': 320, 'errors': ['ba...
} SuperSearch.implementation().get.side_effect = ( mocked_supersearch_get ) with pytest.raises(AssertionError): assert_supersearch_no_errors() assert len(searches) == 1
4815162342lost/get_all_updates_list_via_salt
automatization_scripts/auto_email.py
Python
gpl-3.0
7,682
0.005988
#!/usr/bin/python3 import sqlite3 import datetime import random import csv import itertools import smtplib import glob from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage import sys import os from distutils.sysconfig import get_python_lib import log...
needed servers from csv-files...") servers_for_sending_email = {} csv_files=glob.glob('./*linux_MM*.csv') logging.info("Working with these csv-files: {csv}".format(csv=str(csv_files))) for csv_file_for_open in csv_files: csv_file = open(csv_file_for_open) min_start_time = datetime.datet...
me.now() + datetime.timedelta(minutes=28) patching_schedule_csv = csv.reader(csv_file, delimiter=';') for row in itertools.islice(patching_schedule_csv, 1, None): patching_start_time = datetime.datetime.strptime(row[1], '%d.%m.%Y %H:%M') if patching_start_time > min_start_time an...
google/transitfeed
examples/table.py
Python
apache-2.0
6,035
0.009114
#!/usr/bin/python2.5 # Copyright (C) 2007 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 la...
tions(schedule, table): service_period = schedule.GetDefaultServicePeriod() agency_name, agency_url, agency_timezone = (None, None, None)
for row in table[1:]: command = row[0].lower() if command == 'weekday': service_period.SetWeekdayService() elif command == 'start_date': service_period.SetStartDate(row[1]) elif command == 'end_date': service_period.SetEndDate(row[1]) elif command == 'add_date': service_p...
luke0922/MarkdownEditor
application/utils/template.py
Python
gpl-2.0
1,363
0
#!/usr/bin/env python # encoding: utf-8 import mistune from pygments import highlight from pygments.lexers import get_lexer_by_name from pygments.formatters import html from flask import current_app, render_template from application.models.system import site from application.services.system import has base_env = { ...
base_env) return render_template(template, **kwargs) def format_markdown(mdstr): render = Hi
ghlightRenderer() markdown = mistune.Markdown(renderer=render) return markdown(mdstr)
pyrrho314/recipesystem
trunk/dontload-astrodata_Gemini/RECIPES_Gemini/primitives/primitivesIndex.NIRI.py
Python
mpl-2.0
328
0
# This is added to the
reduction object dictionary, but only one reduction # object per AstroData Type. NOTE: primitives are the
member functions of a # Reduction Object. localPrimitiveIndex = { "NIRI": ("primitives_NIRI.py", "NIRIPrimitives"), "NIRI_IMAGE": ("primitives_NIRI_IMAGE.py", "NIRI_IMAGEPrimitives"), }
stuarteberg/lazyflow
tests/testPathHelpers.py
Python
lgpl-3.0
6,093
0.006565
############################################################################### # lazyflow: data flow based lazy parallel computation framework # # Copyright (C) 2011-2014, the ilastik developers # <team@ilastik.org> # # This program is free software; you can redistribute it and/o...
mplied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # See the files LICENSE.lgpl2 and LICENSE.lgpl3 for full text of the # GNU Lesser General Public License version 2.1 and 3 respectively. # This information is also available on the i...
########## import os from lazyflow.utility.pathHelpers import compressPathForDisplay, getPathVariants, PathComponents SIMULATE_WINDOWS = False class TestPathHelpers(object): @classmethod def setupClass(cls): if SIMULATE_WINDOWS: import ntpath os.sep = ntpath.sep os...
vitlav/korinf
share/eterbuild/korinf/helpers/send_via_pyxmpp.py
Python
agpl-3.0
849
0.014134
#!/usr/bin/python3 # https://bugzilla.altlinux.org/show_bug.cgi?id=33532 #!/usr/bin/env -S python3 -u # -*- coding: utf-8 -*- # # A
simple message-sending script # TODO: When error: No handlers could be found for logger "pyxmpp.Client" import os, sys # python-module-pyxmpp from pyxmpp2.jid import JID from pyxmpp2.jabber.simple import send_message # set in korinf config file jid = os.environ['KORINFERJID'] password = os.environ['KORINFERJIDPASS...
rint("example:") print("\t%s test1@localhost Test 'this is test'" % (sys.argv[0],)) sys.exit(1) recpt,subject,body=sys.argv[1:] jid = JID(jid) if not jid.resource: jid = JID(jid.node,jid.domain,"korinf") recpt = JID(recpt) send_message(jid,password,recpt,body,subject)
baiper06/tutorial-tkinter
Widgets/7. Menu/Menu.py
Python
mit
440
0.020455
from tkinter import * ventana = Tk() ventana.minsize(
500,500) def Opcion1(): print ("click en: opcion uno") def Opcion2(): print ("click en: opcion dos") #se crea el widget menu barramenu = Menu(ventana) barramenu.add_command(label="Opcion uno", command=Opcion1) barramenu.add_command(label="Opcion dos", command=Opcion2) #Se le asigna e
l menu a la ventana ventana.config(menu=barramenu) ventana.mainloop()
nijel/weblate
weblate/lang/apps.py
Python
gpl-3.0
1,144
0
# # Copyright © 2012–2022 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.org/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Lice
nse, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # 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 Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. # from django.apps import AppConfig ...
movicha/dcos
gen/test_template.py
Python
apache-2.0
6,998
0.002572
import pytest import gen.template from gen.template import (For, Replacement, Switch, Tokenizer, UnsetParameter, parse_str) just_text = "foo" more_complex_text = "foo {" def get_tokens(str): return Tokenizer(str).tokens def test_lex(): assert(get_tokens("foo") == [("blob", "foo")...
with pytest.raises(gen.template.SyntaxError): get_tokens("{{ test| }}") with pytest.raises(gen.template.SyntaxError): get_tokens("{{ test | }}") with pytest.raises(gen.template.SyntaxError): get_tokens("{{ test }}") with pytest.raises(gen.template.SyntaxError): get_to...
assert(parse_str("{{ a }}").ast == [Replacement(("a", None))]) assert(parse_str("a {{ a | foo }}{{ b }} c {{ d | bar }}").ast == [ "a ", Replacement(("a", 'foo')), Replacement(("b", None)), " c ", Replacement(("d", 'bar')) ]) assert(parse_str('{% switch foo %}{% ...
Ratfink/kaylee
kayleevc/gui.py
Python
gpl-3.0
7,189
0.000556
# This is part of Kaylee # -- this code is licensed GPLv3 # Copyright 2015-2016 Clayton G. Hobbs # Portions Copyright 2013 Jezra import sys import gi from gi.repository import GObject # Gtk gi.require_version('Gtk', '3.0') from gi.repository import Gtk, Gdk class GTKTrayInterface(GObject.GObject): __gsignals__ =...
rType.CONTROL_MASK, Gtk.AccelFlags.VISIBLE, self.accel_qu
it) # Lock the group accel.lock() # Add the group to the window self.window.add_accel_group(accel) def ccheckbox_clicked(self, widget): checked = self.ccheckbox.get_active() self.lsbutton.set_sensitive(not checked) if checked: self.lsbutton_stoppe...
jianhuashao/WebDownloadJobsManage
post-process/CONFIG.py
Python
apache-2.0
24
0.041667
client_id = '
jian-m
ac'
costastf/python_library_cookiecutter
_CI/scripts/test.py
Python
mit
3,282
0.001523
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: test.py # # Copyright 2018 Costas Tyfoxylos # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without li...
ce and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN...
T, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # import argparse import logging import json import os from bootstrap import bootstrap from library import execute_command, tempdir # This is the main prefix used for logging LOGGER_BASEN...
shunsukeaihara/pyworld
test/test_filter.py
Python
mit
1,201
0
# -*- coding: utf-8 -*- from unittest import TestCase # from nose.tools import eq_ import numpy as np from pysas import w
averead, World from pysas.mcep import estimate_alpha, spec2mcep_from
_matrix, mcep2coef from pysas.synthesis.mlsa import MLSAFilter from pysas.synthesis import Synthesis from pysas.excite import ExcitePulse class SynthesisTest(TestCase): def setUp(self): signal, samplingrate, _ = waveread("test/cmu_arctic/arctic_a0001.wav") self.world = World(samplingrate) ...
ingkebil/trost
scripts/create_tables/create_plants2table.py
Python
gpl-2.0
2,360
0.006356
#!/usr/bin/python import os import sys import math import glob import sql import process_xls as p_xls """ Change to whatever is needed. """ DEFAULT_DATE_STR = '' DB_NAME = 'trost_prod' TABLE_NAME = 'plants2' TABLE = [ 'id INT(11) AUTO_INCREMENT', 'aliquot INT(11)', 'name VARCHAR(45)', 'subspecies_...
, 'Subspecies_Id': (2, 'subspecies_id', int), 'Location_Id': (3, 'location_id', int), 'Culture_Id': (4, 'culture_id', int), 'Sample_Id': (5, 'sampleid', int), 'Description': (6, 'description', str), 'created': (7, 'created', str)} ### def main(argv): if len(ar
gv) == 0: sys.stderr.write('Missing input file.\nUsage: python create_plants2table.py <dir>\n') sys.exit(1) sql.write_sql_header(DB_NAME, TABLE_NAME, TABLE) dir_name = argv[0] fn = '%s/%s' % (dir_name, 'current_plants.xls') data, headers = p_xls.read_xls_data(fn) """ Some ...
hkariti/ansible
lib/ansible/utils/module_docs_fragments/iosxr.py
Python
gpl-3.0
3,401
0.00294
# # (c) 2015, Peter Sprygada <psprygada@ansible.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any late...
"ncclient >= 0.5.3 when using netconf" - "lxml >= 4.1.1 when using netconf
" notes: - For more information on using Ansible to manage network devices see the :ref:`Ansible Network Guide <network_guide>` - For more information on using Ansible to manage Cisco devices see the `Cisco integration page <https://www.ansible.com/integrations/networks/cisco>`_. """
machinecoin-project/machinecoin
test/util/machinecoin-util-test.py
Python
mit
6,744
0.00356
#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2017 The Machinecoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for machinecoin utils. Runs automatically during `make ch...
aise Exception if not outputType: logging.error("Output file %s does not have a file extension" % outputFn) rais
e Exception # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise i...
ict-felix/stack
vt_manager_kvm/src/python/scripts/create_oms.py
Python
apache-2.0
273
0.003663
''' Created on Jun 27, 2010 @author
: jnaous ''' from openflow.dummyom.models import DummyOM def run(): for om in DummyOM.objects.all(): om.delete() for i in xrange(3): om = DummyO
M.objects.create() om.populate_links(10, 20)
EmreAtes/spack
var/spack/repos/builtin/packages/py-asn1crypto/package.py
Python
lgpl-2.1
1,619
0.001235
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore Nationa
l Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our not
ice and the LGPL. # # 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, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARR...
ispmarin/text_norm
src/main.py
Python
mit
961
0.003122
# __author__ = 'ispmarin' from nltk.corpus import stopwords import string from transform.normalizer import * from transform.parser import * # Definitions encoding = "utf-8" separator_mob = "|" separator_cor = "," cep_digits = 8 useful_columns = [0, 12, 13, 15, 26, 27, 28, 29, 30] column_names = ['tel', 'nome', 'cat',...
on) language = 'portuguese' prefi
x_file = '../data/prefixes.csv' with open(prefix_file, 'r') as g: prefixes = g.read().splitlines() address_prefixes = prefixes if __name__ == "__main__": test_string = "Rua XV de Novembro, 123 bloco 23 A" normalized_address = normalize_address( test_string, punctuation, stopwords.words(language...
pinkra/neisse
src/agent/test/testConfig.py
Python
gpl-3.0
486
0.014403
import sys, os import re __dir = os.path.dirname(os.path.realpath(__file__)) sys.path.append(__dir
+ '/../model') import unittest from Config import Config class TestConfig(unittest.TestCase): def test_config(self): config = Config(os.path.dirname(os.path.realpath(__file__)) + '/config.json') self.assertTrue(len(config.getCollectors()) > 0) self.assertTrue(len(config.getData('SystemDat...
'__main__': unittest.main()
hernandito/SickRage
tests/helpers_tests.py
Python
gpl-3.0
16,369
0.000305
#!/usr/bin/env python2.7 # coding=utf-8 # Author: Dustyn Gibson <miigotu@gmail.com> # URL: http://github.com/SickRage/SickRage # # This file is part of SickRage. # # SickRage 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 Softwar...
es(self): """ Test listMediaFiles """ pass @unittest.skip('Not yet implemented') def test_copy_file(self): """ Test copyFile """ pass @unittest.skip('Not yet implemented') def test_move_file(self): """ Test moveFile ...
lf): """ Test rename_ep_file """ pass @unittest.skip('Not yet implemented') def test_file_bit_filter(self):
silviacanessa/oq-hazardlib
openquake/baselib/tests/performance_test.py
Python
agpl-3.0
1,417
0
import time import unittest import pickle import numpy from openquake.baselib.performance import PerformanceMonitor # NB: tests for the HDF5 functionality are in risklib class MonitorTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.mon = P
erformanceMonitor('test') def test_no_mem(self): mon = self.mon('test_no_mem') for i in range(3): with mon: time.sleep(0.1) self.assertGreater(mon.duration, 0.3) mon.flush() def test_mem(self): mon = self.mon('test_mem', measuremem=True) ...
(range(100000))) # allocate some RAM time.sleep(0.1) self.assertGreaterEqual(mon.mem, 0) mon.flush() def test_children(self): mon1 = self.mon('child1') mon2 = self.mon('child2') with mon1: time.sleep(0.1) with mon2: time.sleep...
srinath9/physicalweb
web-service/tests.py
Python
apache-2.0
11,378
0.001758
#!/usr/bin/env python # # Copyright 2015 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 o...
] }) self.assertIn('metadata', result) self.assertEqual(len(result['metadata']), 4) self.assertEqual(result['metadata'][
0]['id'], 'http://benfry.com/distellamap/') self.assertEqual(result['metadata'][1]['id'], 'http://en.wikipedia.org/wiki/' 'Le_D%C3%A9jeuner_sur_l%E2%80%99herbe') self.assertEqual(result['metadata'][2]['id'], ...
slohr/paperlims
paperlims/core/models/site_message.py
Python
mit
236
0.021186
from django.db import models from core.models.base import Base class SiteMessage(Base): message
= models.TextField() class Meta: app_label
= "core" db_table = 'site_message' def __str__(self): return self.message
Hemisphere-Project/HPlayer2
core/interfaces/pyre.py
Python
gpl-3.0
2,225
0.013034
from .base import BaseInterface from time import sleep from pyre import Pyre from pyre import zhelper import zmq class ZyreNode (): def __init__(self, interface, netiface=None): self.interface = interface # Peers book self.book = {} self.topics = [] # Publisher ...
lass PyreInterface (BaseInterface): def __init__(self, hplayer, netiface=None): super().__init__(hplayer, "PYRE") self.node = ZyreNode(self, netiface) def listen(self): self.log( "interface ready") self.stopped.wait() self.log( "closing pyre...") ...
top() # while not self.node.done: # sleep(0.1) self.log( "done.") def activeCount(self): return 0 #len(self.node.book) def peersList(self): return [] #self.node.book
cgre-aachen/gempy
examples/tutorials/ch5_probabilistic_modeling_DEP/ch5_1.py
Python
lgpl-3.0
5,072
0.00276
""" 5.1 - Probabilistic Modeling: Error Propagation ================================================ In this example we will show how easy we can propagate uncertainty from GemPy parameters to final structural models. """ # %% import sys, os sys.path.append("../../gempy") os.environ["THEANO_FLAGS"] = "mode=FAST_RUN,...
be discuss # below but for this lets treat is a simple spatial interpolation in order # to keep the focus on the constraction of the probabilistic model. # # %% geo_model = gp.create_model('2-layers') gp.init_data(geo_model, extent=[0, 12e3, -2e3, 2e3, 0, 4e3], resolution=[100, 10, 200]) # %% geo_model.add_surfaces('...
model.add_surface_values([dz, 0, 0], ['dz']) geo_model.add_surface_values(np.array([2.6, 2.4, 3.2]), ['density']) # %% geo_model.add_surface_points(3e3, 0, 3.05e3, 'surface 1') geo_model.add_surface_points(9e3, 0, 3.05e3, 'surface 1') geo_model.add_surface_points(3e3, 0, 1.02e3, 'surface 2') geo_model.add_surface_poi...
CoderEnko007/Pokedex
tools/searcher.py
Python
lgpl-3.0
337
0.035608
from scipy.spatial import distance as dist class Searcher: def __init__(self, index): self.index = index def search(self, queryFeature): res
ults = {} for (k, feature) in self.index.items(): d = dist.euclidean(queryFeature, feature) results[k] = d results = sorted([(v, k) for (k, v) in
results.items()]) return results
Dr15Jones/root
cint/reflex/python/genreflex/gendict.py
Python
lgpl-2.1
136,187
0.030811
# Copyright CERN, CH-1211 Geneva 23, 2004-2010, All rights reserved. # # Permission to use, copy, modify, and distribute this software for any # purpose is hereby granted without fee, provided that this copyright and # permissions notice appear in all copies and derivatives. # # This software is provided "as is" withou...
--------------------------------------- # This function is not used anymore, because it had a problem with templated types # showing up as members of a scope in the gccxml generated output. If gccxml puts # templated types as members this function should be resurrected for performance # reasons. It shall be called
from self.parse instead of 'for col in [self.class...' def collectCppSelections(self, ns) : for m in ns.get('members').split(): xm = self.xref[m] xelem = xm['elem'] if xelem in ('Namespace',) : self.collectCppSelections(xm['attrs']) cname = self.genTypeName(m) if xelem in ('...
fengbohello/practice
python/func/built-in/abs.py
Python
lgpl-3.0
207
0
def test_abs(a): print "abs(" + str(a) + ") = [" + str(abs(a)) + "]"
test_abs(10) test_abs(10.0) test_abs(-10) test_abs(-10.2) test_abs(long(-10)) test_abs(0) test_abs(0.0)
test_abs(-0) test_abs(-0.0)
fedspendingtransparency/data-act-broker-backend
dataactcore/migrations/versions/ad3dd1c0cf20_add_high_comp_officer_fields_to_.py
Python
cc0-1.0
2,902
0.00827
"""Add high comp officer fields to published_award_financial_assistance table Revision ID: ad3dd1c0cf20 Revises: 5f29b283f23e Create Date: 2019-05-23 08:31:35.225654 """ # revision identifiers, used by Alembic. revision = 'ad3dd1c0cf20' down_revision = '5f29b283f23e' branch_labels = None depends_on = None from alem...
upgrade(engine_name): globals()["upgrade_%s" % engine_name]() def downgrade(engine_name): globals()["downgrade_%s" % engine_name]() def upgrade_data_broker(): # ### commands auto generated by Alembic - please adjust! ### op.
add_column('published_award_financial_assistance', sa.Column('high_comp_officer1_amount', sa.Text(), nullable=True)) op.add_column('published_award_financial_assistance', sa.Column('high_comp_officer1_full_na', sa.Text(), nullable=True)) op.add_column('published_award_financial_assistance', sa.Column('high_comp...
the-blue-alliance/the-blue-alliance
old_py2/helpers/cache_clearer.py
Python
mit
18,615
0.003868
from google.appengine.ext import ndb from consts.media_tag import MediaTag from controllers.api.api_district_controller import ApiDistrictListController, ApiDistrictEventsController, ApiDistrictRankingsController, ApiDistrictTeamsController from controllers.api.api_event_controller import ApiEventController, ApiEventT...
controllers(team_keys, event_keys) + \ cls._get_event_district_points_cache_keys_and_controllers(event_keys) + \ cls._queries_to_cache_keys_and_controllers(get_affected_queries.match_updated(affected_refs)) @classmethod def get_media_cache_keys_and_controllers(cls, affected_refs): ...
erence this media """ reference_keys = affected_refs['references'] years = affected_refs['year'] media_tag_enums = affected_refs['media_tag_enum'] tags = map(lambda media_tag_enum: MediaTag.tag_url_names[media_tag_enum], media_tag_enums) return cls._get_media_cache_keys...
undergroundtheater/gameheart
gameheart/entities/decorators.py
Python
mit
570
0.010526
#Decorators from django.http import HttpResponseRedirect from gameheart.entities.models import UserProfile def c
heck_terms(function): def wrap(request, *args, **kwargs): profile = UserProfile.objects.get(user=request.user) if profile.acceptedterms == False: action = request.path_info red = ''.join(['/terms/?next=',action]) return HttpResponseRedirect(red) else: ...
**kwargs) wrap.__doc__=function.__doc__ wrap.__name__=function.__name__ return wrap
zzyfisherman/moose
python/PresentationBuilder/slidesets/SlideSet.py
Python
lgpl-2.1
11,362
0.013642
# Load python packages import re, sys, math from collections import OrderedDict # Load Moose packages from FactorySystem import MooseObject from ..slides import * ## # Base class for markdown slide generation class SlideSet(MooseObject):
## # Defines the available properties for the SlideSet base class @staticmethod def validParams(): params = MooseObject.validParams() params.addRequiredParam('type', 'The type of slide set to create') params.addParam('title', 'Th
e title of the slide set, if this exists a title slide will be injected') params.addParam('active', 'A list of ordered slide names to output, if blank all slides are output') params.addParam('inactive', 'A list of slide names to exclude from output') params.addParam('contents', False, 'Include table of cont...
josephmfaulkner/stoqs
stoqs/utils/Viz/KML.py
Python
gpl-3.0
15,397
0.005066
import os import sys import time import numpy import logging from stoqs import models as m from django.conf import settings from django.db.models import Avg from django.http import HttpResponse, HttpResponseBadRequest import pprint logger = logging.getLogger(__name__) class InvalidLimits(Exception): pass def r...
epth__gte']), float(self.qparams['sample__depth__lte'])) except KeyError: folderName = "%s_" % (pName,) dataHash = {} for d in data: try: dataHash[d[6]].append(d) except KeyError: dataHash[d[6]] = [] da...
provided') return response descr = self.request.get_full_path().replace('&', '&amp;') logger.debug(descr) try: kml = self.makeKML(self.request.META['dbAlias'], dataHash, pName, folderName, descr, self.request.GET.get('cmin', None), self.request.GET.get('cmax', None)) ...
pijyoi/jsonrpc
testmethods.py
Python
mit
1,581
0.019608
import zmq class JRPC: def __init__(self): self.id = 0 def make_noti(self, method, params=None): noti = {"jsonrpc":"2.0", "method":method} if params is not None: noti["params"] = params return noti def make_req(self, method, params=None): req = self.make_noti(method, params) req["id"] = self.id s...
.make_req("echo", [10, 5]) zsock.send_json(req) rep = zsock.recv_json() assert(rep['result']==req['params']) # test "counter" method and batch req = jrpc.make_req("counter") zsock.send_json([req]*10) batchrep = zsock.recv_json() counts = [rep['result'] for rep in b
atchrep] for k in range(1,len(counts)): assert counts[k] - counts[k-1] == 1 # test "sum" method and batch batchreq = [] for k in range(10): batchreq.append(jrpc.make_req("sum", range(1+k))) zsock.send_json(batchreq) batchrep = zsock.recv_json() for k in range(10): assert(batchrep[k]['result']==sum(range(1+k))) a =...
rtfd/sphinx-autoapi
docs/conf.py
Python
mit
10,156
0.00512
# -*- coding: utf-8 -*- # # Sphinx AutoAPI documentation build configuration file, created by # sphinx-quickstart on Wed Apr 22 15:38:18 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file...
os = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pa
ges. See the documentation for # a list of builtin themes. html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom th...
oyamad/QuantEcon.py
quantecon/util/timing.py
Python
bsd-3-clause
5,239
0
""" Provides Matlab-like tic, tac and toc functions. """ import time import numpy as np class __Timer__: """Computes elapsed time, between tic, tac, and toc. Methods ------- tic : Resets timer. toc : Returns and prints time elapsed since last tic(). tac : Returns and ...
elf.start = t self.last = t def tac(self, verbose=True, digits=2): """ Return and print elapsed time since last `tic()`, `tac()`, or `toc()`. Parameters ---------- verbose : bool, optional(default=True) If True, then prints time. digi
ts : scalar(int), optional(default=2) Number of digits printed for time elapsed. Returns ------- elapsed : scalar(float) Time elapsed since last `tic()`, `tac()`, or `toc()`. """ if self.start is None: raise Exception("tac() without tic()") ...
kzoacn/Grimoire
Training/9.10(ShenyangOnline)/L_gen.py
Python
gpl-3.0
214
0.065421
import random T = 10 for tt in range(T): n = 10 ** 6 print(n) for i in
range(n): print(random.randint(0, 1000), end = ' ') print() for i in ra
nge(n): print(random.randint(1, 1000), end = ' ') print()
Diaoul/subliminal
tests/test_score.py
Python
mit
3,395
0.005007
# -*- coding: utf-8 -*- from __future__ import division from babelfish import Language from subliminal.providers.addic7ed import Addic7edSubtitle from subliminal.providers.opensubtitles import OpenSubtitlesSubtitle from subliminal.providers.podnapisi import PodnapisiSubtitle from subliminal.score import compute_score...
equations def test_episode_equations(): expected_scores = {} for symbol, score in solve_episode_equations().items(): expected_scores[str(symbol)] = score assert episode_scores == expected_scores def test_movie_equations(): expected_scores = {} for symbol, score in solve_movie_eq
uations().items(): expected_scores[str(symbol)] = score assert movie_scores == expected_scores def test_compute_score(episodes): video = episodes['bbt_s07e05'] subtitle = Addic7edSubtitle(Language('eng'), True, None, 'the big BANG theory', 6, 4, None, None, '1080p', None) expected_score = epi...
educreations/activity-tracker
tests/test_redis_backend.py
Python
mit
4,967
0
"""Tests for the activity tracker redis backend. To test with a real redis server instead of the builtin fake server, set the ACTIVITY_TRACKER_TEST_REAL_REDIS environment variable to the number of a local database. All data in that database will be destroyed. """ import datetime import os import unittest import uuid ...
er import ActivityTracker import fakeredis REAL_REDIS_ENV = 'ACTIVITY_TRACKER_TEST_REAL_REDIS' # A few dummy testing values UUI
D1 = '752a46a2-0ae6-3346-9838-d4a1313b9637' UUID2 = 'e1932785-4860-34f3-a593-8ddf66fc4894' UUID3 = 'eb05ee25-807f-3d40-b853-674cf25a1d46' UUID4 = 'd3ba4e99-1e47-3a0e-9c2f-3d9f10a3d1fe' class RedisBackendTestCase(unittest.TestCase): def setUp(self): if REAL_REDIS_ENV not in os.environ: redis_ba...
edx/edx-enterprise
integrated_channels/degreed/migrations/0006_upgrade_django_simple_history.py
Python
agpl-3.0
775
0.00129
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-12-13 15:23 # This is necessary because django-simple-history 2.6.0 changes the model import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('degreed', '0005_auto_20...
prisecustomerconfiguration', name='enterprise_customer', field=models.ForeignKey(blank=True, db_constraint=False, help_text='Enterprise Customer associated with the
configuration.', null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='enterprise.EnterpriseCustomer'), ), ]
jsshack15/hackathon-2015
hacks/views.py
Python
mit
6,441
0.024841
from django.shortcuts import render from django.http import HttpResponse,JsonResponse from django.views import generic from django.views.generic.edit import FormView, CreateView from django.core.urlresolvers import reverse_lazy from django.core.mail import send_mail from hacks.models import Hackathon, CodeMania, SendR...
ubject, from_email, to = 'JSS Hackathon 2015', 'Hackathon 2015<mmil@jssaten.ac.in>', request.POST.get('email', ) # text_content = plaintext.render(d) # html_content = htmly.render(d) # msg = EmailMultiAlterna
tives(subject, text_content, from_email, [to]) # msg.attach_alternative(html_content, "text/html") # msg.send() # # send_mail('Hackathon-2015', 'Here is the message.', 'Microsoft Mobile Innovation Lab <mmil@jssaten.ac.in>', ['deshrajdry@gmail.com'], fail_silently=False) # return HttpResponse(json.dumps({"ev...
david415/sphinxmixcrypto
hypothesis/test_hypothesis.py
Python
lgpl-3.0
3,010
0.002658
# -*- coding: utf-8 -*- import py.test import attr from hypothesis import given, assume from hypothesis.strategies import binary import zope import zope.interface from sphinxmixcrypto import IKeyState, SphinxPacket, sphinx_packet_unwrap, PacketReplayCacheDict, SphinxParams from sphinxmixcrypto import SphinxBodySizeMi...
blic_key(self): pass @given( binary(), binary(), binary(), binary(max_size=1023), bi
nary(), ) def test_hypothesis_toosmall_body_size(alpha, beta, gamma, delta, private_key): packet = SphinxPacket(alpha, beta, gamma, delta) params = SphinxParams(max_hops=5, payload_size=1024) replay_cache = PacketReplayCacheDict() key_state = SphinxNodeKeyState(private_key=private_key) py.test.raise...
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractDellstoriesWordpressCom.py
Python
bsd-3-clause
562
0.033808
def extractDellstoriesWordpressCom(item): ''' Parser for 'dellstories.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or v
ol) 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 buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_...
JohnMarohn/FreqDemod
freqdemod/util.py
Python
gpl-3.0
1,678
0.014303
#!/usr/bin/env python # -*- coding: utf-8 -*- # # util.py # John A. Marohn # 2014/06/28 import math import datetime import uuid import numpy as np import errn
o import os # Modified from http://code.activestate.com/recipes/578238-engineering-notation/ def powerise10(x): """ Return x as a * 10 ^ b with 1 <= a <10""" if x == 0: return 0 , 0 Neg = x <0 if Neg : x = -x a = 1.0 * x / 10**(math.floor(math.log10(x))) b = int(math.floor(math.log10(x))) ...
eng(x): """Return a string representing x in an engineer-friendly notation""" a , b = powerise10(x) if -3<b<3: return "%.4g" % x a = a * 10**(b%3) b = b - b%3 return "%.4gE%s" %(a,b) def silent_remove(filename): """If ``filename`` exists, delete it. Otherwise, return nothing. See ht...
cschnei3/forseti-security
tests/enforcer/enforcer_test.py
Python
apache-2.0
4,766
0.003567
#!/usr/bin/env python # Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
().AsMicroTimestamp.return_value = MOCK_TIMESTAMP
self.mock_time.now().AsSecondsSinceEpoch.return_value = MOCK_TIMESTAMP self.enforcer = enforcer.initialize_batch_enforcer( {}, concurrent_threads=1, max_write_threads=1, max_running_operations=0, dry_run=True) self.expected_summary = ( ...
moradology/kmeans
tests/testkmeans.py
Python
mit
1,642
0.005481
"""Run tests for the kmeans portion of the kmeans module""" import kmeans.kmeans.kmeans as kmeans import numpy as np import random def test_1dim_distance(): """See if this contraption works in 1 dimension""" num1 = random.random() num2 = random.random() assert kmeans.ndim_euclidean_distance(num1, num...
ge(1, 100) centroids = kmeans.random_centroids(k, dimensions) for centroid in centroids:
assert len(centroid) == dimensions def test_iterated_centroid(): """ensure that the average across each dimension is returned""" new_centroid = kmeans.iterated_centroid([[1, 1, 1], [2, 2, 2]],\ [[100, 200, 300]], [(0, 0), (1, 0)]) np.testing.assert_allclose(new_centroid, np.array([[1.5, 1.5, ...
hoangelos/Herd
lib/herd/cluster/client.py
Python
apache-2.0
2,221
0.007204
# -*- coding: utf-8 -*- ## Copyright 2012 Peter Halliday ## ## 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 languag...
t ioloop from tornado import iostream class HerdClusterClient(object): """The client to connect to the HerdCluster nodes. This gets messages that are being subscribed to.""" def __init__(self, seeds=[], port=8888): self.logger = logging.getLogger("herd.cluster.client") self.seeds = seeds ...
M1kol4j/helita
helita/sim/rh15d_vis.py
Python
bsd-3-clause
17,453
0.000115
""" Set of programs and tools visualise the output from RH, 1.5D version """ import os import numpy as np import xarray as xr import matplotlib.pyplot as plt from pkg_resources import resource_filename from ipywidgets import interact, fixed, Dropdown, IntSlider, FloatSlider from scipy.integrate.quadrature import cumtra...
ax.set_ylabel(quantity + ' (n / n*)') elif quantit
y == 'Populations': tmp = n ax.set_ylabel(quantity + ' (m$^{-3}$)') elif quantity == 'LTE Populations': tmp = nstar ax.set_ylabel(quantity + ' (m$^{-3}$)') p_plot.set_ydata(tmp) ax.relim() ...
Jgarcia-IAS/localizacion
openerp/addons-extra/odoo-pruebas/odoo-server/addons/email_template/email_template.py
Python
agpl-3.0
30,293
0.004357
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2009 Sharoon Thomas # Copyright (C) 2010-Today OpenERP SA (<http://www.openerp.com>) # # This program is free software: you can redistribute it ...
"time_format"]) format_date = lang_params.get("date_format", '%B-%d-%Y') format_time = lang_params.get("time_format", '%I-%M %p') fdate = ts.strftime(format_date) ftime = ts.strftime(format_time) return "%s %s (%s)" % (fdate, ftime, tz) try: # We use a jinja2 sandboxed envi...
the mako syntax, in particular # arbitrary Python statements are not accepted, and not all expressions are # allowed: only "public" attributes (not starting with '_') of objects may # be accessed. # This is done on purpose: it prevents incidental or malicious execution of # Python code that may brea...
tjcsl/ion
intranet/apps/itemreg/migrations/0009_auto_20180524_2221.py
Python
gpl-2.0
1,071
0.002801
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2018-05-25 02:21 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): dependencies = [ ('itemreg', '0008_auto_20160...
ser', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), migrations.AlterField( model_name='phoneregistration', name='user', field=models.ForeignKey(null=True, o
n_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), ]
peromo93/instapix
feed/urls.py
Python
mit
228
0
from django.conf.urls import url from . import views app_name = 'feed' url
patterns = [ url(r'^$', views.FeedView.as_view(), name='userfeed'), url(r'ajax/more/$', views.LoadMoreAjax.as_view(), name='ajax_loadmore'),
]
elibixby/gcloud-python
gcloud/resource_manager/project.py
Python
apache-2.0
10,587
0
# Copyright 2015 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 by applicable law or a...
his method will retrieve project metadata. .. warning:: This will overwrite any local changes you've made and not saved via :meth:`update`. See https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects/get :type client: :class:`gcloud.resource_...
ient stored on the current project. """ client = self._require_client(client) # We assume the project exists. If it doesn't it will raise a NotFound # exception. resp = client.connection.api_request(method='GET', path=self.path) self.set_properties_from_api_repr(resource...
crchemist/scioncc
src/pyon/core/security/authentication.py
Python
bsd-2-clause
8,374
0.002388
#!/usr/bin/env python """ @file ion/core/security/authentication.py @author Roger Unwin @author Dorian Raymer @brief routines for working with crypto (x509 certificates and private_keys) """ import binascii import urllib import os import datetime import hashlib try: from M2Crypto import EVP, X509 except ImportEr...
else: return 'Invalid', ' Certificate does not derive from any known root certificates' def is_certificate_in_white_list(self, cert_string): for root_cert in self.white_list: if self.is_certificate_descended_from(cert_string, root_cert): return True retur...
""" tests if the certificate was issued by the passed in certificate authority """ root_cert_attrs = self.decode_certificate_string(root_cert) root_subject = root_cert_attrs['subject'] cert_attrs = self.decode_certificate_string(cert_string) cert_issuer = cert_attrs['is...
joshuahellier/PhDStuff
codes/kmc/2Dim/general2d/lambdaFluc2dCreator.py
Python
mit
1,068
0.002809
import subprocess import sys import os # This code is meant to manage running multiple instances of my KMCLib codes at the same time, # in the name of time efficiency numLambda = 512 numStepsEquilib = 1600000 numStepsAnal = 16000 numStepsSnapshot = 1000 numStepsReq = 16000 sysWidth = 32 sysLength = 32 analInterval = 1...
loat(numLambda-1) runningJobs = [] for rateIndex in range(0, numLambda): currentRate = lambdaMin + rateStepSize*rateIndex botConc = 0.99 topConc = 0.01 jobInput = "2dSteadyFlow.py "+str(botConc)+" "+str(topConc)+" "+str(currentRate)+" "+str(sysWidth)+" "+str(sysLength)+" "+str(analInterval)+" ...
l)+" "+dataLocation+str(rateIndex)+"\n" with open("jobInputs/testInput."+str(jobIndex), 'w') as f: f.write(jobInput) jobIndex += 1
tonnie17/flowlight
examples/run_sftp.py
Python
mit
177
0.011299
from flowlight import Machine m = Machine('host1', connect=True) m
.put('/tmp/remote_file', '/tmp/local_file') # upload m.get('/tmp/local_
file', '/tmp/remote_file') # download
gdetrez/fscons-ticketshop
ticketshop/ticketapp/forms.py
Python
mit
3,715
0.007268
import django.forms as forms from django.core.exceptions import ValidationError from .models import TicketPurchase, Ticket, TicketType class TicketPurchaseForm(forms.ModelForm): class Meta: model = TicketPurchase fields = [ 'buyer_first_name', 'buyer_surname', 'buyer_email', ...
elf, i, **kargs): kargs['instance'] = self.instances[i]
kargs['empty_permitted'] = False return super(BaseTicketFormSet, self)._construct_form(i, **kargs) TicketFormSet = forms.formsets.formset_factory( TicketForm, formset=BaseTicketFormSet, can_delete=False ) class TicketsForm(forms.Form): """ This is the first form: it shows a...
joergdietrich/astropy
astropy/nddata/tests/test_flag_collection.py
Python
bsd-3-clause
1,629
0
# Licensed under a 3-clause BSD style license - see LICENSE.rst # TEST_UNICODE_LITERALS from __future__ import (absolute_import, division, print_function, unicode_literals) import numpy as np from ...tests.helper import pytest from .. import FlagCollection def test_init(): FlagCollect...
(bool) f['d'] = np.ones((1, 2, 3)).astype(str) @pytest.mark.parametrize(('value'), [1, 1., 'spam', [1, 2, 3], (1., 2., 3.)]) def test_setitem_invalid_type(value): f = FlagCollection(shape=(1, 2, 3)) with pytest.raises(Exception) as exc: f['a'] = value assert exc.value.args[0] == 'flags should ...
_setitem_invalid_shape(): f = FlagCollection(shape=(1, 2, 3)) with pytest.raises(ValueError) as exc: f['a'] = np.ones((3, 2, 1)) assert exc.value.args[0].startswith('flags array shape') assert exc.value.args[0].endswith('does not match data shape (1, 2, 3)')
fadenb/hopper.pw
hopperpw/stats/models.py
Python
bsd-3-clause
517
0
# coding
=utf-8 from django.db import models from main.models import BaseModel STAT_TYPES = ( ('user_count', 'User count'), ('host_count', 'Host count'), ('ip_update_count', 'IP update count'), ) class StatisticsEntry(BaseModel): class Meta: verbose_name_plural = 'Statistics Entries' stat_type =...
.created)
e1ven/Waymoot
libs/tornado-2.2/build/lib/tornado/test/process_test.py
Python
mit
5,087
0.001573
#!/usr/bin/env python import logging import os import signal import sys from tornado.httpclient import HTTPClient, HTTPError fr
om tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from tornado.netutil import bind_sockets from tornado.process import fork_processes, task_id from tornado.simple_httpclient import SimpleAsyncHTTPClient from tornado.testing import LogTrapTestCase, get_unused_port from tornado.web import RequestH...
lace LogTrapTestCase # with unittest.TestCase when debugging. class ProcessTest(LogTrapTestCase): def get_app(self): class ProcessHandler(RequestHandler): def get(self): if self.get_argument("exit", None): # must use os._exit instead of sys.exit so unittest's ...