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
ftrader-bitcoinabc/bitcoin-abc
test/functional/wallet_dump.py
Python
mit
6,366
0.000785
#!/usr/bin/env python3 # Copyright (c) 2016-2019 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 dumpwallet RPC.""" import os from test_framework.test_framework import BitcoinTestFramework ...
# Skip them continue addr_keypath = comment.split(" addr=")[1] addr = addr_keypath.split(" ")[0] keypath = None if keytype == "inactivehdseed=1": # ensure the old master is still available ...
=1": # ensure we have generated a new hd master key assert hd_master_addr_old != addr hd_master_addr_ret = addr elif keytype == "script=1": # scripts don't have keypaths keypath = None els...
manevant/django-oscar
src/oscar/apps/promotions/models.py
Python
bsd-3-clause
11,554
0
from django.db import models from django.conf import settings from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _, pgettext_lazy from django.core.urlresolvers import reverse from django.contrib.contenttypes.models import ContentType from django.contrib.c...
object_id=self.id).count() keyword_count \ = KeywordPromotion.objects.filter(content_type
=ctype, object_id=self.id).count() return page_count + keyword_count @python_2_unicode_compatible class RawHTML(AbstractPromotion): """ Simple promotion - just raw HTML """ _type = 'Raw HTML' name = models.CharField(_("Name"), max_length=128) ...
deevarvar/myLab
baidu_code/bcoreapi/monitor/seq_info_collector.py
Python
mit
4,963
0.011582
#-*- coding=utf-8 -*- ''' @description: 影讯信息获取类。 @author: miliang<miliang@baidu.com> ''' import sys sys.path.append('../') import copy import urllib import urllib2 import json import hashlib import time import MySQLdb import redis import socket from monitor.settings import MODE,MYSQL,SEQ_INFO_FILE,RED...
me = SEQ_INFO_FILE try: self.redis = redis.Redis(REDIS_CONF['HOST'],REDIS_CONF['PORT'],REDIS_CONF['DB']) except: print
'Failed to connect to redis.' self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self.conn = '/home/map/miliang/new_api_auto_test/monitor/conn' try: self.sock.connect(self.conn) except: print 'Failed to connect to socket server(mysql up...
jberci/resolwe
resolwe/flow/executors/prepare.py
Python
apache-2.0
3,958
0.001011
""".. Ignore pydocstyle D400. ====================== Flow Executor Preparer ====================== Framework for the manager-resident executor preparation facilities. .. autoclass:: resolwe.flow.executors.prepare.BaseFlowExecutorPreparer :members: """ import logging import os from django.conf import settings f...
_testing logger = logging.getLogger(__name__) # pylint: disable=invalid-name class BaseFlowExecutorPreparer: """Represents the preparation functionality of the executor.""" def extend_settings(self, data_id, files, secrets): """Extend the settings the manager will serialize.
:param data_id: The :class:`~resolwe.flow.models.Data` object id being prepared for. :param files: The settings dictionary to be serialized. Keys are filenames, values are the objects that will be serialized into those files. Standard filenames are listed in ``re...
ninapavlich/scout-and-rove
scoutandrove/apps/sr/migrations/0001_initial.py
Python
mit
6,950
0.005324
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operati...
', blank=True)), ('description', models.TextField(null=True, blank=True)), ('created_by', models.ForeignKey(related_name='sr_test_created_by', on_delete=django.db.models.deletion.SET_NULL, blank=True, to=settings.AUTH_USER_MODEL, null=True)), ('modified_by', models.Foreig...
rue)), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='TestResult', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ...
alfredocdmiranda/challenge-cep
models.py
Python
gpl-3.0
782
0.005115
# -*- coding: utf-8 -*- from sqlalchemy import create_engine from sqlalchemy import Column, Integer, String,
UniqueConstraint from sqlalchemy.orm import s
essionmaker from sqlalchemy.ext.declarative import declarative_base engine = create_engine('sqlite:///challenge.sqlite', echo=False) Session = sessionmaker(bind=engine) session = Session() Base = declarative_base() class Endereco(Base): __tablename__ = "endereco" #id = Column(Integer, primary_key=True) ...
jinnykoo/wuyisj
tests/integration/catalogue/category_tests.py
Python
bsd-3-clause
10,192
0.000785
# -*- coding: utf-8 -*- from django import template from django.core.exceptions import ValidationError from django.test import TestCase from oscar.apps.catalogue import models from oscar.apps.catalogue.categories import create_from_breadcrumbs class TestCategory(TestCase): def setUp(self): self.products...
'Books > Fiction > Horror > Teen', 'Books > Fic
tion > Horror > Gothic', 'Books > Fiction > Comedy', 'Books > Non-fiction > Biography', 'Books > Non-fiction > Programming', 'Books > Childrens', ) for trail in breadcrumbs: create_from_breadcrumbs(trail) def render_template(self, template...
ukholiday94/Project
1stStep/client.py
Python
gpl-3.0
634
0.0347
import socket # Import socket module s = socket.s
ocket() # Create a socket object host = socket.gethostname() # Get local machine name port = 8082 # Reserve a port for your service. s.connect((host, port)) s.send("sen
d".encode()) check = s.recv(1024).decode() print(check) while True: if check == 'ok': f = open('tosend.png','rb') print ('Sending...') l = f.read(1024) while (l): s.send(l) l = f.read(1024) print ('Sending...') f.close() #s.send("endtrans".encode()) print ("Done Sending") s.shutdown(socket.S...
fwenzel/millimeter
apps/shortener/fields.py
Python
bsd-3-clause
709
0.009873
""" CharNullField from http://stackoverflow.com/questions/454436/unique-fields-that-allow-nulls-in-django/1934764#1934764 """ from django.db import models class CharNullField(models.CharField): description = "CharField that stores NULL but returns ''" def to_python(self, value): """return django-frien...
lue(self, value): """Save NULL in DB if field is empty"""
if value=="": return None else: return value #otherwise, just pass the value
VirusTotal/content
Packs/MalwareBazaar/Integrations/MalwareBazaar/MalwareBazaar.py
Python
mit
12,522
0.002316
import copy import demistomock as demisto # noqa: F401 from CommonServerPython import * # noqa: F401 QUERIES = { "tag": "get_taginfo", "signature": "get_siginfo", "file_type": "get_file_type", "clamav": "get_clamavinfo", "imphash": "get_imphash", "yara_rule": "get_yarainfo", "issuer_cn": ...
to MalwareBazaar.', 'illegal': 'The text you provided is not valid.' } VENDOR_NAME = 'MalwareBazaar' LIST_HEADERS = ['md5_hash', 'sha256_hash', 'sha1_hash', 'file_name', 'file_type', 'file_size', 'tags', 'first_seen', 'last_seen'] FILE_HEADERS = ['md5_hash', 'sha256_hash',
'sha1_hash', 'file_name', 'file_type', 'file_size', 'tags', 'first_seen', 'last_seen', 'signature', 'ssdeep', 'reporter', 'imphash', 'yara_rules_names'] class Client(BaseClient): def __init__(self, server_url, verify, proxy, headers, api_key): self.api_key = api_key super().__init_...
pawelmhm/scrapy
scrapy/pipelines/images.py
Python
bsd-3-clause
6,853
0.00073
""" Images Pipeline See documentation in topics/media-pipeline.rst """ import functools import hashlib from contextlib import suppress from io import BytesIO from itemadapter import ItemAdapter from scrapy.exceptions import DropItem, NotConfigured from scrapy.http import Request from scrapy.pipelines.files import Fi...
image_guid = hashlib.sha1(to_bytes(request.url)).hexdigest() return f'full/{image_guid}.jpg' def thumb_path(self, request, thumb_id, response=None, info=None): thumb_guid
= hashlib.sha1(to_bytes(request.url)).hexdigest() return f'thumbs/{thumb_id}/{thumb_guid}.jpg'
MediaMath/t1-python
run_acs.py
Python
apache-2.0
8,732
0.00126
# ! /usr/bin/env python from __future__ import print_function import random from terminalone import T1, filters from terminalone.utils import credentials from terminalone.vendor import six from terminalone.errors import AuthRequiredError from dotenv import load_dotenv import os dotenv_path = os.path.join(os.getcwd...
ts, tes
t_get_all, test_entity_get_save, test_full, test_limit, test_include, test_include_traversal, test_include_plural, test_include_multi, test_find, test_target_dimensions, test_permissions, test_picard_meta, test_report_meta, ...
mitdbg/modeldb
client/verta/tests/test_cli/test_repository.py
Python
mit
3,580
0
import os import pytest from click.testing import CliRunner from verta._cli import cli from verta._internal_utils import _config_utils pytest.skip("repository sub-CLI has been disabled", allow_module_level=True) class TestInit: def test_init(self): runner = CliRunner() with runner.isolated_fil...
config() as config: remotes = config['remotes'] remote = remotes[name] assert remote['url'] == url assert remote['branch'] == "master" def test_add_and_use_if_only(self): # TODO: create a new repo and use it name1 = "origin" ur...
url2 = "https://www.verta.ai/" runner = CliRunner() with runner.isolated_filesystem(): runner.invoke(cli, ['init']) runner.invoke(cli, ['remote', 'add', name1, url1]) with _config_utils.read_merged_config() as config: assert config['current-re...
bikash/h2o-dev
py2/testdir_single_jvm/test_parse_nfs.py
Python
apache-2.0
2,673
0.010475
import unittest, sys sys.path.extend(['.','..','../..','py']) import os import h2o2 as h2o import h2o_cmd, h2o_import as h2i, h2o_browse as h2b from h2o_test import find_file, dump_json, verboseprint expectedZeros = [0 for i in range(11)] CAUSE_FAIL = False def assertEqualMsg(a, b): assert a == b, "%s %s" % (a, b) ...
elf): h2o.check_sandbox_for_errors() @classmethod def setUpClass(cls): h2o.init() @classmethod def tearDownClass(cls): h2o.tear_down_cloud() def test_pars
e_nfs(self): print "run as user 0xcustomer on machine with nfs /mnt/0xcustomer-datasets/c1" tryList = [ ('iris2.csv', 'iris2.hex', 1, 30), ] for (csvFilename, hex_key, multiplyExpected, timeoutSecs) in tryList: importFolderPath = "/mnt/0xcustomer-datasets/c1" ...
jasonkuster/merge-bot
mergebot_frontend/views.py
Python
apache-2.0
3,308
0.002116
from mergebot_frontend import app from flask import abort, render_template, send_from_directory from mergebot_frontend.models import Poller, QueuedItem, WorkItemStatus @app.route("/") def index(): """Root handler for website; serves list of pollers. Returns: Index template with the list of active...
y.filter_by( project_name=proj, item_id=last_start.item_id, ).order_by(WorkItemStatus.timestamp).first() return render_template('project.html', poller=poller, queue=queue, active=activ
e) @app.route('/<proj>/<int:item_id>') def item(proj, item_id): """Item page handler, shows all work item updates for a work item. Args: proj: Project under which this work item lives. item_id: Unique identifier for this work item. For a pull request, PR #. Returns: Item temp...
celestian/simCTC
sctc.py
Python
mit
2,726
0.000367
import pyglet import tkinter WINDOW_WIDTH = 800 # x WINDOW_HEIGHT = 600 # y LEVEL = 6 # original was 4 X_SIZE = 2 * LEVEL Y_SIZE = 3 * LEVEL def get_resolution(): root = tkinter.Tk() return root.winfo_screenwidth(), root.winfo_screenheight() def get_position(x, y): return ((x // X_SIZE) * X_SIZE, ...
self.y)) def on_mouse_release(self, x, y, button, modifiers): if button == pyglet.window.mouse.LEFT: Rail(self.batch, get_position(self.x, self.y)) if __name__ == '__main__': window = AppWin(width=WINDOW_WIDTH, height=WINDOW_HE
IGHT) window.set_exclusive_mouse(True) window.set_mouse_visible(False) pyglet.app.run()
umitproject/openmonitor-desktop-agent
umit/icm/agent/Application.py
Python
gpl-2.0
19,850
0.009521
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 S2S Network Consultoria e Tecnologia da Informacao LTDA # # Author: Zhongjie Wang <wzj401@gmail.com> # Tianwei Liu <liutianweidlut@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the term...
############ #Add more condition to check login legal self.login(self.peer_info.Username,self.peer_info.Password, True) else: if self.use_gui: self.gtk_main.show_login() else: self.login_without_gui() ...
"" self.aggregator.available = False self.speer_by_manual.peer_communication() def login_without_gui(self): """ Users login without username or password """ username = False password = False if g_config.has_section("cre...
eddiedb6/ej
web/metadata/EJUIFinanceDebtTab.py
Python
mit
7,198
0.003056
{ # Financial Page - debt tab "uidFinanceTabDebtPanel": { W3Const.w3PropType: W3Const.w3TypePanel, W3Const.w3PropSubUI: [ "uidFinanceTabDebtQueryPanel", "uidFinanceTabDebtAddPanel" ] }, # Finance Page - debt tab, query "uidFinanceTabDebtQueryPanel": {...
3Const.w3ApiDataValue: W3Const.w3Session }] }], W3Const.w3PropEvent: { W3Const.w3EventClick: [ W3Const.w3PlaceHolder_1 ] } }, "uidDebtFilterAddButton": { W3Const.w3PropType: W3Const.w3TypeButton, W3Const.w3PropString: "s...
onst.w3EventClick: [ "W3HideUI('uidFinanceTabDebtQueryPanel')", "W3DisplayUI('uidFinanceTabDebtAddPanel')" ] } }, # Finance Page - debt tab, query, table "uidDebtTable": { W3Const.w3PropType: W3Const.w3TypeTable, W3Const.w3PropSubUI: [ ...
stdlib-js/stdlib
lib/node_modules/@stdlib/stats/base/dists/arcsine/ctor/benchmark/python/benchmark.scipy.py
Python
apache-2.0
5,040
0.002381
#!/usr/bin/env python # # @license Apache-2.0 # # Copyright (c) 2018 The Stdlib Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # ...
ations`: number of iterations # Examples ``` python pyt
hon> benchmark("random", "from random import random;", "y = random()", 1000000) ``` """ t = timeit.Timer(stmt, setup=setup) print_version() i = 0 while i < REPEATS: print("# python::" + name) COUNT[0] += 1 elapsed = t.timeit(number=iterations) print_results(iter...
kinglogxzl/rqalpha
build/lib/rqalpha/data/dtsk_python_interface/utility/normalization.py
Python
apache-2.0
958
0.005219
import numpy as np import copy from copy import deepcopy #normalize the list into range [-1,1] def linear_normalization(data): normalization = deepcopy(data) for index, datai in enumerate(normalization): datai = float(datai) normalization[index] = datai max = np.max(normalization) min =...
#normalize the list by substracting mean and divided by standard deviation (zscore) def z_score(data): normalization = deepcopy(data) average =
np.mean(normalization) std = np.std(normalization) for index, datai in enumerate(normalization): datai = (datai-average)/std normalization[index] = datai return normalization samplelist = [1, 2, 3, 4, 5] linearsample = linear_normalization(samplelist) zscoresample = z_score(samplelist)
DJMelonz/basic-blog
markdown/extensions/html_tidy.py
Python
bsd-3-clause
2,159
0.003705
#!/usr/bin/env python """ HTML Tidy Extension for Python-Markdown ======================================= Runs [HTML Tidy][] on the output of Python-Markdown using the [uTidylib][] Python wrapp
er. Both libtidy and uTidylib must be installed on your system. Note than any Tidy [options][] can be passed in as extension configs. So, for example, to output HTML rather than XHTML, set ``output_xhtml=0``. To indent the output, set ``indent=auto`` and to have Tidy wrap the output in ``<html>`` and ``<body>`` tags...
ns]: http://tidy.sourceforge.net/docs/quickref.html Copyright (c)2008 [Waylan Limberg](http://achinghead.com) License: [BSD](http://www.opensource.org/licenses/bsd-license.php) Dependencies: * [Python2.3+](http://python.org) * [Markdown 2.0+](http://www.freewisdom.org/projects/python-markdown/) * [HTML Tidy](http:/...
xingjian-f/Leetcode-solution
313. Super Ugly Number.py
Python
mit
751
0.031957
class Solution(object): def nthSuperUglyNumber(self, n, primes):
""" :type n: int :type primes: List[int] :rtype: int """ if n == 1: return 1 from heapq import heappop, heappush base = [(primes[i], 0, primes[i]) for i in range(len(primes))] ugly = [1] for i in range(n-1)
: while True: val, idx, p_base = heappop(base) if val <= ugly[-1]: heappush(base, (p_base*ugly[idx+1], idx+1, p_base)) else: break ugly.append(val) heappush(base, (p_base*ugly[idx+1], idx+1, p_base)) # print ugly return ugly[...
7kbird/chrome
chrome/common/extensions/docs/server2/servlet.py
Python
bsd-3-clause
4,151
0.012286
# Copyright 2013 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. class RequestHeaders(object): '''A custom dictionary impementation for headers which ignores the case of requests, since different HTTP libraries seem t...
(self): return repr(self._dict) class Request(object): '''Request data. ''' def __init__(self, p
ath, host, headers): self.path = path.lstrip('/') self.host = host.rstrip('/') self.headers = RequestHeaders(headers) @staticmethod def ForTest(path, host=None, headers=None): return Request(path, host or 'http://developer.chrome.com', headers or {}) def __repr__(self): return 'Request(path=...
dp7-PU/ECTools
CutTOA5File.py
Python
mit
1,054
0.000949
# This is a script to get part of the large TOA file data. import numpy as np # Define the start time of the TOA5 file tStartTOA5 = np.datetime64('2016-06-14 18:20:52.5') # Define time interval you would like to take from the TOA5 file tStart = np.datetime64('2016-06-18T00:00:00.0') tEnd = np.datetime64('2016-06-19T0...
/ 100 print iEnd # Open file to get lines lines = [] fileName = r"C:\Users\pdphy\Documents\20160601\TOA5_ts3_160627.dat" with open(fileName, 'r') as f: for i, line in enumerate(f): if i < 4: lines.append(
line) elif (i > iStart) & (i < iEnd): lines.append(line) #print i elif i > iEnd: break outputFile = r'\Users\pdphy\Documents\20160601\TOA5_ts3_160618.dat' with open(outputFile, 'w') as f: for line in lines: f.write(line)
wolverineav/horizon-bsn
horizon_bsn/bsndashboard/networktemplateassignment/panel.py
Python
apache-2.0
858
0.001166
# 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 t...
izon from horizon_bsn.bsn
dashboard import dashboard class Networktemplateassignment(horizon.Panel): name = _("Network Template Assignment") slug = "networktemplateassignment" dashboard.Bsndashboard.register(Networktemplateassignment)
ykaneko/neutron
neutron/plugins/ml2/config.py
Python
apache-2.0
1,496
0
# Copyright (c) 2013 OpenSt
ack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://
www.apache.org/licenses/LICENSE-2.0 # # Unless 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 per...
cgqyh/pyalgotrade-mod
testcases/quandl_test.py
Python
apache-2.0
8,579
0.002681
# PyAlgoTrade # # Copyright 2011-2015 Gabriel Martin Becedillas Ruiz # # 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 ap...
e(), None) def testDownloadAndParseDailyNoAdjClose(self): with common.TmpDir() as tmpPath: instrument = "ORCL" path = os.path.join(tmpPath, "quandl-daily-orcl-2013.csv") quandl.download_daily_bars("GOOG", "NASDAQ_ORCL", 2013, path, auth_token) bf = quandlfeed...
ent, path) bf.loadAll() self.assertEquals(bf[instrument][-1].getDateTime(), datetime.datetime(2013, 12, 31)) self.assertEquals(bf[instrument][-1].getOpen(), 37.94) self.assertEquals(bf[instrument][-1].getHigh(), 38.34) self.assertEquals(bf[instrument][-1].getL...
oysstu/pyopencl-in-action
ch14/rdft.py
Python
mit
3,847
0.00182
""" Listing 14.1: The discrete Fourier transform (for real numbers) """ import numpy as np import pyopencl as cl import utility import matplotlib.pyplot as plt NUM_POINTS = 2 ** 8 kernel_src = ''' __kernel void rdft(__global float *x) { int N = (get_global_size(0)-1)*2; int num_vectors = N/4; float X_real...
(arg); w_imag = sin(arg); input = vload4(i, x); X_real += dot(input, w_real); X_imag -= dot(input, w_imag); } barrier(CLK_GLOBAL_MEM_FENCE); if(get_global_id(0) == 0) { x[0] = X_real; } else if(get_global_id(0) == get_global_size(0)-1) { x[1] = X_real; } else {...
xt, create command queue and program dev = utility.get_default_device() context = cl.Context(devices=[dev]) queue = cl.CommandQueue(context, dev) # Build program in the specified context using the kernel source code prog = cl.Program(context, kernel_src) try: prog.build(options=['-Werror'], devices=[dev]) except: ...
jbassen/edx-platform
lms/djangoapps/instructor/management/commands/collect_student_forums_data.py
Python
agpl-3.0
1,826
0.002191
""" C
ommand to retrieve aggregated student forums data in a .csv """ import csv import optparse import os from django.core.management.base import BaseCommand, CommandError from opaque_keys import InvalidKeyError from opaque_keys.edx.locations import SlashSeparatedCourseKey from instructor.u
tils import collect_student_forums_data class Command(BaseCommand): """ Retrieve aggregated student forums data, write to .csv """ help = ('Usage: collect_course_forums_data <course_id> --output-dir=<output_dir>') args = '<course_id>' option_list = BaseCommand.option_list + ( optparse...
CDSP/zephserver
examples/zephserversettings.py
Python
gpl-3.0
2,360
0.008054
# -*- coding: utf-8 -*- ''' Copyright 2015 Centre de données socio-politiques (CDSP) Fondation nationale des sciences politiques (FNSP) Centre national de la recherche scientifique (CNRS) License This program is free software: you can redistribute it and/or modify it under the terms of the GNU Gene...
omhandler_service/RoomHandler', 'zephserver.service.socket_service/StartSocket', 'zephserver.service.django_session_service/ZephSession', ] TASKS_PATH = {
'TaskInterface':'zephserver.task.task_interface/TaskInterface', 'TaskPing':'zephserver.task.task_ping/TaskPing', } CLUSTER_SERVER_LIST = [ { 'hostname' : 'zephserver', 'address' : 'localhost', 'port' : 22631 }, ] #fichier pour interdire le demarage de plusieurs serveur en meme temps LOCK_FILE...
sserrot/champion_relationships
venv/Lib/site-packages/qtpy/tests/test_qt3dinput.py
Python
mit
1,343
0.002234
from __future__ import absolute_import import pytest from qtpy import PYQT5, PYSIDE2 @pytest.mark.skipif(not (PYQT5 or PYSIDE2), reason="Only available in Qt5 bindings") def test_qt3dinput(): """Test the qtpy.Qt3DInput namespace""" Qt3DInput = pytest.importorskip("qtpy.Qt3DInput") assert Qt3DInput.QAxisA...
Input.QKeyboardDevice is not None assert Qt3DInput.QMouseDevice is not None assert Qt3DInput.QAxis is not None assert Qt3DInput.QInputChord is not None assert Qt3DInput.QMouseEvent is not None assert Qt3DInput.QKeyboardHandler is not None assert Qt3DInput.QKeyEvent is not None assert Qt3DInp...
rt Qt3DInput.QInputAspect is not None assert Qt3DInput.QLogicalDevice is not None assert Qt3DInput.QAction is not None assert Qt3DInput.QAbstractPhysicalDevice is not None assert Qt3DInput.QAxisSetting is not None
thegouger/django-quicksurvey
surveyapp/survey/views.py
Python
mit
1,774
0.019166
from django.http import HttpResponse from django.shortcuts import render from survey.models import Choice from survey.forms import ChoiceForm import csv import random # Create your views here. def index(request): examples = ['controlling Exposure', 'changing Temperature', 'modifying Highlights', 'changing Shadows...
nging the Constrast'] if request.method == 'POST': f = ChoiceForm(request.POST) if f.is_valid(): newChoice = f.save() if request.session.get('previous_responses', False): prev_response_array = request.session['previous_responses'] prev_response_array.appe
nd({'program':newChoice.program, 'text':newChoice.text}) request.session['previous_responses'] = prev_response_array else: request.session['previous_responses'] = [{'program':newChoice.program, 'text':newChoice.text}]; return render(request, 'index.html', {'previous':1, 'previous_responses'...
WikiWatershed/gwlf-e
test/unittests/test_UrbanRunoffLiter.py
Python
apache-2.0
753
0.005312
import numpy as np from .VariableUnitTest import VariableUnitTest from gwlfe.MultiUse_F
xns.Runoff import UrbRunoffLiter class TestUrbanRunoffLiter(VariableUnitTest): def test_UrbanRunoffLiter(self): z = self.z np.testing.assert_array_almost
_equal( UrbRunoffLiter.UrbRunoffLiter_f(z.NYrs, z.DaysMonth, z.InitSnow_0, z.Temp, z.Prec, z.NRur, z.NUrb, z.Area, z.CNI_0, z.AntMoist_0, z.Grow_0, z.CNP_0, z.Imper, z.ISRR, z.ISRA), UrbRunoffLiter.UrbRunoffLiter(z.NYrs, z.DaysMonth, z.InitSnow_0, z.Te...
louismerlin/merlin-hub
hub/multim/models.py
Python
mit
476
0.008403
from django.db import models class Photo(
models.Model): photo_text = models.CharField(max_length=200) image = models.ImageField() pub_date = models.DateTimeField('date published') def __str__(self): return self.photo_text class Comment(models.Model): photo = models.ForeignKey(Photo) comment_text = models.CharField(max_length=2...
rn self.comment_text
ProjectSWGCore/NGECore2
scripts/mobiles/dathomir/domesticated_brackaset.py
Python
lgpl-3.0
1,640
0.027439
import sys from services.spawn import MobileTemplate from services.spawn import WeaponTemplate from resources.datatables import WeaponType from resources.datatables import Difficulty from resources.datatables import Options from java.util import Vector def addTemplate(core): mobileTemplate = MobileTemplate() mobi...
ssistRange(12) mobileTemplate.setStalker(False) mobileTemplate.setOptionsBitmask(Options.ATTACKABLE) templates = Vector() templates.add('object/mobile/shared_brackaset_hue.iff') mobileTemplate.setTemplates(templates) weaponTemplates = Vector() weapontemplate = Weapon
Template('object/weapon/melee/unarmed/shared_unarmed_default.iff', WeaponType.UNARMED, 1.0, 6, 'kinetic') weaponTemplates.add(weapontemplate) mobileTemplate.setWeaponTemplateVector(weaponTemplates) attacks = Vector() attacks.add('bm_bite_4') attacks.add('bm_kick_4') attacks.add('bm_spit_4') mobileTemplate.setD...
tsilva/appier_scaffold
src/models/base.py
Python
apache-2.0
6,730
0.016642
#!/usr/bin/python # -*- coding: utf-8 -*- import re import time import uuid import calendar import datetime import threading import unidecode import appier import appier_extras LOCKS_MAP = {} """ Map with locks indexed by name """ class Base(appier_extras.admin.Base): id = dict( typ...
= "id" ), index = True ) description = dict( default = True ) @classmethod def _build(cls, model, map): appier_extras.admin.Base._build(model, map) enabled = model.get("enabled", None) model["status"] = enable
d and "enabled" or "disabled" @classmethod def lock_g(cls, name): model_name = cls.__name__ model_name_l = model_name.lower() lock_name = "%s_%s" % (model_name_l, name) lock = LOCKS_MAP.get(lock_name, threading.RLock()) lock.acquire() LOCKS_MAP[lock_name...
finnss/ttm4115-server
webserver/webapp/migrations/0001_initial.py
Python
mit
2,162
0.003238
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-31 00:07 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django.util
s.timezone class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Plant', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True
, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('upper_moisture_bound', models.IntegerField(default=100)), ('lower_moisture_bound', models.IntegerField(default=0)), ], ), migrations.CreateModel( n...
seem-sky/newspaper
newspaper/packages/jieba/__init__.py
Python
mit
11,308
0.016537
from __future__ import with_statement __version__ = '0.31' __license__ = 'MIT' import re import os import sys import finalseg import time import tempfile import marshal from math import log import random import threading from functools import wraps DICTIONARY = "dict.txt" DICT_LOCK = threading.RLock() trie = None # t...
turn wrapped def __cut_all(sentence): dag = get_DAG(sentence) old_j = -1 for k,L in dag.iteritems(): if len(L)==1 and k>old_j:
yield sentence[k:L[0]+1] old_j = L[0] else: for j in L: if j>k: yield sentence[k:j+1] old_j = j def calc(sentence,DAG,idx,route): N = len(sentence) route[N] = (0.0,'') for idx in xrange(N-1,-1,-1): cand...
sassoftware/conary
conary_test/recipes.py
Python
apache-2.0
40,164
0.002017
# # Copyright (c) SAS Institute 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 w...
self.ComponentSpec('user', '%(essentialsbindir)s/user') self.ComponentSpec('script', '%(essentialbindir)s/script') self.Strip(debuginfo=False) """ libhelloRecipeNoVersion = libhelloRecipePreface + """\ self.Run('%(cc)s %(ldflags)s -fPIC -shared -Wl,-soname,libhello.so -o libhello.so libhello.c...
lf.Install('libhello.so', '%(libdir)s/libhello.so', mode=0644) self.Install('true', '%(essentialsbindir)s/ldconfig', mode=0755) self.Install('user', '%(essentialsbindir)s/user', mode=0755) self.Create('/etc/ld.so.conf', contents='/lib') self.Create('%(essentialbindir)s/script', ...
jtpereyda/boofuzz
unit_tests/test_string.py
Python
gpl-2.0
8,751
0.003428
import itertools import math import unittest from collections import Counter, OrderedDict import pytest from boofuzz import * @pytest.fixture(autouse=True) def clear_requests(): yield blocks.REQUESTS = {} blocks.CURRENT = None class TestString(unittest.TestCase): def _given_string(self): s...
omkeys(list(map(fit_to_size, String._fuzz_library))), generator): n += 1 self.assertEqual(expected, uut.encod
e(actual)) for expected, actual in zip(String._variable_mutation_multipliers, generator): n += 1 self.assertEqual(fit_to_size(self.default_default_value * expected), uut.encode(actual)) if max_len <= len(self.default_default_value * expected): ...
justusc/Elemental
examples/interface/LSE.py
Python
bsd-3-clause
4,375
0.048914
# # Copyright (c) 2009-2015, Jack Poulson # All rights reserved. # # This file is part of Elemental and is under the BSD 2-Clause License, # which can be found in the LICENSE file in the root directory, or at # http://opensource.org/licenses/BSD-2-Clause # import El, time, random n0 = n1 = 50 numRowsB = 5 numRH...
: print "LSE time:", endLSE-startLSE, "seconds" if display: El.Display( X, "X" ) if output: El.Print( X, "X" ) E = El.DistMultiVec() El.Copy( C, E ) El.SparseMultiply( El.NORMAL, -1., A, X, 1., E ) residNorm = El.FrobeniusNorm( E ) if display: El.Display
( E, "C - A X" ) if output: El.Print( E, "C - A X" ) if worldRank == 0: print "|| C - A X ||_F / || C ||_F =", residNorm/CNorm El.Copy( D, E ) El.SparseMultiply( El.NORMAL, -1., B, X, 1., E ) equalNorm = El.FrobeniusNorm( E ) if display: El.Display( E, "D - B X" ) if output: El.Print( E, "D - B X" ) if worldRa...
WinawerLab/sco
sco/impl/benson17/__init__.py
Python
gpl-3.0
14,418
0.015467
#################################################################################################### # sco/impl/benson17/__init__.py # Implementation details of the SCO specific to the Benson et al. 2017 publications. # by Noah C. Benson ''' The sco.impl.benson17 namespace contains default values for all of the option...
divisive_normalization_parameters data-table; currently this is sco.impl.benson17.divisively_normalize_Heeger1992. ''' sat = sco.util.lookup_labels(labels, saturation_constants_by_label) rxp = sco.util.lookup_labels(labels, divisive_exponents_by_label) tr = {'heeger1992': '.divisivel...
sfreq': '.divisively_normalize_spatialfreq', 'square': '.divisively_normalize_Heeger1992_square', 'heeger1992_square': '.divisively_normalize_Heeger1992_square'} dns = divisive_normalization_schema.lower() return (_pimms.itable(saturation_constant=sat, divisive_exponen...
Manabu-GT/saucelabs-gradle-plugin
sample/appium/android_sauce_labs.py
Python
apache-2.0
1,447
0.00622
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Author : Manabu Shimobe """ __author__ = "Manabu Shimobe" from appium import webdriver from appium import SauceTestCase, on_platforms from time import sleep from logging import getLogger, StreamHandler, Formatter, DEBUG from os import environ import json # load de...
AVIS_COMMIT', environ.get('SAUCE_COMMIT')), 'versionName': environ.get('SAUCE_APK_VERSION_NAME'), 'versionCode': environ.get('SAUCE_APK_VERSION_CODE')} platform['build'] = "build-%s" % environ.get('TRAVIS_BUILD_NUMBER', 'local') json_file.close() # set up...
Level(DEBUG) logger.addHandler(handler) # the emulator is sometimes slow SLEEP_TIME = 1 @on_platforms(platforms) class AndroidSauceTests(SauceTestCase): def test_settings(self): sleep(SLEEP_TIME) # Check if successfully started MainActivity self.assertEqual('.MainActivity', s...
WarrenWeckesser/numpy
numpy/core/tests/test_einsum.py
Python
bsd-3-clause
44,838
0.001137
import itertools import numpy as np from numpy.testing import ( assert_, assert_equal, assert_array_equal, assert_almost_equal, assert_raises, suppress_warnings, assert_raises_regex, assert_allclose ) # Setup for optimize einsum chars = 'abcdefghij' sizes = np.array([2, 3, 4, 5, 4, 3, 2, 6, 5, 4, 3]) glob...
i] for i in range(3)]) b = np.einsum(a, [0, 0], [0], optimize=do_opt) assert_(b.base is a) assert_equal(b, [a[i, i] for i in range(3)]) # diagonal with various ways of broadcasting an additional dimension a = np.arange(27) a.shape = (3, 3, 3) ...
= np.einsum("...ii->...i", a, optimize=do_opt) assert_(b.base is a) assert_equal(b, [[x[i, i] for i in range(3)] for x in a]) b = np.einsum(a, [Ellipsis, 0, 0], [Ellipsis, 0], optimize=do_opt) assert_(b.base is a) assert_equal(b, [[x[i, i] for i in range(3)] ...
liyongyue/dnsspider
dns/rdtypes/IN/NSAP_PTR.py
Python
isc
889
0.001125
# Copyright (C) 2003-2005 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND ...
HETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import dns.rdtypes.nsbase class NSAP_PTR(dns.rdtypes.nsbase.UncompressedNS): """NSAP-
PTR record""" pass
skoczen/weexist
project/envs/live.py
Python
bsd-2-clause
451
0.002217
from envs.common import * DEBUG = False TEMPLATE_
DEBUG = DEBUG # EMAIL_BACKEND = 'django_ses.SESBackend' STATIC_URL = 'http://%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME COMPRESS_URL = STATIC_URL FAVICON_URL = "%sfavicon.ico" % STATIC_URL DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' STATICFILES_STORAGE = "backends.CachedS3BotoStorage" COMPRE...
vipullakhani/mi-instrument
mi/dataset/parser/zplsc_c.py
Python
bsd-2-clause
17,455
0.003094
#!/usr/bin/env python """ @package mi.dataset.parser.zplsc_c @file /mi/dataset/parser/zplsc_c.py @author Rene Gelinas @brief Parser for the zplsc_c dataset driver This file contains code for the zplsc_c parser and code to produce data particles. The ZPLSC sensor, series C, provides acoustic return measurements from ...
e averaged in time ('num_pings_burst', c_ushort), # 062
- Number of pings that have been acquired in this burst ('ping_period', c_ushort), # 064 - Ping period in seconds ('first_ping', c_ushort), # 066 - First ping number (if averaged, first averaged ping number) ('second_ping', c_ushort), # 068 - Last ping number (if aver...
inveniosoftware/invenio-oaiserver
tests/data/v5/__init__.py
Python
mit
253
0
# -*- coding: utf-8 -*- # # This file i
s part of Invenio. # Copyright (C) 2016-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE fil
e for more details. """Tests data."""
ivanalejandro0/cabinet
cabinet/auth.py
Python
gpl-2.0
2,708
0
#!/usr/bin/env python # -*- coding: utf-8 -*- import errno import os from nacl.exceptions import CryptoError from cabinet.person import Person def mkdir_p(path): """ Creates the path and all the intermediate directories that don't exist Might raise OSError :param path: path to create :type...
encrypted_data = b_encrypted_data.decode('u
tf-8') with open(filename, 'a') as f: f.write(encrypted_data) f.write('\n') def _get_vault_key(self, filename): # Cycle each line on the file until one can be decrypted with the given # decryptor b_decrypted_data = None with open(filename, 'r') as f:...
squared9/Robotics
Follow_Me-Semantic_Segmentation/code/utils/plotting_tools.py
Python
mit
6,172
0.006805
# Copyright (c) 2017, Udacity # 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. Redistributions of source code must retain the above copyright notice, this # list of conditions and the fol...
th.join(path, subset_name, 'images', '*.jpeg'))) def get_mask_files(path, subset_name): return sorted(glob.glob(os.path.join(path, subset_name, 'masks', '*.png'))) def get_pred_files(subset_name): return sorted(glob.glob(os.path.join('..','data', 'runs', subset_name, '*.png'))) def get_im_f...
ray(get_im_files(path, subset_name)) masks = np.array(get_mask_files(path, subset_name)) shuffed_inds = np.random.permutation(np.arange(masks.shape[0])) ims_subset = ims[shuffed_inds[:n_file_names]] masks_subset = masks[shuffed_inds[:n_file_names]] if not pred_dir_suffix: return list...
eduNEXT/edunext-platform
common/lib/capa/capa/tests/test_util.py
Python
agpl-3.0
6,792
0.00149
# coding=utf-8 """ Tests capa util """ import unittest import ddt from lxml import etree from capa.tests.helpers import test_capa_system from capa.util import ( compare_with_tolerance, contextualize_text, get_inner_html_from_xpath, remove_markup, sanitize_html ) @ddt.ddt class UtilTest(unittes...
t result = compare_with_tolerance(110.1, 100.0, '10.0', False) assert not result # Test relative t
olerance (string) result = compare_with_tolerance(111.0, 100.0, '0.1', True) assert result result = compare_with_tolerance(112.0, 100.0, '0.1', True) assert not result # Test absolute tolerance (float) result = compare_with_tolerance(109.9, 100.0, 10.0, False) ass...
Edgar324/GeoVis
geovismain/views.py
Python
apache-2.0
1,399
0.008578
from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from geovismain.models import Dataset, User from geovismain.serializer import UserSerializer from netCDF4 import Dataset import json, base64 from django.http.response import JsonResponse @api_...
rn Response(serializer.data) @api_view(['GET']) def data_value(request): if request.method == 'GET': # read the metadata rootgrp = Datas
et('E:/Data/00_24/info.nc', format='NETCDF4') xfLen = len(rootgrp.dimensions['xf']) yfLen = len(rootgrp.dimensions['yf']) rootgrp.close() # read the data file = open('E:/Data/00_24/mslp_mean/2002010200.mslp', 'rb') temp = file.read() file.close() ...
danielSbastos/gistified
migrations/versions/e424d03ba260_.py
Python
mit
652
0.001534
"""empty message Rev
ision ID: e424d03ba260 Revises: ace8d095a26b Create Date: 2017-10-12 11:25:11.775853 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'e424d03ba260' down_revision = 'ace8d095a26b' branch_labels = None depends_on = None def upgrade(): # ### commands auto gen...
## commands auto generated by Alembic - please adjust! ### op.drop_column('gist', 'lang') # ### end Alembic commands ###
Teagan42/home-assistant
homeassistant/components/zha/core/device.py
Python
apache-2.0
22,089
0.000543
""" Device for Zigbee Home Automation. For more details about this component, please refer to the documentation at https://home-assistant.io/integrations/zha/ """ import asyncio from datetime import timedelta from enum import Enum import logging import time from zigpy import types import zigpy.exceptions from zigpy.p...
@property def model(self): """Return model for device."""
if self._zigpy_device.model is None: return UNKNOWN_MODEL return self._zigpy_device.model @property def manufacturer_code(self): """Return the manufacturer code for the device.""" if self._zigpy_device.node_desc.is_valid: return self._zigpy_device.node_desc.manuf...
GoogleCloudPlatform/IoT-Icebreaker
appengine/pubsub-to-datastore/test_deploy.py
Python
apache-2.0
1,902
0.002629
#!/usr/bin/env python # 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...
or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and
# limitations under the License. """Test classes for the pubsub-to-datastore module.""" import os import time import unittest import urllib import json import sys sys.path.insert(1, 'lib') import httplib2 GAE_HOST = "pubsub-to-datastore-dot-cloud-iot-dev.appspot.com" def url_for(path): """Returns the URL o...
joaander/hoomd-blue
hoomd/hpmc/pytest/test_compute_sdf.py
Python
bsd-3-clause
8,801
0.000454
from __future__ import print_function from __future__ import division import hoomd import pytest import numpy as np import hoomd.hpmc.pytest.conftest def test_before_attaching(): xmax = 0.02 dx = 1e-4 sdf = hoomd.hpmc.compute.SDF(xmax=xmax, dx=dx) assert np.isclose(sdf.xmax, xmax) assert np.isclos...
7686, 0.89134056, 0.78446042, 0.8952503, 0.84624311, 0.79573064, 0.85422345, 0.88918562, 0.75531048,
0.82884413, 0.83369698, 0.77627999, 0.84187759, 0.87986859, 0.86356705, 0.90929237, 0.83017397, 0.86393341, 0.81426374, 0.80991068, 0.86676111, 0.75232448, 0.8021119, 0.68794232, 0.69039919, 0.71421068, 0.77667793, 0.82113389, 0.70256397, 0.83293526, 0.69512453, 0.75148262, 0.7407287, 0.74124134, 0....
BackupTheBerlios/kimchi
src/ui/mvc/model/KColumnModel.py
Python
bsd-3-clause
4,629
0.01361
# coding: utf-8 ''' Copyright (c) 2010, Alexandru Dancu All
rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions a
re met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other mater...
ThreatConnect-Inc/tcex
tcex/api/tc/v3/tags/tag.py
Python
apache-2.0
4,012
0.000499
"""Tag / Tags Object""" # standard library import json from typing import Optional, Union # first-party from tcex.api.tc.v3.api_endpoints import ApiEndpoints from tcex.api.tc.v3.object_abc import ObjectABC from tcex.api.tc.v3.object_collection_abc import ObjectCollectionABC from tcex.api.tc.v3.tags.tag_filter import T...
"" super().__init__(kwargs.pop('session', None)) # properties self._model = TagModel(**kwargs) self._nested_field_name = 'tags'
self._nested_filter = 'has_tag' self.type_ = 'Tag' @property def _api_endpoint(self) -> str: """Return the type specific API endpoint.""" return ApiEndpoints.TAGS.value @property def model(self) -> 'TagModel': """Return the model data.""" return self._model ...
blahu/pynet-mat
LearnPythonCourse/class7/ex4.py
Python
apache-2.0
58
0
#!/us
r/bin/env python # Class 7 # Exercise 4 # Author Mat
cleesmith/sentdex_scikit_machine_learning_tutorial_for_investing
p23.py
Python
mit
3,675
0.023673
# back testing import numpy as np import matplotlib.pyplot as plt from sklearn import svm, preprocessing import pandas as pd from matplotlib import style import statistics style.use("ggplot")
FEATURES = [ 'DE Ratio', 'Trailing P/E', 'Price/Sales', 'Price/Book', 'Profit Margin', 'Operating Margin', 'Return on Assets', 'Return on Equity', 'Revenue Per Share', 'Market Cap', 'Enterprise Value', 'Forward P/E', 'PEG Ratio', 'Enterprise Valu
e/Revenue', 'Enterprise Value/EBITDA', 'Revenue', 'Gross Profit', 'EBITDA', 'Net Income Avl to Common ', 'Diluted EPS', 'Earnings Growth', 'Revenue Growth', 'Total Cash', 'Total Cash Per Share', 'Total Debt', 'Current Ratio', 'Book Value Per Share', 'Cash Flow', 'Beta', 'Held by Insiders...
synergeticsedx/deployment-wipro
lms/djangoapps/django_comment_client/management/commands/sync_user_info.py
Python
agpl-3.0
622
0
""" One-off script to sync all user information to the discussion service (later info will be synced automatically) """ from django.core.management.base import BaseCommand from django.contrib.auth.models import User import lms.lib.comment_c
lient as cc class Command(BaseCommand): """ Management command for add
ing all users to the discussion service. """ help = 'Sync all user ids, usernames, and emails to the discussion service' def handle(self, *args, **options): for user in User.objects.all().iterator(): cc_user = cc.User.from_django_user(user) cc_user.save()
lqhuang/SAXS-tools
RAW/SASbuild_Clibs.py
Python
gpl-3.0
21,915
0.006297
#****************************************************************************** # This file is part of RAW. # # RAW 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 ...
W_LENGTH; int half_win_len; int hist_length; hist_length = PyObject_Length(py_hist); half_window_size = 15; data = (double *) qmatrix_array->data; /* Pointer to the numpy array version of qmatrix */ window_ptr = window; half_window_size = (WINDOW_LENGTH / 2.0); win_len = ...
len; x++) for( y = 0; y < ylen; y++) { rel_x = x-x_c; rel_y = y_c-y; r = int( std::sqrt((rel_y*rel_y) + (rel_x*rel_x)) ); //res(x,y) = r; if( r < high_q && r > low_q && mask(x,y) == 1) // && in_image(x,y) > 0) ...
giannitedesco/funky
funky/playerlist.py
Python
gpl-3.0
4,819
0.007885
import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk,Gdk from .plantlist import PlantList from funky.cards import cards
colors = ( Gdk.RGBA(0.22265625, 0.234375, 0.6484375), Gdk.RGBA(0.58984375, 0.20703125, 0.54296875), Gdk.RGBA(0.71484375, 0.70703125, 0.23828125), Gdk.RGBA(0.6171875, 0.171875, 0.19921875), Gdk.RGBA(0.34765625,
0.48046875, 0.42578125), Gdk.RGBA(0.60546875, 0.4609375, 0.2265625), ) class PlayerRow(Gtk.ListBoxRow): def __init__(self, p, prev = None): super(PlayerRow, self).__init__() vbox = Gtk.Box(orientation = Gtk.Orientation.VERTICAL, spacing = 5) self.add(vbox) ...
erazor83/libdynamixel
contrib/python-swig/examples/read_model.py
Python
gpl-2.0
398
0.042714
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys sys.path=['../']+sys.path import dynamixel ctx=dynamixel.dynamixel_new_rtu('/dev/ttyACM0', 1000000, 'E', 8, 1) con=dynamixel.dynamixel_connect(ctx) dynamixel.dynamixel_set_debug(ct
x,True) if con==0: for i in range(1,19): ret=dynamixel.dynamixel_read_data( ctx, i, dynamixel.DYNAMIXE
L_R_MODELNUMBER_L, 4 ) print(i,ret)
analyseuc3m/ANALYSE-v1
lms/djangoapps/course_api/blocks/tests/test_api.py
Python
agpl-3.0
3,474
0.002879
""" Tests for Blocks api.py """ from django.test.client import RequestFactory from course_blocks.tests.helpers import EnableTransformerRegistryMixin from student.tests.factories import UserFactory from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestC...
('chapter', 'chapter_y', False), ('sequential', 'sequential_x1', False), ): block = self.store.get_item(self.course.id.make_usage_key(block_type, block_name)) if is_inside_of_structure:
self.assertIn(unicode(block.location), blocks['blocks']) else: self.assertNotIn(unicode(block.location), blocks['blocks'])
pabell/pylcsim
lcpsd.py
Python
mit
5,329
0.010509
""" .. module:: lcpsd :synopsis: Generate signals from PSD models. .. moduleauthor:: Riccardo Campana <campana@iasfbo.inaf.it> """ import numpy as np import astropy.modeling.models from .psd_models import * def lcpsd(dt=1., nbins=65536, mean=0., rms=1., seed=None, models=None, phase_shift=None, time_shift=None, v...
lized to one standard deviation # 2. to "mean" mean and std. dev. = mean*rms # (where rms is the fractional rms) rate = (rate-avg)/std * mean * rms + mean if verbose: print("Generated curve: mean = {} std.dev = {} ".format(avg, std)) print("Rescaled curve: mean = {} std.dev = {}".fo...
np.mean(rate), np.std(rate))) return time, rate
rljacobson/Guru
guru/RunFlask.py
Python
mit
2,460
0.011382
#We don't use sagenb.notebook.run_notebook because we want the server in the same python environment as our app so we have access to the Notebook and Worksheet objects. ######### # Flask # ######### import os, random from guru.globals import GURU_PORT, GURU_NOTEB
OOK_DIR import sagenb.notebook.notebook as notebook from sagenb.misc.misc import find_next_available_port import flask_server.base as flask_base def startServer(notebook_to_use=None, open_browser=False, debug_mode=False): #notebook_directory = os.path.join(DOT_SAGENB, "sage_notebook.sagenb") #Setup the noteb...
otebook_directory) notebook_to_use.user_manager().add_user('admin', 'admin','rljacobson@gmail.com',force=True) notebook_to_use.save() #Write out changes to disk. notebook_directory = notebook_to_use._dir #Setup the flask app. opts={} opts['startup_token'] = '{0:x}'.format(random.randin...
TribeMedia/synapse
synapse/storage/end_to_end_keys.py
Python
apache-2.0
7,540
0
# -*- coding: utf-8 -*- # Copyright 2015, 2016 OpenMarket Ltd # # 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 applic
able law or agreed to in writing, software # distributed under the License is distributed on an
"AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from twisted.internet import defer from canonicaljson import encode_canonical_json import ujson as json from ._base import SQ...
marcocor/expert-finding
src/main/python/expertfinding/preprocessing/create_profile.py
Python
apache-2.0
1,232
0.003247
#!/usr/local/bin/python2.7 # encoding: utf-8 from __future__ import division from argparse import ArgumentParser import logging import sys from expertfinding import ExpertFinding from collections import Counter def main(): '''Command line options.''' parser = ArgumentParser() parser.add_argument("-n", "...
e", nargs="+", help="Names of people to profile") parser.add_argument("-s", "--storage_db", required=True, action="store", help="Storage DB file") args = parser.parse_args() exf = ExpertFinding(args.storage_db, False) for name in args.names: a_id = exf.author_id(name)[0] print a_id, exf...
_iaf(a_id)[:50]: years_freq = ", ".join("{}{}".format(y, "(x{})".format(freq) if freq > 1 else "") for y, freq in sorted(Counter(years).items(), key=lambda p: p[0])) print u"{} freq={:.1%} importance={:.2f} entity_rarity={:.2f} max_rho={:.3f} years={}".format(entity, freq, ef_iaf*100, iaf, max_r...
reanahub/reana-client
reana_client/validation/utils.py
Python
mit
3,953
0.002024
# -*- coding: utf-8 -*- # # This file is part of REANA. # Copyright (C) 2021, 2022 CERN. # # REANA is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """REANA client validation utilities.""" import sys from typing import Dict, NoReturn, ...
import validate_operational_options
from reana_commons.validation.utils import validate_reana_yaml, validate_workflow_name from reana_client.printer import display_message from reana_client.validation.compute_backends import validate_compute_backends from reana_client.validation.environments import validate_environment from reana_client.validation.para...
Ichag/openerp-server
openerp/workflow/wkf_expr.py
Python
agpl-3.0
4,082
0.00343
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the...
_actions_server = openerp.registry(cr.dbname)['ir.actions.server'] context = { 'active_model': model, 'active_id': id, 'active_ids': [id] } result = ir_actions_server.run(cr, uid, [activity['action_id']], context) return result def execute(cr, ident, workitem, activity): """ Evaluate the action spe...
ignal): """ Test if a transition can be taken. The transition can be taken if: - the signal name matches, - the uid is SUPERUSER_ID or the user groups contains the transition's group, - the condition evaluates to a truish value. """ if transition['signal'] and signal != transition...
andrebellafronte/stoq
stoqlib/gui/wizards/purchasewizard.py
Python
gpl-2.0
23,998
0.001
# -*- coding: utf-8 -*- # vi:si:et:sw=4:sts=4:ts=4 ## ## Copyright (C) 2005-2012 Async Open Source <http://www.async.com.br> ## All rights reserved ## ## 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 Softw...
elf, button): self._add_supplier() def on_supplier__content_changed(self, supplier): self.edit_supplier.set_sensitive(bool(self.supplier.get_selected())) def on_edit_supplier__clicked(self, button): self._edit_supplier() def on_open_date__validate(self, widget, date): if s...
ror( _("Open date must be set to today or " "a future date")) def on_expected_freight__validate(self, widget, value): if value < 0: return ValidationError(_(u'The expected freight value must be a ' 'positive number.')) cla...
glotaran/glotaran
glotaran/__init__.py
Python
gpl-3.0
577
0
# Glotaran package __init__.py from . import model, parameter,
io # noqa: F401 __version__ = '0.0.10' ParameterGroup = parameter.ParameterGrou
p read_parameter_from_csv_file = ParameterGroup.from_csv read_parameter_from_yml = ParameterGroup.from_yaml read_parameter_from_yml_file = ParameterGroup.from_yaml_file from .parse import parser # noqa: E402 read_model_from_yml = parser.load_yml read_model_from_yml_file = parser.load_yml_file import pkg_resources...
whiteclover/Medoly
t/template_managert.py
Python
apache-2.0
1,721
0
#!/usr/bin/env python # # Copyright 2016
Medoly # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or
agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import unittest from medoly.kanon.manage...
tonnrueter/pymca_devel
PyMca/ArraySave.py
Python
gpl-2.0
23,377
0.003764
#/*########################################################################## # Copyright (C) 2004-2012 European Synchrotron Radiation Facility # # This file is part of the PyMca X-ray Fluorescence Toolkit developed at # the ESRF by the Software group. # # This file is free software; you can redistribute it and/or modi...
" % 'PyMca' dtype = '<S%d' % len(txt) h5file.attrs.create(attr, txt, dtype=dtype) #if 'format_version' not in self.attrs and len(h5file) == 0: # h5file.attrs['format_version'] = __format_version__ return h5file def getHDF5FileInstanceAndBuffer(filename, shape, ...
interpretation=None, compression=None): if not HDF5: raise IOError('h5py does not seem to be installed in your system') if os.path.exists(filename): try: os.remove(filename) except: raise IOError("Cannot overwrite existing...
google-research/corenet
src/corenet/super_resolution.py
Python
apache-2.0
5,226
0.003444
# Copyright 2021 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, software # distributed under the License is distributed o...
he License for the specific language governing permissions and # limitations under the License. """Routines for building training and evaluation pipelines.""" import logging from typing import Tuple import torch as t from corenet import pipeline from corenet import state as state_lib from corenet.geometry import tra...
LuminosoInsight/langcodes
langcodes/language_lists.py
Python
mit
8,650
0.000116
# This is the list of language codes with the 'modern' level of support in CLDR # (compared to 'full', which contains many more languages). We use this as the # list of languages that we store specific name-to-code mappings for. CLDR_LANGUAGES = { 'af', 'am', 'ar', 'az', 'be', 'bg', 'bn', ...
"Quechua", "Mirandese", "Livonian", "Bengali", "Skolt Sami", # Proto-Balto-Slavic "Pitjantjatjara", "Georgian", "North Frisian", "Tetum", "Tongan
", # Mauritian Creole "Torres Strait Creole", "Papiamentu", "Lao", "Malagasy", "Interlingue", "Aragonese", "Istriot", "Sumerian", "Proto-Celtic", "Võro", # Proto-Polynesian "Nepali", "Chickasaw", "Akkadian", "Middle Armenian", "Cimbrian", "Somali",...
presidentielcoin/presidentielcoin
qa/rpc-tests/bipdersig-p2p.py
Python
mit
6,875
0.003927
#!/usr/bin/env python3 # Copyright (c) 2015-2016 The Presidentielcoin 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 Comparison
TestFramework from test_framework.util import * from test_framework
.mininode import CTransaction, NetworkThread from test_framework.blocktools import create_coinbase, create_block from test_framework.comptool import TestInstance, TestManager from test_framework.script import CScript from io import BytesIO import time # A canonical signature consists of: # <30> <total len> <02> <len ...
google-research/google-research
etcmodel/models/hotpotqa/data_utils.py
Python
apache-2.0
12,364
0.010676
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
he leader was John Smith (1895-1943). Answer: 1895 The original whitespace-tokenized answer will be "(1895-1943).". However after tokenization, our tokens
will be "( 1895 - 1943 ) .". So we can match the exact answer, 1895. The purpose of this function is to find such "better match". However, this is not always possible. Consider the following: Question: What country is the top exporter of electornics? Context: The Japanese electronics industry is the lag...
miltonruelas/cursotecnico
branch/l10n_pe_ple08/report/sunat_8_1_print.py
Python
agpl-3.0
2,003
0.002496
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (c) 2011 NUMA Extreme Systems (www.numaes.com) for Cubic ERP - Teradata SAC. (http://cubicerp.com). # # WARNING: This program as such is intended to be use...
# # This program is Free Software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # ...
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, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # ###################################################...
oudeismetis/missed-moment
export/usb.py
Python
mit
2,456
0.000407
from os import listdir from os.path import exists, expanduser, isfile import re from subprocess import CalledProcessError, check_call import logging from pyudev import Context, Monitor video_pattern = re.compile('missed-moment.*merged.*mp4') MEDIA_DIR = '/missed_moment_media' USB_MOUNT_DIR = '/missed_moment_usb' USB_...
, 'mount', device_name, expanduser(USB_MOUNT_DIR)]) # mk dir on usb if doesn't exist if not exists(USB_DIR): check_call(['sudo', 'mkdir', expanduser(USB_DIR)]) except CalledProcessError as e: logging.error(f'error: {e}') else: _copy_files() finally: check_...
ame], timeout=60) logging.info(f'USB {device_name} ejected') def main(): logging.basicConfig(level=logging.INFO) logging.info('starting missed-moment-usb') context = Context() monitor = Monitor.from_netlink(context) monitor.filter_by(subsystem='block', device_type='partition') mon...
ireaderlab/zkdash
lib/uimodule/query.py
Python
apache-2.0
1,160
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Copyright (c) 2015,掌阅科技 All rights reserved. 摘 要: query.py 创 建 者: WangLichao 创建日期: 2015-03-06 """ # pylint: disable=arguments-differ from tornado.web import UIModule OPERATOR = { 'like': '包含', '=': '等于', '!=': '不等于', '>': '大于', '>=': '大于等于', ...
def render(self, column, default_column, default_operator, time_flag=False): ''' Args: column: 数据库列字典 default_column: 默认列 operator: 操作字典 default_operator: 默认操作 time_flag: 输入为时间字段标记 ''' return self.render_string("...
r=default_operator, operator=OPERATOR, time_flag=time_flag)
oddbitdev/schelling_model
schelling.py
Python
mit
6,435
0.001399
import random import operator import copy from collections import Counter class Env(object): directions = [[1, -1], [1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1]] empty = 'empty' @classmethod def flatten_list(cls, ls): l = [] for el in ls: if isinstance(el, li...
o(self, l=None): return self.neighbors.get(l if l else self.label, 0) class World(object): def __init__(self, cols, rows, tiles): self.cols = cols self.rows = rows self.tiles_bucket = Env.flatten_list([[tile] * tile.d_weight for tile in tiles]) self.tiles = tiles se...
for col in range(cols): uid = Env.build_uid(col, row) tile_type = random.choice(self.tiles_bucket) tile = Tile(tile_type.label, tile_type.preference) tile.set_position(col, row) self.tilemap[uid] = tile self.update_tiles()...
jeremiah-c-leary/vhdl-style-guide
vsg/tests/process/test_rule_014.py
Python
gpl-3.0
1,153
0.004337
import os import unittest from vsg.rules import process from vsg import vhdlFile from vsg.tests import utils sTestDir = os.path.dirname(__file__) lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTest
Dir,'rule
_014_test_input.vhd')) lExpected = [] lExpected.append('') utils.read_file(os.path.join(sTestDir, 'rule_014_test_input.fixed.vhd'), lExpected) class test_process_rule(unittest.TestCase): def setUp(self): self.oFile = vhdlFile.vhdlFile(lFile) self.assertIsNone(eError) def test_rule_014(self)...
atomistic-machine-learning/SchNet
src/schnet/nn/layers/rbf.py
Python
mit
966
0
import numpy as np import tensorflow as t
f from .module import Module class RBFExpansion(Module): def __init__(self, low, high, gap, dim=1, name=None): self.low = low self.high = high self.gap = gap self.dim = dim xrange = high - low self.centers = np.linspace(low, high, int(np.ceil(xrange / gap))) ...
f.centers = self.centers[:, np.newaxis] self.n_centers = len(self.centers) self.fan_out = self.dim * self.n_centers super(RBFExpansion, self).__init__(name) def _forward(self, d): cshape = tf.shape(d) CS = d.get_shape() centers = self.centers.reshape((1, -1)).astype(...
MrLi008/mysimpledebugger
Gray_Hat_Python/src/simpledebugger/version001/__init__.py
Python
gpl-3.0
176
0.014493
''' This is version
001 about 程序最简单最粗糙的版本 my_debugger_defines.py # 数据结构 my_debu
gger.py # 功能 my_test_%.py # 测试 '''
djds23/jobs-board
migrations/versions/1a0db86d91f_initial_model_definitions.py
Python
bsd-3-clause
3,462
0.015309
"""Initial model definitions Revision ID: 1a0db86d91f Revises: None Create Date: 2014-04-04 01:10:20.064006 """ # revision identifiers, used by Alembic. revision = '1a0db86d91f' down_revision = None from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please a...
sa.String(length=255), nullable=False), sa.Column('password', sa.String(length=255), nullable=True), sa.Column('active', sa.Boolean(), nullable=True), sa.Column('confirmed_at', sa.DateTime(), nullable=True), sa.Column('last_login_at', sa.DateTime(), nullable=True), sa.Column('current_login_at', sa....
e), sa.Column('current_login_ip', sa.String(length=100), nullable=True), sa.Column('login_count', sa.Integer(), nullable=True), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('email'), sa.UniqueConstraint('password'), sa.UniqueConstraint('username') ) op.create_table('role', sa.C...
deevarvar/myLab
sprd/vowifi/mengine_parser/helper/call.py
Python
mit
9,784
0.004804
# -*- coding=utf-8 -*- # author: zhihua.ye@spreadtrum.com # define struct about vt call statistics # from lib.logConf import * from helper.excelhelper import * class Call: def __init__(self): self.time = dict() self.time['start'] = None # incoming/outgoing self.time['end'] =...
self.streamid = '' self.logger = logConf() class AudioCall(Call): def __init__(self): Call.__init__(self) # TODO: add audio stat later pass def dumpcall(self): pass class VtCall(Call): def __init__(self):
# if call __init__. should call __init__ Call.__init__(self) # video first sps, pps, key frame self.time['firstsps'] = '' self.time['firstpps'] = '' self.time['kframe'] = '' # camera info self.camerainfo = dict() self.camerainfo['cami...
chunchih/article-matching
word2vec-model/wiki_seg_jieba.py
Python
bsd-3-clause
1,035
0.010795
# -*- coding: utf-8 -*- import jieba import logging import io import codecs def main(): logging.basicCon
fig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) # jieba custom setting. jieba.set_dictionary('jieba_dict/dict.txt.big') # load stopwords set
stopwordset = set() with io.open('jieba_dict/stopwords.txt','r',encoding='utf-8') as sw: for line in sw: stopwordset.add(line.strip('\n')) texts_num = 0 output = codecs.open('wiki_seg.txt','w','utf8') with io.open('wiki_zh_tw.txt','r',encoding='utf-8') as content : for ...
cliffano/swaggy-jenkins
clients/python-legacy/generated/openapi_client/models/pipelinelatest_run.py
Python
mit
14,032
0
# coding: utf-8 """ Swaggy Jenkins Jenkins API clients generated from Swagger / Open API specification # noqa: E501 The version of the OpenAPI document: 1.1.2-pre.0 Contact: blah@cliffano.com Generated by: https://openapi-generator.tech """ try: from inspect import getfullargspec except Im...
organization of this PipelinelatestRun. # noqa: E501 :return: The organization of this PipelinelatestRun. # noqa: E501 :rtype: str """ return self._organization @organization.setter def organization(self, organization
): """Sets the organization of this PipelinelatestRun. :param organization: The organization of
eawag-rdm/resup
resup/resup.py
Python
agpl-3.0
25,324
0.004265
# -*- coding: utf-8 -*- import ckanapi import ckanapi.cli.progressbar as progressbar import requests import argparse import hashlib import tarfile import time import gzip import shutil import uuid import re import sys import os import io import stat import time import urllib3 import cPickle as pickle urllib3.disable_w...
hich is suited to ' 'describe heterogeneous sets of files.') pa_put.add_argument('--upload_empty', action='store_true',
help='upload empty files instead f the real resources.') pa_put.add_argument('--tmpdir', metavar='TMPDIR', type=str, default=os.curdir, help='The directory for temporary files, such as ' + 'checksums and parts of fi...
kennedyshead/home-assistant
homeassistant/components/azure_event_hub/__init__.py
Python
apache-2.0
8,280
0.001691
"""Support for Azure Event Hubs.""" from __future__ import annotations import asyncio import json import logging import time from typing import Any from azure.eventhub import EventData from azure.eventhub.aio import EventHubProducerClient, EventHubSharedKeyCredential from azure.eventhub.exceptions import EventHubErro...
that each send will schedule the next after the inter
val. self._next_send_remover = async_call_later(self.hass, 10, self.async_send) async def async_shutdown(self, _: Event): """Shut down the AEH by queueing None and calling send.""" if self._next_send_remover: self._next_send_remover() if self._listener_remover: ...
victorywang80/Maintenance
saltstack/src/salt/states/service.py
Python
apache-2.0
14,706
0.000204
# -*- coding: utf-8 -*- ''' Starting or restarting of services and daemons. =============================================== Services are defined as system daemons typically started with system init or rc scripts, services can be defined as running or dead. .. code-block:: yaml httpd: service: - run...
' service {0} started').format(name) return ret elif started is None: ret['comment'] = ('Disable is not available on this minion,' ' service {0} is in the desired state' ).format(name) return ret ...
' service {0} is dead').format(name) return ret # Service can be disabled if __salt__['service.disabled'](name): # Service is disabled if started is True: ret['changes'][name] = True ret['comment'] = ('Service {0} is already disabled,' ...
ethankennerly/as2cs
typographify/typographify.py
Python
mit
1,383
0.002169
from simpleparse.parser import Parser from sys import stdin, stdout, stderr from typo_html import codes def typographify(input): """ Run from parent directory. >>> import os >>> os.chdir('typographify') >>> print typographify(open('typographify.txt').read()) <strong>strong</strong> <em>words</...
'parsed %s chars of %s' % (taglist
[-1], len(input)) return text if '__main__' == __name__: input = stdin.read() stdout.write(typographify(input))
beobal/cassandra-dtest
stress_tool_test.py
Python
apache-2.0
2,137
0.002808
import pytest import logging from dtest import Tester from tools.data import rows_to_list since = pytest.mark.since logger = logging.getLogger(__name__) @since('3.0') class TestStressSparsenessRatio(Tester): """ @jira_ticket CASSANDRA-9522 Tests for the `row-population-ratio` parameter to `cassandra-st...
ec)]) session = self.patient_cql_connection(node) written
= rows_to_list(session.execute('SELECT * FROM keyspace1.standard1;')) num_nones = sum(row.count(None) for row in written) num_results = sum(len(row) for row in written) assert abs(float(num_nones) / num_results - expected_ratio) <= delta
cuauv/software
serial/seriald/configure.py
Python
bsd-3-clause
740
0.001351
#!/usr/bin/env python from build import ninja_common build = ninja_common.Build('serial/seriald') build.build_cmd( 'auv-seriald', [ 'main.cpp', 'config.cpp', 'device.cpp', 'device_list.cpp', 'sub_status.c
pp', ], deps=['nanomsg'], auv_deps=['shm', 'auvlog', 'auv-serial', 'fmt'],) #build.test_gtest( # 'seriald-new', # [ # 'config.cpp', # 'device.cpp', # 'device_list.cpp', # 'sub_status.cpp', # # 'test/config/config.cpp', #
# 'test/device/device.cpp', # ], # deps=['nanomsg', 'cppformat'], # auv_deps=['shm', 'auvlog', 'auv-serial'],)
cisco-openstack/tempest
tempest/common/utils/__init__.py
Python
apache-2.0
4,477
0
# Copyright (c) 2015 Hewlett-Pack
ard Development Company, L.P. # # 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...
RANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import functools from functools import partial import testtools from tempest import config from tempest.exceptions import InvalidServiceTag from t...
nzinov/maze
run_tests.py
Python
gpl-3.0
578
0
#!/bin/python3 from test.test import run_test from reader import read_field from sys impor
t exit import os failed = 0 run = 0 os.chdir("test/") for test_file in os.listdir(path='.'): if test_file.endswith(".test"): print("Running {}".format(test_file)) run += 1 if not run_test(test_file): failed += 1 os.chdir("../game_archive/") for field in os.listdir(path='.'): ...
read_field(field) print("Run {}, failed {}".format(run, failed)) if failed > 0: exit(1)
mscuthbert/abjad
abjad/tools/datastructuretools/test/test_datastructuretools_CyclicMatrix___init__.py
Python
gpl-3.0
1,618
0.000618
# -*- encoding: utf-8 -*- from abjad import * def test_datastructuretools_CyclicMatrix___init___01(): r'''Initializes from rows. ''' cyclic_matrix = datastructuretools.CyclicMat
rix(( (0, 1, 2, 3), (10, 11, 12, 13), (20, 21, 22, 23), )) assert cyclic_matrix.rows == \ ((0, 1, 2, 3), (10, 11, 12, 13), (20, 21, 22, 23)) assert cyclic_matrix.columns == \ ((0, 10, 20), (1, 11, 21), (2, 12, 22), (3, 13, 23)) def test_datastructuretools_Cycli...
cyclic_matrix = datastructuretools.CyclicMatrix(columns=( (0, 10, 20), (1, 11, 21), (2, 12, 22), (3, 13, 23), )) assert cyclic_matrix.rows == \ ((0, 1, 2, 3), (10, 11, 12, 13), (20, 21, 22, 23)) assert cyclic_matrix.columns == \ ((0, 10, 20), (1, 11, 2...
kevinah95/bmc-sequence-alignment
algorithms/needleman_wunsch/plot_nw.py
Python
mit
3,189
0.010982
import matplotlib.pyplot as plt import matplotlib.ticker as ticker import numpy as np import datetime from Bio.Seq import Seq if __name__ == '__main__': from needleman_wunsch import needleman_wunsch else: from .needleman_wunsch import needleman_wunsch #------------------------------- def plot_nw(seq_alpha_col,...
er", va="center", fontweight="semibold") for i, l in enumerate(headv): ax.text(-1, i + 1, l, ha="center", va="center", fontweight="semibold") ax.xaxis.set_minor_locator(ticker.FixedLocator( np.arange(-1.5, score_matrix.shape[1] - .5, 1))) ax.yaxis.set_minor_loca
tor(ticker.FixedLocator( np.arange(-1.5, score_matrix.shape[1] - .5, 1))) plt.tick_params(axis='both', which='both', bottom='off', top='off', left="off", right="off", labelbottom='off', labelleft='off') #-----------ax.set_aspect('auto') ax.grid(True, which='mino...