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 |
|---|---|---|---|---|---|---|---|---|
eeshangarg/zulip | zerver/migrations/0342_realm_demo_organization_scheduled_deletion_date.py | Python | apache-2.0 | 438 | 0 | # Generated by Django 3.2.5 on 2021-08-12 18:41
from django.db import migrations, models
class Migra | tion(migrations.Migration):
dependencies = [
("zerver", "0341_usergroup_is_system_group"),
]
operations = [
migrations.AddField(
model_name="realm",
name="demo_organization_scheduled_deletion_date",
field=models.DateTimeField(default=None, null=True) | ,
),
]
|
tscheff/Davis | davis_c.py | Python | mit | 10,939 | 0.003382 | """
Interface module for the C-version of davis.
Molecular Dynamics Simulation on a Sphere
Please see README.md for details.
MIT license
Copyright(c) 2015 - 2019 Tim Scheffler
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Softw... | S IN THE SOFTWARE.
"""
import ctypes as c
import numpy as np
import math
import queue
import threadi | ng
import fibonacci_sphere
import glob
import os
import sys
possible_clibs = glob.glob("davis_clib*")
if "win32" in sys.platform:
possible_clibs = [lib for lib in possible_clibs if "-win_" in lib]
elif "darwin" in sys.platform:
possible_clibs = [lib for lib in possible_clibs if "-darwin" in lib]
if len(possib... |
hzj123/56th | pombola/core/management/commands/core_import_basic_positions_csv.py | Python | agpl-3.0 | 2,345 | 0.010235 | # This is a very simple script to import basic CSV with the following columns:
#
# person_name
# position_title
# place_kind
# place_name
# organisation_kind
# organisation_name
#
# The various person etc entries will be created if needed (ie if there is no
# exact match).
#
# GOTCHAS
#
# * If the organis... | d) = model.objects.get_or_create(defaults=defaults, **kwargs)
return obj
class Command(LabelCommand):
| help = 'Import positions from a very basic CSV format'
args = '<positions CSV file>'
# option_list = LabelCommand.option_list + (
# make_option('--commit', action='store_true', dest='commit', help='Actually update the database'),
# )
def handle_label(self, input_filename, **options):
... |
jakemalley/training-log | manage.py | Python | mit | 4,168 | 0.010797 | # manage.py
# Jake Malley
# 15/01/2015
"""
Manage.py file uses Flask-Script to create a Manager
to allow us to run the app server and open a shell
inside the application context. It also provided the ability
to create custom commands. As well as perform database migrations.
"""
# Imports
from flask.ext.script import ... | orna | do.httpserver import HTTPServer
from tornado.ioloop import IOLoop
# Import signal used to stop tornado with ctrl-c.
import signal
# Define a callback to stop the server.
def stop_tornado(signum, frame):
# Stop the loop.
IOLoop.instance().stop()
signal.signal(signal.SIGINT, stop... |
Gorgel/khd_projects | khd_projects/khd_projects/urls.py | Python | mit | 890 | 0.007865 | from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
admin.au | todiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'openlc.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^$', include( | 'projects.urls', namespace="index")),
url(r'^blockly/', include('blockly.urls', namespace="blockly")),
url(r'^projects/', include('projects.urls', namespace="projects"))
)
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'documen... |
ospaceteam/outerspace | server/lib/rsa/core.py | Python | gpl-2.0 | 1,834 | 0.003273 | # -*- coding: utf-8 -*-
#
# Copyright 2011 Sybre | n A. Stüvel <[email protected]>
#
# 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 Licens | e at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language ... |
jijianwen/Learn | Linux/linux_tests/nfs_network_load/test.py | Python | gpl-2.0 | 4,473 | 0.00626 | #!/usr/bin/python
#
# Usage:
# sudo ./reproducer.py num_threads num_iterations_per_thread nfs_share
#
# Example:
# sudo ./reproducer.py 5 10 IPADDRESS:/path/to/dir
# Will run 5 threads, each with 10 iterations, writing to the NFS share at IPADDRESS:/path/to/dir
#
# Prerequisites:
# 1. Install a base trusty cont... | or t in threads:
# t.join()
# Re-write above code by making use of docker
# Run the build.sh to build the docker image first.
# # sh build.sh
import re
class WorkerThread (threading.Thread):
def __init__(self, id, num_iterations, nfs_server):
threading.Thread.__init__(self)
self.id = id
... | self.nfs_server = nfs_server
def run(self):
print("Starting thread%d" % self.id)
clone_name = "clone%d" % self.id
for i in range(self.num_iterations):
print("Thread%d at iteration %d/%d" % (self.id, i, self.num_iterations))
os.system("docker run --name=%s --privilege... |
ArchaeoPY/ArchaeoPY | GUI_Templates/mplwidget.py | Python | gpl-2.0 | 1,485 | 0.003367 | #!/usr/bin/env python
# Python Qt4 bindings for GUI objects
from PyQt4 import QtGui
# import the Qt4Agg FigureCanvas object, that binds Figure to
# Qt4Agg backend. It also inherits from QWidget
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
# Matplotlib Figure object
from matplotlib... | Class to represent the FigureCanvas widget"""
def __init__(self):
# setup Matplotlib Figure and Axis
self.fig = Figure()
self.ax = self.fig.add_subplot(111)
# initialization of the canvas
FigureCanvas.__init__(self, self.fig)
# we define the widget as expandable
... | tem of updated policy
FigureCanvas.updateGeometry(self)
class MplWidget(QtGui.QWidget):
"""Widget defined in Qt Designer"""
def __init__(self, parent = None):
# initialization of Qt MainWindow widget
QtGui.QWidget.__init__(self, parent)
# set the canvas to the Matplotlib widget... |
napalm-automation/napalm-yang | napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/ospfv2/areas/area/lsdb/lsa_types/lsa_type/lsas/lsa/opaque_lsa/traffic_engineering/tlvs/tlv/link/sub_tlvs/sub_tlv/__init__.py | Python | apache-2.0 | 37,904 | 0.001214 | # -*- coding: utf-8 -*-
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClassType
from pyangbind.lib.yangtypes import TypedListType
from pyangbind.lib.yangtypes import YANGBool
from pyangbind.lib.yangtypes import YANGListTy... | net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=False)""",
}
)
self.__state = t
if hasattr(self, "_set"):
self._set()
def _unset_state(self):
self.__state = YANGDynClass(
ba | se=state.state,
is_container="container",
yang_name="state",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
extensions |
Damicristi/Ising-Model-in-2D | Tools/Initialize_lattice_plot.py | Python | gpl-3.0 | 547 | 0.042357 | #Author: Damodar Rajbhandari
#!/usr/bin/python3
import numpy as np
import matplotlib.pyplot as plot
from random import *
L = 10
"""
This represents, there are "L" (eg. 3) either in
one row or column. Hence,
Total sites = L*L
"""
for i in range(L):
for j in range(L):
if randint(0, 1) > 0.5:
plot.scatter(i... | spin down
|
plot.xlabel('x →')
plot.ylabel('y →')
plot.title('Initial configuration of our lattice')
plot.show()
|
mhbu50/erpnext | erpnext/accounts/report/share_ledger/share_ledger.py | Python | gpl-3.0 | 1,816 | 0.026432 | # Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
from frappe import _
def execute(fil | ters=None):
if not filters: filters = {}
if not filters.get("date"):
frappe.throw(_("Please select date"))
columns = get_columns(filters)
date = filters.get("date")
data = []
if not filters.get("shareholder"):
pass
else:
transfers = get_all_transfers(date, filters.get("shareholder"))
for transfer in... | 'Transfer':
if transfer.from_shareholder == filters.get("shareholder"):
transfer.transfer_type += ' to {}'.format(transfer.to_shareholder)
else:
transfer.transfer_type += ' from {}'.format(transfer.from_shareholder)
row = [filters.get("shareholder"), transfer.date, transfer.transfer_type,
trans... |
z01nl1o02/tests | learn_svd.py | Python | gpl-2.0 | 1,675 | 0.015522 | import os,sys,cv2,pdb
from sklearn.decomposition import TruncatedSV | D
from pylab import *
def get_feature(imgpath):
img = cv2.imread(imgpath,0)
img = cv2.resize(img,(32,64))
img = np.float32(img)
img = img / 255
img = np.reshape(img, (1,32*64))
return img
def extract_sample_from_image(imgdir):
feats = []
for rdir, pdir, names in os.walk(imgdir+'pos'):
... | fname = os.path.join(rdir, name)
feats.append(get_feature(fname))
for rdir, pdir, names in os.walk(imgdir+'neg'):
for name in names:
sname,ext = os.path.splitext(name)
if 0 == cmp(ext, '.jpg'):
fname = os.path.join(rdir, name)
... |
caw/curriculum | db/migrations/0053_auto_20161112_2146.py | Python | gpl-3.0 | 543 | 0.001842 | # -*- | coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-12 10:46
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('db', '0052_auto_20161112_2141'),
]
operations = [
migrations.AlterField(
| model_name='yearlevel',
name='name',
field=models.CharField(blank=True, choices=[(1, '1'), (2, '2'), (3, 'A'), (4, '3B'), (5, '4C'), (6, '5D')], max_length=30, null=True),
),
]
|
AdrianaDinca/bitcoin | qa/rpc-tests/import-rescan.py | Python | mit | 7,007 | 0.00157 | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (start_nod... | id]
if import_node.rescan:
assert_equal(balance, amount)
assert_equal(len(spend_tx), 1)
assert_equal(spend_tx[0]["account"], "")
assert_equal(spend_tx[0]["amount"] + spend_tx[0]["fee"], -amount)
assert_eq... | assert_equal("trusted" not in spend_tx[0], True)
assert_equal("involvesWatchonly" not in txs[0], True)
else:
assert_equal(balance, 0)
assert_equal(spend_tx, [])
if __name__ == "__main__":
ImportRescanTest().main()
|
iulian787/spack | var/spack/repos/builtin/packages/pngwriter/package.py | Python | lgpl-2.1 | 1,625 | 0.003077 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Pngwriter(CMakePackage):
"""PNGwriter is a very easy to use open source graphics library t... | as its output format. The interface has been designed to be as simple
and intuitive as possible. It supports plotting and reading pixels in the
RGB (red, green, blue), H | SV (hue, saturation, value/brightness) and CMYK
(cyan, magenta, yellow, black) colour spaces, basic shapes, scaling,
bilinear interpolation, full TrueType antialiased and rotated text support,
bezier curves, opening existing PNG images and more.
"""
homepage = "http://pngwriter.sourceforge.net/"
... |
TNG/svnfiltereddump | src/svnfiltereddump/__init__.py | Python | gpl-3.0 | 1,146 | 0.000873 |
from Main import run
#
# The Big Plan
#
# Decide what to do with a revision
from DumpController import DumpController, STRATEGY_DUMP_HEADER, STRATEGY_IGNORE, STRATEGY_SYNTHETIC_DELETES, STRATEGY_DUMP_SCAN, STRATEGY_BOOTSTRAP, DUMP_HEADER_PSEUDO_REV
# Generate the lumps for t | hat
from DumpHeaderGenerator import DumpHeaderGenerator
from BootsTrapper import BootsTrapper
from DumpFilter import DumpFilter, UnsupportedDumpVersionException
from SyntheticDeleter import SyntheticDeleter
from Revi | sionIgnorer import RevisionIgnorer
# Build the lumps
from LumpBuilder import LumpBuilder
# Fix length fields, drop empty revisions
from LumpPostProcessor import LumpPostProcessor
#
# SVN Abstraction layer
#
from SvnLump import SvnLump
from SvnDumpReader import SvnDumpReader
from SvnDumpWriter import SvnDumpWriter
fro... |
dhalperi/beam | sdks/python/apache_beam/runners/runner.py | Python | apache-2.0 | 12,102 | 0.006858 | #
# 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 us... |
Args:
pvalue: A PValue instance whose cached value is requested.
During the runner's execution only the | results of the primitive transforms
are cached. Whenever we are looking for a PValue that is the output of a
composite transform we need to find the output of its rightmost transform
part.
"""
if not hasattr(pvalue, 'real_producer'):
real_producer = pvalue.producer
while real_producer.p... |
paulmand3l/elevendance | registration/urls.py | Python | mit | 154 | 0.006494 | from django.conf. | urls import patterns, include, url
urlpatterns = patterns('checki | n.views',
url(r'^checkin/$', 'checkin', name="checkin-checkin"),
)
|
showyou/anzu | common/model.py | Python | mit | 4,110 | 0.037796 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# マルコフテーブル等定義
import sqlalchemy
from sqlalchemy.orm import scoped_session, sessionmaker, mapper
from sqlalchemy import MetaData
from sqlalchemy import Column, MetaData, Table, types
from datetime import datetime
class OhayouTime(object):
pass
class Markov(object):
pass... | ),
Column('now', types.Unicode(32)),
Column('next', types.Unicode(32)),
Column('count', types.Float,default=1),
Column('lastupdate', types.DateTime, default=datetime.now),
mysql_engine = 'InnoDB',
mysql_charset= 'utf8'
)
# 応答キュー。順番固定
retQueue = Table("retQueue",metadata,
Colu... |
Column('reply_id', types.BigInteger(20), default=0),
mysql_engine = 'MyISAM',
mysql_charset = 'utf8'
)
# hotな単語一覧
hot = Table("hot",metadata,
Column('id', types.Integer, primary_key=True),
Column('word', types.Unicode(140)),
Column('datetime',types.DateTime, default=dateti... |
Lyla-Fischer/xblock-sdk | workbench/test/test_runtime.py | Python | agpl-3.0 | 6,112 | 0.002291 | """Test Workbench Runtime"""
from unittest import TestCase
import mock
from django.conf import settings
from xblock.fields import Scope
from xblock.runtime import KeyValueStore
from xblock.runtime import KvsFieldData
from xblock.reference.user_service import UserService
from ..runtime import WorkbenchRuntime, Scena... | Runtime('test_user')
# Default services should still be available
self._assert_default_services(runtime)
# An additiona | l service should be provided
self._assert_service(runtime, 'stub', StubService)
# Check that the service has the runtime attribute set
service = runtime.service(self.xblock, 'stub')
self.assertIs(service.runtime, runtime)
@mock.patch.dict(settings.WORKBENCH['services'], {
'... |
olimp-web/quest_manager | quest_map/admin.py | Python | mit | 124 | 0.008065 | from django.contrib impor | t admin
f | rom .models import Station, Quest
admin.site.register(Quest)
admin.site.register(Station) |
alphagov/digitalmarketplace-api | migrations/versions/1290_sf_allow_declaration_reuse_add_column.py | Python | mit | 747 | 0.006693 | """sf_allow_declaration_reuse_add_column
create supplier_frameworks.allow_declaration_reuse column as nullable in an initial, small
transaction. we will backfill it with defaults la | ter to minimize table locking time.
Revision ID: 1290
Revises: 1280
Create Date: 2019-06-10 17:00:02.464675
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '1290'
down_revision = '1280'
def upgrade():
# create column as nullable in an initial, small tran... | nullable=True))
def downgrade():
op.drop_column('supplier_frameworks', 'allow_declaration_reuse')
|
polyaxon/polyaxon | platform/coredb/coredb/managers/runs.py | Python | apache-2.0 | 2,268 | 0.000441 | #!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, 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 ... | et_run_model().objects.create(
project_id=project_id,
user_id=user_id,
name=name,
description=description,
readme=readme,
tags=tags,
kind=V1RunKind.JOB,
is_managed=False,
raw_content=raw_content,
meta_info=meta_info,
status_conditio... | "Run is created",
).to_dict()
],
)
return instance
def base_approve_run(run: BaseRun):
pending = run.pending
if pending:
new_pending = None
if (
(pending == V1RunPending.BUILD and run.status == V1Statuses.CREATED)
or pending == V1RunPending.U... |
pytroll/satpy | utils/fetch_avhrr_calcoeffs.py | Python | gpl-3.0 | 4,773 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015 Satpy developers
#
# This file is part of satpy.
#
# satpy 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... | h2.txt"}
}
def get_page(url):
"""Retrieve the given page."""
return ur | llib2.urlopen(url).read()
def get_coeffs(page):
"""Parse coefficients from the page."""
coeffs = {}
coeffs['datetime'] = []
coeffs['slope1'] = []
coeffs['intercept1'] = []
coeffs['slope2'] = []
coeffs['intercept2'] = []
slope1_idx, intercept1_idx, slope2_idx, intercept2_idx = \
... |
adamjace/envcheckr | tests/test_envcheckr.py | Python | mit | 983 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_envcheckr
----------------------------------
Tests for `envcheckr` module.
"""
import pytest
from envcheckr import envcheckr
def test_parse_lines():
lines_a = envcheckr.parse_lines('tests/env')
asser | t len(lines_a) == 3
lines_b = envcheckr.parse_lines('tests/env.example')
assert len(lines_b) == 7
def test_parse_key():
lines = envcheckr.parse_lines('tests/env')
assert(envcheckr.parse_key(lines[0])) == 'FRUIT'
assert(envcheckr.parse_key(lines[1])) == 'DRINK'
assert(envcheckr.parse_key(lines[... | == 'ANIMAL'
def test_get_missing_keys():
file_a = 'tests/env'
file_b = 'tests/env.example'
missing_keys = envcheckr.get_missing_keys(file_a, file_b)
assert(len(missing_keys)) == 4
assert(missing_keys[0]) == 'FOOD=Pizza\n'
assert(missing_keys[1]) == 'CODE=Python\n'
assert(missing_keys[2]) ... |
pi-bot/.v2 | python-code/ultrasound.py | Python | gpl-3.0 | 680 | 0.017647 | import arduino
from arduino import Commands
from arduino im | port Arduino
from time import sleep
TRIGGER_PIN = arduino.A3
class Ultrasound():
def __init__(self):
self.board = Arduino()
self.board.connect()
def getDistance(self):
distance = int(self.board.sendCommand(Commands.READ_ULTRASOUND,TRIGGER_PIN,0))
# large distances are... | stance
if __name__ == '__main__':
ultra = Ultrasound()
while True:
print(ultra.getDistance())
sleep(1)
|
cathyyul/sumo-0.18 | tools/output/generateITetrisIntersectionMetrics.py | Python | gpl-3.0 | 12,974 | 0.00316 | #!/usr/bin/env python
"""
@file generateITetrisIntersectionMetrics.py
@author Daniel Krajzewicz
@author Lena Kalleske
@author Michael Behrisch
@date 2007-10-25
@version $Id: generateITetrisIntersectionMetrics.py 14425 2013-08-16 20:11:47Z behrisch $
SUMO, Simulation of Urban MObility; see http://sumo-sim.org... | ['nbStops'])
nbStops.append(nbStopsInfo)
tWaitTimeInfo = sum(lanesInfo[lane.getID()]['tWaitTime'])
tWaitTime.append(tWaitTimeInfo)
tlsInfo[tlID] = {}
tlsInfo[tlID]['mQueueLen'] = mean(mQueueLen) / T
tlsInfo[tlID]['mWaitTime'] = mean(tWa | itTime) / T
tlsInfo[tlID]['nbStops'] = sum(nbStops)
tlsInfo[tlID]['tWaitTime'] = sum(tWaitTime)
return tlsInfo
def mergeInfos(tlsInfoAll, tlsInfoOne, metric):
for tl in tlsInfoOne.keys():
tlsInfoAll[tl][metric] = tlsInfoOne[tl]
def getStatisticsOutput(tlsInfo, outputfile):
opfile =... |
sonicrules1234/sonicbot | oldplugins/randfact.py | Python | bsd-3-clause | 378 | 0.007937 | import re, urllib2
arguments = ["self", "info", "args"]
helpstring = "randfact"
minlevel = 1
def main(connection, info, args) :
"""Returns a random fact"""
source = urllib2.urlopen("http://randomfunfacts.com/").read()
| fact = re.search(r"<strong><i>(.*)</i></strong>", source)
connection.msg(info["channel"], "%s: %s" % (info["sender | "], fact.group(1)))
|
grondo/flux-core | src/bindings/python/flux/resource/__init__.py | Python | lgpl-3.0 | 469 | 0 | ###############################################################
# Copyright 2020 Lawrence Livermore National Security, LLC
# (c | .f. AUTHORS, NOTICE.LLNS, COPYING)
#
# This file is part of the Flux resource manager framework.
# For details, see https://github.com/flux-framework.
#
# SPDX-License-Identifier: LGPL-3.0
###############################################################
from flux.resource.Rlist import Rl | ist
from flux.resource.ResourceSet import ResourceSet
|
helmuthb/devfest-at-site | handlers/api.py | Python | mit | 1,264 | 0.037975 | from google.appengine.ext import ndb
import settings
from core import model
import common
from webapp2_extras.i18n import gettext as _
class RPCHandler(common.BaseAPIHandler):
def get(self, action, *args):
args = self.request.GET
for arg in args:
args[arg] = self.request.... | ail = args | ['email']
self.current_user.put()
self.prep_json_response(200, message = _("Email updated!"))
else:
self.prep_json_response(400, key = "noemail")
class RESTHandler(common.BaseRESTHandler):
def get(self, *args, **kwargs):
pass
|
andresailer/DIRAC | ResourceStatusSystem/scripts/dirac-rss-list-status.py | Python | gpl-3.0 | 5,951 | 0.043018 | #!/usr/bin/env python
"""
dirac-rss-list-status
Script that dumps the DB information for the elements into the standard output.
If returns information concerning the StatusType and Status attributes.
Usage:
dirac-rss-list-status
--element= Element family to be Synchronized ( Sit... | ; None if default
--name= ElementName; None if default
--tokenOwner= Owner of the token; None if default
--statusType= StatusType; None if default
--status= Status; None if default
Verbosity:
-o LogLevel=LEVEL NOTICE by default, levels... | , version
from DIRAC.Core.Base import Script
from DIRAC.ResourceStatusSystem.Client import ResourceStatusClient
from DIRAC.Core.Utilities.PrettyPrint import printTable
__RCSID__ = '$Id:$'
subLogger = None
switchDict = {}
def registerSwitches():
'''
Registers all swi... |
sippy/b2bua | sippy/UaStateGeneric.py | Python | bsd-2-clause | 1,909 | 0.003667 | # Copyright (c) 2003-2005 Maxim Sobolev. All rights reserved.
# Copyright (c) 2006-2014 Sippy Software, Inc. All rights reserved.
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistrib... | he above c | opyright notice,
# this list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARR... |
pfalcon/micropython | examples/rp2/pio_uart_tx.py | Python | mit | 1,250 | 0.0056 | # Example using PIO to create a UART TX interface
from machine import Pin
from rp2 import PIO, StateMachine, asm_pio
UART_BAUD = 115200
PIN_BASE = 10
NUM_UARTS = 8
@asm | _pio(sideset_init=PIO.OUT_HIGH, out_init=PIO.OUT_HIGH, out_shiftdir=PIO.SHIFT_RIGHT)
def uart_tx():
# fmt: off
# Block with TX deasserted until data available
pull( | )
# Initialise bit counter, assert start bit for 8 cycles
set(x, 7) .side(0) [7]
# Shift out 8 data bits, 8 execution cycles per bit
label("bitloop")
out(pins, 1) [6]
jmp(x_dec, "bitloop")
# Assert stop bit for 8 cycles total (incl 1 for pull())
nop() .side(1) ... |
pcu4dros/pandora-core | workspace/lib/python3.5/site-packages/setuptools/command/easy_install.py | Python | mit | 87,125 | 0.000161 | #!/usr/bin/env python
"""
Easy Install
------------
A tool for doing automatic download/extract/build of distutils-based Python
packages. For detailed documentation, see the accompanying EasyInstall.txt
file, or visit the `EasyInstall home page`__.
__ https://setuptools.readthedocs.io/en/latest/easy_in | stall.html
"""
from glob import glob
from distutils.util import get_platform
from distutils.util import convert_path, subst_vars
from distutils.errors import (
DistutilsArgError, DistutilsOptionError,
DistutilsError, DistutilsPlatformError,
)
from distutils.command.install import INSTALL_SCHEMES, SCHEME_KEYS
... | hutil
import tempfile
import zipfile
import re
import stat
import random
import textwrap
import warnings
import site
import struct
import contextlib
import subprocess
import shlex
import io
from setuptools.extern import six
from setuptools.extern.six.moves import configparser, map
from setuptools import Command
from ... |
gmatteo/pymatgen | pymatgen/optimization/linear_assignment_numpy.py | Python | mit | 8,207 | 0.000731 | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This module contains an algorithm to solve the Linear Assignment Problem.
It has the same functionality as linear_assignment.pyx, but is much slower
as it is vectorized in numpy rather than cython
"""
__a... | p)
u1 = temp[j1]
temp[j1] = np.inf
j2 = np.argmin(temp)
u2 = temp[j2]
if u1 < u2:
self._v | [j1] -= u2 - u1
elif self._y[j1] != -1:
j1 = j2
k = self._y[j1]
if k != -1:
self._x[k] = -1
self._x[i] = j1
self._y[j1] = i
i = k
if k == -1 or abs(u1 - u2)... |
adampresley/trackathon | model/StringHelper.py | Python | mit | 668 | 0.031437 | import re, random, string
from Service import Service
class StringHelper(Service):
articles = ["a", "an", "the", "of", "is"]
def randomLetterString(self, numCharacters = 8):
return "".join(random.choice(string.ascii | _letters) for i in range(numCharacters))
def tagsToTuple(self, tags):
return tuple(self.titleCase(tag) for tag in tags.split(",") if tag.strip())
def titleCase(self, s):
wordList = s.split(" ")
resu | lt = [wordList[0].capitalize()]
for word in wordList[1:]:
result.append(word in self.articles and word or word.capitalize())
return " ".join(result)
def validEmail(self, email):
return re.match(r"[^@]+@[^@]+\.[^@]+", email)
|
Ingenico-ePayments/connect-sdk-python3 | ingenico/connect/sdk/domain/payment/definitions/refund_output.py | Python | mit | 9,736 | 0.004827 | # -*- coding: utf-8 -*-
#
# This class was auto-generated from the API references found at
# https://epayments-api.developer-ingenico.com/s2sapi/v1/
#
from ingenico.connect.sdk.domain.payment.definitions.order_output import OrderOutput
from ingenico.connect.sdk.domain.payment.definitions.refund_bank_method_specific_out... |
def from_dictionary(self, dictionary):
super(RefundOutput, self).from_dictionary(dictionary)
if 'amountPaid' in dictionary:
self.amount_paid = dictionary['amountPaid']
if 'bankRefundMethodSpecificOutput' in dictionary:
if not isinstance(dictionary['bankRefundMethodS... | value = RefundBankMethodSpecificOutput()
self.bank_refund_method_specific_output = value.from_dictionary(dictionary['bankRefundMethodSpecificOutput'])
if 'cardRefundMethodSpecificOutput' in dictionary:
if not isinstance(dictionary['cardRefundMethodSpecificOutput'], dict):
... |
moreati/pyscard | smartcard/Examples/scard-api/sample_control.py | Python | lgpl-2.1 | 4,389 | 0.000911 | #! /usr/bin/env python
"""
Sample for python PCSC wrapper module: send a Control Code to a card or
reader
__author__ = "Ludovic Rousseau"
Copyright 2007-2010 Ludovic Rousseau
Author: Ludovic Rousseau, mailto:[email protected]
This file is part of pyscard.
pyscard is free software; you can redistribute it and... | rror(
'Failed to list readers: ' + SCardGetErrorMessage(hresult))
print('PCSC Readers:', readers)
if len(readers) < 1:
raise error('No | smart card readers')
for zreader in readers:
print('Trying to Control reader:', zreader)
try:
hresult, hcard, dwActiveProtocol = SCardConnect(
hcontext, zreader, SCARD_SHARE_DIRECT, SCARD_PROTOCOL_T0)
if hresult != SCARD_S_SUCCESS:
... |
remybaranx/qtaste | TestSuites/TestSuite_QTaste/EngineSuite/QTASTE_DATA/QTASTE_DATA_02/TestScript.py | Python | gpl-3.0 | 1,538 | 0.015605 | # encoding= utf-8
# Copyright 2007-2009 QSpin - www.qspin.be
#
# This file is part of QTaste framework.
#
# QTaste is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the... | U Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with QTaste. If not, see <http://www.gnu.org/licenses/>.
##
# QTaste Data driven test: Check the TIMEOUT data handling.
# <p>
# This test case has the goal to verify that the TIM... | MEOUT [Integer] specify the TIMEOUT value to 5
##
from qtaste import *
def Step1():
"""
@step In CSV file, define TIMEOUT to 5
@expected None
"""
pass
def Step2():
"""
@step Call the verb neverReturn()
@expected Test is "Failed", reason: <i>Test execution timeout.</i><p>
Script call stac... |
arvinsahni/ml4 | flask/app/__init__.py | Python | mit | 73 | 0.013699 | from flask import Flask
app = Flask(__name__)
from app im | port vizarvin
| |
tiagocardosos/stoq | stoqlib/lib/test/test_stringutils.py | Python | gpl-2.0 | 2,658 | 0.004891 | # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
##
## Copyright (C) 2013 Async Open Source
##
## 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; either version 2
## of the License, or... | ), u'2')
self.assertEqual(max_value_for([u'9', u'10']), u'10')
| self.assertEqual(max_value_for([u'009', u'10']), u'010')
self.assertEqual(max_value_for([u'a09', u'999']), u'a09')
|
ElsaMJohnson/pythonprograms | galaxyperlin.py | Python | mit | 4,116 | 0.054665 | #!/home/elsa/Ureka/variants/common/bin/python
#Code to generate an image with perlin noise as background.
#Used in UO scientific computing course Spring 2016
#Perlin code and noise package is from Casey Duncan
#https://github.com/caseman/noise/examples/2dtexture.py
#Remaining code by Elsa M. Johnson
from noise impor... | = (s2n*s2n +np.sqrt(s2n**4.+4*ns | e*s2n*s2n))/2
fct=sig/fs
b=b/fct
#note to find location of b max: where(b==b.max())
totimg = b+noisearr
plt.figure()
plt.imshow(totimg,cmap=plt.cm.Greys_r)
return totimg
#Next routine calculates the mean and stand dev of random pixels
def imgstats(arr,sz=100):
# imm=np.mean(arr[x-sz/2:x+sz/2,y-sz/2:y+sz/2])
# ... |
saulshanabrook/django-dumper | test/models.py | Python | mit | 2,381 | 0.00042 | from django.db import models
from django.core.urlresolvers import reverse
from django.contrib.contenttypes.models import ContentType
try: # new import added in Django 1.7
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.fields import GenericRelation
except Impor... | pleModel, related_name='related_set')
def dependent_paths(self):
yield self.get_absolute_url()
def get_absolute_url(self):
return reverse('related-detail', kwargs={'slug': self.slug})
class GenericRelationModel(models.Model):
slug = models.CharField(max_length=200, default='slug')
c... | t_object = GenericForeignKey('content_type', 'object_id')
def dependent_paths(self):
yield self.content_object.get_absolute_url()
class RelatedToGenericModel(models.Model):
slug = models.CharField(max_length=200, default='slug')
generic_related = GenericRelation(GenericRelationModel)
def get... |
JimJiangX/BoneDragon | example/tests/db/base.py | Python | apache-2.0 | 912 | 0 | # Copyright (c) 2012 NTT DOCOMO, INC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
| # a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# ... | st base class."""
from example.common import context as example_context
from example.tests import base
class DbTestCase(base.TestCase):
def setUp(self):
super(DbTestCase, self).setUp()
self.context = example_context.get_admin_context()
|
tmcrosario/odoo-sicon | sicon/report/unrelated_documents.py | Python | agpl-3.0 | 2,065 | 0 | from odoo import api, fields, models, tools
class UnrelatedDocumentsReport(models.Model):
_name = "sicon.unrelated_documents.report"
_description = 'Documents not related yet to any concession'
_auto = False
dependence_id = fields.Many2one(comodel_name='tmc.dependence',
... | N doc.dependence_id = dep.id
LEFT JOIN tmc_document_type doc_type
ON doc.document_type_id = doc_type.id
| )
WHERE doc_topic.name = 'Concesiones Generales'
AND doc_type.abbreviation = 'DEC'
AND doc.id NOT IN (
SELECT
document_id
FROM sicon_event e WHERE document_id IS NOT NULL)
... |
weso/CWR-DataApi | tests/parser/dictionary/encoder/record/test_publisher_for_writer.py | Python | mit | 1,487 | 0 | # -*- coding: utf-8 -*-
import unittest
from cwr.parser.encoder.dictionary import PublisherForWriterDictionaryEncoder
from cwr.interested_party import PublisherForWriterRecord
"""
Publisher for Writer record to dictionary encoding tests.
The following cases are tested:
"""
__author__ = 'Bernardo Martínez Garrido'
... | st.TestCase):
def setUp(self):
self._encoder = PublisherForWriterDictionaryEncoder()
def test_encoded(self):
data = Pub | lisherForWriterRecord(record_type='SPU',
transaction_sequence_n=3,
record_sequence_n=15,
publisher_ip_n='111',
writer_ip_n='222',
... |
jmvasquez/redashtest | tests/models/test_api_keys.py | Python | bsd-2-clause | 634 | 0.001577 | from tests import BaseTestCase
from redash.models import ApiKey
class TestApiKeyGetByObject(BaseTestCase):
| def test_returns_none_if_not_exists(self):
dashboard | = self.factory.create_dashboard()
self.assertIsNone(ApiKey.get_by_object(dashboard))
def test_returns_only_active_key(self):
dashboard = self.factory.create_dashboard()
api_key = self.factory.create_api_key(object=dashboard, active=False)
self.assertIsNone(ApiKey.get_by_object(dashb... |
funbaker/astropy | astropy/io/votable/tests/exception_test.py | Python | bsd-3-clause | 1,250 | 0 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# LOCAL
from ....tests.helper import catch_warnings
from .. import converters
from .. import exceptions
from .. import tree
def test_reraise():
def fail():
raise RuntimeError("This failed")
try:
try:
fail()
... | else:
assert False
def test_parse_vowarning():
config = {'pedantic': True,
'filename': 'foo.xml'}
pos = (42, 64)
with catch_warnings(exceptions.W47) as w:
field = tree.Field(
None, name='c', datatype='char',
| config=config, pos=pos)
c = converters.get_converter(field, config=config, pos=pos)
parts = exceptions.parse_vowarning(str(w[0].message))
match = {
'number': 47,
'is_exception': False,
'nchar': 64,
'warning': 'W47',
'is_something': True,
'message': 'Mi... |
mk23/snmpy | lib/snmpy/module/disk_utilization.py | Python | mit | 1,260 | 0.001587 | import datetime
import logging
import os
import snmpy.module
import subprocess
LOG = logging.getLogger()
class disk_utilization(snmpy.module.TableModule):
def __init__(self, conf):
conf['table'] = [
{'dev': 'string'},
{'wait': 'integer'},
{'util': 'integer'},
... | : %s', ' '.join(comm))
for line in subprocess.check_output(comm, stderr=open(os.devnull, 'w')).split('\n'):
LOG.debug('line: | %s', line)
part = line.split()
if part and part[0] != 'Average:' and part[1].startswith('dev'):
disk[part[-9]] = [int(float(part[-3])), int(float(part[-1]))]
for line in open('/proc/diskstats'):
name = 'dev{}-{}'.format(*line.split()[0:2])
self.a... |
opps/opps-feedcrawler | setup.py | Python | mit | 1,484 | 0.000674 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from setuptools import setup, find_packages
from opps import feedcrawler
install_requires = ["opps"]
classifiers = ["Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
... | opps/opps-feedcrawler/tarball/master",
license=feedcrawler.__license__,
packages=find_packages(exclude=('doc', 'docs',)),
package_dir={'opps': 'opps'},
install_requires | =install_requires,
)
|
dukhlov/oslo.messaging | oslo_messaging/_drivers/protocols/amqp/drivertasks.py | Python | apache-2.0 | 4,126 | 0 | # Copyright 2014, Red Hat, Inc.
#
# Licensed under the Apache License, Version | 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://w | ww.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing perm... |
andnovar/networkx | networkx/algorithms/centrality/__init__.py | Python | bsd-3-clause | 382 | 0 | from .betweenness import *
from | .betweenness_subset import *
from .closeness import *
from .subgraph_alg import *
from .current_flow_closeness import *
from .current_flow_betweenness import *
from .current_flow_betweenness_subset import *
from .degree_alg import *
from .dispersion import *
from .eigenvector import *
from .h | armonic import *
from .katz import *
from .load import *
|
aptivate/econsensus | django/econsensus/publicweb/tests/settings_test.py | Python | gpl-3.0 | 9,245 | 0.002055 | from django.test.testcases import SimpleTestCase
from publicweb.extra_models import (NotificationSettings, OrganizationSettings,
NO_NOTIFICATIONS, FEEDBACK_MAJOR_CHANGES)
from django.contrib.auth.models import User, AnonymousUser
from organizations.models import Organization
from django.db.models.fields.related imp... | t_context_data()
self.assertIn('organization', context)
self.assertTrue(context['organization'])
@patch('publicweb.views.Organization.objects',
new=MagicMock(
spec=Organization.objects,
get=create_fake_organization,
filter=create_fake_or... | ngs_form(self):
user = UserFactory.build(id=1)
organization = create_fake_organization(id=2, slug='test')
request = RequestFactory().get('/')
request.user = user
context = UserNotificationSettings.as_view()(
request,
org_slug=orga... |
botherder/volatility | volatility/plugins/linux/ifconfig.py | Python | gpl-2.0 | 3,392 | 0.008255 | # Volatility
# Copyright (C) 2007-2013 Volatility Foundation
#
# This file is part of Vola | tility.
#
# Volatility is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Volatility is distributed in the hope that it will be useful... | ic License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Volatility. If not, see <http://www.gnu.org/licenses/>.
#
"""
@author: Andrew Case
@license: GNU General Public License 2.0
@contact: [email protected]
@organization:
"""
import volatility.... |
wearespindle/quickly.press | manage.py | Python | mit | 276 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE",
"qu | ickly.settings")
f | rom django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
tseaver/google-cloud-python | websecurityscanner/synth.py | Python | apache-2.0 | 1,969 | 0.00965 | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | this library."""
import synthtool as s
from synthtool import gcp
gapic = gcp.GAPICGenerator()
common = gcp.CommonTemplates()
# ----------------------------------------------------- | -----------------------
# Generate websecurityscanner GAPIC layer
# ----------------------------------------------------------------------------
versions = ["v1alpha", "v1beta"]
for version in versions:
library = gapic.py_library(
"websecurityscanner",
version,
config_path=f"/google/cloud/websecuritysc... |
willprice/arduino-sphere-project | scripts/example_direction_finder/temboo/Library/RightScale/ShowServer.py | Python | gpl-2.0 | 4,124 | 0.005092 | # -*- coding: utf-8 -*-
############ | ###################################################################
#
# ShowServer
# Display a comrephensive set of information about the querried server such as: state information, serv | er templates used, SSH key href, etc.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo 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/LICE... |
pmisik/buildbot | master/buildbot/test/unit/test_mq_simple.py | Python | gpl-2.0 | 2,849 | 0 | # This file is part of Buildbot. Buildbot 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, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | self.mq.startConsuming(callback, ('a', None))
yield self.mq.produce(('a', 'b'), 'foo')
d = self.mq.stopService()
self.assertFalse(d.called)
d1.callback(None)
self.as | sertTrue(d.called)
|
Elico-Corp/openerp-7.0 | stock_back2back_order_proc/stock.py | Python | agpl-3.0 | 26,042 | 0.008064 | # -*- encoding: utf-8 -*-
# © 2014 Elico Corp (https://www.elico-corp.com)
# Licence AGPL-3.0 or later(http://www.gnu.org/licenses/agpl.html)
from datetime import datetime
from dateutil.relativedelta import relativedelta
import time
from osv import fields, orm, osv
from tools.translate import _
import netsvc
import ... | new_picks, context=None, move_obj=False):
'''Recursively copy the chained move until a location in retention mode or the end.
@return id of the new first move.
'''
if not move_obj:
move_obj = self.pool.get('stock.move')
move_tbc = move_obj.browse(cr, | uid, move_id, context)
move_dest_id = False
if move_tbc.move_dest_id and move_tbc.location_dest_id.retention_mode == 'thru': # If there is move_dest_id in the chain and the current location is in thru mode, we need to make a copy of that, then use it as new move_dest_id.
move_dest_i... |
nsalomonis/AltAnalyze | import_scripts/peakAnnotation.py | Python | apache-2.0 | 4,178 | 0.0146 | import sys,string,os
sys.path.insert(1, os.path.join(sys.path[0], '..')) ### import parent dir dependencies
import export
import unique
import traceback
""" Intersecting Coordinate Files """
def cleanUpLine(line):
line = string.replace(line,'\n','')
lin | e = string.replace(line,'\c','')
data = string.replace( | line,'\r','')
data = string.replace(data,'"','')
return data
def eCLIPimport(folder):
eCLIP_dataset_peaks={}
annotations=[]
files = unique.read_directory(folder)
for file in files:
if '.bed' in file:
peaks={}
dataset = file[:-4]
print dataset
... |
Kronuz/sublime-rst-completion | indent_list_item.py | Python | bsd-3-clause | 3,382 | 0.003253 | import re
import sublime
import sublime_plugin
class IndentListItemCommand(sublime_plugin.TextCommand):
bullet_pattern = r'([-+*]|([(]?(\d+|#|[a-y]|[A-Y]|[MDCLXVImdclxvi]+))([).]))'
bullet_pattern_re = re.compile(bullet_pattern)
line_pattern_re = re.compile(r'^\s*' + bullet_pattern)
spaces_re = re.co... | es = self.spaces_re.match(new_line).group(0)
if prev_spaces == spaces:
line = sublime.Region(line.begin() - 1, line.end())
endings = ['.', ')']
# Transform the bullet to the next/previous bu | llet type
if self.view.settings().get('list_indent_auto_switch_bullet', True):
bullets = self.view.settings().get('list_indent_bullets', ['*', '-', '+'])
def change_bullet(m):
bullet = m.group(1)
try:
return bul... |
arthurSena/processors | tests/fixtures/api/fda_applications.py | Python | mit | 543 | 0.001842 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import pytest
@pytest.fixture
def fda_application(conn, organization):
fda_application = {
'id': 'ANDA018659',
'organisation... | ctive_ingredients': 'ALLOPURINOL',
}
fda_application_id = conn['database']['fda_applications'].insert(fda_application) |
return fda_application_id
|
alexjarosch/sia-fluxlim | sia_fluxlim/__init__.py | Python | gpl-3.0 | 57 | 0 | from sia_fluxlim | .oggm_flowline import MUSCLSuperBeeMod | el
|
turdusmerula/kipartman | kipartman/dialogs/panel_modules.py | Python | gpl-3.0 | 13,205 | 0.064142 | # -*- coding: utf-8 -*-
###########################################################################
## Python code generated with wxFormBuilder (version Dec 22 2017)
## http://www.wxformbuilder.org/
##
## PLEASE DO *NOT* EDIT THIS FILE!
###########################################################################
impo... | ########################################################################
## Class PanelModules
###########################################################################
class PanelModules ( wx.Panel ):
def __init__( self, parent ):
wx.Panel.__init__ ( self, parent, id = wx.ID_ANY, pos = wx.DefaultPosition, size... |
bSizer1 = wx.BoxSizer( wx.VERTICAL )
self.m_splitter2 = wx.SplitterWindow( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.SP_3D|wx.SP_LIVE_UPDATE )
self.m_splitter2.Bind( wx.EVT_IDLE, self.m_splitter2OnIdle )
self.m_splitter2.SetMinimumPaneSize( 300 )
self.panel_path = wx.Panel( self.m_splitte... |
emmdim/guifiAnalyzer | traffic/tests/testUrl.py | Python | gpl-3.0 | 295 | 0.016949 |
import urllib2
url = "http://ifolderlinks.ru/404"
req = urllib2.Req | uest(url)
#try:
response = urllib2.urlopen(req,timeout=3)
#except urllib2.HTTPError as e:
# print 'The server couldn\'t fulfill the request.'
# print 'Error code: ', e.code
print response | .info()
#print response.read()
|
LibreTime/libretime | playout/setup.py | Python | agpl-3.0 | 1,522 | 0.000657 | from os import chdir
from pathlib import Path
from setuptools import setup
# Change directory since setuptools uses relative paths
here = Path(__file__).parent.resolve()
chdir(here)
setup(
name="libretime-playout",
version="1.0",
description="LibreTime Playout",
author="LibreTime Contributors",
u... | e_playout",
"libretime_playout.notify",
"libretime_liquidsoap",
],
package_data={"": ["**/*.liq", "*.cfg", "*.types"]},
entry_points={
"console_scripts": [
"libretime- | playout=libretime_playout.main:cli",
"libretime-liquidsoap=libretime_liquidsoap.main:cli",
"libretime-playout-notify=libretime_playout.notify.main:cli",
]
},
python_requires=">=3.6",
install_requires=[
"amqplib",
"configobj",
"defusedxml",
"kom... |
bryndivey/ohmanizer | electronics/migrations/0011_auto_20141120_2136.py | Python | apache-2.0 | 2,732 | 0.001098 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
class Migration(migrations.Migration):
dependencies = [
('electronics', '0010_auto_20141120_0704'),
]
operations = [
migrations.CreateModel(
name='Order',... | serialize=False, auto_created=True, primary_key=True)),
('quantity', models.IntegerField(default=1)),
('price', models.IntegerField(blank=Tr | ue)),
('component', models.ForeignKey(to='electronics.Component')),
('order', models.ForeignKey(to='electronics.Order')),
],
options={
},
bases=(models.Model,),
),
migrations.CreateModel(
name='WishItem',
... |
partofthething/home-assistant | homeassistant/components/vera/climate.py | Python | apache-2.0 | 4,982 | 0.000401 | """Support for Vera thermostats."""
from typing import Any, Callable, List, Optional
import pyvera as veraApi
from homeassistant.components.climate import (
| DOMAIN as PLATFORM_DOMAIN,
ENTITY_ID_FORMAT,
ClimateEntity,
)
from homeassistant.components.climate.const import (
FAN_AUTO,
FAN_ON,
HVAC_MODE_COOL,
HVAC_MODE_HEAT,
HVAC_MODE_HEAT_COOL,
HVAC_MODE_OFF,
SUPPORT_FAN_MODE,
SUPPORT_TARGET_TEMPERATURE,
)
from homeassistant.config_entri... | rom homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import Entity
from homeassistant.util import convert
from . import VeraDevice
from .common import ControllerData, get_controller_data
FAN_OPERATION_LIST = [FAN_... |
mozilla/mozilla-ignite | apps/challenges/migrations/0019_add_judge_group.py | Python | bsd-3-clause | 13,599 | 0.007501 | # encoding: 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):
"""Give members of the judge group permission to judge all submissions.
Create the group and the permission if... | , [], {}),
'end_date': ('django.db.models.fields.DateTimeField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.files.ImageF | ield', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'moderate': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['projects.Project']"}),
'slug': ('django.db.models.fields.Slug... |
jmcomber/FlaskDB | flaskr/__init__.py | Python | mit | 4,142 | 0.00169 | #!/usr/bin/python3
# -*- coding: latin-1 -*-
import os
import sys
import psycopg2
import json
from bson import json_util
from pymongo import MongoClient
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash
def create_app():
app = Flask(__name__)
return app
app... | except Exception as e:
print(e)
return render_template('file.html', results=pairs)
@app.route("/mongo | ", methods=['GET','POST'])
def mongo():
query = request.args.get("query")
print(query)
results = eval('mongodb.'+query)
results = json_util.dumps(results, sort_keys=True, indent=4)
if "find" in query:
return render_template('mongo.html', results=results)
else:
return "ok"
@app.... |
kinow-io/kinow-python-sdk | kinow_client/apis/directors_api.py | Python | apache-2.0 | 71,299 | 0.002216 | # coding: utf-8
"""
Server API
Reference for Server API (REST/Json)
OpenAPI spec version: 2.0.6
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import sys
import os
import re
# python 2 and python 3 compatibility library
from six im... | llback_function(response):
>>> pprint(response)
>>>
>>> thread = api.attach_director_to_product_with_http_info(product_id, director_id, callback=callback_function)
:param callback function: The callback | function
for asynchronous request. (optional)
:param int product_id: Product ID to fetch (required)
:param int director_id: Director ID to attach (required)
:return: None
If the method is called asynchronously,
returns the request thread.
""... |
Forage/Gramps | gramps/plugins/drawreport/descendtree.py | Python | gpl-2.0 | 66,269 | 0.007092 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2000-2007 Donald N. Allingham
# Copyright (C) 2007-2008 Brian G. Matherly
# Copyright (C) 2010 Jakim Friant
# Copyright (C) 2009-2010 Craig J. Anderson
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the... | ---------------------------------
_BORN = _('short for born|b.')
_DIED = _('short for died|d.')
_MARR = _('short for married|m.')
_RPT_NAME = 'descend_chart'
from gramps.plugins.lib.libtreebase import *
#------------------------------------------------------------------------
#
# Box classes
#
#---------------------... | needed
"""
def __init__(self, boxstr):
BoxBase.__init__(self)
self.boxstr = boxstr
self.next = None
self.father = None
def calc_text(self, database, person, family):
""" A single place to calculate box text """
gui = GuiConnect()
calc = gui.calc_l... |
dabear/torrentstatus | torrentstatus/plugins/builtin.torrent.onstart.settorrentlabels.py | Python | lgpl-3.0 | 3,296 | 0.003337 | from torrentstatus.plugin import iTorrentAction
from torrentstatus.utorrent.connection import Connection
from contextlib import contextmanager
from torrentstatus.bearlang import BearLang
from torrentstatus.settings import config, labels_config
from torrentstatus.utils import intTryParse
@contextmanager
def utorrent... | "defined in configuration file. Error:{0}".format(err))
else:
print("Connection to utorrent web ui ok")
print ("Got torrent '{0}' with hash {1} and tracker {2}. \n Setting new_labels: {3}"
.format(utorrentargs.torrentname, utorrentargs... | |
gslab-econ/gslab_python | gslab_scons/log_paths_dict.py | Python | mit | 5,515 | 0.009066 | import os
import sys
import scandir
import pymmh3 as mmh3
import misc
def log_paths_dict(d, record_key = 'input', nest_depth = 1, sep = ':',
cl_args_list = sys.argv):
'''
Records contents of dictionary d at record_key on nest_depth.
Assumes unnested elements of d follow human-name: file... | include_checksum, file_limit):
'''
Create a header for the file characteristics to grab.
Adjusts file_limit for existence of header.
'''
files_info = [['file path', 'file size in bytes']]
if include_checksum:
files_info[0].append('MurmurHash3')
f | ile_limit += 1
return files_info, file_limit
def do_more_files(files_info, file_limit):
'''
True if files_info has fewer then file_limit elements.
'''
return bool(len(files_info) < file_limit)
def scan_dir_wrapper(dirs, files_info, inpath, include_checksum, file_limit,
this_f... |
EugenePig/gcloud-python | gcloud/bigquery/test_job.py | Python | apache-2.0 | 50,613 | 0.00002 | # 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... | self.USER_EMAIL,
}
if st | arted or ended:
resource['statistics']['startTime'] = self.WHEN_TS * 1000
if ended:
resource['statistics']['endTime'] = (self.WHEN_TS + 1000) * 1000
return resource
def _verifyInitialReadonlyProperties(self, job):
# root elements of resource
self.assertEqua... |
kurainooni/nw.js | test/remoting/package/test.py | Python | mit | 2,877 | 0.004519 | import | time
import os
import shutil
import zipfile
import platform
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
t | estdir = os.path.dirname(os.path.abspath(__file__))
nwdist = os.path.join(os.path.dirname(os.environ['CHROMEDRIVER']), 'nwdist')
appdir = os.path.join(testdir, 'app')
pkg1 = os.path.join(testdir, 'pkg1')
pkg2 = os.path.join(testdir, 'pkg2')
pkg3 = os.path.join(testdir, 'pkg3')
try:
shutil.rmtree(pkg1)
shutil... |
Nickito12/stepmania-server | smserver/chat_commands/general.py | Python | mit | 14,861 | 0.007604 | #!/usr/bin/env python3
# -*- coding: utf8 -*-
from smserver import models
from smserver import smutils
from smserver.chathelper import with_color
from smserver.chatplugin import ChatPlugin
from smserver.models import ranked_chart
from smserver.models.ranked_chart import Diffs
class ChatHelp(ChatPlugin):
command... | .filter_by(name=message).first()
if not newfriend:
serv.send_message("Unknown user %s" % with_color(message), to="me")
return
if newfriend.name == user.name:
serv.send_message("Cant befriend yourself", to="me")
return
fr... | ndship.user2_id == newfriend.id)) | \
(models.Friendship.user2_id == user.id) & (models.Friendship.user1_id == newfriend.id))
if not friendships.first():
serv.session.add(models.Friendship(user1_id = user.id, user2_id = newfriend.id, state = 0))
serv.send_mes... |
keenondrums/sovrin-node | sovrin_node/test/upgrade/test_pool_upgrade_no_loop_reinstall.py | Python | apache-2.0 | 1,232 | 0.000812 | from copy import deepcopy
import pytest
from sovrin_node.test import waits
from stp_core.loop.eventually import eventually
from plenum.common.constants import VERSION
from sovrin_common.constants import REINSTALL
from sovrin_node.test.upgrade.helper import bumpedVersion, checkUpgradeScheduled, \
ensureUpgradeSen... | de_log import UpgradeLog
import sovrin_node
def test_upgrade_does_not_get_into_loop_if_reinstall(
looper,
tconf,
nodeSet,
validUpgrade,
trustee | ,
trusteeWallet,
monkeypatch):
new_version = bumpedVersion()
upgr1 = deepcopy(validUpgrade)
upgr1[VERSION] = new_version
upgr1[REINSTALL] = True
# An upgrade scheduled, it should pass
ensureUpgradeSent(looper, trustee, trusteeWallet, upgr1)
looper.run(
eventually(
... |
rdkit/rdkit-orig | rdkit/Chem/SATIS.py | Python | bsd-3-clause | 3,432 | 0.015734 | # $Id$
#
# Copyright (C) 2001-2006 greg Landrum and Rational Discovery LLC
#
# @@ All Rights Reserved @@
# This file is part of the RDKit.
# The contents are covered by the terms of the BSD license
# which is included in the file license.txt, found at the root
# of the RDKit source tree.
#
""" Functionality for ... | es[j][1]
found = 1
break
if found:
break
codes[i] = ''.join(['%02d'%(x) for x in code])
return codes
if __name__ == '__main__':
smis = ['CC(=O)NC','CP(F)(Cl)(Br)(O)',
'O=CC(=O)C','C(=O)OCC(=O)O','C(=O)[O-]']
for smi in smis | :
print smi
m = Chem.MolFromSmiles(smi)
codes = SATISTypes(m)
print codes
|
alumarcu/dream-framework | dream/core/models/team.py | Python | gpl-3.0 | 598 | 0 | from django.db.models import Model, CharField, DateTimeField, ForeignKey
from django.utils.translation im | port ugettext_lazy as _
from dream.core.definitions import GENDER_CHOICES, GENDER_UNDEFINED
from . import Club
class Team(Model):
club = ForeignKey(Club)
name = CharField(_('team name'), max_length=60)
gender = CharField(
_('gender'),
max_length=1,
choices=GENDER_CHOICES,
... | ified = DateTimeField(auto_now=True)
def __str__(self):
return self.name
|
lightd22/smartDraft | src/models/base_model.py | Python | apache-2.0 | 599 | 0.006678 | import tensorflow as tf
class Ba | seModel():
def __init__(self, name, path):
self._name = name
self._path_to_model = path
self._graph = tf.Graph()
self.sess = tf.Session(graph=self._graph)
def _ | _del__(self):
try:
self.sess.close()
del self.sess
finally:
print("Model closed..")
def build_model(self):
raise NotImplementedError
def init_saver(self):
raise NotImplementedError
def save(self):
raise NotImplementedError
def ... |
dsparrow27/zoocore | zoo/libs/utils/timeutils.py | Python | gpl-3.0 | 1,936 | 0.001033 | from datetime import datetime, timedelta
def formatFrameToTime(start, current, fr | ameRate):
total = current - start
seconds = float(total) / float(frameRate)
minutes = int(seconds / 60.0)
seconds -= minutes * 60
return ":".join(["00", str(minutes).zfill(2),
str(round(seconds, 1)).zfill(2),
str(int(current)).zfill(2)])
def formatModifie... | m dateTime: The datetime instance to be formatted
:type dateTime: :class:`datatime`
:returns A string representing the datetime in a nice format
:rtype: str
.. code-block:: python
from datetime import datetime
now = datetime.now()
format_modified_date_time_str(now)
# r... |
alphagov/stagecraft | stagecraft/apps/dashboards/tests/factories/factories.py | Python | mit | 1,931 | 0 | import factory
from ...models import Dashboard, Link, ModuleType, Module
from ....organisati | on.tests.factories import NodeFactory, NodeTypeFactory
class DashboardFactory(factory.DjangoModelFactory):
class Meta:
model = Dashboard
status = 'published'
title = "title"
slug = factory.S | equence(lambda n: 'slug%s' % n)
class LinkFactory(factory.DjangoModelFactory):
class Meta:
model = Link
url = factory.Sequence(lambda n: 'https://www.gov.uk/link-%s' % n)
title = 'Link title'
link_type = 'transaction'
dashboard = factory.SubFactory(DashboardFactory)
class ModuleTypeFac... |
jmesteve/saas3 | openerp/addons/xml_export/__init__.py | Python | agpl-3.0 | 64 | 0 | #
# X | ML Export, (C) Agaplan 2011
#
import models
| import wizard
|
m48/sgl | docs/source/conf.py | Python | gpl-3.0 | 11,475 | 0.006536 | # -*- coding: utf-8 -*-
#
# sgl documentation build configuration file, created by
# sphinx-quickstart on Sat Mar 12 15:33:34 2016.
#
# 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.
#
# All c... | here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_... | hey can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.napoleon',
'sphinx.ext.todo',
'sphinx.ext.coverage',
# 'sphinx.ext.viewcode',
]
# Misc config
napoleon_numpy_docstring = False
autodoc_member_order = "bysource"
... |
Edanprof/ScoreM | script_execute.py | Python | gpl-3.0 | 768 | 0.002604 | from s | elenium import webdriver
import os
driver = webdriver.PhantomJS()
driver.get("http://info.nowgoal.com/en/team/summar | y.aspx?TeamID=59")
driver.execute_script('leftSide(selectTeamID, arrTeam);\
if (coach.length>0){ mainTitle(teamDetail, coach[0][2 + lang], coach[0][0]);\
} else { mainTitle(teamDetail,"", 0);\
}\
var mainDiv=document.getElementById("div_Table2");\
... |
rwl/PyCIM | CIM15/IEC61970/WiresPhaseModel/SwitchPhase.py | Python | mit | 3,967 | 0.003025 | # Copyright (C) 2010-2011 Richard Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish... | RS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN | THE SOFTWARE.
from CIM15.IEC61970.Core.PowerSystemResource import PowerSystemResource
class SwitchPhase(PowerSystemResource):
"""Single phase of a multi-phase switch when its attributes might be different per phase.Single phase of a multi-phase switch when its attributes might be different per phase.
"""
... |
Mikescher/Project-Euler_Befunge | compiled/Python3/Euler_Problem-091.py | Python | mit | 1,054 | 0.050285 | #!/usr/bin/env python3
# transpiled with BefunCompile v1.3.0 (c) 2017
def td(a,b):
return ((0)if(b==0)else(a//b))
def tm(a,b):
return ((0)if(b==0)else(a%b))
x0=50
x1=0
x2=50
x3=88
x4=88
def _0():
return 1
def _1():
global x3
global x0
global x4
x3=x0
x4=x3+1
return 2
def _2():
g... | t1
t0=x3-1
t1=6
x3=x3-1
return (6)if((t0)!=0)else(4)
def _4():
global t0
global x2
global t1
t0=x2-1
t1=x2-1
x2=t1
return (1)if((t0)!=0)else(5)
def _5():
global x1
global x0
print(x1+(3*x0*x0),end=" ",flush=True)
return 8
def _6():
global x4
global x... | 1+(((0)if(tm((x3-x4)*x3,x2)!=0)else(1))*2)
x4=x4+1
return 2
m=[_0,_1,_2,_3,_4,_5,_6,_7]
c=0
while c<8:
c=m[c]()
|
ivotkv/neolixir | neolixir/dummy.py | Python | mit | 2,382 | 0.007976 | # -*- coding: utf-8 -*-
#
# The MIT License (MIT)
#
# Copyright (c) 2013 Ivo Tzvetkov
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the ri... | def __repr__(self):
return "<{0} (0x{1:x}): ({2}) {3}>".format(self.__class__.__name__, id(self),
self.id, self.properties)
class DummyNode(DummyEntity):
__slots__ = []
class DummyRelationship(DummyEntit | y):
__slots__ = ['start_node', 'type', 'end_node']
def __init__(self, id, start_node, type, end_node, properties=None):
self.id = id
self.start_node = start_node
self.type = type
self.end_node = end_node
self.properties = properties or {}
def __repr__(self):
... |
jmbergmann/yogi | yogi-python/yogi/private/tcp.py | Python | gpl-3.0 | 10,200 | 0.002647 | from .connections import *
import threading
import weakref
class TcpConnection(NonLocalConnection):
def __init__(self, handle: c_void_p):
NonLocalConnection.__init__(self, handle)
yogi.YOGI_CreateTcpClient.restype = api_result_handler
yogi.YOGI_CreateTcpClient.argtypes = [POINTER(c_void_p), c_void_p, c_... | def cancel_connect(self) -> None:
yogi.YOGI_CancelTcpConnect(self._hand | le)
yogi.YOGI_CreateTcpServer.restype = api_result_handler
yogi.YOGI_CreateTcpServer.argtypes = [POINTER(c_void_p), c_void_p, c_char_p, c_uint, c_void_p, c_uint]
yogi.YOGI_AsyncTcpAccept.restype = api_result_handler
yogi.YOGI_AsyncTcpAccept.argtypes = [c_void_p, c_int, CFUNCTYPE(None, c_int, c_void_p, c_void_p), c_v... |
RRMoelker/codecook-bash | config.py | Python | mit | 277 | 0.018051 | # -*- coding: utf-8 -*
"""
Config file path resolution
""" |
import os
from xdg import BaseDirectory
def get_config_file():
dir_full_path = BaseDirectory.save_data_path('codecook-bash.config')
file_full_path = os | .path.join(dir_full_path, 'user.config')
return file_full_path |
DailyActie/Surrogate-Model | 01-codes/scikit-learn-master/examples/applications/plot_tomography_l1_reconstruction.py | Python | mit | 5,461 | 0.001282 | """
======================================================================
Compressive sensing: tomography reconstruction with L1 prior (Lasso)
======================================================================
This example shows the reconstruction of an image from a set of parallel
projections, acquired along dif... | lidation
# with LassoCV
rgr_lasso = Lasso(alpha=0.001)
rgr_lasso.fit(proj_operator, proj.ravel( | ))
rec_l1 = rgr_lasso.coef_.reshape(l, l)
plt.figure(figsize=(8, 3.3))
plt.subplot(131)
plt.imshow(data, cmap=plt.cm.gray, interpolation='nearest')
plt.axis('off')
plt.title('original image')
plt.subplot(132)
plt.imshow(rec_l2, cmap=plt.cm.gray, interpolation='nearest')
plt.title('L2 penalization')
plt.axis('off')
plt... |
soerendip42/rdkit | rdkit/VLib/NodeLib/SmartsMolFilter.py | Python | bsd-3-clause | 2,727 | 0.017968 | # $Id$
#
# Copyright (C) 2003 Rational Discovery LLC
# All Rights Reserved
#
from rdkit import RDConfig
import sys,os,types
from rdkit import Chem
from rdkit.VLib.Filter import FilterNode
class SmartsFilter(FilterNode):
""" filter out molecules matching one or more SMARTS patterns
There is a count associate... | >>> ms = [x for x in suppl]
>>> len(ms)
8
We can pass in | SMARTS strings:
>>> smas = ['C=O','CN']
>>> counts = [1,2]
>>> filt = SmartsFilter(patterns=smas,counts=counts)
>>> filt.AddParent(suppl)
>>> ms = [x for x in filt]
>>> len(ms)
5
Alternatively, we can pass in molecule objects:
>>> mols =[Chem.MolFromSmarts(x) for x in smas]
>>>... |
michaelconnor00/gbdxtools | tests/unit/test_catalog.py | Python | mit | 9,207 | 0.006951 | '''
Authors: Donnie Marino, Kostas Stamatiou
Contact: [email protected]
Unit tests for the gbdxtools.Catalog class
'''
from gbdxtools import Interface
from gbdxtools.catalog import Catalog
from auth_mock import get_mock_gbdx_session
import vcr
import unittest
"""
How to use the mock_gbdx_session and vcr to cr... | ndDate='2008-01-03T00:00:00.000Z')
assert len(results) == 759
@vcr.use_cassette('tests/unit/cassettes/test_catalog_search_filters1.yaml',filter_headers=['authorization'])
def test_catalog_search_filters1(self):
c = Catalog(self.gbdx)
filters = [
"(sensorPlat... | 0",
"offNadirAngle < 10"
]
results = c.search(startDate='2008-01-01T00:00:00.000Z',
endDate='2012-01-03T00:00:00.000Z',
filters=filters,
searchAreaWkt="POLYGON ((30.1 9.9, 30.1 10.1, 29.... |
kret0s/gnuhealth-live | tryton/server/trytond-3.8.3/trytond/modules/health_icd10/tests/__init__.py | Python | gpl-3.0 | 36 | 0 | fr | om test_health_icd10 import suite
| |
tiancj/emesene | emesene/gui/qt4ui/widgets/StatusButton.py | Python | gpl-3.0 | 2,828 | 0.001414 | # -*- 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.
#
#... | tus.OFFLINE
self.set_status(self | .status)
self.menu.triggered.connect(self.statusactionchange)
self.setMenu(self.menu)
# show status menu on button click
self.clicked.connect(self.showMenu)
def statusactionchange(self, action):
status = self.invertStatus[str(action.text())]
self.set_status(status)
... |
tgerdes/toolbot | toolbot/adapter/irc.py | Python | mit | 3,433 | 0 | import irc3
from toolbot.adapter import Adapter
from toolbot.message import (
TextMessage,
EnterMessage,
LeaveMessage,
TopicMessage)
@irc3.plugin
class Irc3ToToolbot:
requires = ['irc3.plugins.core', ]
def __init__(self, bot):
self.bot = bot
@irc3.event(irc3.rfc.PRIVMSG)
def... | artswith(":"):
channel = channel[1:]
user = bot.brain.userForId(mask, name=mask.n | ick, room=channel)
adapter.receive(EnterMessage(user))
@irc3.event(irc3.rfc.PART)
def part(self, mask, channel, data):
adapter = self.bot.config['adapter']
bot = adapter.bot
if channel.startswith(":"):
channel = channel[1:]
user = bot.brain.userForId(mask, na... |
incuna/django-user-management | user_management/api/avatar/serializers.py | Python | bsd-2-clause | 2,513 | 0.000796 | from django.contrib.auth import get_user_model
from django.db import models
from imagekit.cachefiles import ImageCacheFile
from imagekit.registry import generator_registry
from imagekit.templatetags.imagekit import DEFAULT_THUMBNAIL_GENERATOR
from rest_framework import serializers
User = get_user_model()
class Thumb... | ]
If no options are specified the users avatar is returned.
To crop to 100x100 anchored to the top right:
?width=100&height=100&crop=1&anchor=tr
"""
def __init__(self, *args, **kwargs):
self.generator_id = kwargs.pop('generator_id', DEFAULT_THUMBNA | IL_GENERATOR)
super(ThumbnailField, self).__init__(*args, **kwargs)
def get_generator_kwargs(self, query_params):
width = int(query_params.get('width', 0)) or None
height = int(query_params.get('height', 0)) or None
return {
'width': width,
'height': height,
... |
bwhite/picarus | server/build_site.py | Python | apache-2.0 | 2,094 | 0.00382 | #!/usr/bin/env python
import glob
import subprocess
import argparse
def render_app():
template_names = 'data_prefixes data_projects data_usage models_list models_create models_single models_slice process_thumbnail process_delete process_exif process_modify process_copy workflow_classifier jobs_list jobs_crawlFlic... | _true',
help="Don't minify the source")
args = parser.parse_args()
render_app()
preinclude = ['jquery.min.js', 'bootstrap.min.js', 'undersc | ore-min.js', 'underscore.string.min.js', 'backbone-min.js', 'base64.js', 'jquery.cookie.min.js']
preinclude = ['js/' + x for x in preinclude]
postinclude = ['picarus_api.js', 'app.js']
postinclude = ['js/' + x for x in postinclude]
a = preinclude + list(set(glob.glob('js/*.js')) - set(preinclude) - set(... |
pymedusa/Medusa | ext/github/Hook.py | Python | gpl-3.0 | 9,634 | 0.004463 | # -*- coding: utf-8 -*-
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <[email protected]> #
# Copyright 2012 Zearin <[email protected]> ... | an Liuyang <[email protected]> #
# Copyright 2018 Wan Liuyang <[email protected]> #
# Copyright 2018 sfdye <[email protected]> #
# #
# This file is... | #
# http://pygithub.readthedocs.io/ #
# #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.