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
rmk135/objects
examples/miniapps/factory-patterns/factory_of_factories.py
Python
bsd-3-clause
1,394
0
"""`Factory of Factories` pattern.""" from dependency_injector import containers, providers class SqlAlchemyDatabaseService
: def __init__(self, session, base_class): self.session = session self.base_class = base_class class TokensService: def __init__(self, id_generator, database): self.id_generator = id_generator
self.database = database class Token: ... class UsersService: def __init__(self, id_generator, database): self.id_generator = id_generator self.database = database class User: ... # Sample objects session = object() id_generator = object() class Container(containers.Declar...
mezz64/home-assistant
homeassistant/components/media_source/local_source.py
Python
apache-2.0
7,330
0.000546
"""Local Media Source Implementation.""" from __future__ import annotations import mimetypes from pathlib import Path from aiohttp import web from homeassistant.components.http import HomeAssistantView from homeassistant.components.media_player.const import MEDIA_CLASS_DIRECTORY from homeassistant.components.media_p...
MEDIA_CLASS_MAP, MEDIA_MIME_TYPES from .error import Unresolvable from .models import BrowseMediaSource, MediaSource, MediaSourceItem, PlayMedia @callback def async_setup(hass: HomeAssista
nt) -> None: """Set up local media source.""" source = LocalSource(hass) hass.data[DOMAIN][DOMAIN] = source hass.http.register_view(LocalMediaView(hass, source)) class LocalSource(MediaSource): """Provide local directories as media sources.""" name: str = "Local Media" def __init__(self,...
callowayproject/django-objectpermissions
objectpermissions/signals.py
Python
apache-2.0
227
0.008811
import d
jango.dispatch # Whenever a permission object is saved, it sends out the signal. This allows # models to keep their permissions in sync permission_changed = django.dispatch.Signal(providing_args=('to_whom', 'to
_what'))
googleapis/python-retail
samples/interactive-tutorials/product/import_products_bq_test.py
Python
apache-2.0
1,917
0.002087
# Copyright 2022 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 ...
e(dataset, valid_products_table) assert re.match(".*import products from big query table request.*", output) assert re.match(".*the operation was started.*", output) assert re.match( ".*projects/.*/locations/global/catalogs/default_catalog/branches/0/operations/import-products.*", output, ...
0.*", output)
desec-io/desec-stack
test/e2e2/spec/test_api_rrset.py
Python
mit
2,838
0.002467
import pytest from conftest import DeSECAPIV1Client @pytest.mark.parametrize("init_rrsets", [ { ('www', 'A'): (3600, {'1.2.3.4'}), ('www', 'AAAA'): (3600, {'::1'}), ('one', 'CNAME'): (3600, {'some.example.net.'}), ('other', 'TXT'): (3600, {'"foo" "bar"', '"bar" "foo"'}), } ]) ...
('sub', 'CDNSKEY'): (3600, {'257 3 15 l02Woi0iS8Aa25FQkUd9RMzZHJpBoRQwAQEX1SxZJA4='}), # non-apex DNSSEC (
'sub', 'CDS'): (3600, {'35217 15 2 401781b934e392de492ec77ae2e15d70f6575a1c0bc59c5275c04ebe80c6614c'}), # dto. # ('sub', 'DNSKEY'): (3600, {'257 3 15 l02Woi0iS8Aa25FQkUd9RMzZHJpBoRQwAQEX1SxZJA4='}) # no pdns support >= 4.6 }, ]) def test(api_user_domain_rrsets: DeSECAPIV1Client, rrsets: dict): api_use...
thefirstwind/s3qloss
tests/t4_adm.py
Python
gpl-3.0
2,378
0.002103
''' t4_adm.py - this file is part of S3QL (http://s3ql.googlecode.com) Copyright (C) 2008-2009 Nikolaus Rath <Nikolaus@rath.org> This program can be distributed under the terms of the GNU GPLv3. ''' from __future__ import division, print_function, absolute_import from s3ql.backends import local from s3ql.backends.c...
(BASEDIR, 'bin', 's3qladm'),
'--quiet', 'passphrase', self.storage_url ], stdin=subprocess.PIPE) print(self.passphrase, file=proc.stdin) print(passphrase_new, file=proc.stdin) print(passphrase_new, file=proc.stdin) proc.stdin.close() self.ass...
ludovic-bouguerra/tutorial-travis-docker
webservice/views.py
Python
gpl-3.0
237
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from
django.shortcuts i
mport render from django.http import HttpResponse def hello_world_view(request): return HttpResponse("hello world", content_type="text/plain")
andersonjonathan/Navitas
navitas/contents/migrations/0018_auto_20170329_1549.py
Python
mit
483
0.00207
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import contents.models class Migration(migrations.Migration): dependencies = [ ('contents', '0017_auto_20170329_1504'), ] operations = [ migrations.AlterField( model_name...
field=models.ImageField(null=True, upload_to=contents.models.get_front_pa
ge_image_path), ), ]
progdupeupl/pdp_website
pdp/utils/tests.py
Python
agpl-3.0
3,776
0
# coding: utf-8 # # This file is part of Progdupeupl. # # Progdupeupl is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Progdu...
long with Progdupeupl. If not, see <http://www.gnu.org/licenses/>. """Tests for utils app.""" import unittest import hashlib from django.contrib.auth.models import User from django_dynamic_fixture import G from pdp.member.models import Profile, ActivationToken from pdp.utils.templatetags.profile import profile fro...
lateTagsTests(unittest.TestCase): """Test for the custom template tags about users.""" def setUp(self): self.user = G(User) def test_profile_none(self): """Test the output of profile templatetag if profile does not exist.""" self.assertEqual(None, profile(self.user)) def test...
hickey/amforth
core/devices/atmega16u4/device.py
Python
gpl-2.0
10,989
0.070252
# Partname: ATmega16U4 # generated automatically, do not edit MCUREGS = { 'WDTCSR': '&96', 'WDTCSR_WDIF': '$80', 'WDTCSR_WDIE': '$40', 'WDTCSR_WDP': '$27', 'WDTCSR_WDCE': '$10', 'WDTCSR_WDE': '$08', 'PORTD': '&43', 'DDRD': '&42', 'PIND': '&41', 'SPCR': '&76', 'SPCR_SPIE': '$80', 'SPCR_SPE': '...
', 'TIFR4_OCF4B': '$20', 'TIFR4_TOV4': '$04', 'DT4': '&212', 'DT4_DT4L': '$FF', 'PORTB': '&37', 'DDRB': '&36', 'PINB': '&35', 'PORTC': '&40', 'DDRC': '&39', 'PINC': '&38', 'PORTE': '&46', 'DDRE': '&45', 'PINE': '&44', 'PORTF': '&49', 'DDRF': '&48', 'PINF': '&47', 'ADMUX': '&124', 'ADMUX_REFS':...
RA_ADATE': '$20', 'ADCSRA_ADIF': '$10', 'ADCSRA_ADIE': '$08', 'ADCSRA_ADPS': '$07', 'ADC': '&120', 'ADCSRB': '&123', 'ADCSRB_ADHSM': '$80', 'ADCSRB_MUX5': '$20', 'ADCSRB_ADTS': '$17', 'DIDR0': '&126', 'DIDR0_ADC7D': '$80', 'DIDR0_ADC6D': '$40', 'DIDR0_ADC5D': '$20', 'DIDR0_ADC4D': '$10'...
ffalcinelli/wstunnel
wstunnel/client.py
Python
lgpl-3.0
10,007
0.001799
# -*- coding: utf-8 -*- # Copyright (C) 2013 Fabio Falcinelli # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Thi...
lf._address_list = [] @property def address_list(self): return self._address_list def handle_stream(self, stream, address): """ Handle a new client connect
ion with a proxy over websocket """ logger.info("Got connection from %s on %s" % (tuple_to_address(stream.socket.getpeername()), tuple_to_address(stream.socket.getsockname()))) self.ws_conn = WebSocketProxyConnection(self.ws_url, stream, addr...
mixturemodel-flow/tensorflow
tensorflow/python/estimator/model_fn.py
Python
apache-2.0
12,164
0.004357
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
rain_op` will be ignored in eval and infer modes. Example: ```python def my_model_fn(mode, features, labels): predictions = ... loss = ... train
_op = ... return tf.estimator.EstimatorSpec( mode=mode, predictions=predictions, loss=loss, train_op=train_op) ``` Alternatively, model_fn can just populate the arguments appropriate to the given mode. Example: ```python def my_model_fn(mode, features,...
Chedi/airflow
airflow/contrib/operators/bigquery_operator.py
Python
apache-2.0
2,155
0.003712
import logging from airflow.contrib.hooks.bigquery_hook import BigQueryHook from airflow.models import BaseOperator from airflow.utils import apply_defaults class BigQueryOperator(BaseOperator): """ Executes BigQuery SQL queries in a specific BigQuery database """ template_fields = ('bql', 'destinatio...
m bigquery_conn_id: reference to a specific BigQuery hook.
:type bigquery_conn_id: string :param delegate_to: The account to impersonate, if any. For this to work, the service account making the request must have domain-wide delegation enabled. :type delegate_to: string """ super(BigQueryOperator, self).__init__(*args, **kwargs) ...
arenadata/ambari
dev-support/docker/docker/bin/ambaribuild.py
Python
apache-2.0
8,584
0.033667
#!/usr/bin/python # coding: utf-8 # 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...
is set, git clean -xdf is executed for the ambari local git re
po") parser.add_option("-b", "--rebuild", dest="is_rebuild", action="store_true", default=False, help="set this flag if you want to rebuild Ambari code") parser.add_option("-s", "--stack_distribution", dest="stack_distribution", help="set a stack distribution. [HDP|PHD|BIGTOP]. Make sure -...
ryplo/helpme
setup.py
Python
mit
959
0
#!/usr/bin/env python from setuptools import setup, find_packages with open('pypd/version.py') as version_file: exec(compile(version_file.read(), version_file.name, 'exec')) options = { 'name': 'pypd', 'version': __version__, 'packages': find_packages(), 'scripts': [], 'description': 'A python...
raries :: Python Modules', ], 'install_requires': ['ujson', 'requests'], 'tests_require': [], 'cmdclass': {} } setup(**opti
ons)
hmendozap/auto-sklearn
test/test_pipeline/components/classification/test_extra_trees.py
Python
bsd-3-clause
3,415
0.000586
import unittest from autosklearn.pipeline.components.classification.extra_trees import \ ExtraTreesClassifier from autosklearn.pipeline.util import _test_classifier, \ _test_classifier_iterative_fit, _test_classifier_predict_proba import numpy as np import sklearn.metrics import sklearn.ensemble class Extra...
rgets = \ _test_classifier_predict_proba(ExtraTreesClassifier) self.assertAlmostEqual(0.12052046298054782, sklearn.metrics.log_loss( targets, predictions)) def test_default_configuration_sparse(self): for ...
True) self.assertAlmostEqual(0.71999999999999997, sklearn.metrics.accuracy_score(targets, predictions)) def test_default_configuration_iterative_fit(self): for i in range(10): predic...
tallstreet/Whoosh-AppEngine
tests/test_indexing.py
Python
apache-2.0
11,352
0.019204
import unittest from os import mkdir from os.path import exists from shutil import rmtree from whoosh import fields, index, qparser, store, writing class TestIndexing(unittest.TestCase): def make_index(self, dirname, schema): if not exists(dirname): mkdir(dirname) st = store.FileStorag...
dr = ix.doc_reader() ls1 = [dr.doc_field_length(i, "f1") for i in xrange(0, len(lengths))] ls2 = [dr.doc_field_length(i, "f2") for i in xrange(0, len(lengths))] self.assertEqual(ls1, [0]*len(lengths)) self.assertEqual(ls2, lengths) dr.close() ...
def test_lengths_ram(self): s = fields.Schema(f1 = fields.KEYWORD(stored = True, scorable = True), f2 = fields.KEYWORD(stored = True, scorable = True)) st = store.RamStorage() ix = index.Index(st, s, create = True) w = writing.IndexWriter(ix) w.ad...
dcosentino/edx-platform
lms/djangoapps/oai/settings.py
Python
agpl-3.0
1,073
0.008388
from django.conf import settings from datetime import timedelta # Endpoint settings OAI_BASE_URL="http" if settings.HTTPS == "on": OAI_BASE_URL="https" OAI_BASE_URL=OAI_BASE_URL+"://"+settings.SITE_NAME REPOSITORY_NAME = settings.PLATFORM_NAME ADMIN_EMAIL = settings.TECH_SUPPORT_EMAIL OAI_ENDPOINT_NAME = 'oai' R...
FORMAT = 'o
ai_dc' OWN_SET_PREFIX = settings.PLATFORM_NAME DISABLE_PRINT_OWN_SET_PREFIX= True RESUMPTION_TOKEN_SALT = 'change_me' # salt used to generate resumption tokens if hasattr(settings, 'OAI_SETTINGS'): OAI_ENDPOINT_NAME = settings.OAI_SETTINGS.get('OAI_ENDPOINT_NAME') RESULTS_LIMIT = settings.OAI_SETTINGS.get('RES...
akalipetis/djoser
djoser/compat.py
Python
mit
267
0
from djoser.conf import settings __all__ = ['settings'] def get_user_email(user): email_field_name = get
_user_email_field_name(user) return getattr(user, email_field_name, None) def get_user
_email_field_name(user): return user.get_email_field_name()
MikeDMorgan/scRNAseq
pipeline_docs/pipeline_scRnaseq/__init__.py
Python
mit
24
0
fro
m trackers
import *
emesene/emesene
emesene/gui/qt4ui/TrayIcon.py
Python
gpl-3.0
5,102
0
# -*- coding: utf-8 -*- # This file is part of emesene. # # emesene 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. # #...
on == QtGui.QSystemTrayIcon.Trigger: if not self._main_window.isVisible(): self._mai
n_window.show() self._main_window.activateWindow() self._main_window.raise_() else: # visible if self._main_window.isActiveWindow(): self._main_window.hide() else: self._main_window.activateWindow() ...
Callek/build-relengapi
relengapi/lib/time.py
Python
mpl-2.0
304
0
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at
http://mozilla.org/MPL/2.0/. import datetime import pytz def now(): return datetime.datetime.utcnow(
).replace(tzinfo=pytz.UTC)
CRImier/pyLCI
output/drivers/mcp23008.py
Python
apache-2.0
2,598
0.007698
import smbus from time import sleep def delay(time): sleep(time/1000.0) def delayMicroseconds(time): sleep(time/1000000.0) from hd44780 import HD44780 class Screen(HD44780): """A driver for MCP23008-based I2C LCD backpacks. The one tested had "WIDE.HK" written on it.""" def __init__(self, bus=1, ad...
self.i2c_init() HD44780.__init__(self, debug=self.debug, **kwargs) def i2c
_init(self): """Inits the MCP23017 IC for desired operation.""" self.setMCPreg(0x05, 0x0c) self.setMCPreg(0x00, 0x00) def write_byte(self, byte, char_mode=False): """Takes a byte and sends the high nibble, then the low nibble (as per HD44780 doc). Passes ``char_mode`` to ``self.writ...
ChameleonCloud/blazar
blazar/db/exceptions.py
Python
apache-2.0
1,705
0
# Copyright (c) 2014 Intel Corporation # # 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 ...
ion)
: msg_fmt = _('An unknown database exception occurred') class BlazarDBDuplicateEntry(BlazarDBException): msg_fmt = _('Duplicate entry for %(columns)s in %(model)s model was found') class BlazarDBNotFound(BlazarDBException): msg_fmt = _('%(id)s %(model)s was not found') class BlazarDBInvalidFilter(Blaz...
stamen/fieldpapers
decoder/apiutils.py
Python
gpl-2.0
6,689
0.007325
from urlparse import urljoin from os.path import dirname, basename from xml.etree import ElementTree from mimetypes import guess_type from StringIO import StringIO import requests def update_print(apibase, password, print_id, progress): """ """ params = {'id': print_id} data = dict(progress=progress,...
] != 'file' and 'name' in input.attrib:
fields[input.attrib['name']] = input.attrib['value'] elif input.attrib['type'] == 'file': files[input.attrib['name']] = (basename(file_path), file_contents) if len(files) == 1: base_url = [el.text for el in form.findall(".//*") if el.get('id', '') == 'base-url'][0] ...
MingLin-home/Ming_slim
preprocessing/cifarnet_preprocessing.py
Python
gpl-3.0
4,252
0.007291
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
ge = tf.image.random_flip_left_right(distorted_image) tf.summary.image('distorted_image', tf.expand_dims(distorted_image, 0)) # Because these operations are not commutative, consider randomizing # the order their operation. distorted_image = tf.image.random_brightness(distorted_image, ...
ted_image, lower=0.2, upper=1.8) # Subtract off the mean and divide by the variance of the pixels. return tf.image.per_image_standardization(distorted_image) def preprocess_for_eval(image, output_height, output_width): """Preprocesses the given image for evaluation. ...
nicfit/nicfit.py
examples/asyncio_example.py
Python
mit
371
0.005391
#!/usr/bin/env python import time from nicfit.aio import Application async def _main(args): print(args) print("Sleeping 2...") time.sleep(2) print("Sleeping 0...") return 0 def atex
it(): print("atexit") app = Application(_main, atexit=atexit) app.arg_parser.add_argument("--example", help="Example cli") app.run() as
sert not"will not execute"
steveandroulakis/mytardis
tardis/tardis_portal/tests/test_rmexperiment.py
Python
bsd-3-clause
4,827
0.008494
from compare import expect from django.contrib.auth.models import User from django.test import TestCase from django.test.client import Client from django.core.management import call_command import sys from tardis.tardis_portal.models import \ Experiment, Dataset, Dataset_File, ExperimentACL, License, UserProfile...
(len(exp1_.get_datafiles())).to_be(3) expect(len(exp2_.get_datafiles())).to_be(5) # Remove first experiment
and check that the shared dataset hasn't been removed call_command('rmexperiment', exp1_.pk, confirmed=True) expect(Dataset_File.objects.all().count()).to_be(5) expect(len(exp2_.get_datafiles())).to_be(5) #Remove second experiment call_command('rmexperiment', exp2_.pk, ...
lapisdecor/bzoinq
bzoinq/playit.py
Python
mit
240
0
import subprocess fro
m pkg_resources import resource_filename def playit(file): """ Function used to play a sound file """ filepath = resource_filename(__name__, 'sound/' + file) subprocess
.Popen(["paplay", filepath])
wazo-pbx/xivo-auth
alembic/versions/97e2d9949db_revert_add_plugin_event_acl_to_the_.py
Python
gpl-3.0
2,816
0.00071
"""revert: add plugin event acl to the admin backend Revision ID: 97e2d9949db Revises: 1e5140290977 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '97e2d9949db' down_revision = '1e5140290977' POLICY_NAME = 'wazo_default_admin_policy' ACL_TEMPLATES = ['events...
_template_id) return acl_template_ids def downgrade(): conn = op.get_bind() policy_uuid = _get_policy_uuid(conn, POLICY_NAME) acl_template_ids = _insert_acl_template(conn, ACL_TEMPLATES) op.bulk_insert( policy_template, [ {'policy_uuid': policy_uuid, 'template_id': temp...
nd() acl_template_ids = _find_acl_templates(conn, ACL_TEMPLATES) if acl_template_ids: policy_uuid = _get_policy_uuid(conn, POLICY_NAME) delete_query = policy_template.delete().where( sa.sql.and_( policy_template.c.policy_uuid == policy_uuid, policy_tem...
martylee/Python
CSC410-Project-1-master/minic/pretty_minic.py
Python
gpl-2.0
658
0.00152
from . import minic_ast class PrettyGenerator(object): def __init__(self): # Statements start with indentation of self.indent_level spaces, using # the _make_indent method # self.indent_level = 0 def _make_indent(self): return ' ' * s
elf.indent_level def visit(self, node): method = 'v
isit_' + node.__class__.__name__ return getattr(self, method, self.generic_visit)(node) def generic_visit(self, node): #~ print('generic:', type(node)) if node is None: return '' else: return ''.join(self.visit(c) for c_name, c in node.children())
allebacco/PyNodeGraph
pynodegraph/__init__.py
Python
mit
286
0.006993
from node_view import NodeGraphView from node_scene import NodeGraphScene from items.node_item import NodeItem from items.connectio
n_item import ConnectionItem from items.connector_item i
mport BaseConnectorItem, IOConnectorItem, InputConnectorItem, OutputConnectorItem import node_utils
sha-red/django-shared-utils
shared/utils/views/alphabetical_pagination.py
Python
mit
1,768
0.002828
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db.models import F, Func, Value class AlphabeticalPaginationMixin(object): alphabetical_pagination_field = 'name' def get_alphabetical_pagination_field(self): return self.alphabetical_pagination_field def get_selected_l...
**{self.get_alphabetical_pagination_field(): ''} ) return qs def get_queryset(self): qs = self.get_base_queryset() # FIXME Select Umlauts (using downgrade and also downgrade sort_name field?) # FIXME Select on TRIM/LEFT as in get_letter_choices filter = { ...
phabetical_pagination_field) def get_letter_choices(self): return self.get_base_queryset().annotate(name_lower=Func( Func( Func( F(self.get_alphabetical_pagination_field()), function='LOWER'), function='TRIM'), Value("1"), function...
wazo-pbx/xivo-auth
alembic/versions/2d4882d39dbb_add_graphql_acl_to_users.py
Python
gpl-3.0
3,250
0.001538
"""add graphql ACL to users Revision ID: 2d4882d39dbb Revises: c4d0e9ec46a9 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '2d4882d39dbb' down_revision = 'dc2848563b53' POLICY_NAME = 'wazo_default_user_policy' ACL_TEMPLATES = ['dird.graphql.me'] policy_tabl...
g(80)) ) acl_template_table = sa.sql.table( 'auth_acl_template', sa.Column('id', sa.Integer), sa.Column('template', sa.Text) ) policy_templa
te = sa.sql.table( 'auth_policy_template', sa.Column('policy_uuid', sa.String(38)), sa.Column('template_id', sa.Integer), ) def _find_acl_template(conn, acl_template): query = ( sa.sql.select([acl_template_table.c.id]) .where(acl_template_table.c.template == acl_template) .limi...
PEAT-AI/Automato
Surveillance/make_ndvi.py
Python
gpl-3.0
1,020
0.009804
#!/usr/bin/env python # -*- coding: utf-8 -*- # # ndvi_test.py # # Copyright 2015 rob <rob@Novu> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # ...
Floor, Boston, # MA 02110-1301, USA. # # '''just a annoying dummy to get rid of Gtk2 and Gtk3 incompatibilities''' from infrapix import infrapix impo
rt sys infrapix.ndvi(sys.argv[1],sys.argv[2], show_histogram = True,)
ssssam/ansible-modules-core
packaging/os/apt.py
Python
gpl-3.0
24,239
0.004868
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2012, Flowroute LLC # Written by Matthew Williams <matthew@flowroute.com> # Based on yum module written by Seth Vidal <skvidal at fedoraproject.org> # # This module is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public Lic...
s for Debian/Ubuntu). version_added: "0.0.2" options: name: description: - A package name, like C(foo), or package specifier with version, like C(foo=1.0). Name wildcards (fnmatch) like C(apt*) and version wildcards like C(foo=1.0*) are also supported. required:
false default: null state: description: - Indicates the desired package state. C(latest) ensures that the latest version is installed. C(build-dep) ensures the package build dependencies are installed. required: false default: present choices: [ "latest", "absent", "present", "build-dep" ] ...
tilemapjp/OSGeo.GDAL.Xamarin
gdal-1.11.0/swig/python/samples/gdal2grd.py
Python
mit
4,946
0.006066
#!/usr/bin/env python ############################################################################### # $Id: gdal2grd.py 27044 2014-03-16 23:41:27Z
rouault $ # # Project: GDAL Python samples # Purpose: Script to write out ASCII GRD rasters (used in Golden Software # Surfer)
# from any source supported by GDAL. # Author: Andrey Kiselev, dron@remotesensing.org # ############################################################################### # Copyright (c) 2003, Andrey Kiselev <dron@remotesensing.org> # Copyright (c) 2009, Even Rouault <even dot rouault at mines-paris dot org> #...
Snifer/BurpSuite-Plugins
faraday/model/workspace.py
Python
gpl-2.0
20,725
0.008733
#!/usr/bin/env python ''' Faraday Penetration Test IDE - Community Version Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/) See the file 'doc/LICENSE' for the license information ''' import os import model.api import model import time import datetime from model.report import ReportManager from model.dif...
roller(self, model_controller): self._model_controller = model_controller def getContainee(self): return self.container def set_path(self, path): self._path = path def get_path(self): return self._path def set_report_path(self, path): self._report_pa...
= path if not os.path.exists(self._report_path): os.mkdir(self._report_path) self._workspace_manager.report_manager.path = self.report_path def get_report_path(self): return self._report_path path = property(get_path, set_path) report_path = property(get_report_pat...
garbear/EventGhost
plugins/Serial/__init__.py
Python
gpl-2.0
13,068
0.003367
# This file is part of EventGhost. # Copyright (C) 2005 Lars-Peter Voss <bitmonster@eventghost.org> # # EventGhost 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 # (a...
self, port=0, baudrate=9600, bytesize=3, p
arity=0, stopbits=0, handshake=0, generateEvents=False, terminator="\\r", prefix="Serial", encodingNum=0, ): text = self.text panel = eg.ConfigPanel() portCtrl = panel.SerialPortChoice(
abstract-open-solutions/djc.recipe2
djc/recipe2/recipe.py
Python
bsd-3-clause
11,686
0.00077
import logging, os, random from zc.buildout import UserError, easy_install from zc.recipe.egg import Egg SETTINGS_TEMPLATE = ''' from %(settings_module)s import * SECRET_KEY = "%(secret)s" %(settings_override)s ''' SCRIPT_TEMPLATES = { 'wsgi': easy_install.script_header + ''' %(relative_paths_setup)s import s...
self.buildout['buildout']['parts-directory'], self.name ) self.options.setdefault('extra-paths', '') self.options.setdefault('environment-vars', '') self.options.setdefault('sites-directory', self.sites_default) self.options.setdefault('settings-override', '') self.o...
tdefault('manage-py-file', 'django') self.eggs = [ ] if 'eggs' in self.buildout['buildout']: self.eggs.extend(self.buildout['buildout']['eggs'].split()) if 'eggs' in self.options: self.eggs.extend(self.options['eggs'].split()) self.working_set = None self....
mirobot/mirobot-py
setup.py
Python
mit
623
0.033708
from distutils.core import setup s
etup( name = 'mirobot', packages = ['mirobot'], version = '1.0.3', description = 'A Python library to control Mirobot (http://mirobot.io)', author = 'Ben Pirt', author_email = 'ben@pirt.co.uk', url = 'https://github.com/mirobot/mirobot-py', download_url = 'https://github.com/mirobot/mirobot-py/tarball/v...
, 'control', 'mirobot'], classifiers = ['Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Education', 'License :: OSI Approved :: MIT License'], install_requires=[ "websocket-client", ], )
python-rope/rope
rope/base/__init__.py
Python
lgpl-3.0
161
0
"""Base rope packag
e This package contains rope core modules that are used by other modules and packages. """ __all__ = ["project", "libutils", "exceptio
ns"]
perimosocordiae/sparray
bench/benchmarks/ops.py
Python
mit
1,302
0.016129
import scipy.sparse as ss impor
t warn
ings warnings.simplefilter('ignore', ss.SparseEfficiencyWarning) from sparray import FlatSparray class Operations(object): params = [['FlatSparray', 'csr_matrix']] param_names = ['arr_type'] def setup(self, arr_type): mat = ss.rand(3000, 4000, density=0.1, format='csr') if arr_type == 'FlatSparray': ...
tariq786/datafying_bitcoin
sp_batch_hdfs.py
Python
gpl-3.0
3,652
0.026013
from pyspark import SparkConf, SparkContext from jsonrpc.authproxy import AuthServiceProxy import json import sys #This is batch processing of bitcoind (locally run bitcoin daemon) #RPC (Remote Procedure Call) block's json stored #in HDFS. Currently 187,990 blocks' json representation is #stored in HDFS. The HDFS file...
"mapreduce.job.output.value.class": "org.apache.hadoop.io.Writable"} keyConv = "org.apache.spark.examples.pythonconverters.StringToImmutableBytesWritableConverter" valueConv = "org.apache.spark.examples.pythonconverters.StringListToPut
Converter" #row key id,id, cfamily=tx_fee_col,column_name = tx_fee, column_value=x #datamap = tx_fee_rdd.map(lambda x: ("tx_fee",x) ) #( rowkey , [ row key , column family , column name , value ] ) datamap = tx_fee_rdd.map(lambda x: (str(x[0]), [str(x[0]),"tx_fee_col","tx_...
dockermeetupsinbordeaux/docker-zabbix-sender
docker_zabbix_sender/stats.py
Python
apache-2.0
2,565
0.00234
# encoding: utf-8 """Provides collection of events emitters""" import time from . import EndPoint def container_count(host_fqdn, docker_client, statistics): """ Emit events providing: - number of containers - number of running containers - number of crashed containers   :param host_fqdn:...
tics): """Emit the ip addresses of containers. """ for stat in statistics: containerId = stat['id'] details = docker_client.inspect_container(containerId) yield { 'hostname':
EndPoint.container_hostname(host_fqdn, stat['name']), 'timestamp': stat['timestamp'], 'key': EndPoint.EVENT_KEY_PREFIX + 'ip', 'value': details['NetworkSettings']['IPAddress'] } def cpu_count(host_fqdn, docker_client, statistics): """Emit the number of CPU available for ...
rocky/python-uncompyle6
test/simple_source/bug33/05_nonlocal.py
Python
gpl-3.0
230
0.004348
# From Python 3.6 funct
ools.py # Bug was in detecting "nonlocal" access def not_bug(): cache_token = 5 def register(): nonlocal cache_token return cache_token == 5 return register() assert not_
bug()
MOOOWOOO/Q400K
app/user/__init__.py
Python
gpl-3.0
125
0.008
# coding
: utf-8 from flask import Blueprint __author__ = 'Jux.Liu' user = Blueprint('user', __name__) from . import vie
ws
jtiki/djangocms-cascade
cmsplugin_cascade/link/plugin_base.py
Python
mit
2,939
0.003403
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.apps import apps from django.forms import widgets from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from django.utils.safestring import mark_safe from cmsplugin_cascade.fields ...
}'.format(**link) if linktype == 'email': return 'mailto:{email}'.format(**link) # otherwise try to resolve by model if 'model' in link and 'pk' in link: if not hasattr(obj, '_link_model'): Model = apps.get_model(*link['model'].split('.')) ...
except Model.DoesNotExist: obj._link_model = None if obj._link_model: return obj._link_model.get_absolute_url() def get_ring_bases(self): bases = super(LinkPluginBase, self).get_ring_bases() bases.append('LinkPluginBase') return bases...
aplicatii-romanesti/allinclusive-kodi-pi
.kodi/addons/plugin.video.salts/scrapers/__init__.py
Python
apache-2.0
4,030
0.005707
__all__ = ['scraper', 'local_scraper', 'pw_scraper', 'uflix_scraper', 'watchseries_scraper', 'movie25_scraper', 'merdb_scraper', '2movies_scraper', 'icefilms_scraper', 'movieshd_scraper', 'yifytv_scraper', 'viooz_scraper', 'filmstreaming_scraper', 'myvideolinks_scraper', 'filmikz_scraper', 'clickplay_scraper...
scraper', 'noobroom_scraper', 'solar_scraper', 'vkbox_scraper', 'directdl_scraper', 'movietv_scraper', 'moviesonline7_scraper', 'streamallthis_scraper', 'afdah_scraper', 'streamtv_scraper', 'moviestorm_scraper', 'wmo_scraper', 'zumvo_scraper', 'wso_scraper', 'tvrelease_scraper', 'hdmz_scraper', 'c...
craper', 'yifystreaming_scraper', 'mintmovies_scraper', 'playbox_scraper', 'shush_proxy', 'mvsnap_scraper', 'pubfilm_scraper', 'pctf_scraper', 'rlssource_scraper', 'couchtunerv1_scraper', 'couchtunerv2_scraper', 'tunemovie_scraper', 'watch8now_scraper', 'megabox_scraper', 'dizilab_scraper', 'beinm...
daniaki/Enrich2
enrich2/sequence/aligner.py
Python
gpl-3.0
21,237
0.002025
# Copyright 2016-2017 Alan F Rubin, Daniel C Esposito # # This file is part of Enrich2. # # Enrich2 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 Licens
e, or # (at your option) any later version. # # Enrich2 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; withou
t 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 Enrich2. If not, see <http://www.gnu.org/licenses/>. """ Enrich2 aligner module ========...
SUSE/spacewalk-osad2
setup.py
Python
gpl-2.0
4,111
0.002189
#!/usr/bin/env python from distutils.core import setup, run_setup, Command import zmq.auth import shutil import os OSAD2_PATH = os.path.dirname(os.path.realpath(__file__)) OSAD2_SERVER_CERTS_DIR = "/etc/rhn/osad2-server/certs/" OSAD2_SERVER_PUB_KEY = os.path.join(OSAD2_SERVER_CERTS_DIR, "public_keys/server.key") OSA...
ame, 'You mus
t specify a client name' assert os.path.isdir(OSAD2_SERVER_CERTS_DIR), \ 'Certificates storage dir doesn\'t exist: %s' % OSAD2_SERVER_CERTS_DIR keyfile = os.path.join(OSAD2_SERVER_CERTS_DIR, "public_keys/" + self.name + '.key') server_keyfile = os.path.join(OSAD2_SERVER_CERTS_DIR, 'pr...
OscarES/serpentinetracker
examples/atf/atfExt.py
Python
gpl-3.0
1,975
0.017722
import pylab as pl import scipy as sp from serpentine import * from elements import * import visualize class AtfExt : def __init__(self) : print 'AtfExt:__init__' # set twiss parameters mytwiss = Twiss() mytwiss.betax = 6.85338806855804 mytwiss.alphax = 1.11230788371885 ...
29410712918 mytwiss.alphay = -1.91105724003646 mytwiss.etay = 0 mytwiss.etayp = 0 mytwiss.nemitx = 5.08807339588144e-006 mytwiss.nemity = 50.8807339588144e-009 mytwiss.sigz = 8.00000000000000e-003 mytwiss.sigP = 1.03999991965541e-003 mytwiss.pz_cor ...
,twiss=mytwiss) # zero zero cors self.atfExt.beamline.ZeroCors() # Track self.atfExt.Track() readings = self.atfExt.GetBPMReadings() # Visualisation self.v = visualize.Visualize() def moverCalibration(self, mag, bpms) : pass ...
repotvsupertuga/tvsupertuga.repository
script.module.cryptolib/lib/cryptopy/cipher/rijndael_test.py
Python
gpl-2.0
9,568
0.037312
#! /usr/bin/env python """ cryptopy.cipher.rijndael_test Tests for the rijndael encryption algorithm Copyright (c) 2002 by Paul A. Lambert Read LICENSE.txt for license information. """ from cryptopy.cipher.rijndael import Rijndael from cryptopy.cipher.base import noPadding from binascii ...
ct = '7d15479076b69a46ffb3b3beae97ad8313f622f67fedb487de9f06b9ed9c8f19') RijndaelTestVec( i = 'dev_vec.txt 32 byte block, 20 byte key',
key = '2b7e151628aed2a6abf7158809cf4f3c762e7160',
reneploetz/mesos
src/python/cli_new/lib/cli/plugins/base.py
Python
apache-2.0
5,461
0.000366
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
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 Licen
se for the specific language governing permissions and # limitations under the License. """ Plugin's Base Class """ import sys import cli from cli.docopt import docopt PLUGIN_NAME = "base-plugin" PLUGIN_CLASS = "PluginBase" VERSION = "Mesos Plugin Base 1.0" SHORT_HELP = "This is the base plugin from which all o...
sigma-geosistemas/django-tenants
dts_test_project/dts_test_project/settings.py
Python
mit
3,048
0.000656
""" Django settings for dts_test_project project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR...
ddleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.core.context_proce...
text_processors.static', 'django.contrib.messages.context_processors.messages', ) # Internationalization # https://docs.djangoproject.com/en/1.6/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.django...
jendrikseipp/rednotebook-elementary
win/build-installer.py
Python
gpl-2.0
831
0.002407
#! /usr/bin/env python3 import argparse import logging import os from utils import run logging.basicConfig(level=logging.INFO) def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('dist_dir') parser.add_argument('version') return parser.parse_args() args = parse_args() DIR = os...
DIR = os.path.dirname(DIR) DIST_DIR = os.path.abspath(args.dist_dir) DRIVE_C = os.path.join(DIST_DIR, 'drive_c') WINE_RN_DIR = os.path.join(DRIVE_C, 'rednotebook') WINE_RN_WIN_DIR = os.path.join(WINE
_RN_DIR, 'win') os.environ['WINEPREFIX'] = DIST_DIR ISCC = os.path.join(DRIVE_C, 'Program Files (x86)', 'Inno Setup 5', 'ISCC.exe') VERSION_PARAM = '/dREDNOTEBOOK_VERSION=%s' % args.version run(['wine', ISCC, VERSION_PARAM, 'rednotebook.iss'], cwd=WINE_RN_WIN_DIR)
seanbell/opensurfaces
server/licenses/admin.py
Python
mit
621
0.00161
from django.contrib import admin from common.admin import AutoUserMixin from licenses.models import License class LicenseA
dmin(AutoUserMixin, admin.ModelAdmin): fieldsets = [ (None, { 'fields': ['added', 'name', 'url', 'creative_commons', 'cc_attribution', 'cc_noncommercial', 'cc_no_deriv', 'cc_share_alike'] }), ] # fiel
ds readonly_fields = ['added'] list_display = ['name', 'url'] # field display list_filter = ['name', 'added'] search_fields = ['name', 'url'] admin.site.register(License, LicenseAdmin)
ajylee/gpaw-rtxs
gpaw/lcao/pwf2.py
Python
gpl-3.0
16,299
0.00135
import numpy as np from ase import Hartree from gpaw.aseinterface import GPAW from gpaw.lcao.overlap import NewTwoCenterIntegrals from gpaw.utilities import unpack from gpaw.utilities.tools import tri2full, lowdin from gpaw.lcao.tools import basis_subset2, get_bfi2 from gpaw.coulomb import get_vxc as get_ks_xc from gp...
shape[1] assert No <= Nw self.V_oM, V_uM = V_nM[:No], V_nM[No:] F_MM = S_MM - np.dot(self.V_oM.T.conj(), self.V_oM) U_ow, U_lw, U_Ml = get_rot(F_MM, self.V_oM, Nw - No) self.U_Mw = np.dot(U_Ml, U_lw) self.U_ow = U_ow - np.dot(self.V_oM, self.U_Mw) if lcao...
?? XXX self.S_ww = self.rotate_matrix(np.ones(1), S_MM) P_uw = np.dot(V_uM, self.U_Mw) self.norms_n = np.hstack(( np.dot(U_ow, np.linalg.solve(self.S_ww, U_ow.T.conj())).diagonal(), np.dot(P_uw, np.linalg.solve(self.S_ww, P_uw.T.conj())).diagonal())) def rotate_matrix...
eiri/nixie
tests/test_nixie_errors.py
Python
mit
579
0.015544
import unittest, uuid from nixie.core import Nixie, KeyError class NixieErrorsTestCa
se(unittest.TestCase): def test_read_missing(self): nx = Nixie() self.assertIsNone(nx.read('missing')) def test_update_missing(self): nx = Nixie() with self.assertRaises(KeyError): nx.update('missing') def test_update_with_wrong_value(self): nx = Nixie() key = nx.create() with...
nx.update(key, 'a') def test_delete_missing(self): nx = Nixie() with self.assertRaises(KeyError): nx.delete('missing')
MERegistro/meregistro
meregistro/shortcuts.py
Python
bsd-3-clause
533
0
from django.shortcuts import render_to_response from django.core.context_processors import csrf from django.conf import settings def my_render(request, template, context={}):
context.update(csrf(request)) context['STATIC_URL'] = settings.STATIC_URL context['flash'] = request.get_flash() context['user'] = request.user context['user_perfil']
= request.get_perfil() context['credenciales'] = set(request.get_credenciales()) context['settings'] = settings return render_to_response(template, context)
ozgurgunes/django-cmskit
cmskit/articles/forms.py
Python
mit
1,271
0.008655
# -*- coding: utf-8 -*- from django import forms from cmskit.articles.models import Index, Article from cms.plugin_pool import plugin_pool from cms.plugins.text.widgets.wymeditor_widget import WYMEditor from cms.plugins.text.settings import USE_TINYMCE def get_editor_widget(): """ Returns the Django form Widg...
for page in self.fields['page'].queryset: choices.append( (page.id, ''.join(['- '*page.level, page.__unicode__()])) ) self.fields['page'].choices = choices class ArticleForm(forms.ModelForm): body = forms.CharField(widget=get_editor_widget()) ...
le
wehr-lab/RPilot
autopilot/core/pilot.py
Python
gpl-3.0
26,194
0.005612
""" """ import os import sys import datetime import logging import argparse import threading import time import socket import json import base64 import subprocess import warnings import numpy as np import pandas as pd from scipy.stats import linregress import tables warnings.simplefilter('ignore', category=tables.Na...
rminal we connect to. * **TERMINALIP** - IP Address of our upstream Terminal. * **MSGPORT** - Port used by our own networking object * **HARDWARE** - Any hardware and its mapping to GPIO pins. No pins are required to be set, instead each task defines which pins it needs. Currently the default configur...
, if any, audio server to use (`'jack'`, `'pyo'`, or `'none'`) * **NCHANNELS** - Number of audio channels * **FS** - Sampling rate of audio output * **JACKDSTRING** - string used to start the jackd server, see `the jack manpages <https://linux.die.net/man/1/jackd>`_ eg:: jackd -P75 -p16 -t2000 -dal...
ndparker/wolfe
wolfe/scheduler/_job.py
Python
apache-2.0
6,561
0
# -*- coding: ascii -*- r""" :Copyright: Copyright 2014 - 2016 Andr\xe9 Malo or his licensors, as applicable :License: 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....
t((succ, (True, virtual_id))) if parent is not None: graph.add(parent, (True, virtual_id)) pre.append(parent) else: graph.ad
d((False, None), (True, virtual_id)) except DependencyCycle as e: # remap to our input (todos and not some weird virtual IDs) raise DependencyCycle([ todos[virtuals[tup[1]]][2] for tup in e.args[0] ]) # 2) resolve the graph (create topological order) id_mapping = {} ...
horkko/biomaj
biomaj/notify.py
Python
agpl-3.0
2,306
0.001735
from builtins import str from builtins import object import smtplib import email.utils from biomaj.workflow import Workflow import logging import sys if sys.version < '3': from email.MIMEText import MIMEText else: from email.mime.text import MIMEText class Notify(object): """ Send notifications ""...
logging.info('Notify:none') return admins = bank.config.get('mail.admin') if not admins: logging.info('Notify: no mail.admin defined') return admin_list = admins.split(',') logging.info('Notify:' + bank.config.get('mail.admin')) mfr...
ank.config.get('mail.from') log_file = bank.config.log_file msg = MIMEText('') if log_file: fp = None if sys.version < '3': fp = open(log_file, 'rb') else: fp = open(log_file, 'r') msg = MIMEText(fp.read(2000000)) ...
karstenw/nodebox-pyobjc
examples/New Functions/twyg/demo1.py
Python
mit
1,032
0.014535
from __future__ import print_function import os twyg = ximport('twyg') # reload(twyg) datafiles = list(filelist( os.path.abspath('example-data'))) datafile = choice(datafiles) configs = [ 'boxes', 'bubbles', 'edge', 'flowchart', 'hive', 'ios', 'jellyfish',
'junction1', 'junction2', 'modern', 'nazca', 'rounded', 'square', 'synapse', 'tron'] colorschemes = [ 'aqua', 'azure', 'bordeaux', 'clay', 'cmyk', 'cobalt', 'colors21', 'crayons', 'earth', 'forest', 'grape', 'honey', 'inca', 'jelly', 'kelp', 'mango', 'mellow', 'me...
, 'mustard', 'neo', 'orbit', 'pastels', 'quartz', 'salmon', 'tentacle', 'terracotta', 'turquoise', 'violet'] config = choice(configs) colorscheme = choice(colorschemes) margins = ['10%', '5%'] print( config ) print( colorscheme ) print( os.path.basename(datafile) ) print() twyg.gene...
python-attrs/attrs
tests/test_slots.py
Python
mit
18,010
0
# SPDX-License-Identifier: MIT """ Unit tests for slots-related functionality. """ import pickle import sys import types import weakref import pytest import attr from attr._compat import PY2, PYPY, just_warn, make_set_closure_cell # Pympler doesn't work on PyPy. try: from pympler.asizeof import asizeof ...
hod def staticmethod(): return "staticmethod" if not PY2: def my_class(self): return __class__ d
ef my_super(self): """Just to test out the no-arg super.""" return super().__repr__() @attr.s(slots=True, hash=True) class C1Slots(object): x = attr.ib(validator=attr.validators.instance_of(int)) y = attr.ib() def method(self): return self.x @classmethod def class...
Debian/dak
daklib/conftest.py
Python
gpl-2.0
1,325
0.000755
# This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as publish
ed by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # This progr
am 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 pro...
johnbachman/belpy
indra/sources/eidos/processor.py
Python
mit
18,394
0
import re import copy import logging import datetime import objectpath from indra.statements import * logger = logging.getLogger(__name__) class EidosProcessor(object): """This processor extracts INDRA Statements from Eidos JSON-LD output. Parameters ---------- json_dict : dict A JSON dicti...
if self.doc.dct is not None: annotations['document_creation_time'] = self.do
c.dct.to_json() epistemics = {} negations = self.get_negation(relation) hedgings = self.get_hedging(relation) if hedgings: epistemics['hedgings'] = hedgings if negations: # This is the INDRA standard to show negation epistemics['negated'] = Tr...
dana-i2cat/felix
modules/resource/manager/stitching-entity/src/handler/geni/v3/extensions/sfa/trust/gid.py
Python
apache-2.0
10,122
0.004149
#---------------------------------------------------------------------- # Copyright (c) 2008 Board of Trustees, Princeton University # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and/or hardware specification (the "Work") to # deal in the Work without restriction, i...
from handler.geni.v3.extensions.sfa.trust.certificate import Certificate from handler.geni.v3.extensions.sfa.util.faults import GidInvalidParentHrn, GidParentHrn from handler.geni.v3.extensions.sfa.util.sfalogging import logger from handler.geni.v3.extensions.sfa.util.xrn import hrn_to_
urn, urn_to_hrn, hrn_authfor_hrn ## # Create a new uuid. Returns the UUID as a string. def create_uuid(): return str(uuid.uuid4().int) ## # GID is a tuple: # (uuid, urn, public_key) # # UUID is a unique identifier and is created by the python uuid module # (or the utility function create_uuid() in gid.py)....
meltiseugen/DocumentsFlow
DocumentsFlow/settings.py
Python
mit
3,117
0.001283
""" Django settings for DocumentsFlow project. Generated by 'django-admin startproject' using Django 1.10.3. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ imp...
'context_processors': [ 'django.template.context_processors.debug', 'django.temp
late.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'DocumentsFlow.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settin...
rparent/django-lock-tokens
tests/settings.py
Python
mit
1,481
0
# -*- coding: utf-8 from __future__ import a
bsolute_import, unicode_literals import django DEBUG = True USE_TZ = True # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "o0fy)a6pmew*fe9b+^wf)96)2j8)%6oz555d7by7_(*i!b8wj8"
DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:", } } ROOT_URLCONF = "tests.urls" INSTALLED_APPS = [ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.sites", "django.contrib.staticfiles", ...
strahlex/pymachinetalk
pymachinetalk/tests/test_dns_sd.py
Python
mit
13,743
0.000291
# coding=utf-8 import pytest @pytest.fixture def dns_sd(): from pymachinetalk import dns_sd return dns_sd @pytest.fixture def sd(): from pymachinetalk import dns_sd sd = dns_sd.ServiceDiscovery() return sd def test_registeringServicesFromServiceContainerWorks(dns_sd, sd): service = dns_s...
cal.', 'Foo on Bar 127.0.0.1._machinekit._tcp.local.', ) assert service.ready is True def test_serviceInfoSetsAllRelevantValuesOfService(dns_sd): service = dns_sd.Service(type_='halrcomp') service_info = ServiceInfoFactory().create( name='Foo on Bar', uuid=b'987654321',
version=5, host='10.0.0.10', protocol='tcp', port=12456, server='sandybox.local', ) service.add_service_info(service_info) assert service.uri == 'tcp://10.0.0.10:12456' assert service.name == service_info.name assert service.uuid == '987654321' assert service....
shivaco/selfbot
cogs/role_perms.py
Python
gpl-3.0
398
0.012563
from discord.ext import commands class Github: def __init__(self, bot): self.bot = bot @commands.command(pass_context=True) async def permrole(self, ctx, argument:str): await self.bot.say(';py fo
r perm in discord.ut
ils.get(ctx.message.server.roles, name="{}").permissions: print(perm)'.format(argument)) def setup(bot): bot.add_cog(Github(bot))
mattvperry/ktane-py
ktane/__init__.py
Python
mit
173
0.005848
from .command_line_mixins import CommandLineMixins from .module import Module from .console_app import ConsoleApp __all__ = ['CommandLineMixins', 'Module', 'Con
soleApp']
JarryShaw/jsntlib
src/NTLArchive/__init__.py
Python
gpl-3.0
100
0
# -*- co
ding: utf-8 -*- '''
Caution: For Python 2.7, `__init__.py` file in folders is nessary. '''
sirca/clusterous
clusterous/defaults.py
Python
apache-2.0
3,073
0.002603
# Copyright 2015 Nicta # # 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, softwa...
't2.small' default_zone = 'a' controller_root_volume_size = 50 # GB cluster_username = 'ubuntu' cluster_user_home_dir = '/home/ubuntu' shared_volume_path = '/home/data/' shared_volume_size = 20 # GB remote_scripts_dir = 'ansible/remote' default_cluster_d
ef_filename = 'default_cluster.yml' remote_host_scripts_dir = 'clusterous' remote_host_key_file = 'key.pem' remote_host_vars_file = 'vars.yml' container_id_script_file = 'container_id.sh' mesos_port = 5050 marathon_port = 8080 central_logging_port = 8081 nat_ssh_port_forwarding = 22000 # How many seconds to wait for...
JocelynDelalande/moulinette-yunohost
lib/yunohost/hook.py
Python
agpl-3.0
10,947
0.004111
# -*- coding: utf-8 -*- """ License Copyright (C) 2013 YunoHost This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any l...
action, custom_hook_folder) return { 'hooks': result } def hook_callback(action, hooks=[], args=None): """ Execute all scripts binded to an action Keyword argument: action -- Action name hooks -- List of hooks names to execute
args -- Ordered list of arguments to pass to the script """ result = { 'succeed': list(), 'failed': list() } hooks_dict = {} # Retrieve hooks if not hooks: hooks_dict = hook_list(action, list_by='priority', show_info=True)['hooks'] else: hooks_n...
nischal2002/m-quiz-2016
quiz.py
Python
mit
1,704
0.016432
import sys # this allows you to read the user input from keyboard also called "stdin" import classOne # This imports all the classOne functions import classTwo # This imports all the classTwo functions import classThree # This imports all the classThree functions import classFour # This imports all the classFour fun...
__name__ == '__main__': while(True) : usersClass = getUsersClass() if (usersClass != False) : break print(QUIZ_INSTRUCTIONS) sys.stdin.readline() if (usersClass == 1) : classOne.classOneQuiz() elif (usersClass == 2) : classTwo.classTwoQuiz() elif(use...
assThree.classThreeQuiz() elif(usersClass == 4): classFour.classFourQuiz()
Kreis-Unna/PostNAS_Search
PostNAS_AccessControl.py
Python
gpl-2.0
12,848
0.006305
# -*- coding: utf-8 -*- import os import getpass import json from qgis.PyQt.QtCore import QSettings from qgis.PyQt.QtSql import QSqlDatabase, QSqlQuery from qgis.PyQt.QtWidgets import QMessageBox from qgis.core import * import qgis.core class PostNAS_AccessControl: def __init__(self, username = None): if(...
query.bindValue(":access",self.access) query.exec_() if(query.lastError().number() == -1): return True else: QgsMessageLog.logMessage("Datenbankfehler beim Update: " + query.lastError().text(),'PostNAS-Suche', Qgis.Critical) return ...
n(self): if(self.getUsername() != None): self.__openDB() sql = "SELECT lower(username) as username FROM public.postnas_search_access_control WHERE access = 0 AND lower(username) = :username" query = QSqlQuery(self.db) if (self.dbSchema.lower() != "public"): ...
dandeliondeathray/niancat-micro
slackrest/features/steps/chat.py
Python
apache-2.0
2,243
0.001337
from behave import given, when, then from slackrest.app import SlackrestApp from slackrest.command import Visibility, Method import json class GiveMeAReply: pattern = '!givemeareply' url_format = '/reply' visibility = Visibility.Any body = None method = Method.GET class GiveMeANotification: ...
e containing '{}'".format(event['message'][
'text'])) assert msg in event['message']['text'] @given(u'I set the notification channel to "{notification_channel_id}"') def step_impl(context, notification_channel_id): context.notification_channel_id = notification_channel_id @given(u'I map "!givemeareply" to /reply') def step_impl(context): pass @...
cypreess/django-getpaid
docs/conf.py
Python
mit
8,687
0.001381
# -*- coding: utf-8 -*- # # django-getpaid documentation build configuration file, created by # sphinx-quickstart on Mon Jul 16 21:16:46 2012. # # 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. ...
lt is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or...
sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_la...
antonsergeev/tesselect
gwyddion_import.py
Python
mit
1,734
0.008661
# Script loads 3d data fr
om text file (after Gwyddion text importing of AFM file) import re import numpy as np def ReadData(file_name): ''' Load 3d data array from a text file. The text file is imported from Gwyddion (free SPM data analysis software). Parameters ---------- file_name : str Relative path to a t...
MxM matrix of SPM data width : float Width of image (in meters) height : float Height of image (in meters) pixel_height : float Height of one pixel (in meters) height_unit : float Measurement unit coefficient (in unit/meter) ''' comments = [] # List of...
MQFN/MQFN
bbmq/server/models.py
Python
apache-2.0
3,993
0.004758
# -------------------------------- Database models---------------------------------------------------------------------- import sys, os import sqlalchemy from sqlalchemy import create_engine sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) import secrets import settings MY...
PORT, MYSQL_DATABASE_NAME) engine = create_engine(database_url) from sqlalchemy import Column, Integer, String, Boolean, DateTime, Text from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import ForeignKey from s...
import sessionmaker Base = declarative_base() class ModelManager(object): """ Model manager """ @classmethod def create_session(cls, engine): """ create a session based :param engine: engine object :return: returns the created session object """ Se...
Orav/kbengine
kbe/src/lib/python/Lib/distutils/versionpredicate.py
Python
lgpl-3.0
5,298
0.002643
"""Module for parsing and testing package version predicate strings. """ import re import distutils.version import operator re_validPackage = re.compile(r"(?i)^\s*([a-z_]\w*(?:\.[a-z_]\w*)*)(.*)", re.ASCII) # (package) (rest) re_paren = re.compile(r"^\s*\((.*)\)
\s*$") # (list) inside of parentheses re_splitComparison = re.compile(r"^\s*(<=|>=|<|>|!=|==)\s*([^\s,]+)\s*$") # (comp) (version) def splitUp(pred): """Parse a single version comparison. Return (comparison string, StrictVersion) """ res = re_splitComparison.match(pred) if not res: ...
rStr = res.groups() return (comp, distutils.version.StrictVersion(verStr)) compmap = {"<": operator.lt, "<=": operator.le, "==": operator.eq, ">": operator.gt, ">=": operator.ge, "!=": operator.ne} class VersionPredicate: """Parse and test package version predicates. >>> v = VersionPr...
datagovuk/ckanext-archiver
ckanext/archiver/commands.py
Python
mit
19,891
0.001408
import logging import os import sys import time import re import shutil import itertools import ckan.plugins as p from pylons import config from ckan.lib.cli import CkanCommand from ckan.lib.helpers import OrderedDict REQUESTS_HEADER = {'content-type': 'application/json'} class Archiver(CkanCommand): ''' D...
.filter_by(owner_org=group.id)) else: packages.extend(group.packages(with_private=True)) if not self.options.queue: self.options.queue = 'bulk' continue # try arg as a package id/name ...
gappleto97/Senior-Project
main.py
Python
mit
2,530
0.001581
from common import bounty, peers, settings from common.safeprint import safeprint from multiprocessing import Queue, Value from time import sleep, time import pickle def sync(): from multiprocessing import Manager man = Manager() items = {'config': man.dict(), 'peerList': man.list(), ...
'bountyList': man.list(), 'bountyLock': bounty.bountyLock, 'keyList': man.list()} items['config'].update(settings.config) items['peerList'].extend(peers.peerlist) items['bountyList'].extend(bounty.bountyList) safeprint(items) peers.sync(items) return items def initP...
ear = peers.listener(settings.config['port'], settings.config['outbound'], queue, live, settings.config['server']) ear.daemon = True ear.items = sync() ear.start() mouth = peers.propagator(settings.config['port'] + 1, live) mouth.daemon = True mouth.items = ear.items mouth.start() f...
Kniyl/mezzanine
mezzanine/core/middleware.py
Python
bsd-2-clause
12,608
0.000317
from __future__ import unicode_literals from future.utils import native_str from django.contrib import admin from django.contrib.auth import logout from django.contrib.messages import error from django.contrib.redirects.models import Redirect from django.core.exceptions import MiddlewareNotUsed from django.core.urlres...
except KeyError: try: csrf_token = request.COOKIES[settings.CSRF_COOKIE_NAME] except KeyError: pass if csrf_token: request.META["CSRF_COOKIE"] = csrf_token contex
t = Reques
ademilly/waterflow
waterflow/_version.py
Python
mit
16,749
0
# This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains t...
print("discarding '%s', no digits" % ",".join(refs-tags)) if verbose: print("likely tags: %s" % ",".join(s
orted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print("picking %s" % r) return {"version": r, "full-revisionid": keywords...
OpenMORA/mora-base
scripts/morautils.py
Python
gpl-3.0
2,018
0.041625
# Utility functions for OpenMORA scripts # # Part of OpenMora - https://github.com/OpenMORA import os, sys, string import platform import yaml def get_mora_paths(): """ Returns a list of paths with MORA modules, from the env var MORA_PATH """ if not 'MORA_PATH' in os.environ: print('**ERROR** Environment variabl...
nv vars for p in mora_paths: tstPath = os.path.normpath(p + "/mora-base") if os.path.exists(tstPath): morabase_dir = tstPath if (len(morabase_dir)==0) or (not os.
path.exists(morabase_dir)): print("Couldn't detect mora-base in MORA_PATH!!") sys.exit(1) return morabase_dir import sys, math def progress(percent): ''' source: http://gunslingerc0de.wordpress.com/2010/08/13/python-command-line-progress-bar/ ''' width = 74 marks = math.floor(width * (percent / 100.0)) spac...
trafi/djinni
test-suite/handwritten-src/python/test_proxying.py
Python
apache-2.0
5,511
0.009254
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from foo_receiver import FooReceiver from foo_listener_bf import FooListenerBfHelper from PyCFFIlib_cffi import ffi, lib import gc class FooListenerBfImpl: def delete_fl_in_fl(self): print ("Not to b...
hold same implementation fl_cpp_1 = fr.send_return(fl_cpp) fl_cpp_2 = fr.send_return(fl_cpp_1) fr_set_get(fr, fl_cpp_2, "Goodbye") assert lib.equal_handles_cw__foo_listener_bf(fl_cpp._cpp_imp
l, fl_cpp_1._cpp_impl) and \ lib.equal_handles_cw__foo_listener_bf(fl_cpp_1._cpp_impl, fl_cpp_2._cpp_impl) fl = fl_1 = fl_2 = fl_cpp = fl_cpp_1 = fl_cpp_2 = None gc.collect() fr = None gc.collect() assert 0 == len(FooListenerBfHelper.c_data_set) def fr_fl_set_get(fr, fl_in_fl, b): ...
kernevil/samba
python/samba/tests/dckeytab.py
Python
gpl-3.0
2,161
0
# Tests for source4/libnet/py_net_dckeytab.c # # Copyright (C) David Mulder <dmulder@suse.com> 2018 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at yo...
eytab from samba import tests from samba.param import LoadParm enable_net_export_keytab() def open_bytes(filename): if sys
.version_info[0] == 3: return open(filename, errors='ignore') else: return open(filename, 'rb') class DCKeytabTests(tests.TestCase): def setUp(self): super(DCKeytabTests, self).setUp() self.lp = LoadParm() self.lp.load_default() self.creds = self.insta_creds(tem...
robdennis/sideboard
sideboard/tests/test_server.py
Python
bsd-3-clause
19,922
0.001757
from __future__ import unicode_literals import json import socket from uuid import uuid4 from time import sleep from urllib import urlencode from random import randrange from unittest import TestCase from Queue import Queue, Empty from contextlib import closing from urlparse import urlparse, parse_qsl import pytest im...
rt_error_with(self, *args, **kwargs): if args: self.ws.ws.send(str(args[0])) else: self.ws._send(**kwargs) assert 'error' in self.next() def call(self, **params): callback = 'callback{}'.format(randrange(1000000)) self.ws._se
nd(callback=callback, **params) result = self.next() assert callback == result['callback'] return result def subscribe(self, **params): params.setdefault('client', self.client) return self.call(**params) def unsubscribe(self, client=None): self.call(action='unsu...
mhvk/astropy
astropy/cosmology/__init__.py
Python
bsd-3-clause
830
0
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ astropy.cosmology contains classes and functions for cosmological distance measures and other cosmology-related calculations. See the `Astropy documentation <https://docs.astropy.org/en/latest/cosmology/index.html>`_ for more detailed usage examples a...
nces thereof + funcs.__all__ + para
meter.__all__ + utils.__all__) # utils
amcat/amcat
navigator/views/tests/test_article_views.py
Python
agpl-3.0
10,397
0.003078
from django.core.urlresolvers import reverse from django.test import Client from amcat.models import ArticleSet, Sentence, Article, Role from amcat.tools import amcattest, sbd import navigator.forms from navigator.views.article_views import ArticleSplitView, handle_split, get_articles, ArticleDetailsView class TestSp...
e="test_article_split_view_set") self.assertEqual(response.status_code, 200) self.assertTrue(new_set.exists()) self.assertEqual(article, new_set[0].articles.all()[0]) @amcattest.use_elastic def test_handle_split(self): from amcat.tools import amcattest from functools imp...
f.create_test_sentences() project = amcattest.create_test_project() aset1 = amcattest.create_test_set(4, project=project) aset2 = amcattest.create_test_set(5, project=project) aset3 = amcattest.create_test_set(0) # Creates a codingjob for each articleset, as handle_split should ...
s0hvaperuna/Not-a-bot
bot/commands.py
Python
mit
2,568
0.000389
import logging from discord.ext import commands from bot.cooldowns import CooldownMapping, Cooldown from bot.globals import Auth from utils.utilities import is_owner, check_blacklist, no_dm
terminal = logging.getLogger('terminal') def command(*args, **attrs): if 'cls' not in attrs: attrs['cls'] = Command return commands.command(*args, **attrs) def group(name=None, **attrs): """Uses custom Group class""" if 'cls' not in attrs:
attrs['cls'] = Group return commands.command(name=name, **attrs) def cooldown(rate, per, type=commands.BucketType.default): """See `commands.cooldown` docs""" def decorator(func): if isinstance(func, Command): func._buckets = CooldownMapping(Cooldown(rate, per, type)) else: ...
BleuLlama/LlamaPyArdy
Python/devices/lib_RC2014_BusSupervisor.py
Python
mit
4,512
0.068927
#!/usr/bin/python ################################################################################ # Bus Supervisor Interface # # - interfaces to the MCP23017 and PCF8574 IO expander chips # # The logic for this was ported from Dr Scott M. Baker's project: # http://www.smbaker.com/z80-retrocomputing-4-bus-supervisor # ...
###############################
### from libArdySer import ArdySer from lib_GenericChip import GenericChip from GS_Timing import delay from lib_MCP23017_IOExpander16 import MCP23017_IOExpander16 from lib_PCF8574_IOExpander8 import PCF8574_IOExpander8 class RC2014_BusSupervisor: ################################## # class variables ardy = None ...
h2oai/h2o-3
h2o-py/tests/testdir_javapredict/pyunit_PUBDEV_8330_GLM_mojo_gamma_offset.py
Python
apache-2.0
1,402
0.021398
import sys, os sys.path.insert(1, "../../../") import h2o from tests import pyunit_utils from random import randint import tempfile def glm_gamma_offset_mojo(): train = h2o.import_file(path=pyunit_utils.locate("smalldata/prostate/prostate_complete.csv.zip")) y = "DPROS" x = ["AGE","RACE","CAPSULE","DCAPS...
d_save_model_generic(params, x, train, y, "glm", tmpdir) # build and save mojo model MOJONAME = pyunit_utils.getMojoName(glm_gamma_model._id) h2o.download_csv(train[x_offset], os.path.join(tmpdir, 'in.csv')) # save test file, h2o predict/mojo use same file pred_h2o, pred_mojo = pyunit_utils.mojo_predict(g...
h2o.download_csv(pred_h2o, os.path.join(tmpdir, "h2oPred.csv")) print("Comparing mojo predict and h2o predict...") pyunit_utils.compare_frames_local(pred_h2o, pred_mojo, 0.1, tol=1e-10) # compare mojo and model predict if __name__ == "__main__": pyunit_utils.standalone_test(glm_gamma_offset_mojo) else: ...
powellc/timberwyck
manage.py
Python
bsd-3-clause
313
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "timberwyc
k.settings") os.environ.setdefault("DJANGO_CONFIGURATION", "Dev") from configurations.management import execute_from_command_line execute_from_command_line(sys.argv)
fangdingjun/example1
python/ssh_c.py
Python
gpl-3.0
1,479
0.005409
#!/usr/bin/env python # -*- coding: utf-8 -*- import paramiko import threading import sys import re import time import os def start_shell(h, u, p): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(h, 22, u, p) s = ssh.invoke_shell() w = threading.Th...
.sub(str(i),"",d) sys.stdout.write(d) sys.stdout.flush() # time.sleep(0.1) try: s.close() except: pass # os.kill(os.getpid(), 15) # sys.exit(0) def write_chanel
(s): try: while True: c = sys.stdin.read(1) if not c: s.close() break a = s.send(c) if a == 0: s.close() break except: pass if __name__ == '__main__': import sys if len(sys.a...
orting/emphysema-estimation
Experiments/07-MICCAI/Scripts/PredictTrain.py
Python
gpl-3.0
1,630
0.019018
#!/usr/bin/python3 import sys, subprocess def main(argv=None): if argv is None: argv = sys.argv experiments = { 1 : ('Continuous', 'COPD'), 2 : ('Binary', ' COPD'), 3 : ('Continuous', 'EmphysemaExtentLung'), 4 : ('Binary', 'EmphysemaExtentLung'), } try: ...
ers = ['5', '10', '20', ]#'15', '20', ]#'25', '30'] params = { 'histograms' : '24', } for k in numberOfClusters:
out = 'Out/Training/MaxIterations1000/%s_%s_k%s_' % (experiment + (k,)) cmd = [ prog, "--instances", instances, '--bag-membership', bagMembership, '--model', modelPattern % (experiment + (k,)), "--histograms", params['histograms'], "-...