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 |
|---|---|---|---|---|---|---|---|---|
mrpau/kolibri | kolibri/core/discovery/utils/network/search.py | Python | mit | 6,523 | 0.00138 | import json
import logging
import socket
from contextlib import closing
from django.core.exceptions import ValidationError
from django.db import connection
from zeroconf import get_all_addresses
from zeroconf import NonUniqueNameException
from zeroconf import ServiceInfo
from zeroconf import USE_IP_OF_OUTGOING_INTERFA... | fListener()
ZEROCONF_STATE["zeroconf"].add_service_listener(
SERVICE_TYPE, ZEROCONF_STATE["listener"]
)
def get_peer_in | stances():
try:
return ZEROCONF_STATE["listener"].instances.values()
except AttributeError:
return []
|
klahnakoski/jx-sqlite | vendor/jx_python/expressions/between_op.py | Python | mpl-2.0 | 438 | 0 | # encoding: utf-8
#
#
# This Source Code Form is subject to the terms of the Mozilla Pu | blic
# 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/.
#
# Contact: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __future__ import absolute_import, division, unicode_literals
from jx_base.expressions import | BetweenOp as BetweenOp_
class BetweenOp(BetweenOp_):
pass
|
smithk86/flask-sse | flask_sse/server_sent_event.py | Python | mit | 1,387 | 0.000721 | import json
from copy import copy
from collections import OrderedDict
# SSE "protocol" is described here: http://mzl.la/UPFyxY
class ServerSentEvent(object):
def __init__(self, data=None, event=None, retry=None, id=None):
if data is None and event is None:
raise ValueError('data and event can... | __(self):
if self.retry:
yield 'retry', self.retry
yield 'data', self.data
if sel | f.event:
yield 'event', self.event
if self.id:
yield 'id', self.id
def __str__(self):
return '{}\n\n'.format('\n'.join(
['{}: {}'.format(k, v) for k, v in self.format().items()]
))
def __repr__(self):
return '<ServerSentEvent event="{}">'.for... |
RainbowAcademy/ScriptingLectures | 2015/ContourLine/DisplaceFromImage.py | Python | gpl-2.0 | 4,181 | 0.028223 | __author__ = 'a.paoletti'
import maya.cmds as cmd
import os
import sys
sys.path.append("C://Users//a.paoletti//Desktop//MY//CORSOSCRIPTING - DISPLACE_GEOTIFF//gdalwin32-1.6//bin")
import colorsys
def getTexture():
"""
:rtype : String
:return : Nome della texture applicata al canale color del lambert... | temp\\AHN2_060')
# register all of the drivers
gdal.AllRegister()
# open the image
ds = gdal.Open(filepath, GA_ReadOnly)
if ds is None:
print 'Could not open image'
sys.exit(1)
# get image size
rows = ds.RasterYSize
cols = ds.RasterXSize
bands = ds.RasterCount
# ge | t georeference info
transform = ds.GetGeoTransform()
xOrigin = transform[0]
yOrigin = transform[3]
pixelWidth = transform[1]
pixelHeight = transform[5]
# loop through the coordinates
for xValue, yValue in zip(xValues, yValues):
# get x,y
x = xValue
y = yValue
# compute pixel offset
xOff... |
eldruz/tournament_registration | tournament_registration/capitalism/models.py | Python | bsd-3-clause | 3,092 | 0.000323 | from satchless.item import InsufficientStock, StockedItem
from datetime import date
from django.utils.text import slugify
from django.core.urlresolvers import reverse
from django.utils import timezone
from django.db import models
from django_prices.models import PriceField
from django.core.exceptions import Validation... | product = TournamentProduct.objects.get(pk=product_id)
for attribute, value in kwargs.items():
assert attribute in additional_attributes
setatt | r(tourney_product, attribute, value)
tourney_product.save()
return tourney_product
def delete_tournament_product(self, product_id):
tourney_product = TournamentProduct.objects.get(pk=product_id)
tourney_product.delete()
class TournamentProduct(Product):
tournament = models.One... |
openstack/vitrage-dashboard | vitrage_dashboard/alarms/panel.py | Python | apache-2.0 | 733 | 0 | # Copyright 2015 IBM Corp.
#
# 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, sof... |
# limitations under the License.
from django.utils.translation import ugettext_lazy as _
import horizon
class AlarmsVitrage(horizon.Panel):
name = | _("Alarms")
slug = "vitragealarms"
|
NERC-CEH/jules-jasmin | majic/joj/lib/wms_capability_cache.py | Python | gpl-2.0 | 2,164 | 0.00878 | """
Manages a Beaker cache of WMS capabilities documents.
@author: rwilkinson
"""
import logging
from beaker.cache import CacheManager
from beaker.util import parse_cache_config_options
from joj.lib.wmc_util import GetWebMapCapabilities
log = logging.getLogger(__name__)
class WmsCapabilityCache():
""" Manages a... | config.get('wmscapabilitycache.type', 'file'),
'cache.data_dir': config.get('wmscapabilitycache.data_dir', '/tmp/ecomaps/wmscapabilitycache/data'),
'cache.lock_dir': config.get('wmscapabilitycache.lock_dir', None)
}
cacheMgr = CacheManager(**parse_cache_config... | aching %s" % ("enabled" if self.enableCache else "disabled"))
def getWmsCapabilities(self, wmsurl, forceRefresh):
"""Gets the WMS capabilities for an endpoint URL from the cache or WMS server if not found in the cache.
"""
if self.enableCache:
def __doGet():
"""M... |
cragwen/hello-world | py/interpy/4_MapFilterReduce.py | Python | unlicense | 542 | 0.012915 | items = [1, 2, 3, 4, 5]
squared = []
for i in items:
| squared.append(i**2)
print(squared)
squared = []
squared = list(map(lambda x: x**2, items))
print(squared)
def multiply(x):
return (x*x)
def add(x):
return (x+x)
funcs = [multiply, add]
for i in range(5):
value = map(lambda x:x(i), funcs)
print(list(value))
number_list = range(-5, 5)
less_than_zero ... | o))
from functools import reduce
product = reduce( (lambda x, y: x * y), [1, 2, 3, 4])
print(product) |
traverseda/python-client | test/test_concurrency.py | Python | apache-2.0 | 341 | 0 | from nose.tools import with_setup, eq_ as eq
from common import vim, cleanup
from threading import Timer
@with_setup(setup=cleanup)
def test_interrupt_from_another_thread():
session = vim.session
| timer = Timer(0.5, lambda: session.threadsafe_call(lambda: session.stop()))
timer.start()
eq(vim.session.nex | t_message(), None)
|
nwjs/chromium.src | mojo/public/tools/mojom/mojom_parser.py | Python | bsd-3-clause | 19,670 | 0.00788 | #!/usr/bin/env python
# Copyright 2020 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Parses mojom IDL files.
This script parses one or more input mojom files and produces corresponding
module files fully describing th... | ing from module paths to absolute file paths for all
inputs given to this execution of the script.
asts: A map from each input mojom's absolute path to its parsed AST.
dependencies: A mapping of which input mojoms depend on each other, indexed
by absolute file path.
loaded_modules: A mapping... | d so far, including non-input
modules that were pulled in as transitive dependencies of the inputs.
module_metadata: Metadata to be attached to every module loaded by this
helper.
Returns:
None
On return, loaded_modules will be populated with the loaded input mojom's
Module as well a... |
pu239ppy/authentic2 | authentic2/decorators.py | Python | agpl-3.0 | 764 | 0.003927 | from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from functools import wraps
TRANSIENT_USER_TYPES = []
def is_transient_user(user):
return isinstance(user, tuple(TRANSIENT_USER_TYPES))
def prevent_access_to_transient_users(view_func):
def _wrapped_view(re... | **kwargs):
'''Test if the user is transient'''
for user_type in TRANSIENT_USER_TYPES:
if is_transient_user(request.user):
return HttpResponseRedirect('/')
return view_func(request, *args, **kwargs)
return login_required(wraps(view_func)(_wrapped_view))
def to_lis... | list(func(*args, **kwargs))
return f
|
sserrot/champion_relationships | venv/Lib/site-packages/pip/_internal/index/collector.py | Python | mit | 22,838 | 0 | """
The main purpose of this module is to expose LinkCollector.collect_links().
"""
import cgi
import functools
import itertools
import logging
import mimetypes
import os
import re
from collections import OrderedDict
from pip._vendor import html5lib, requests
from pip._vendor.distlib.compat import unescape
from pip._... | lru_cache", noop_lru_cache) # type: LruCache
def _match_vcs_scheme(url):
# type: (str) -> Optional[str]
"""Look for VCS schemes in the URL.
Returns the matched VCS scheme, or None if there's no match.
"""
for scheme in | vcs.schemes:
if url.lower().startswith(scheme) and url[len(scheme)] in '+:':
return scheme
return None
def _is_url_like_archive(url):
# type: (str) -> bool
"""Return whether the URL looks like an archive.
"""
filename = Link(url).filename
for bad_ext in ARCHIVE_EXTENSIONS:... |
svera/clouddump | tools.py | Python | gpl-2.0 | 1,226 | 0.006525 | import json
import sys
import logging
import logging.handlers
def load_config():
'''Loads application configuration from a JSON file'''
try:
json_data = open('config.json')
config = json.load(json_data)
json_data.close()
return config
except Exception:
print """T... | getLogger('clouddump')
log_file_handler = logging.handlers.RotatingFileHandler(
file_ | name, maxBytes = 10**9)
log_format = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
log_file_handler.setFormatter(log_format)
logger.addHandler(log_file_handler)
logger.setLevel(logging.DEBUG)
if len(sys.argv) > 1:
if sys.argv[1] == '-v' or sys.argv[1] == '--verbose':
... |
rero/reroils-app | tests/api/patron_transactions/test_patron_transactions_permissions.py | Python | gpl-2.0 | 7,427 | 0 | # -*- coding: utf-8 -*-
#
# RERO ILS
# Copyright (C) 2020 RERO
# Copyright (C) 2020 UCLouvain
#
# 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, version 3 of the License.
#
# This program ... | ission_url)
assert res.status_code == 200
data = get_json(res)
assert not data['read']['can']
assert not data['update']['can']
assert not data['delete']['can']
def test_pttr_permissions(patron_martig | ny,
librarian_martigny,
system_librarian_martigny,
org_martigny, patron_transaction_overdue_saxon,
patron_transaction_overdue_sion,
patron_transaction_overdue_martigny):
"""Test patron t... |
electrolinux/pootle | pootle/core/search/broker.py | Python | gpl-3.0 | 2,440 | 0.002049 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the L | ICENSE file for a copy of the license and the
# AUTHORS file for copyrig | ht and authorship information.
from . import SearchBackend
import importlib
import logging
class SearchBroker(SearchBackend):
def __init__(self, config_name=None):
super(SearchBroker, self).__init__(config_name)
self._servers = {}
if self._settings is None:
return
f... |
maaaaz/androwarn | warn/search/manifest/manifest.py | Python | lgpl-3.0 | 4,316 | 0.01089 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# This file is part of Androwarn.
#
# Copyright (C) 2012, 2019, Thomas Debize <tdebize at mail.com>
# All rights reserved.
#
# Androwarn is free software: you can redistribute it | and/or modify
# it under the terms of the GNU Les | ser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Androwarn 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 PARTIC... |
idekerlab/py2cytoscape | py2cytoscape/data/session_client.py | Python | mit | 839 | 0.001192 | import requests
import warnings
warnings.warn('\n\n\n**** data.session_client will be deprecated in the next py2cytoscape release. ****\n\n\n')
class SessionClient(object):
def __init__(self, url):
self.__url = url + 'session'
def delete(self):
requests.delete(self.__url)
def save(self... | None):
if file_name is No | ne:
raise ValueError('Session file name is required.')
get_url = self.__url
params = {'file': file_name}
res = requests.get(get_url, params=params)
return res
|
renegelinas/mi-instrument | mi/dataset/driver/flord_g/ctdbp_p/dcl/test/test_flord_g_ctdbp_p_dcl_recovered_driver.py | Python | bsd-2-clause | 893 | 0.003359 | import os
| import unittest
from mi.core.log import get_logger
from mi.dataset.dataset_driver import ParticleDataHandler
from mi.dataset.driver.ctdbp_p.dcl.resource import RESOURCE_PATH
from mi.dataset.driver.flord_g.ctdbp_p.dcl.flord_g_ctdbp_p_dcl_recovered_dri | ver import parse
_author__ = 'jeff roy'
log = get_logger()
class DriverTest(unittest.TestCase):
def test_one(self):
source_file_path = os.path.join(RESOURCE_PATH, 'ctdbp01_20150804_061734.DAT')
particle_data_handler = ParticleDataHandler()
particle_data_handler = parse(None, source_fi... |
justasabc/kubernetes-ubuntu | smartfootball/okooo/okooo_setting.py | Python | apache-2.0 | 796 | 0.023869 | from setting import MATCH_TYPE_JC,MATCH_TYPE_M14
#url_m14_fmt = "http://www.okooo.com/livecenter/zucai/?mf=ToTo&date=15077"
#url_jc_fmt = "http://www.okooo.com/livecenter/jingcai/?date=2015-05-26"
url_jc_fmt = "http://www.okooo.com/livecenter/jingcai/?date={0}"
url_m14_fmt = "http://www.okooo.com/livecenter/zucai/?mf=... | ef get_url_jc(dt):
dt_str = dt.strftime("%Y-%m-%d")
return url_jc_fmt.format(dt_str)
def get_url_m14(sid):
return url_jc_m14.format(sid)
def get_url_odds_change(okooo_id,bookmaker_id=2):
return url_jc_odds_change_fmt.format(okooo_id,bookmaker_id)
OKOOO_BOOKMAKER_DATA = {
"jingcai":2,
}
| |
harisibrahimkv/wye | wye/workshops/mixins.py | Python | mit | 6,362 | 0.000629 | from django.contrib import messages
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
from django.http import Http404
from django.http import HttpResponseForbidden
from django.http import HttpResponseRedirect, JsonResponse
from django.shortcuts import render
from wye.base... | email update.
"""
if exclude_emails is None:
exclude_emails = []
# Collage POC and admin email
poc_admin_user = Profile.get_user_with_type(
user_type=['Collage POC', 'admin']
).values_list('email', flat=True)
# Org user email
org_user_em... | ester.user.filter(
is_active=True
).values_list('email', flat=True)
# all presenter if any
all_presenter_email = self.object.presenter.values_list(
'email', flat=True
)
# List of tutor who have shown interest in that location
region_interested_memb... |
dimagi/commcare-hq | corehq/form_processor/migrations/0026_caseforms_to_casetransaction.py | Python | bsd-3-clause | 1,422 | 0.00211 | from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('form_processor', '0025_caseforms_server_date'),
]
operations = [
migrations.CreateModel(
name='CaseTransaction',
fields=[
('id', models.AutoField(ver... | ', db_index=False, on_delete=models.CASCADE)),
],
options={
'ordering': ['server_date'],
},
bases=(models.Model,),
),
migrations.AlterUniqueTogether(
name='caseforms',
unique_together=None,
),
migrati... | ='CaseForms',
),
migrations.AlterUniqueTogether(
name='casetransaction',
unique_together=set([('case', 'form_uuid')]),
),
]
|
vmdowney/oclc-udev | oclc_udev.py | Python | mit | 7,800 | 0.010128 | # This script only works for OCLC UDEV reports created after December 31, 2015
import csv
import datetime
import re
import requests
import sys
import time
from lxml import html
user_date = raw_input('Enter report month and year (mm/yyyy) or year only (yyyy): ')
if len(user_date) == 7: # For running a report for a si... | eph_hol = line[27:-2].split('-')[0]
elif tag == '949':
for data in record_data:
data['Library'] = line[line.index('=l')+2:-2] # 949 field within subfield l and line end indicator ("+|")
else:
... |
if tag == data['Error Field']:
if tag == '008' or tag == '006':
data['Error Line'] = line[27:].rstrip('|').rstrip('+')
elif data['Error Position'] == '':
... |
jkandasa/integration_tests | cfme/tests/openstack/cloud/test_volumes.py | Python | gpl-2.0 | 1,818 | 0.00055 | """Tests for Openstack cloud volumes"""
import fauxfactory
import pytest
from cfme.cloud.provider.openstack import OpenStackProvider
from cfme.utils.appliance.implementations.ui import navigate_to
from cfme.utils.blockers import BZ
from cfme.utils.log import logger
pytestmark = [
pytest.mark.usefixtures("setup_... | .name)
volume = collection.create(name=fauxfactory.gen_alpha(),
storage_manager=storage_manager,
tenant=provider.data['provisioning']['cloud_tenant'],
| size=VOLUME_SIZE,
provider=provider)
yield volume
try:
if volume.exists:
volume.delete(wait=False)
except Exception:
logger.warning('Exception during volume deletion - skipping..')
@pytest.mark.meta(blockers=[BZ(150... |
arviz-devs/arviz | arviz/tests/helpers.py | Python | apache-2.0 | 21,624 | 0.00148 | # pylint: disable=redefined-outer-name, comparison-with-callable
"""Test helper functions."""
import gzip
import importlib
import logging
import os
import sys
from typing import Any, Dict, List, Optional, Tuple, Union
import cloudpickle
import numpy as np
import pytest
from _pytest.outcomes import Skipped
... | """Share default draw count."""
return 500
@pytest.fixture(scope="module")
def chains():
"""Share default chain count."""
return 2
def create_model(seed=10):
"""Create model with fake data."""
np.ra | ndom.seed(seed)
nchains = 4
ndraws = 500
data = {
"J": 8,
"y": np.array([28.0, 8.0, -3.0, 7.0, -1.0, 1.0, 18.0, 12.0]),
"sigma": np.array([15.0, 10.0, 16.0, 11.0, 9.0, 11.0, 10.0, 18.0]),
}
posterior = {
"mu": np.random.randn(nchains, ndraws),
"tau":... |
sburnett/seattle | repy/tests/ut_repytests_testremovefilefnf.py | Python | mit | 88 | 0.022727 | # | pragma error
#pragma repy
removefile("this.file.does.not.exist") # should fail (FNF | )
|
awsok/SaltAdmin | view/index.py | Python | gpl-2.0 | 10,160 | 0.012983 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
from main import *
import time
import random
import urllib2
import json
#import os
def genToken(L):
CharLib = map(chr,range(97,123)+range(65,91)+range(48,58))
Str = []
for i in range(L):
Str += random.sample(CharLib,1)
return ''.join(Str)
# Key is md... | 错误
return "error"
class Logout:
def GET(self):
uid = getCookie('Username')
token | = getCookie('Token')
sidName = getCookie('xk_session')
if uid and token and sidName:
uid = decryptUID(uid)
#sfile = 'session/' + sidName
# 删除会话文件,貌似kill方法会把sessionID文件干掉
#try:
# os.remove(sfile)
#except Exception,e:
... |
anhstudios/swganh | data/scripts/templates/object/tangible/wearables/ithorian/shared_ith_bandolier_s08.py | Python | mit | 472 | 0.04661 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
res | ult.template = "object/tangible/wearables/ithorian/shared_ith_bandolier_s08.iff"
result.attribute_template_id = 11
result.stfName("wearables_name","ith_bandolier_s08")
#### BEGIN | MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
l33tdaima/l33tdaima | p838m/push_dominoes.py | Python | mit | 1,778 | 0.001125 | class Solution:
def pushDominoesSim(self, dominoes: str) -> str:
prev, curr, N = None, ["." | ] + list(dominoes) + ["."], len(dominoes)
while prev != curr:
prev = curr[:]
i = 1
while i <= N:
if curr[i] == "." and prev[i - 1] == "R" and prev[i + 1] != "L":
curr[i], i = "R", i + 1
i += 1
| i = N
while i >= 1:
if curr[i] == "." and prev[i + 1] == "L" and prev[i - 1] != "R":
curr[i], i = "L", i - 1
i -= 1
return "".join(curr[1:-1])
def pushDominoes(self, dominoes: str) -> str:
d, n = list("L" + dominoes + "R"), len(... |
annikaliebgott/ImFEATbox | features_python/ImFEATbox/GlobalFeatures/Intensity/_SVDF.py | Python | apache-2.0 | 4,317 | 0.008571 | import numpy as np
from scipy.misc import imrotate
from ImFEATbox.__helperCommands import conv2float
from scipy.stats import skew, kurtosis
def SVDF(I, returnShape=False):
"""
Input: - I: A 2D image
Output: - Out: A (1x780) vector containing 780 metrics calculated
from singular... | ctor
#np.prod(np.shape(eig_U[:100,:]))
Out = np.hstack([np.ndarray.flatten(dia_elements[:40,:]),
np.ndarray.flatten(eig_U[:100,:]),
np.ndarray.flatten(eig_V[:100,:]),
det_U, det_V, trace_U, trace_V, rank_U, rank_V, skewness_U, skewness_V,
kurtosis_U, kurtosis | _V, mean_U, mean_V, mean_S, std_U, std_V, std_S,
median_eig_U, median_eig_V, max_eig_U, max_eig_V])
return Out
|
sdwfrost/piggy | extract_CDR3.py | Python | mit | 749 | 0.048064 | import sys
import re
from Bio import Seq,SeqIO
iname=sys.argv[1]
cdr3p=re.compile("(TT[TC]|TA[CT])(TT[CT]|TA[TC]|CA[TC]|GT[AGCT]|TGG)(TG[TC])(([GA][AGCT])|TC)[AGCT]([ACGT]{3}){5,32}TGGG[GCT][GCT]")
# Utility functions
def get_records(filename):
records=[]
for record in SeqIO.parse(filename,"fasta"):
records.... | d)
return records
records=get_records(iname)
numrecords=len(records)
results=[]
for i in range(numrecords):
r=records[i]
strseq=str(r.seq)
m=cdr3p.search(strseq)
if m!=None:
mspan=m.span()
result=strseq[mspan[0]:mspan[1]]
else:
result=""
results.append(result)
for i in range(numrecords):
... | |
gratefulfrog/lib | python/pymol/colorramping.py | Python | gpl-2.0 | 13,994 | 0.011862 | import math
class ColorPoint:
"""
Simple color-storage class; stores way-points on a color ramp
"""
def __init__(self,idx,col,colType):
# index, X-coordinate, on a palette
self.idx = idx
# color; usually an RGBA quad
self.color = col
# One of ColorTypes members
... | ret_x = x
elif startX > X:
for x in range(int(startX)-1, int(X)-1, -1):
if x in self.keys:
br | eak
ret_x = x
return ret_x
def getPoint(self, pt):
"""
Returns a true index (horizontal potision) of a given point.
"""
if pt in self.canvas_ids:
return self.canvas_ids[pt]
return None
def getRampList(self):
"""
Retur... |
gwct/core | python/generators/muscle_gen.py | Python | gpl-3.0 | 5,889 | 0.014943 | #!/usr/bin/python
############################################################
# Generates commands for the muscle alignment program
############################################################
import sys, os, core, argparse
############################################################
# Options
parser = argparse.Arg... | pacedOut("# Job file:", pad) + output_file, outfile);
core.PWS("# ----------", outfile);
core.PWS("# SLURM OPTIONS", outfile);
core.PWS(core.spacedOut("# Submit file:", pad) + submit_file, outfile);
core.PWS(core.spacedOut("# SLURM partition:", pad) + args.part, outfile);
core.PWS(core.spacedOut( | "# SLURM ntasks:", pad) + str(args.tasks), outfile);
core.PWS(core.spacedOut("# SLURM cpus-per-task:", pad) + str(args.cpus), outfile);
core.PWS(core.spacedOut("# SLURM mem:", pad) + str(args.mem), outfile);
core.PWS("# ----------", outfile);
core.PWS("# BEGIN CMDS", outfile);
#####################... |
batxes/4Cin | SHH_WT_models/SHH_WT_models_final_output_0.1_-0.1_11000/mtx1_models/SHH_WT_models22582.py | Python | gpl-3.0 | 17,582 | 0.025082 | import _surface
import chimera
try:
import chimera.runCommand
except:
pass
from VolumePath import markerset as ms
try:
from VolumePath import Marker_Set, Link
new_marker_set=Marker_Set
except:
from VolumePath import volume_path_dialog
d= volume_path_dialog(True)
new_marker_set= d.new_marker_set
marker_set... | er_sets:
s=new_marker_set('particle_6 geometry')
marker_sets["particle_6 geometry"]=s
s= marker_sets["particle_6 geometry"]
mark=s.pla | ce_marker((5657.6, 1350.01, 1989.44), (0.7, 0.7, 0.7), 753.151)
if "particle_7 geometry" not in marker_sets:
s=new_marker_set('particle_7 geometry')
marker_sets["particle_7 geometry"]=s
s= marker_sets["particle_7 geometry"]
mark=s.place_marker((5635.18, 436.967, 2062), (1, 0.7, 0), 1098.07)
if "particle_8 geometry"... |
devasia1000/anti_adblock | examples/har_extractor.py | Python | mit | 10,062 | 0.004373 | """
This inline script utilizes harparser.HAR from https://github.com/JustusW/harparser
to generate a HAR log object.
"""
try:
from harparser import HAR
from pytz import UTC
except ImportError as e:
import sys
print >> sys.stderr, "\r\nMissing dependencies: please run `pip install mitmproxy[exam... | self.__page_count__ += 1
return "autopage_%s" % str(self.__page_count__)
def set_page_ref(self, page, ref):
self.__page_ref__[page] = ref
def get_page_ref(self, page):
return self.__page_ref__.get(page, None)
def get_page_list(self):
return self.__page_list__
def s... | of HAR generation. As it will probably be necessary to cluster logs by IPs or reset them
from time to time.
"""
context.dump_file = None
if len(argv) > 1:
context.dump_file = argv[1]
else:
raise ValueError('Usage: -s "har_extractor.py filename" '
'(- ... |
rlindner81/pyload | module/plugins/crypter/CrockoComFolder.py | Python | gpl-3.0 | 875 | 0.002286 | # -*- coding: utf-8 -*-
from module.plugins.internal.SimpleCrypter import SimpleCrypter
class CrockoComFo | lder(SimpleCrypter):
__name__ = "CrockoComFolder"
__type__ = "crypter"
__version__ = "0.06"
__status__ = "testing"
__pattern__ = r'http://(?:www\.)?crocko\.com/f/.+'
__config__ = [("activated", "bool", "Activated", True),
("use_premium", "bool", "Use premium account if availab... | efault;Yes;No",
"Create folder for each package", "Default"),
("max_wait", "int", "Reconnect if waiting time is greater than minutes", 10)]
__description__ = """Crocko.com folder decrypter plugin"""
__license__ = "GPLv3"
__authors__ = [("zoidberg", "zoidberg@mujmail.cz"... |
Agent007/deepchem | deepchem/rl/envs/tictactoe.py | Python | mit | 3,149 | 0.013973 | import numpy as np
import copy
import random
import deepchem
class TicTacToeEnvironment(deepchem.rl.Environment):
"""
Play tictactoe against a randomly acting opponent
"""
X = np.array([1.0, 0.0])
O = np.array([0.0, 1.0])
EMPTY = np.array([0.0, 0.0])
ILLEGAL_MOVE_PENALTY = -3.0
LOSS_PENALTY = -3.... | r(TicTacToeEnvironment.O):
self._terminated = True
return TicTacToeEnvironment.LOSS_PENALTY
if self.game_over():
self._terminated = True
return TicTacToeEnvironment.DRAW_REWARD
return TicTacToeEnvi | ronment.NOT_LOSS
def get_O_move(self):
empty_squares = []
for row in range(3):
for col in range(3):
if np.all(self._state[0][row][col] == TicTacToeEnvironment.EMPTY):
empty_squares.append((row, col))
return random.choice(empty_squares)
def check_winner(self, player):
for i ... |
isyippee/nova | nova/objects/fields.py | Python | apache-2.0 | 19,847 | 0.00005 | # Copyright 2013 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | er the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from collections import OrderedD | ict
from distutils import versionpredicate
import netaddr
from oslo_utils import strutils
from oslo_versionedobjects import fields
import six
# TODO(berrange) Temporary import for Arch class
from nova.compute import arch
# TODO(berrange) Temporary import for CPU* classes
from nova.compute import cpumodel
# TODO(berra... |
shakamunyi/sahara | sahara/tests/unit/plugins/vanilla/hadoop2/test_validation.py | Python | apache-2.0 | 4,497 | 0 | # Copyright (c) 2014 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | on(ex.InvalidComponentCountException):
self._validate_case(1, 0, 2, 10, 3, 0, 0)
| with testtools.ExpectedException(ex.InvalidComponentCountException):
self._validate_case(1, 0, 1, 1, 3, 2, 1)
with testtools.ExpectedException(ex.InvalidComponentCountException):
self._validate_case(1, 0, 1, 1, 3, 1, 2)
with testtools.ExpectedException(ex.InvalidComponentCoun... |
hasadna/OpenTrain | webserver/opentrain/timetable/migrations/0006_auto__add_field_tttrip_date.py | Python | bsd-3-clause | 2,370 | 0.006329 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'TtTrip.date'
db.add_column(u'timetable_tttrip', 'date',
... | db.models.fields.DateTimeField')(null=True, b | lank=True),
keep_default=False)
def backwards(self, orm):
# Deleting field 'TtTrip.date'
db.delete_column(u'timetable_tttrip', 'date')
models = {
u'timetable.ttstop': {
'Meta': {'object_name': 'TtStop'},
u'id': ('django.db.models.fields.A... |
ooblog/yonmoji_ge | LTsv/LTsv_gui.py | Python | mit | 127,236 | 0.032237 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division,print_function,absolute_import,unicode_literals
import sys
import os
import subprocess
import codecs
import ctypes
import struct
import uuid
import datetime
import math
from LTsv_file import *
from LTsv_printf import *
LTsv_Tkinter=True
t... | LTsv_uuid=LTsv_widget_oldID
else:
LTsv_uuid=uuid.uuid4().hex+'+'+str(time.time())
LTsv_widget_oldID=LTsv_uuid
return LTsv_uuid
LTsv_widget_oldID=LTsv_widget_newUUID()
def LTsv_widget_newobj(LTsv_widgetPAGE,LTsv_widgetoption,widget_obj):
global LTsv_widgetOBJ,LTsv_widgetOBJcount
LTsv_wid... | widgetOBJcount))
LTsv_widgetOBJ[str(LTsv_widgetOBJcount)]=widget_obj; LTsv_widgetOBJcount+=1
return LTsv_widgetPAGE
def LTsv_widget_getobj(LTsv_widgetPAGE,LTsv_widgetoption):
LTsv_widgetOBJcount=LTsv_readlinerest(LTsv_widgetPAGE,LTsv_widgetoption)
if LTsv_widgetOBJcount in LTsv_widgetOBJ:
retur... |
Xaroth/plex-export | docs/conf.py | Python | mit | 9,091 | 0.00517 | # -*- coding: utf-8 -*-
#
# destiny_account documentation build configuration file, created by
# sphinx-quickstart on Tue Apr 15 00:23:55 2014.
#
# 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 fil... | .
release = setup_info.VERSION
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the ... | tch files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, ... |
entwanne/NAGM | games/test_game/attacks.py | Python | bsd-3-clause | 1,048 | 0.009579 | from nagm.engine.attack import Attack
from .types import *
from .defs import precision, stat, heal, offensive, faux_chage_effect
prec = precision(prec=0.9)
mimi_queue = Attack(name='Mimi-queue', type=normal, effects=(prec, stat(stat='dfse', value=-1),))
charge = Attack(name='Charge', type=normal, effects=(prec, offens... | ack(name='Flamèche', type=feu, e | ffects=(prec, offensive(force=20),))
pistolet_a_o = Attack(name='Pistolet à o', type=eau, effects=(prec, offensive(force=20),))
eclair = Attack(name='Éclair', type=electrik, effects=(prec, offensive(force=20),))
soin = Attack(name='Soin', type=normal, effects=(prec, heal(heal=50),), reflexive=True)
abime = Attack(name=... |
chrisws/scummvm | devtools/tasmrecover/tasm/parser.py | Python | gpl-2.0 | 7,312 | 0.040618 | # ScummVM - Graphic Adventure Engine
#
# ScummVM is the legal property of its developers, whose names
# are too numerous to list here. Please refer to the COPYRIGHT
# file distributed with this source distribution.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU ... | lf
def link(self):
for addr, exp | r in self.link_later:
v = self.eval_expr(expr)
print "link: patching %04x -> %04x" %(addr, v)
while v != 0:
self.binary_data[addr] = v & 0xff
addr += 1
v >>= 8
|
DeltaEpsilon-HackFMI2/FMICalendar-REST | schedule/models.py | Python | mit | 4,666 | 0.00349 | # -*- coding: utf-8 -*-
from django.db import models
from datetime import datetime
class Place(models.Model):
"""
Holder object for basic info about the rooms
in the university.
"""
room_place = models.CharField(max_length=255)
floor = models.IntegerField()
def __unicode__(self):
... | nk=True, default=None, null=True)
events = models.ManyToManyField(Event, blank=True, default=None, null=True)
def __unicode__(self):
return self.name
class Comment(models.Model):
from_user = models.ForeignKey(Student, blank=True, default=None, null=True)
event = models.ForeignKey(Event, bl... | etime.now())
desc = models.TextField() |
commtrack/commtrack-core | apps/xformmanager/forms.py | Python | bsd-3-clause | 1,428 | 0.009804 | from django import forms
from models import FormDataGroup
import re
# On this page, users can upload an xsd file from their laptop
# Then they get redirected to a page where they can download the xsd
class RegisterXForm(forms.Form):
file = forms.FileField()
form_display_name= forms.CharField(max_length=128, l... | s={'size':'80'}))
view_name = forms.CharField(widget=forms.TextInput(attrs={'size':'40'}))
def clean_view_name(self):
view_name = self.cleaned_data["view_name"]
if not re.match(r"^\w+$", view_name):
raise forms.Validati | onError("View name can only contain numbers, letters, and underscores!")
# check that the view name is unique... if it was changed.
if self.instance.id:
if FormDataGroup.objects.get(id=self.instance.id).view_name != view_name and \
FormDataGroup.objects.filter(view_name=view_n... |
saltastro/pysalt | proptools/ImageDisplay.py | Python | bsd-3-clause | 3,112 | 0.008355 | ################################# LICENSE ##################################
# Copyright (c) 2009, South African Astronomical Observatory (SAAO) #
# All rights reserved. #
# #
############... | ersion Date
-----------------------------------------------
S M Crawford (SAAO) 0.1 19 Jun 2011
"""
import os
import pyds9 as ds9
class ImageDisplay:
def __init__(self, target='ImageDisplay:*'):
self.ds9 = ds9.ds9()
def display(self, filename, pa=None):
cmd='file %s' % filen... | set('rotate to %f' % pa)
else:
self.ds9.set('rotate to %f' % 0)
def regions(self, rgnstr):
cmd = 'regions %s'
def rssregion(self, ra, dec):
"""Plot the FOV for RSS"""
# cmd='color=green dashlist=8 3 width=1 font="helvetica 10 normal roman" select=0 highlite=1 dash=0 f... |
privacyidea/privacyidea | privacyidea/lib/challenge.py | Python | agpl-3.0 | 5,837 | 0.000857 | # -*- coding: utf-8 -*-
# privacyIDEA is a fork of LinOTP
#
# 2014-12-07 Cornelius Kölbel <cornelius@privacyidea.org>
#
# Copyright (C) 2014 Cornelius Kölbel
# License: AGPLv3
#
# This code is free software; you can redistribute it and/or
# modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
# Licen... | uery.filter(Challenge.transaction_id ==
transaction_id)
if challenge is not None:
# filter for this challenge
sql_query = sql_query.filter(Challenge.challenge == challenge)
challenges = sql_query.all()
return | challenges
@log_with(log)
def get_challenges_paginate(serial=None, transaction_id=None,
sortby=Challenge.timestamp,
sortdir="asc", psize=15, page=1):
"""
This function is used to retrieve a challenge list, that can be displayed in
the Web UI. It sup... |
drestuart/delvelib | src/world/WorldMapClass.py | Python | lgpl-3.0 | 6,833 | 0.009074 | '''
Created on Feb 26, 2014
@author: dstuart
'''
import LevelClass as L
import Util as U
class Region(object):
def __init__(self, **kwargs):
self.mapTiles = set()
self.name = None
self.worldMap = None
# TODO:
# worldMapId = Column(Integer, ForeignKey("levels.id"))
def a... | super(WorldMap, self).__init__(**kwargs)
self.name = None
self.mapTiles | = set()
self.regions = set()
self.num_regions = kwargs['num_regions']
self.creatures = set()
# Initialize self.hasTile
self.hasTile = []
for dummyx in range(self.width):
newCol = []
for dummyy in range(self.height):
... |
jwlawson/tensorflow | tensorflow/contrib/rnn/python/ops/lstm_ops.py | Python | apache-2.0 | 24,941 | 0.005052 | # 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... | The weight matrix for input gate peephole connection.
wcf: A `Tensor`. Must have the same type as `x`.
The weight matrix for forget gate peepho | le connection.
wco: A `Tensor`. Must have the same type as `x`.
The weight matrix for output gate peephole connection.
forget_bias: An optional `float`. Defaults to `1`. The forget gate bias.
cell_clip: An optional `float`. Defaults to `-1` (no clipping).
Value to clip the 'cs' value to. Disable... |
github/codeql | python/ql/test/3/library-tests/PointsTo/inheritance/test.py | Python | mit | 496 | 0.012097 | class Base(object):
def meth(self):
| pass
class Derived1(Base):
def meth(self):
return super().meth()
class Derived2(Derived1):
def meth(self):
return super().meth()
class Derived3(Derived1):
pass
class Derived4(Deri | ved3, Derived2):
def meth(self):
return super().meth()
class Derived5(Derived1):
def meth(self):
return super().meth()
class Derived6(Derived5, Derived2):
def meth(self):
return super().meth()
|
ujvl/ray-ng | python/ray/tests/test_memory_scheduling.py | Python | apache-2.0 | 4,709 | 0 | import numpy as np
import unittest
import ray
from ray import tune
from ray.rllib import _register_all
MB = 1024 * 1024
@ray.remote(memory=100 * MB)
class Actor(object):
def __init__(self):
pass
def ping(self):
return "ok"
@ray.remote(object_store_memory=100 * MB)
class Actor2(object):
... | ok), 0)
finally:
ray.shutdown()
def testObjectStoreMemoryRequest(self):
try:
ray.init(num_cpus=1, object_store_memory=300 * MB)
# fits first 2 (70% allowed)
a = Actor2.remote()
b = Actor2. | remote()
ok, _ = ray.wait(
[a.ping.remote(), b.ping.remote()],
timeout=60.0,
num_returns=2)
self.assertEqual(len(ok), 2)
# does not fit
c = Actor2.remote()
ok, _ = ray.wait([c.ping.remote()], timeout=5.0)
... |
StackVista/sts-agent-integrations-core | sqlserver/check.py | Python | bsd-3-clause | 27,601 | 0.002935 | '''
Check the performance counters from SQL Server
See http://blogs.msdn.com/b/psssql/archive/2013/09/23/interpreting-the-counter-values-from-sys-dm-os-performance-counters.aspx
for information on how to report the metrics available in the sys.dm_os_performance_counters table
'''
# stdlib
import traceback
from context... | much : we expect it. leave checks disabled
self.do_check[instance_key] = False
self.log.warning("Database %s does not exist. Disabling checks for this instance." % (context))
else:
# yes we do. Keep trying
... | QLConnectionError:
self.log.exception("Skipping SQL Server instance")
continue
def _check_db_exists(self, instance):
"""
Check if the database we're targeting actually exists
If not then we won't do any checks
This allows the same config to be install... |
drnextgis/QGIS | python/plugins/processing/algs/grass7/ext/r_li_padcv.py | Python | gpl-2.0 | 1,324 | 0 | # -*- coding: utf-8 -*-
"""
***************************************************************************
r_li_padcv.py
-------------
Date : February 2016
Copyright : (C) 2016 by Médéric Ribreux
Email : medspx at medspx dot fr
********************************... | ********************************************************************
"""
from __future__ import absolute_import
__author__ = 'Médéric Ribreux'
__date__ = 'February 2016'
__copyright__ = '(C) 2016, Médéric Ribreux'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
from .... | configFile(alg)
|
danclaudiupop/django-test-html-form | setup.py | Python | bsd-3-clause | 546 | 0 | from setuptools import setup, find_package | s
setup(
name='django-test-html-form',
version='0.1',
description="Make your Django HTML form tests more explicit and concise.",
long_description=open('README.rst').read(),
keywords='django test assert',
author='Dan Claudiu Pop',
author_email='dancladiupop@gmail.com',
url='https://gith... | include_package_data=True,
install_requires=[
'beautifulsoup4',
],
)
|
mirumee/django-messages | django_messages/tests.py | Python | bsd-3-clause | 2,362 | 0.008044 | import datetime
from django.test import TestCase
from django.contrib.auth.models import User
from django_messages.models import Message
class SendTestCase(TestCase):
def setUp(self):
self.user1 = User.objects.create_user('user1', 'user1@example.com', '123456')
self.user2 = User.objects.create_user(... | Text 2')
self.msg1.sender_deleted_at = datetime.datetime.now()
self.msg2.recipient_deleted_at = datetime.datetime.now()
self.msg1.sav | e()
self.msg2.save()
def testBasic(self):
self.assertEquals(Message.objects.outbox_for(self.user1).count(), 1)
self.assertEquals(Message.objects.outbox_for(self.user1)[0].subject, 'Subject Text 2')
self.assertEquals(Message.objects.inbox_for(self.user2).count(),1)
... |
shankari/folium | folium/folium.py | Python | mit | 14,914 | 0 | # -*- coding: utf-8 -*-
"""
Folium
-------
Make beautiful, interactive maps with Python and Leaflet.js
"""
from __future__ import absolute_import
from branca.colormap import StepColormap
from branca.utilities import color_brewer
from .map import LegacyMap, FitBounds
from .features import GeoJson, TopoJson
class ... | tead of SVG. This can increase performance
considerably in some cases (e.g. many thousands of circle
markers on the map).
no_touch : bool, default F | alse
Forces Leaflet to not use touch events even if it detects them.
disable_3d : bool, default False
Forces Leaflet to not use hardware-accelerated CSS 3D
transforms for positioning (which may cause glitches in some
rare environments) even if they're supported.
Returns
----... |
Anfauglith/iop-hd | test/functional/zapwallettxes.py | Python | mit | 3,234 | 0.002474 | #!/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.
"""Test the zapwallettxes functionality.
- start two iopd nodes
- create two transactions on node 0 - one... | not persistmempool.
# The unconfirmed transaction is zapped and is no longer in the wallet.
self.stop_node(0)
self.start_node(0, ["-zapwallettxes=2"])
# tx1 is still be available because it was confirmed
assert_equal(self.nodes[0].gettransaction(txid1)['txid'], txid1)
... | ttransaction, txid2)
if __name__ == '__main__':
ZapWalletTXesTest().main()
|
ffunenga/virtuallinks | tests/core/core.py | Python | mit | 375 | 0 | import sys
import os
import shutil
def import_package(name):
_filepath = os.path.abspath(__file__)
path = backup = os.path.dirname(_filepath)
while os.path.basename(path) != name:
path = os.pat | h.join(path, '..')
path = os.path.abspath(path)
if path != backup:
| sys.path.insert(0, path)
module = __import__(name)
return module
|
yifeng-li/DECRES | rbm.py | Python | bsd-3-clause | 22,163 | 0.006723 | """
A module of restricted Boltzmann machine (RBM) modified
from the Deep Learning Tutorials (www.deeplearning.net/tutorial/).
Copyright (c) 2008-2013, Theano Development Team All rights reserved.
Modified by Yifeng Li
CMMT, UBC, Vancouver
Sep 23, 2014
Contact: yifeng.li.cn@gmail.com
"""
from __future__ import divisi... | heano.config.floatX)
return [pre_sigmoid_v1, v1_mean, v1_sample]
def gibbs_hvh(self, h0_sample):
''' This function implements one step of Gibbs sampling,
starting from the hidden state'''
pre_sigmoid_v1, v1_mean, v1_sample = self.sample_v_given_h(h0_sample)
pre_sigmoid_h... | pre_sigmoid_h1, h1_mean, h1_sample]
def gibbs_vhv(self, v0_sample):
''' This function implements one step of Gibbs sampling,
starting from the visible state'''
pre_sigmoid_h1, h1_mean, h1_sample = self.sample_h_given_v(v0_sample)
pre_sigmoid_v1, v1_mean, v1_sample = s... |
w1ll1am23/home-assistant | tests/components/zwave_js/common.py | Python | apache-2.0 | 1,508 | 0.002653 | """Provide common test tools for Z-Wave JS."""
AIR_TEMPERATURE_SENSOR = "sensor.multisensor_6_air_temperature"
HUMIDITY_SENSOR = "sensor.multisensor_6_humidity"
ENERGY_SENSOR = "sensor.smart_plug_with_two_usb_ports_value_electric_consumed_2"
POWER_SENSOR = "sensor.smart_plug_with_two_usb_ports_value_electric_consumed"
... | OR = "sensor.multisensor_6_home_security_motion_sensor_status"
PROPERTY_DOOR_STATUS_BINARY_SENSOR = (
"binary_sensor.aug | ust_smart_lock_pro_3rd_gen_the_current_status_of_the_door"
)
CLIMATE_RADIO_THERMOSTAT_ENTITY = "climate.z_wave_thermostat"
CLIMATE_DANFOSS_LC13_ENTITY = "climate.living_connect_z_thermostat"
CLIMATE_EUROTRONICS_SPIRIT_Z_ENTITY = "climate.thermostatic_valve"
CLIMATE_FLOOR_THERMOSTAT_ENTITY = "climate.floor_thermostat"
C... |
dmnfarrell/peat | PEATSA/Tools/HIVTools/CombinationConverter.py | Python | mit | 4,305 | 0.029268 | #! /usr/bin/env python
import sys
import PEAT_SA.Core as Core
import Protool
import itertools
def getPathSequence(combinations):
path = []
currentSet = set(combinations[0].split(','))
path.append(combinations[0])
for i in range(1, len(combinations)):
newSet = set(combinations[i].split(','))
newElement = newSe... | []
for combination in path:
print fold[combination],
folds.append(fold[combination])
print '\n'
return values, folds
#Read in types
typeData = Core.Matrix.matrixFromCSVFile(sys.argv[2])
typeIndex = typeData.indexOfColumnWithHeader('Type')
#Get all entries for specified drug
drugName = sys.argv[4]
trimMat... | = Core.Matrix.PEATSAMatrix(rows=[[0]*9], headers=typeData.columnHeaders())
drugNameIndex = typeData.indexOfColumnWithHeader('Drug Name')
for row in typeData:
if row[drugNameIndex] == drugName:
trimMatrix.addRow(row)
#Read in combinations
combinationData = Core.Matrix.matrixFromCSVFile(sys.argv[1])
mutationCodes =... |
quantumlib/OpenFermion-FQE | src/fqe/fqe_decorators.py | Python | apache-2.0 | 14,347 | 0.000767 | # Copyright 2020 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... | check_diagonal_coulomb(ops_mat[1]):
out = diagonal_coulomb.DiagonalCoulomb(ops_mat[1], e_0=e_0)
else:
| dtypes = [xx.dtype for xx in ops_mat.values()]
dtypes = numpy.unique(dtypes)
assert len(dtypes) == 1
for i in range(maxrank + 1):
if i not in ops_mat:
mat_dim = tuple([2 * norb for _ in range((i + 1) * 2)])
ops_mat[i] = num... |
lmazuel/azure-sdk-for-python | azure-mgmt-containerservice/azure/mgmt/containerservice/models/container_service_diagnostics_profile.py | Python | mit | 1,170 | 0.000855 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | f __init__(self, vm_diagnostics):
super(ContainerServ | iceDiagnosticsProfile, self).__init__()
self.vm_diagnostics = vm_diagnostics
|
omi/stl-api-gateway | omi_api/client.py | Python | mit | 10,377 | 0.001253 | # Copyright 2017 ContextLabs B.V.
import time
import hashlib
import urllib
import requests
import sawtooth_signing as signing
from base64 import b64decode
from random import randint
from sawtooth_omi.protobuf.work_pb2 import Work
from sawtooth_omi.protobuf.recording_pb2 import Recording
from sawtooth_omi.protobuf.iden... | ction_ids=[txn.header_signature],
)
batch_header_bytes = batch_header.SerializeToString()
batch_signature = key_handler.ecdsa_sign(batch_header_bytes)
batch_signature_bytes = key_handler.ecdsa_serialize_compact(batch_signature)
batch_signature_hex = batch_signature_bytes.hex()
batch = Batch(
... |
batch_list = BatchList(batches=[batch])
batch_bytes = batch_list.SerializeToString()
batch_id = batch_signature_hex
url = "%s/batches" % base_url
headers = {
'Content-Type': 'application/octet-stream',
}
r = requests.post(url, data=batch_bytes, headers=headers)
r.raise_for_st... |
rCorvidae/OrionPI | src/tests/Devices/Containers/__init__.py | Python | mit | 188 | 0.010638 | from .TestContainersDeviceAndM | anager import TestContainerDeviceDataFlow
from .TestContainersRe | ceivingSerialDataAndObserverPattern import TestContainersReceivingSerialDataAndObserverPattern |
DarkFenX/Phobos | util/__init__.py | Python | gpl-3.0 | 1,042 | 0.003839 | #===============================================================================
# Copyright (C) 2014-2019 Anton Vorobyov
#
# This file is part of Phobos.
#
# Phobos 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 Softwa | re Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Phobos 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Phobos. If not, see <http://www.gnu.org/licenses/>.
#==========================================================... |
crodjer/paster | setup.py | Python | gpl-3.0 | 2,026 | 0.001974 | #!/usr/bin/env python
# Copyright (C) 2011 Rohan Jain
# Copyright (C) 2011 Alexis Le-Quoc
#
# 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
# (a... | See the
# GNU General Public License for more details.
#
# | You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
from sys import version
from os.path import expanduser
import paster
if version ... |
aruneli/rancher-test | ui-selenium-tests/locators/RackspaceLocators.py | Python | apache-2.0 | 1,212 | 0.006601 | __author__ = 'Arunkumar Eli'
__email__ = "elrarun@gmail.com"
from selenium.webdriver.common.by import By
class DigitalOceanLocators(object):
ACCESS_KEY_INPUT = (By.ID, 'accessKey')
SECRET_KEY_INPUT = (By.ID, 'secretKey')
NEXT_BTN = (By.CSS_SELECTOR, "button.btn.btn-primary")
AVAILABILITY_ZONE = (By.XP... | IO_BTN=(By.XPATH,"//section[5]/div[1]/div[2]/div[2]/div[2]/label/input")
SET_INSTANCE_OPTION_BTN = (By.XPATH, "//div[2]/button")
SLIDE_BAR_CLICK_3 = (By.XPATH, "//div[2]/div[3]/div")
HOST_NAME_INPUT = (By.ID, "prefix")
HOST_DESC_INPUT = (By.ID, "description")
HOST_INSTANCE_TYPE_SELECT = (By.ID, "ins... | on")
|
CongLi/avocado-vt | scripts/scan_results.py | Python | gpl-2.0 | 4,423 | 0 | #!/usr/bin/env python
"""
Script to fetch test status info from sqlit data base. Before use this
script, avocado We must be lanuch with '--journal' option.
"""
import os
import sys
import sqlite3
import argparse
from avocado.core import data_dir
from dateutil import parser as dateparser
def colour_result(result):
... | cur.execute("select tag, time, action, status from test_journal")
while True:
# First record contation start info, second contain end info
# merged start info and end info into one record.
data = cur.fetchmany(2)
if not data:
break
... | e = None
end_str = None
elapsed = None
start_time = dateparser.parse(data[0][1])
start_str = start_time.strftime("%Y-%m-%d %X")
if len(data) > 1:
status = "Finshed"
result = data[1][3]
end_time = dateparser.parse... |
mpreisler/scap-security-guide-debian | scap-security-guide-0.1.21/shared/modules/xccdf2csv_stig_module.py | Python | gpl-2.0 | 1,883 | 0.002124 | #!/usr/bin/python
import sys
import csv
import lxml.etree as ET
# This script creates a CSV file from an XCCDF file formatted in the
# structure of a STIG. This should enable its ingestion into VMS,
# as well as its comparison with VMS output.
xccdf_ns = "http://checklists.nist.gov/xccdf/1.1"
disa_cciuri = "http://... |
def node_to_text(node):
textslist = node.xpath(".//text()")
return ''.join(textslist)
def main():
if len(sys.argv) < 2:
print "Provide an XCCDF file to convert into a CSV file."
sys.exit(1)
xccdffile = sys.argv[1]
xccdftree = parse_xml_file(xccdffile)
rules = xccdftree.finda... | for rule in rules:
cci_refs = [ref.text for ref in rule.findall("{%s}ident[@system='%s']"
% (xccdf_ns, disa_cciuri))]
srg_refs = [ref.text for ref in rule.findall("{%s}ident[@system='%s']"
% (xccdf_... |
ReproducibleBuilds/diffoscope | diffoscope/presenters/html/html.py | Python | gpl-3.0 | 30,030 | 0.001632 | # -*- coding: utf-8 -*-
#
# diffoscope: in-depth comparison of files, archives, and directories
#
# Copyright © 2014-2015 Jérémy Bobbio <lunar@debian.org>
# © 2015 Reiner Herrmann <reiner@reiner-h.de>
# © 2 | 012-2013 Olivier Matz <zer0@droids-corp.org>
# © 2012 Alan De Smet <adesmet@cs.wisc.edu>
# © 2012 Sergey Satskiy <sergey.satskiy@gmail.com>
# © 2012 scito <info@scito.ch>
#
#
| # diffoscope 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.
#
# diffoscope is distributed in the hope that it will be useful,
# but WI... |
phenopolis/phenopolis | tests/test_my_patients.py | Python | mit | 2,878 | 0.009382 | # Uncomment to run this module directly. TODO comment out.
#import sys, os
#sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
# End of uncomment.
import unittest
import subprocess
import runserver
from flask import Flask, current_app, jsonify
from views import neo4j_driver
from views import my_patients
fr... | ] = 'test_users'
self.app = runserver.app.test_client()
#helper.create_neo4j_demo_user()
helper.login(self.app)
helper.my_patients_neo4j_data()
def tearDown(self):
self.app.get('/logout', follow_redirects=True)
def test_my_patients_page(self):
page = self.app... | def test_my_patients_functionality(self):
app = Flask(__name__)
with app.test_request_context():
records = my_patients.get_individuals('demo')
# Here we create the Flask Response object, containing json,
# that the /my_patients page receives. We then test
... |
pomegranited/edx-platform | lms/djangoapps/course_api/serializers.py | Python | agpl-3.0 | 3,293 | 0.001518 | """
Course API Serializers. Representing course catalog data
"""
import urllib
from django.core.urlresolvers import reverse
from django.template import defaultfilters
from rest_framework import serializers
from lms.djangoapps.courseware.courses import course_image_url, get_course_about_section
from xmodule.course_... | zer for Course objects
| """
course_id = serializers.CharField(source='id', read_only=True)
name = serializers.CharField(source='display_name_with_default')
number = serializers.CharField(source='display_number_with_default')
org = serializers.CharField(source='display_org_with_default')
description = serializers.Serial... |
ddico/odoo | addons/l10n_ch/models/account_invoice.py | Python | agpl-3.0 | 11,966 | 0.005265 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import re
from odoo import models, fields, api, _
from odoo.exceptions import ValidationError, UserError
from odoo.tools.float_utils import float_split_str
from odoo.tools.misc import mod10r
l10n_ch_ISR_NUMBER_LENGTH ... | ner_bank_id.l10n_ch_isr_subscription_chf
| else:
#we don't format if in another currency as EUR or CHF
continue
if isr_subscription:
isr_subscription = isr_subscription.replace("-", "") # In case the user put the -
record.l10n_ch_isr_subscription = _f... |
damiencalloway/djtut | mysite/polls/admin.py | Python | mit | 570 | 0.014035 | from django.contrib import admin
from pol | ls.models import Choice, Poll
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
class PollAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlin... | ate'
admin.site.register(Poll, PollAdmin)
|
Pennapps-XV/backend | root/parse-server.py | Python | gpl-3.0 | 2,081 | 0.005766 | import json
import sys
import requests
from collections import Counter
from wapy.api import Wapy
from http.server import BaseHTTPRequestHandler, HTTPServer
wapy = Wapy('frt6ajvkqm4aexwjksrukrey')
def removes(yes):
no = ["Walmart.com", ".", ","]
for x in no:
yes = yes.replace(x, '')
return yes
def... | ne.split(' ')
for word in line:
large.append(word)
#print(large)
c = Counter(large).most_common( | )
keywords = []
for x in c:
if x[1] > threshold:
keywords.append(x[0])
print(keywords)
return ' '.join(keywords)
def parse_wallmart(keywords):
products = wapy.search(' '.join(keywords))
out = {}
out['name'] = products[0].name
out['rating'] = products[0].customer_ra... |
nafitzgerald/allennlp | allennlp/modules/elmo.py | Python | apache-2.0 | 18,830 | 0.002921 | import json
from typing import Union, List, Dict, Any
import torch
from torch.autograd import Variable
from torch.nn.modules import Dropout
import numpy
import h5py
from overrides import overrides
from allennlp.common.file_utils import cached_path
from allennlp.common.checks import ConfigurationError
from allennlp.c... | vant section of the options file is something like:
.. example-code::
| .. code-block:: python
{'char_cnn': {
'activation': 'relu',
'embedding': {'dim': 4},
'filters': [[1, 4], [2, 8], [3, 16], [4, 32], [5, 64]],
'max_characters_per_token': 50,
'n_characters': 262,
'n_highway': 2
... |
tomsilver/nupic | examples/opf/tools/MirrorImageViz/mirrorImageViz.py | Python | gpl-3.0 | 7,336 | 0.023719 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | ap = max([len(seen[m][1].intersection(y[4])) for m in xr | ange(len(seen))])
cellOverlap = max([len(seen[m][0].intersection(y[1])) for m in xrange(len(seen))])
for m in xrange( len(seen) ):
if len(seen[m][1].intersection(y[4]))==inputOverlap:
closestInputs.append(seen[m][2])
if len(seen[m][0].intersection(y[1]))==cellOverlap:
clo... |
vesche/HotC | old/server_proto.py | Python | unlicense | 1,750 | 0 | #
# HotC Server
# CTN2 Jackson
#
import socket
def _recv_data(conn):
data = conn.recv(1024)
command, _, arguments = data.partition(' ')
return command, arguments
def game(conn):
print 'success'
def login_loop(conn):
while True:
command, arguments = _recv_data(conn)... | with open('login.d', 'w') as f:
f.write(str(logins))
conn.se | nd('register_success')
def main():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('0.0.0.0', 1337))
sock.listen(5)
while True:
conn, addr = sock.accept()
login_loop(conn)
game(con... |
ashh87/caffeine | caffeine/core.py | Python | gpl-3.0 | 20,950 | 0.008497 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2009 The Caffeine Developers
#
# 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... | r "DPMS".
self.screensaverAndPowersavingType = None
# Set to True when the detection routine is in progress
self.attemptingToDetect = | False
self.dbusDetectionTimer = None
self.dbusDetectionFailures = 0
# Set to True when sleep seems to be prevented from the perspective of the user.
# This does not necessarily mean that sleep really is prevented, because the
# detection routine could be in progress.
s... |
sargas/scipy | scipy/ndimage/interpolation.py | Python | bsd-3-clause | 25,990 | 0.001578 | # Copyright (C) 2003-2005 Peter J. Verveer
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following d... | T OF SUBSTITUTE
# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT | OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from __future__ import division, print_function, absolute_import
import math
import numpy
from . import _ni_support
from . import _nd_image
__all__ = ['spline_filter1d', 'spline_filter', 'geometric_transform',
'map_coordinat... |
Yordan92/Pac-man-multiplayer | MakeGraph.py | Python | gpl-3.0 | 3,015 | 0.038143 | import pygame
from PacManMap import *
class MakeGraph:
def __init__(self):
self.shortest_path_from_one_to_other = {}
self.nodes = self.find_nodes()
def get_shortest_path(self):
return self.shortest_path_from_one_to_other
def get_nodes(self):
return self.nodes
def find_nodes(self):
nodes = []
for row... | 1] != 0):
if ((row_n > 0 and Map1[row_n - 1][col_n] != 0) or
(row_n < len(Map1[0]) - 2 and Map1[row_n + 1][col_n] != 0)):
nodes.append((col_n, row_n))
Map[col_n][row_n] = 3
return nodes
def is_p_vertex(self, vertex):
if ((vertex[0] < 0 or vertex[0] >= len(Map)) or
(vertex[1] < 0 ... | alse
return True
def bfs(self, vertex):
Path_all_in_Matrix = {}
Path_all_in_Matrix[vertex] = vertex
Path_to_Nodes = {}
Path_to_Nodes[vertex] = vertex
queue = [vertex]
Visited = [vertex]
all_Nodes = self.find_nodes()
all_Nodes.remove(vertex)
while queue != []:
new_v = queue.pop(0)
new_v_adj =... |
MyRobotLab/pyrobotlab | home/kwatters/harry/gestures/cyclegesture2.py | Python | apache-2.0 | 481 | 0.079002 | def cyclegesture2():
##for x in range( | 5):
welcome()
sleep(1)
relax()
sleep(2)
fingerright()
sleep(1)
isitaball()
sleep(2)
removeleftarm()
sleep(2)
handdown()
sleep(1)
fullspeed()
i01.giving()
sleep(5)
removeleftarm()
sleep(4)
takeball()
sleep(1)
surrender()
sleep(6)
isitaball()
sleep(6)
dropit()
sleep(2)
... | leep(5)
i01.disable()
|
lzanuz/django-watermark | setup.py | Python | bsd-3-clause | 1,660 | 0.001205 | import os
from setuptools import setup, find_packages
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.j | oin(os.path.abspath(__file__), os.pardir)))
from watermarker import __vers | ion__
setup(
name='django-watermark',
version=__version__,
packages=find_packages(exclude=['example']),
include_package_data=True,
license='BSD License',
description="Quick and efficient way to apply watermarks to images in Django.",
long_description=README,
keywords='django, watermark,... |
Alidron/alidron-isac | isac/transport/pyre_node.py | Python | mpl-2.0 | 6,714 | 0.00134 | # Copyright (c) 2015-2020 Contributors as noted in the AUTHORS file
#
# 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/.
# System imports
import json
import logging
import... | elf._running = True
self.start()
while self._running:
try:
# logger.debug('Polling')
| items = dict(self.poller.poll(timeout))
# logger.debug('polled out: %s, %s', len(items), items)
while len(items) > 0:
for fd, ev in items.items():
if (self.inbox == fd) and (ev == zmq.POLLIN):
self._process_mes... |
hehongliang/tensorflow | tensorflow/python/training/checkpointable/util_test.py | Python | apache-2.0 | 72,153 | 0.005502 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | n.ops import variables
from tensorflow.python.training import adam
from tensorflow.python.training import checkpoint_management
from tensorflow.python.training import momentum
from tensorflow.python.training import saver as saver_lib
from tensorflow.python.training import training_util
from tensorflow.python.training.c... | as checkpointable_utils
class NonLayerCheckpointable(tracking.Checkpointable):
def __init__(self):
super(NonLayerCheckpointable, self).__init__()
self.a_variable = checkpointable_utils.add_variable(
self, name="a_variable", shape=[])
# pylint: disable=not-callable
class MyModel(training.Model):
... |
sysadminmatmoz/ingadhoc | account_invoice_commercial/__init__.py | Python | agpl-3.0 | 366 | 0 | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# | directory
##############################################################################
from . | import account_invoice
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
kutu/pyirsdk | setup.py | Python | mit | 783 | 0 | #!python3
from setuptools import setup
from irsdk import VERSION
setup(
name='pyirsdk',
version=VERSION,
description='Python 3 implementation of iRacing SDK',
author='Mihail Latyshov',
author_email='kutu182@gmail.com',
url='https://github.com/kutu/pyirsdk',
py_modules=['irsdk'],
licens... | rating System :: Microsoft :: Windows',
'Program | ming Language :: Python :: 3.7',
'Topic :: Utilities',
],
entry_points={
'console_scripts': ['irsdk = irsdk:main'],
},
install_requires=[
'PyYAML >= 5.3',
],
)
|
OpenTSDB/tcollector | collectors/0/riak.py | Python | lgpl-3.0 | 5,780 | 0.000519 | #!/usr/bin/env python
# This file is part of tcollector.
# Copyright (C) 2013 The tcollector Authors.
#
# 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 3 of the License, o... | otal
- riak.memory.allocated
- riak.executing_mappers
- riak.sys_process_count
- riak.read_repairs
- riak.connections
- riak.connected_node | s
"""
import json
import os
import sys
import time
from collectors.etc import riak_conf
from collectors.lib import utils
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
CONFIG = riak_conf.get_default_config()
MAP = {
'vnode_gets_total': ('vnode.requests', 'type=g... |
privacyidea/privacyidea | privacyidea/api/audit.py | Python | agpl-3.0 | 4,483 | 0.002903 | # -*- coding: utf-8 -*-
#
# http://www.privacyidea.org
# (c) cornelius kölbel, privacyidea.org
#
# 2018-11-21 Cornelius Kölbel <cornelius.koelbel@netknights.it>
# Remove the audit log based statistics
# 2016-12-20 Cornelius Kölbel <cornelius.koelbel@netknights.it>
# Restrict download to certain ti... | you can redistribute it and/or
# modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
# License as published by the Free Software Foundation; either
# version 3 of the License, or any later version.
#
# This code is distributed in the hope that it will be useful,
# but W | ITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU AFFERO GENERAL PUBLIC LICENSE for more details.
#
# You should have received a copy of the GNU Affero General Public
# License along with this program. If not, see <http://www.gnu.org/license... |
OpenChemistry/avogadrolibs | avogadro/qtplugins/scriptfileformats/formatScripts/zyx.py | Python | bsd-3-clause | 2,841 | 0.001408 | """
/******************************************************************************
This source file is part of the Avogadro project.
Copyright 2013 Kitware, Inc.
This source code is released under the New BSD License, (the "License").
Unless required by applicable law or agreed to in writing, software
di... | "files with reversed coordinates. Demonstrates " +\
"the implementation of a user-scripted file format."
metaData['fileExtensions'] = ['zyx']
metaData['mimeTypes'] = [ | 'chemical/x-zyx']
return metaData
def write():
result = ""
# Just copy the first two lines: numAtoms and comment/title
result += sys.stdin.readline()
result += sys.stdin.readline()
for line in sys.stdin:
words = line.split()
result += '%-3s %9.5f %9.5f %9.5f' %\
(... |
miiila/hungry-in-karlin | decide.py | Python | mit | 218 | 0 |
import random
from subprocess import call
import ya | ml
with open('./venues.yml') as f:
venues = yaml.load(f)
venue = random.choice(venues)
pri | nt(venue['name'])
print(venue['url'])
call(['open', venue['url']])
|
dipapaspyros/bdo_platform | query_designer/migrations/0013_remove_query_dataset_query.py | Python | mit | 405 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-07-19 14:51
from __future__ import unicode_li | terals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('query_designer', '0012_query_dataset_query') | ,
]
operations = [
migrations.RemoveField(
model_name='query',
name='dataset_query',
),
]
|
dsparrow27/zoocore | zoo/libs/pyqt/errors.py | Python | gpl-3.0 | 777 | 0.002574 | from widgets import messagebox as msg
class QtBaseException(Exception):
"""
Custom Exception base class used to handle exception with our on subset of options
"""
def __init__(self, message, displayPopup=False, *args):
"""initializes the exception, use cause to di | splay the cause of the exception
:param message: The exception to display
:param cause: the cause of the error eg. a variable/class etc
:param args: std Exception args
"""
self.message = message
if displayPopup:
self.showDialog()
super(self.__class__... | setText(self.message)
messageBox.exec_()
|
ethanbao/artman | artman/tasks/requirements/ruby_requirements.py | Python | apache-2.0 | 1,142 | 0 | # Copyright 2016 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 agree... | anguage governing permissions and
# limitations under the License.
"""Requirements for Ruby codegen."""
from artman.tasks.requirements import task_requirement_base
class RubyFormatRequirements(task_requirement_base.TaskRequirementBase):
@classmethod
def require(cls):
return ['rubocop']
@classm... | .TaskRequirementBase):
@classmethod
def require(cls):
return ['rake']
@classmethod
def install(cls):
# Intentionally do nothing
pass
|
PIVX-Project/PIVX | test/functional/rpc_bind.py | Python | mit | 6,476 | 0.004324 | #!/usr/bin/env python3
# Copyright (c) 2014-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test running pivxd with the -rpcbind and -rpcallowip options."""
import sys
from test_framework.netut... | assert_equal,
assert_raises_rpc_error,
get_datadir_path,
get_rpc_proxy,
rpc_port,
rpc_url
)
class RPCBindTest(PivxTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.bind_to_localhost_only = False
self.num_nodes = 1
def setup_network(sel... | m_nodes, None)
def add_options(self, parser):
parser.add_option("--ipv4", action='store_true', dest="run_ipv4", help="Run ipv4 tests only", default=False)
parser.add_option("--ipv6", action='store_true', dest="run_ipv6", help="Run ipv6 tests only", default=False)
parser.add_option("--nonloo... |
repotvsupertuga/tvsupertuga.repository | script.module.streamtvsupertuga/lib/resources/lib/sources/en_torrents/__init__.py | Python | gpl-2.0 | 199 | 0.01005 | # -*- coding: utf-8 -*-
i | mport os.path
files = os.listdir(os.path.dirname(__file__))
__all__ = [filename[:-3] for filename in files if not filename.startswith('__') and filename.endswith('.py')]
| |
GabrielBrascher/cloudstack | test/integration/component/test_multiple_nic_support.py | Python | apache-2.0 | 24,109 | 0.00141 | # 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... | = random.randrange(90, 99)
cls.testdata["shared_network_sg"]["name"] = "Shared-Network | -SG-Test-vlan" + str(random_subnet_number)
cls.testdata["shared_network_sg"]["displaytext"] = "Shared-Network-SG-Test-vlan" + str(random_subnet_number)
cls.testdata["shared_network_sg"]["vlan"] = "vlan://" + str(random_subnet_number)
cls.testdata["shared_network_sg"]["startip"] = "192.168." + st... |
Gab-km/papylon | tests/test_gen.py | Python | mit | 4,520 | 0.002434 | def test_gen_generate_returns_generated_value():
from papylon.gen import Gen
def gen():
while True:
yield 1
sut = Gen(gen)
actual = sut.generate()
assert actual == 1
def test_such_that_returns_new_ranged_gen_instance():
from papylon.gen import choose
gen = choose(-20,... | from papylon.gen import choose
try:
choose(-1, -1)
except ValueError:
assert True
return
assert False
def test_when_choose_takes_arguments_where_min_value_is_float_then_returns_gen_instance_which_generates_float_value():
from papylon.gen import choose
sut = choose(-2.0,... | == float
assert -2.0 <= actual <= 2.0
def test_when_choose_takes_arguments_where_max_value_is_float_then_returns_gen_instance_which_generates_float_value():
from papylon.gen import choose
sut = choose(-5, 10.0)
actual = sut.generate()
assert type(actual) == float
assert -5.0 <= actual <= 10.0... |
ColtonProvias/pytest-watch | pytest_watch/watcher.py | Python | mit | 6,256 | 0.00016 | from __future__ import print_function
import os
import time
import subprocess
from colorama import Fore, Style
from watchdog.events import (
FileSystemEventHandler, FileModifiedEvent, FileCreatedEvent,
FileMovedEvent, FileDeletedEvent)
from watchdog.observers import Observer
from watchdog.observers.polling im... | self.run(sort | ed(set(summary)))
def on_any_event(self, event):
if isinstance(event, tuple(WATCHED_EVENTS)):
if self.spooler is not None:
self.spooler.enqueue(event)
else:
self.on_queued_events([event])
def run(self, summary=None):
"""Called when a file... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.