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
isaacyeaton/global-dyn-non-equil-gliding
Code/script_kinematic_squirrel.py
Python
mit
43,039
0.001928
# -*- coding: utf-8 -*- """ Created on Wed Aug 13 21:22:12 2014 %reset -f %pylab %clear %load_ext autoreload %autoreload 2 @author: isaac """ from __future__ import division import numpy as np import matplotlib.pyplot as plt import pandas as pd from scipy.interpolate import UnivariateSpline import time # to load a...
mport plots reload(plots) from plots import bmap, rcj, tl import squirrel reload(squirrel) import eqns reload(eqns) # %% Load in all squirrel data df = pd.read_excel('Data/Bahlman20
13/Bahlman rsif20120794supp2.xls', 'Sheet1') ntrials = int(len(df.columns) / 2) # %% Run through all trials, smooth, and make a bunch of plots fig1, ax1 = plt.subplots() fig11, (ax12, ax13) = plt.subplots(2, 1, sharex=True) fig2, ax2 = plt.subplots() fig3, ax3 = plt.subplots() fig4, ax4 = plt.subplots() fig5, ax5 = ...
Joshuacru/djsample
src/apps/notes/urls.py
Python
mit
312
0
from
django.conf.urls import url from .views import NewNoteView, NoteDetailView, NoteListView urlpatterns = [ url(r'^$', NewNoteView.as_view(), name='home'), url(r'^(?P<pk>\w+)/$', NoteDetailView.as_view(), name='note-detail'
), url(r'^public-notes/$', NoteListView.as_view(), name='public-notes') ]
mosajjal/mitmproxy
mitmproxy/contrib/kaitaistruct/jpeg.py
Python
mit
8,139
0.003563
# This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild # The source was jpeg.ksy from here - https://github.com/kaitai-io/kaitai_struct_formats/blob/24e2d00048b8084ceec30a187a79cb87a79a48ba/image/jpeg.ksy import array import struct import zlib from enum import Enum from kai...
parent self._root = _root if _root
else self self.id = self._root.ComponentId(self._io.read_u1()) self.sampling_factors = self._io.read_u1() self.quantization_table_id = self._io.read_u1() @property def sampling_x(self): if hasattr(self, '_m_sampling_x'): ...
kamagatos/django-compresshtml
compresshtml/middleware.py
Python
bsd-2-clause
515
0.001942
# Copyright 2012 django-compresshtml authors. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. from compresshtml import compress_html from django.conf import settings class CompressHtmlMiddleware(object): def process_response(self, request...
ponse): compress = getattr(settings, "COMPRESS_HTML", not settings.DEBUG) if compress: response.content = compress_html(response.content) retur
n response
zetasyanthis/myarchive
src/myarchive/db/db.py
Python
mit
3,698
0.000541
# @Author: Zeta Syanthis <zetasyant
his> # @Date: 2017/07/21 # @Email: zeta@zetasyanthis.org # @Project: MyArchive # @Last modified by: zetasyanthis # @Last modified time: 2017/07/21 # @License MIT """Generic database module using SQLAlchemy.""" import logging from sqlalchemy import create_engine, event from sqlalchemy.engine.url import URL as SQ...
ogging.getLogger(__name__) class DB(object): """Database linking files and tags.""" SQLITE_MEMORY_URL = 'sqlite:///:memory:' db_url = property(lambda self: self.__db_url, # pylint: disable=W0212 doc='Protected SQLAlchemy URL object.') engine = property(lambda self: self.__engi...
pymir3/pymir3
mir3/lib/naive_bayes.py
Python
mit
1,643
0.011564
import numpy import numpy.linalg def training(inputs, minvar=0.1): """Trains a naive-bayes classifier using inputs Returns means and variances of the classifiers """ return numpy.mean(inputs, axis=0), numpy.maximum(minvar, numpy.var(inputs, axis=0)) def gaussian(input, mu, sigma2): """Calculates ...
Each element should be in a row! """ out = numpy.ones(inputs.shape[0]) for j in xrange(inputs.shape[1]): if variances[j] != 0: out = out * \ (gaussian (inputs[:,j], means[j], variances[j])) return out def n
aive_bayes(test, train): """Implements the whole naive bayes flow. Returns a likelihood array """ m, v = training(train) return likelihood(test, m, v) def naive_bayes_multidimensional(test, train): """Naive bayes analysis keeping dimensions isolated """ m, v = training(train) out =...
jason-weirather/IDP
utilities/gtf2genepred.py
Python
apache-2.0
3,498
0.012864
#!/usr/bin/python import sys import os ################################################################################ if len(sys.argv) >= 2: gtf_filename = sys.argv[1] else: print("usage: python GTF2refFlat.py GTFfilename") print("or ./GTF2refFlat.py GTFfilename") sys.exit(1) #####################...
########################### print "start: gtf file" gtf = open(gtf_filename, 'r') gtf_dict = {} for line in gtf: if line[0] == "#": continue line_list = line.strip().split("\t") chr_name = line_list[0] feature = line_list[2] line_list[3]= int(line_list[3]) line_list[4]= int(line_list[4])...
nd = line_list[6] frame = line_list[7] attribute_list = line_list[8].strip(";").split("; ") attribute_dict = {} for item in attribute_list: item_list = item.split(" ") attribute_dict[item_list[0]]=item_list[1].strip("\"") transcript_id = attribute_dict["transcript_id"] if attrib...
gzqichang/wa
qi18n/qi18n/management/commands/test_i18n.py
Python
mit
418
0.002392
from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.models import User class Command(BaseCommand): help =
"TEST i18n" def add_arguments(self, parser): parser.add_argument('action', nargs='?', help='action ?') def handle(self, *args, **options): from .
.. import tests action = options.get('action') print("Unknown action:", action)
cppisfun/GameEngine
foreign/boost/tools/build/v2/test/configuration.py
Python
gpl-3.0
4,839
0.004133
#!/usr/bin/python # Copyright 2008 Jurko Gospodnetic # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) # Test that Boost Build configuration file handling. import BoostBuild import os.path import string ######...
utput_line(testMessage % configFileNames[0], False) t.expect_output_line(testMessage % configFileNames[1], False) t.expect_output_line(testMessage % configFileNames[2], False) t.run_build_system('--user-config="%s"' % configFileNames[0]) t.expect_output_line(implicit
ConfigLoadMessage, False) t.expect_output_line(explicitConfigLoadMessage) t.expect_output_line(testMessage % configFileNames[0] ) t.expect_output_line(testMessage % configFileNames[1], False) t.expect_output_line(testMessage % configFileNames[2], False) t.run_build_system('--user-config...
chinchliff/autophy
other_scripts/src_stephen/update_database.py
Python
gpl-3.0
1,302
0.036098
#!/usr/bin/env python import sys,sqlite3,os if __name__ == "__main__": if len(sys.argv) != 3: print ("usage: update_database database_name division") pri
nt ("\t\tdatabase_name = any database name that will be referred to later") print ("\t\tdivision = the division as recognized by NCBI (used for downloading)") print ("\t\t\texample: use pln for the plant division") sys.exit(0) database = sys.argv[1] div = sys.argv[2] if os.path.exists(database) == False: p...
instead") sys.exit(0) con = sqlite3.connect(database) print("downloading taxonomy") os.system("wget ftp://ftp.ncbi.nih.gov/pub/taxonomy/taxdump.tar.gz") os.system("tar -xzvf taxdump.tar.gz") os.system("./update_names_dmp_pysqlite "+database+" names.dmp nodes.dmp") os.system("./rebuild_tree_pysqlite "+datab...
yossigo/mockredis
mockredis/tests/test_zset.py
Python
apache-2.0
20,160
0.000794
from nose.tools import assert_raises, eq_, ok_ from mockredis.tests.fixtures import setup, teardown class TestRedisZset(object): """zset tests""" def setup(self): setup(self) def teardown(self): teardown(self) def test_zadd(self): key = "zset" values = [("one", 1), ...
b"one"], self.redis.zrange(key, 0, -3)) eq_([], self.
redis.zrange(key, 0, -4)) # negative starts eq_([], self.redis.zrange(key, -1, 0)) eq_([b"three"], self.redis.zrange(key, -1, -1)) eq_([b"two", b"three"], self.redis.zrange(key, -2, -1)) eq_([b"one", b"two", b"three"], self.redis.zrange(key, -3, -1)) eq_([b"one", b"two",...
joshzarrabi/e-mission-server
emission/storage/decorations/trip_queries.py
Python
bsd-3-clause
2,808
0.004274
import logging import pymongo import emission.net.usercache.abstract_usercache as enua import emission.core.get_database as edb import emission.core.wrapper.trip as ecwt import emission.core.wrapper.section as ecws import emission.core.wrapper.stop as ecwst import emission.storage.decorations.timeline as esdt def c...
urr_query.update({"user_id": user_id}) trip_doc_cursor = edb.get_trip_new_db().find(curr_query).sort(time_query.timeType, pymongo.ASCENDING) # TODO: Fix "TripIterator" and return it instead of this list return [ecwt.Trip(doc) for doc in trip_doc_cursor] def get_aggregate_trips(time_query, box=None): cu...
curr_query.update({"end_loc" : {"$geoWithin" : {"$box": box}}}) trip_doc_cursor = edb.get_trip_new_db().find(curr_query).sort(time_query.timeType, pymongo.ASCENDING) return [ecwt.Trip(doc) for doc in trip_doc_cursor] def get_trip(trip_id): """ Returns the trip for specified trip id. :rtype : emis...
jiahaoliang/group-based-policy
setup.py
Python
apache-2.0
1,058
0.00189
#!/usr/bin/env python # Copyright (c) 2013 Hewlett-Packard 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 # # Unle...
F ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # THIS FILE IS MANAGED BY THE GLOBAL REQUIREMENTS REPO - DO NOT EDIT import setuptools # In python < 2.7.4, a lazy loading of package `pbr` will break # setuptools if some ot...
ept ImportError: pass setuptools.setup( setup_requires=['pbr>=1.8'], pbr=True)
cyouwork/Python_Factory
DbUtil/itorndb.py
Python
apache-2.0
5,890
0.000186
#!/usr/bin/env python # coding=utf-8 """围绕mysql官方python数据库驱动,对torndb极简改造 torndb原为facebook/tornado的一部分,自3.0版本后已经剥离成独立的开源项目""" from __future__ import absolute_import, division, with_statement import copy import itertools import logging import os import time try: from mysql import connector except ImportError: ...
n cursor.description] return [Row(itertools.izip(column_names, row)) for row in cursor] finally: cursor.close() def get(self, query, *args, **kwargs): """返回唯一的查询结果""" rows = self.query(query, *args, **kwargs) if not rows: return None elif ...
e(self, query, *args, **kwargs): """执行给定的query并返回影响的最后一条记录的主键id""" return self.execute_lastrowid(query, *args, **kwargs) def execute_lastrowid(self, query, *args, **kwargs): """执行给定的query并返回影响的最后一条记录的主键id""" cursor = self._cursor() try: self._execute(cursor, quer...
huaying/ins-crawler
inscrawler/fetch.py
Python
mit
5,418
0.001846
import re from time import sleep from .settings import settings def get_parsed_mentions(raw_text): regex = re.compile(r"@([\w\.]+)") regex.findall(raw_text) return regex.findall(raw_text) def get_parsed_hashtags(raw_text): regex = re.compile(r"#(\w+)") regex.findall(raw_text) return regex.f...
Igw0E ._7UhW9.xLCgt a" likers_elems = list(browser.find(liker_elems_css_selector)) last_liker = None while likers_elems: for ele in likers_elems: likers[
ele.get_attribute("href")] = ele.get_attribute("title") if last_liker == likers_elems[-1]: break last_liker = likers_elems[-1] last_liker.location_once_scrolled_into_view sleep(0.6) likers_elems = list(browser.find(liker_elems_css_selector)) dict_post["likers"]...
mythmon/edwin
edwin/settings.py
Python
mpl-2.0
4,380
0
import os from configurations import Configuration from configurations import values from edwin import bundles def path(*components): root = os.path.dirname(os.path.dirname(__file__)) return os.path.abspath(os.path.join(root, *components)) class ConstantSettings(bundles.BundleConfiguration, Configuration)...
yjs') PIPELINE_CSS_COMPRESSOR = 'pipeline.compressors.cssmin.CSSMinCompressor' PIPELINE_CSSMIN_BINARY = path('node_modules/.bin/cssmin') PIPELINE_LESS_BINARY = path('node_modules/.bin/lessc') PIPELINE_BROWSERIFY_BINARY = path('node_modules/.
bin/browserify') PIPELINE_BROWSERIFY_ARGUMENTS = '-t babelify' LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': ('%(asctime)s [%(process)d] [%(levelname)s] ' + 'pathname=%(pathname)...
Emercoin/emcweb
engine/emcweb/emcweb_webapi/views/encrypt.py
Python
gpl-3.0
3,163
0.002213
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os import time from flask import current_app from flask_restful import reqparse from emcweb.emcweb_webapi.login_resource import LoginResource from emcweb.emcweb_webapi.utils import client from emcweb.tasks import make_wallet_link_encrypt from emc...
}, 500 for i in ran
ge(60): if result.ready(): time.sleep(10) return {'result_status': True} time.sleep(1) time.sleep(10) return {'result_status': True} api.add_resource(EncryptAPI, '/encrypt')
Narbulus/GroupmeSimulator
setup.py
Python
mit
2,067
0.00387
import json, requests, os, sys, util, load_messages, shutil, simulate # Load the list of groups the user is a member of print("Loading user group information") groups = util.get_rest('groups', params={"per_page": 100}) if groups is None: print("Unable to lo
ad user's group information") sys.exit(1) sim_ids = map(lambda conf: conf['simulation_id'], util.CONFIG['groups'].values()) sim_ids
= list(sim_ids) groups = list(filter(lambda group: group['id'] not in sim_ids, groups)) for i, group in enumerate(groups): print('\t' + str(i + 1) + '. ' + group["name"]) num = int(input("Group to simulate [1-" + str(len(groups)) + "]: ")) while num < 1 or num > len(groups): print("Number must be between 1 a...
TwoBitAlchemist/NeoAlchemy
neoalchemy/primitives.py
Python
mit
4,384
0.000228
import six from .cypher import Create, Match, Merge, Exists from .exceptions import DetachedObjectError from .shared.objects import GraphObject, SetOnceDescriptor try: str = unicode except NameError: pass class NodeMeta(type): def __init__(cls, class_name, bases, attrs): cls.labels = SetOnceDesc...
and isinstance(labels[0], Node): node = labels[0] properties.update({key: prop.copy() for key, prop in node.items()}) else: node = None super(Node, self).__init__(**properties) if node is not None: self.labels = node.labels self.type = ...
try: self.type = labels[-1] except IndexError: self.type = None def copy(self, shallow=False, **properties): var = properties.pop('var', self.var) if shallow: copy = Node(self, graph=self.graph, var=var) else: copy = Node(...
rasmadeus/iyoume
iyoume/waybill/urls.py
Python
gpl-2.0
408
0.002451
from django.conf.urls import patterns, url f
rom iyoume.waybill import views as dr urlpatterns = patterns('', url(r'^add/', dr.make_waybill), url(r'^del/', dr.remove_waybill), url(r'^find/', dr.search_waybill), url(r'^take/', dr.take_place), url(r'^trips/', dr.trips), url(r'^cancel_trip/', dr.cancel_trip), url(r'^passangers/', dr.pass...
url(r'^travel/', dr.travel), )
raully7/unionpay
unionpay/config.py
Python
mit
529
0
# -*- coding: utf-8 ''' 关于银联支付的若干配置 ''' # 基本信息 version = '1.0.0' charset = 'UTF-8' # 请求url trade_url = 'https://mgate.unionpay.com/gateway/merchant/trade' query_url = 'https://mgate.un
ionpay.com/gateway/merchant/query' # 商户信息 # 商户ID mer_id = 'XXXXXXXXXXXXXXX' # 回调地址 mer_backend_url = 'https://www.XXXX.com/callback/up/' # 签名相关 secret_key = 'XXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXX' sign_method = 'MD5' field_signature = 'signature' field_sign_method = 'signMethod'
jawilson/home-assistant
tests/components/agent_dvr/test_init.py
Python
apache-2.0
1,876
0.000533
"""Test Agent DVR integration.""" from unittest.mock import AsyncMock, patch from agent import AgentError from homeassistant.components.agent_dvr.const import DOMAIN from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant from . import CONF_DATA, create_entry from test...
cMock() mocked_agent.is_available = available return mocked_agent def _patch_init_agent(mocked_agent): return patch( "homeassistant.components.agent_dvr.Agent", return_value=mocked_agent, ) asy
nc def test_setup_config_and_unload( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker ): """Test setup and unload.""" entry = await init_integration(hass, aioclient_mock) assert entry.state == ConfigEntryState.LOADED assert len(hass.config_entries.async_entries(DOMAIN)) == 1 assert entry...
sunwukong123/projectE
2 - Even Fibonacci numbers.py
Python
gpl-3.0
139
0.021583
a = 0 b = 1 sum = 0 while (b < 4000000):
if (b % 2 == 0): sum += b b += a a =
b - a print (sum)
crossroadchurch/paul
tests/utils/__init__.py
Python
gpl-2.0
2,109
0
# -*- coding: utf-8 -*- # vim: autoindent shiftwidth=4 expandtab textwidth=120 tabstop=4 softtabstop=4 ############################################################################### # OpenLP - Open Source Lyrics Projection # # ------------------------------------------------------...
# # Software Foundation; version 2 of the License. # #
# # This program is distributed in the hope that it will be useful, but WITHOUT # # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # # more details. ...
yohanboniface/memopol-core
memopol/campaign/views.py
Python
agpl-3.0
8,612
0.010683
# Create your views here. import random import json import hashlib import smtplib from django.shortcuts import render_to_response, get_object_or_404 from django.conf import settings from django.template import RequestContext from django.contrib.auth.models import User from django.contrib import messages from django.h...
nfirm(request, id, key): feedback=None try: feedback=Debriefing.objects.get(pk=id, valid=key) except ObjectDoesNotExist: messages.add_message(request, messages.INFO, "Thank you! Either already confirmed, or object doesn't exist") ...
HttpResponseRedirect('/campaign/list/') feedback.valid='' feedback.save() messages.add_message(request, messages.INFO, 'Thank you for your confirmation') return HttpResponseRedirect('/campaign/view/%s/' % feedback.campaign.id) def report(request, pk): ...
PatSunter/pyOTPA
Isochrones/isobands_matplotlib.py
Python
bsd-3-clause
5,552
0.020533
#!/usr/bin/env python ''' isobands_matplotlib.py is a script for creating isobands. Works in a similar way as gdal_contour, but creating polygons instead of polylines This version requires matplotlib, but there is another one, isobands_gdal.py that uses only GDAL python Originally created by Roger Veciana i Rovira, m...
Destroy() if __name__ == "__main__": PARSER = ArgumentParser( description="Calculates the isobands from a raster into a vector file") PARSER.add_argument("src_file", help="The raster source file") PARSER.add_argument("out_file", help="The vectorial out file") PARSER.add_argument("-b", ...
source file to process (default 1)", type=int, default = 1, metavar = 'band') PARSER.add_argument("-off", help="The offset to start the isobands (default 0)", type=float, default = 0.0, metavar = 'offset') PARSER.add_argument("-i", help="The interval (default 0)", t...
Xiaofei-Zhang/NAMD_Docking_pipeline
pre_NAMD/pre_NAMD.py
Python
mit
2,553
0.018801
# pre_NAMD.py # Creates the files used for NAMD based on the .pdb file dowloaded from PDB bank # # Usage: # python pre_NAMD.py $PDBID # # $PDBID=the 4 characters identification code of the .pdb file # # Input: # $PDBID.pdb: .pdb file downloaded from PDB bank # # Output: # $PDBID_p.pdb: .pdb file with water mole...
int(*args, file=sys.stderr, **kwargs) # main if len(sys.argv) != 2: print_error("Usage: python pre_NAMD.py $PDBID") sys.exit(-1) mypath = os.path.realpath(__file__) tclpath = os.path.split(mypath)[0] + os.path.se
p + 'tcl' + os.path.sep pdbid = sys.argv[1] logfile = pdbid+'.log' # Using the right path of VMD vmd = "/Volumes/VMD-1.9.2/VMD 1.9.2.app/Contents/vmd/vmd_MACOSXX86" print("Input: "+pdbid+".pdb") # Remove water print("Remove water..") cmdline = '\"'+ vmd + '\"' +' -dispdev text -eofexit < '+ tclpath + 'remove_water.tcl...
shoyer/qspectra
tests/test_operator_tools.py
Python
bsd-2-clause
6,434
0
from numpy.testing import assert_allclose, assert_equal import numpy as np import unittest from qspectra import operator_tools class TestVibrationOperators(unittest.TestCase): def test(self): assert_allclose(operator_tools.vib_annihilate(3), [[0, 1, 0], [0, 0, np.sqrt(2)], [0, 0, ...
): self.assertEqual(operator_tools.full_liouville_subspace('gg'), 'gg')
self.assertEqual(operator_tools.full_liouville_subspace('ee'), 'ee') self.assertEqual(operator_tools.full_liouville_subspace('ge,ee'), 'gg,ge,eg,ee') self.assertEqual(operator_tools.full_liouville_subspace('ge,ee,ff'), 'gg,ge,gf,eg,ee,ef,fg,fe,ff') ...
romank0/kombu
funtests/tests/test_mongodb.py
Python
bsd-3-clause
2,443
0
from nose import SkipTest from kombu import Consumer, Producer, Exchange, Queue from kombu.utils import nested from funtests import transport class test_mongodb(transport.TransportCase): transport = 'mongodb' prefix = 'mongodb' event_loop_max = 100 def before_connect(self): try: ...
lled') def after_connect(self, connection): connection.channel().client # evaluate connection. self.c = self.connection # shortcut def test_fanout(self, name='test_mongodb_fanout'): if not self.verify_alive()
: return c = self.connection self.e = Exchange(name, type='fanout') self.q = Queue(name, exchange=self.e, routing_key=name) self.q2 = Queue(name + '2', exchange=self.e, routing_key=name + '2') channel = c.default_channel producer = Producer(channel, self.e) ...
ValyrianTech/BitcoinSpellbook-v0.3
darwin/rosettastone/rosettastone.py
Python
gpl-3.0
678
0.001475
#!/usr/bin/env python # -*- coding: utf-8 -*- from abc import abstractmethod, ABCMeta class RosettaStone(object): __metaclass__ = ABCMeta def __init__(self, name=None, **kwargs): self.name = name def configure(self, config): if not isinstance(config, dict): raise
Exception('config is not a dict!') for key in self.__dict__.keys(): if key in config: self.__setattr__(key, config[key]) @abstractmethod def genome_template(self): pass @abstractmethod def model_to_genome(self, model): pass @abstractmethod ...
o_model(self, genome): pass
vlukes/sfepy
sfepy/base/plotutils.py
Python
bsd-3-clause
4,706
0.006375
from __future__ import print_function import numpy as nm try: import matplotlib.pyplot as plt import matplotlib as mpl except (ImportError, RuntimeError): plt = mpl
= None #print 'matplotlib import failed!' from sfepy.base.base import output, pause def spy(mtx, eps=None, color='b', **kwargs): """ Show sparsity structure of a `scipy.sparse` matrix. """ aux = mtx.tocoo() ij, val
= nm.concatenate((aux.row[:,nm.newaxis], aux.col[:,nm.newaxis]), 1), aux.data n_item = aux.getnnz() n_row, n_col = aux.shape if eps is not None: output('using eps =', eps) ij = nm.compress(nm.absolute(val) > eps, ij, 0) n_item = ij.shape[0] else: ...
jrbourbeau/cr-composition
processing/legacy/anisotropy/random_trials/process_teststat.py
Python
mit
2,883
0.004856
#!/usr/bin/env python import os import glob import argparse import numpy as np import p
andas as pd import pycondor import comptools as comp if __name__ == "__main__": p = argparse.ArgumentParser( description='Extracts and saves desired information from simulation/data .i3 files') p.add_argument('-c', '--config', dest='config', default='IC86.2012
', choices=['IC79', 'IC86.2012', 'IC86.2013', 'IC86.2014', 'IC86.2015'], help='Detector configuration') p.add_argument('--low_energy', dest='low_energy', default=False, action='store_true', help='Only use events with energy < 10**6.75 GeV')...
erudit/eruditorg
eruditorg/base/viewmixins.py
Python
gpl-3.0
913
0.001095
import inspect from django.utils.translation import activate class MenuItemMixin: """ This mixins injects attributes that start with the 'menu_' p
refix into the context generated by the view it is applied to. This behavior can be used to highlight an item of a navigation component. """ de
f get_context_data(self, **kwargs): context = super(MenuItemMixin, self).get_context_data(**kwargs) vattrs = inspect.getmembers(self, lambda a: not (inspect.isroutine(a))) menu_kwargs = dict(a for a in vattrs if a[0].startswith("menu_")) context.update(menu_kwargs) return context...
svinota/cxnet
cxnet/utils.py
Python
gpl-3.0
8,593
0.010823
""" Misc utils for IPv4 management """ # Copyright (c) 2008-2011 Peter V. Saveliev # # This file is part of Connexion project. # # Connexion 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;...
t_mask(st): """ Return short int mask in form /xx """ st = st.split("/") if len(st) > 1: mask = st[1] if mask.find(".") > 0: mask = msk.index(dqn_to_int(mask)) else: mask = mask_unknown(st[0]) return int(mask) def get_mask(st): """ Return int mas
k for IP """ st = st.split("/") if len(st) > 1: mask = st[1] if mask.find(".") > 0: mask = dqn_to_int(mask) else: mask = msk[int(mask)] else: mask = msk[mask_unknown(st[0])] return mask def get_base(ip,mask,base=32): """ Return networ...
wanderine/nipype
nipype/interfaces/broccoli/tests/test_auto_MotionCorrection.py
Python
bsd-3-clause
1,430
0.023776
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from nipype.testing import assert_equal from nipype.interfaces.broccoli.preprocess import MotionCorrection def test_MotionCorrection_inputs(): input_map = dict(args=dict(argstr='%s', ), device=dict(argstr='-device %d', ), environ=dict(nohash=Tru...
), ignore_exception=dict(nohash=True, usedefault=True, ), in_file=dict(argstr='%s', copyfile=False, mandatory=True, position=0, ), iterations=dict(argstr='-iterations %d', ), output=dict(argstr='-output %s', ), output_type=dict(), platform=dict(argstr='-platform ...
verbose=dict(argstr='-verbose', ), ) inputs = MotionCorrection.input_spec() for key, metadata in input_map.items(): for metakey, value in metadata.items(): yield assert_equal, getattr(inputs.traits()[key], metakey), value def test_MotionCorrection_outputs(): output_map = d...
kenshay/ImageScript
ProgramData/SystemFiles/Python/Lib/site-packages/directpy11/Samples/SampleLights.py
Python
gpl-3.0
2,818
0.011356
"""This sample demonstrates some very simple lightning effects.""" import math import d3d11 import d3d11x from d3d11c import * def heightCallback(x, z, byteIndex, data): return data[byteIndex] * 0.03 class SampleLights(d3d11x.Frame): def onCreate(self): #Heightmap. #self.heightmap = d3d11x....
s") #Sphere mesh. meshPath = d3d11x.getResourceDir("Mesh", "sphere.obj") self.sphere = d3d11x.Mesh(self.device, meshPath) self.sphere.textureView = self.loadTextureView("misc-white.bmp") def createLights(self): #Add 7 lights (maximum defined in 'Shared.fx'). ...
lightTime = self.time * (i * 0.5) #Use sin() and cos() to create a nice little movement pattern. x = math.sin(lightTime) * distance z = math.cos(lightTime) * distance y = self.heightmap.getHeight(x, z) pos = d3d11.Vector(x, y + 1, z) #Se...
yasoob/PythonRSSReader
venv/lib/python2.7/dist-packages/twisted/web/client.py
Python
mit
60,847
0.001874
# -*- test-case-name: twisted.web.test.test_webclient,twisted.web.test.test_agent -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ HTTP client. """ from __future__ import division, absolute_import import os, types try: from urlparse import urlunparse, urljoin, urldefrag from u...
lue) for cookie, cookval in self.factory.cookies.items(): cookieData.append(cookie + b'=' + cookval) if cookieData: self.sendHeader(b'Cookie', b'; '.join(cookieData)) self.
endHeaders() self.headers = {} if data is not None: self.transport.write(data) def handleHeader(self, key, value): """ Called every time a header is received. Stores the header information as key-value pairs in the C{headers} attribute. @type key: C{str...
huggingface/transformers
tests/trainer/test_trainer_utils.py
Python
apache-2.0
18,824
0.003134
# coding=utf-8 # Copyright 2018 the HuggingFace Inc. team. # # 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...
def test_label_smoothing(self): epsilon = 0.1 num_labels = 12 random_logits = torch.randn(4, 5, num_labels) random_labels = torch.randint(0, num_labels, (4, 5))
loss = nn.functional.cross_entropy(random_logits.view(-1, num_labels), random_labels.view(-1)) model_output = SequenceClassifierOutput(logits=random_logits) label_smoothed_loss = LabelSmoother(0.1)(model_output, random_labels) log_probs = -nn.functional.log_softmax(random_logits, dim=-1) ...
cschenck/blender_sim
fluid_sim_deps/blender-2.69/2.69/scripts/modules/rna_xml.py
Python
gpl-3.0
14,054
0.001779
# ***** BEGIN GPL LICENSE BLOCK ***** # # 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 ...
if type(ls) == list: fw("%s<%s>\n" % (ident, attr)) for blend_id in ls: rna2xml_node(ident + ident_val, blend_
id, None) fw("%s</%s>\n" % (ident_val, attr)) # any attribute elif method == 'ATTR': rna2xml_node(root_ident, root_rna, None) if root_node: fw("%s</%s>\n" % (root_ident, root_node)) def xml2rna(root_xml, root_rna=None, # must be set ): def rna...
Br1an6/ACS_Netplumber_Implementation
hsa-python/net_plumbing/demo.py
Python
gpl-2.0
2,719
0.020228
''' Created on Jul 27, 2012 @author: Peyman Kazemian ''' from headerspace.tf import TF from headerspace.hs import headerspace from utils.wildcard import wildcard_create_bit_repeat from net_plumber import NetPlumber from time import time from config_parser.cisco_router_parser import cisco_router from examples.utils.net...
0x3)) N.add_source("yoza-source", hs, [1]) rule_ids = [] for rtr_name in settings["rtr_names"]: f = TF(1) f.load_object_from_file("%s/%s.tf"%(settings["input_path"],rtr_name)) for rule in f.rules: in_ports = rule["in_ports"] out_ports = rule["out_ports"] match = rule["match"] mask = rule["m...
pend(\ N.add_rule(rtr_name, -1, in_ports, out_ports, match, mask, rewrite)\ ) en = time() print "Rule Add Time: ",(en-st)*1000,"ms"
UMD-SEAM/bugbox
framework/Targets/eXtplorer_2_1_0/__init__.py
Python
bsd-3-clause
494
0.004049
# Copyright 2013 University of Maryland. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE.TXT file. import os from framework
.Targets import ApacheTarget class Target(ApacheTarget): def get_path(filename): return os.path.dirname(os.path.realpath(__file__)) + '/' + f
ilename name = "eXtplorer 2.1" application_dir_mapping = [get_path("application"), "/var/www"] chroot_environment = "Debian5"
jlconlin/code2PDF
code2PDF.py
Python
mpl-2.0
10,380
0.001349
import argparse import os import re import subprocess import textwrap import PyPDF2 import pygments import pygments.lexers import pygments.formatters def findSourceFiles(path, extensions): """ Return a list of absoluate paths to found source files. path: Where to search for the source code extensio...
.formatters.get_formatter_by_name( "latex", **la
texOptions) texFilename = "{}.tex".format(title) doc_options = {"title": title, "author": author, "landscape": landscape } texFile = makeLaTeXFile(texFilename, formatter, doc_options) for F in sourceFiles: latexOptions["title"] = os.pat...
rspavel/spack
var/spack/repos/builtin/packages/bml/package.py
Python
lgpl-2.1
1,909
0.003667
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-
level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Bml(CMakePackage): """The basic matrix library (bml) is a collection of various matrix data formats (in dense and sparse) and their associated algorithms for basic matrix operations.""" homep...
op', branch='master') version('1.3.1', sha256='17145eda96aa5e550dcbff1ee7ce62b45723af8210b1ab70c5975ec792fa3d13') version('1.3.0', sha256='d9465079fe77210eb2af2dcf8ed96802edf5bb76bfbfdbcc97e206c8cd460b07') version('1.2.3', sha256='9a2ee6c47d2445bfdb34495497ea338a047e9e4767802af47614d9ff94b0c523') versio...
bcanvural/thesis
synonyms.py
Python
mit
1,419
0.007047
#Synonyms experiment. Pass a string to see its "synonyms" from pyspark.sql import SparkSession, Row from pyspark.ml.feature import Word2Vec, Tokenizer, StopWordsRemover, Word2VecModel import sys; from string import punctuation def strip_punctuation(arr): return [''.join(c for c in s if c not in punctuation) for s ...
tCol="skillText", outputCol="words") to
kenized = tokenizer.transform(df_categories) remover = StopWordsRemover(inputCol="words", outputCol="filtered") removed = remover.transform(tokenized) stripped = removed.select('filtered').rdd.map(lambda x: strip_punctuation(x[0]))\ .map(lambda x: Row(filtered=x)).toDF(['filtered']) # word2vec = ...
InfraBox/infrabox
infrabox/test/api/tokens_test.py
Python
mit
2,458
0.006509
f
rom temp_tools import TestClient from test_template import ApiTestTemplate class TokensTest(ApiTestTemplate): def setUp(s
elf): super(TokensTest, self).setUp() TestClient.execute("""TRUNCATE auth_token""") self.test_token_data = {'description': 'Test token 1', 'scope_push': True, 'scope_pull': True} def test_tokens_root(self): # test unau...
theMentalItchGuy/NLP
migrations/versions/3cee55aae20_.py
Python
mit
847
0.015348
"""empty message Revision ID: 3cee55aae20 Revises: None Create Date: 2015-08-30 22:42:28.320071 """ # revision identifiers, used by Alembic. revision = '3cee55aae20' down_revision = None from alembic import op import
sqlalchemy as sa from sqlalchemy.dialects import postgresql def upgrade(): ### commands auto generat
ed by Alembic - please adjust! ### op.create_table('results', sa.Column('id', sa.Integer(), nullable=False), sa.Column('url', sa.String(), nullable=True), sa.Column('result_all', postgresql.JSON(), nullable=True), sa.Column('result_no_stop_words', postgresql.JSON(), nullable=True), sa.PrimaryKey...
smainand/scapy
scapy/modules/krack/__init__.py
Python
gpl-2.0
965
0
"""Module implementing Krack Attack on client, as a custom WPA Access Point More details on the attack can be found on https://www.krackattacks.com/ Example of use (from the scapy shell): >>> load_module("krack") >>> KrackAP( iface="mon0", # A monitor interface ap
_mac='11:22:33:44:55:66', # MAC (BSSID) to use ssid="TEST_KRACK", # SSID passphrase="testtest", # Associated passphrase ).run() Then, on the target device, connect to "TEST_KRACK" using "testtest" as the passphrase. The output logs will indicate if one of the vulnerability have been tr
iggered. Outputs for vulnerable devices: - IV re-use!! Client seems to be vulnerable to handshake 3/4 replay (CVE-2017-13077) - Broadcast packet accepted twice!! (CVE-2017-13080) - Client has installed an all zero encryption key (TK)!! For patched devices: - Client is likely not vulnerable to CVE-2017-13080 """ fr...
mkreider/cocotb2
examples/wb/hdl/Manifest.py
Python
bsd-3-clause
96
0.09375
files = [ "cocotb_pr
io3.vhd", "cocotb_prio2.vhd", "cocotb_wb_loopback.vhd",
]
yebrahim/pydatalab
solutionbox/ml_workbench/xgboost/analyze.py
Python
apache-2.0
13,669
0.005999
# Copyright 2017 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 ...
ormations. Below is an example features file: { "column_name_1": {"transform": "scale"}, "column_name_3":
{"transform": "target"}, "column_name_2": {"transform": "one_hot"}, "new_feature_name": {"transform": "multi_hot", "source_column": "column_name_4"}, } The format of the dict is `name`: `transform-dict` where the `name` is the name of the transfor...
litecoinz-project/litecoinz
qa/rpc-tests/bip65-cltv-p2p.py
Python
mit
3,533
0.00283
#!/usr/bin/env python2 # # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.test_framework import ComparisonTestFramework from test_framework.util import start_nodes from test_framework.mininode import CTran...
extra_args=[['-debug', '-whitelist=127.0.0.1']], binary=[self.options.testbinary]) self.is_network_split = False def run_test(self): test = TestManager(self, self.options.tmpdir) test.add_all_connections(self.nodes) NetworkThread...
tx'][0] inputs = [{ "txid" : from_txid, "vout" : 0}] outputs = { to_address : amount } rawtx = node.createrawtransaction(inputs, outputs) signresult = node.signrawtransaction(rawtx) tx = CTransaction() f = cStringIO.StringIO(unhexlify(signresult['hex'])) tx.deseri...
trendelkampschroer/PyEMMA
pyemma/plots/networks.py
Python
bsd-2-clause
23,764
0.001304
# Copyright (c) 2015, 2014 Computational Molecular Biology Group, Free University # Berlin, 14195 Berlin, Germany. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # * Redistributions of source ...
lightly curved arrow from (x1,y1) to (x2,y2). Will allow the given patches at start end end. """ # set arrow properties dist = math.sqrt( ((x2 - x1) / float(Dx))**2 + ((y2 - y1) / float(Dy))**2) arrow_curvature *= 0.075 # standard scale rad = arrow_curvature...
xycoords='data', xytext=(x1, y1), textcoords='data', arrowprops=dict(arrowstyle='simple,head_length=%f,head_width=%f,tail_width=%f' % (head_length, head_width, tail_width), ...
w1ll1am23/home-assistant
tests/components/subaru/test_init.py
Python
apache-2.0
4,822
0.000622
"""Test Subaru component setup and updates.""" from unittest.mock import patch from subarulink import InvalidCredentials, SubaruException from homeassistant.components.homeassistant import ( DOMAIN as HA_DOMAIN, SERVICE_UPDATE_ENTITY, ) from homeassistant.components.subaru.const import DOMAIN from homeassista...
tries.async_get_entry(entry.entry_id) assert check_entry assert check_entry.state == ENTRY_STATE_LOADED async def test_unsuccessful_connect(hass): """Test unsuccessful connect due to connectivity.""" entry = await setup_subaru_integration( hass, connect_effect=SubaruException("Service ...
vehicle_data=VEHICLE_DATA[TEST_VIN_2_EV], vehicle_status=VEHICLE_STATUS_EV, ) check_entry = hass.config_entries.async_get_entry(entry.entry_id) assert check_entry assert check_entry.state == ENTRY_STATE_SETUP_RETRY async def test_invalid_credentials(hass): """Test invalid credentials."""...
ivknv/yadisk
yadisk/yadisk.py
Python
lgpl-3.0
38,735
0.002194
# -*- coding: utf-8 -*- import functools import threading import requests from . import functions __all__ = ["YaDisk"] class SelfDestructingSession(requests.Session): """Just like your regular :any:`requests.Session` but with a destructor""" def __init__(self, *args, **kwargs): self._init_complete...
resource :param limit: number of children resources to be included in the response :param offset: number of children resources to be skipped in the response :param preview_size: size of the file preview :param preview_crop: `bool`, cut the preview to the size specified i...
m sort: `str`, field to be used as a key to sort children resources :param fields: list of keys to be included in the response :param timeout: `float` or `tuple`, request timeout :param headers: `dict` or `None`, additional request headers :param n_retries: `int`, maximum...
TheTimmy/spack
lib/spack/spack/schema/modules.py
Python
lgpl-2.1
6,919
0
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
'allOf': [ # Base confi
guration {'$ref': '#/definitions/module_type_configuration'}, {} # Specific dotkit extensions ]}, } }, }, }
rfk/pyenchant
tests/test_checker.py
Python
lgpl-2.1
9,139
0.000547
# pyenchant # # Copyright (C) 2004-2009, Ryan Kelly # # This library is free software; you can redistribute it and/or # modify i
t under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # Th
is library 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 # Lice...
linsicai/or-tools
examples/python/steel.py
Python
apache-2.0
6,315
0.012352
# Copyright 2010 Pierre Schaus pschaus@gmail.com, lperron@google.com # # 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 ...
) if var: v = self.MaxBound() if v + 1 == var.Min(): # Symmetry breaking. If you need to assign to a new bin, # select the first one. solver.Add(var == v + 1) return self.Next(solver) else: # value heuristic (important for difficult problem): #
try first to place the order in the slab that will induce # the least increase of the loss loads = self.getLoads() l, v = min((self.__losstab[loads[i] + weight], i) for i in range(var.Min(), var.Max() + 1) if var.Contains(i) and loads[i] + weight <= sel...
agamdua/rply
tests/test_parser.py
Python
bsd-3-clause
7,871
0
import operator import py from rply import ParserGenerator, ParsingError, Token from rply.errors import ParserGeneratorWarning from rply.token import SourcePosition from .base import BaseTests from .utils import BoxInt, ParserState, RecordingLexer class TestParser(BaseTests): def test_simple(self): pg ...
pg.build() assert parser.parse(iter([ Token("VALUE", "abc"), Token("SPACE", " "), Token("VALUE", "def"), Token("SP
ACE", " "), Token("VALUE", "ghi"), ])) == ["abc", "def", "ghi"] assert parser.parse(iter([])) == [] def test_precedence(self): pg = ParserGenerator(["NUMBER", "PLUS", "TIMES"], precedence=[ ("left", ["PLUS"]), ("left", ["TIMES"]), ]) @pg...
titilambert/home-assistant
tests/components/deconz/test_gateway.py
Python
apache-2.0
6,047
0.001488
"""Test deCONZ gateway.""" from copy import deepcopy import pydeconz import pytest from homeassistant import config_entries from homeassistant.components import deconz, ssdp from homeassistant.helpers.dispatcher import async_dispatcher_connect from tests.async_mock import Mock, patch from tests.common import MockCon...
await hass.async_block_till_done() assert gateway.api.host == "2.3.4.5" a
ssert len(mock_setup_entry.mock_calls) == 1 async def test_reset_after_successful_setup(hass): """Make sure that connection status triggers a dispatcher send.""" gateway = await setup_deconz_integration(hass) result = await gateway.async_reset() await hass.async_block_till_done() assert result i...
qateam123/eq
app/questionnaire/questionnaire_manager.py
Python
mit
5,368
0.001863
import logging from flask import g from flask_login import current_user from app.globals import get_answer_store, get_answers, get_metadata, get_questionnaire_store from app.questionnaire.path_finder import PathFinder from app.schema.block import Block from app.schema.exceptions import QuestionnaireException logger ...
re(self, location): questionnaire_store = get_questionnaire_store(c
urrent_user.user_id, current_user.user_ik) for answer in self.get_state_answers(location.block_id): questionnaire_store.answer_store.add_or_update(answer.flatten()) return questionnaire_store def process_incoming_answers(self, location, post_data): logger.debug("Processing post ...
memo/tensorflow
tensorflow/contrib/training/python/training/feeder_test.py
Python
apache-2.0
10,781
0.005844
# 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...
Consumers(self): # Three feeders, three consumers. servers = self._create_local_cluster(consumer=3, feeder=3) coord = coordinator.Coordinator() # Start the three feeders: f0 = FeederThread(self, coord, servers, 'feeder', 0, prefix='feed0_') f0.add_remote_device('/job:consume
r/task:0') f0.add_remote_device('/job:consumer/task:1') f0.start() f1 = FeederThread(self, coord, servers, 'feeder', 1, prefix='feed1_') f1.add_remote_device('/job:consumer/task:2') f1.add_remote_device('/job:consumer/task:0') f1.start() f2 = FeederThread(self, coord, servers, 'feeder', 2,...
Tehsmash/networking-cisco
networking_cisco/plugins/cisco/l3/drivers/asr1k/asr1k_routertype_driver.py
Python
apache-2.0
33,133
0.000091
# Copyright 2015 Cisco Systems, 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 requir...
# be removed. current = router_context.current hd_id = current[HOSTING_DEVICE_ATTR] if current['gw_port_id'] and hd_id is not None: self._conditionally_remove_global_router(context.elevated(), current) def add_router_in...
1k, VLAN sub-interfaces are used to connect to internal # neutron networks. Only one such sub-interface can be created for each # VLAN. As the VLAN sub-interface is added to the VRF representing the # Neutron router, we must only allow one Neutron router to attach to a # particular Neutr...
remotelockbox/remotelockbox
app_test.py
Python
mit
1,992
0.001004
import os import unittest os.environ['SIMULATE_HARDWARE'] = '1' os.environ['LOCK_SETTINGS_PATH'] = 'test-settings' import db from app import app primary_pin = '1234' sub_pin = '0000' class AppTestCase(unittest.TestCase): def setUp(self): app.testing = True self.app = app.test_client() d...
y locked' in rv.data rv = self.app
.post('/unlock', follow_redirects=True) # still locked assert b'Box has been locked for' in rv.data def login(self, pin): return self.app.post('/', data={'inputPassword': pin}, follow_redirects=True) def logout(self): re...
lyoniionly/django-cobra
src/cobra/models/fields/autoslugfield.py
Python
apache-2.0
7,531
0.000133
""" AutoSlugField taken from django-extensions at 15d3eb305957cee4768dd86e44df1bdad341a10e Uses Oscar's slugify function instead of Django's Copyright (c) 2007 Michael Trier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"...
ance, self.attname) # model_instance is being modified, and overwrite is False, # so inste
ad of doing anything, just return the current slug return slug # strip slug depending on max_length attribute of the slug field # and clean-up slug_len = slug_field.max_length if slug_len: slug = slug[:slug_len] slug = self._slug_strip(slug) if s...
googleinterns/contextual-query-rewrites
models/lasertagger/test_realizer_arbitrary_reordering.py
Python
apache-2.0
1,307
0.000765
import unittest import tagging class TestRealizerArbitraryReordering(unittest.TestCase): """ Tests for the realizer with arbitrary reordering enabled. """ def test_realize_output_in_order(self): """ Test for when source tokens occur in the same relative orde...
"]) tags_str = ['KEEP|1', 'KEEP|0', 'KEEP|and', 'DELETE', 'KEEP|3'] tags = [tagging.Tag(tag) for tag in tags_str] result = editing_task.realize_output([tags]) expec
ted = "word2 word1 and word3 " self.assertEqual(expected, result) if __name__ == '__main__': unittest.main()
python-dirbtuves/akl.lt
akllt/dataimport/tests/utils.py
Python
agpl-3.0
1,418
0
import pathlib import pkg_resources from django.contrib.contenttypes.models import ContentType from wagtail.wagtailcore.models import Site from wagtail.wagtailcore.models import Page def fixture(path): return pathlib.Path(pkg_resources.resource_filename( 'akllt', 'dataimport/tests/fixtures/%s' % path ...
content_type=page_content_type, path='00010001', depth=2, numchild=0, url_path='/home/', ) # Create default site return Site.objects.create( hostname='localhost', root_page_id=homepage.id, is_default_site=True ) def get_default_site(): ...
wagtail_initial_data()
laslabs/vertical-medical
medical_prescription_disease_state/tests/test_medical_prescription_order_line.py
Python
agpl-3.0
2,956
0
# -*- coding: utf-8 -*- # © 2016 LasLabs Inc. # License GPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). from odoo.tests.common import TransactionCase class TestMedicalPrescriptionOrderLine(TransactionCase): def setUp(self): super(TestMedicalPrescriptionOrderLine, self).setUp() self.pat...
.update({ 'patient_id': self.patient_id.id, 'physician_id': self.physician_id.id, }) self.rx_id = self.env['medical.prescription.order'].create( self.order_vals, ) self.vals.update({ 'disease_id': self.disease_id.id, 'medicament...
nt_id.id, 'physician_id': self.physician_id.id, }) return self.env['medical.prescription.order.line'].create( self.vals ) def test_inactive_course_complete(self, ): rec_id = self._new_record() rec_id.is_course_complete = True self.assertEqual(...
swappsco/django-qa
test_project/core/views.py
Python
mit
4,130
0.001211
from django.c
ontrib.auth import logout from django.shortcuts import render from django.http import HttpResponseRedirect, Htt
pResponse from django.template import RequestContext from django.shortcuts import render from django.contrib.auth import authenticate, login from .forms import UserForm def register(request): # Like before, get the request's context. context = RequestContext(request) # A boolean value for telling the tem...
saltstack/salt
salt/modules/win_wua.py
Python
apache-2.0
39,211
0.001071
""" Module for managing Windows Updates using the Windows Update Agent. List updates on the system using the following functions: - :py:func:`win_wua.available <salt.modules.win_wua.available>` - :py:func:`win_wua.list <salt.modules.win_wua.list_>` This is an easy way to find additional information about updates ava...
update database as is. Default is ``True`` .. versionadded:: 3001 Returns: dict: Returns a dict containing either a summary or a li
st of updates: .. code-block:: cfg Dict of Updates: {'<GUID>': { 'Title': <title>, 'KB': <KB>, 'GUID': <the globally unique identifier for the update>, 'Description': <description>, 'Downloaded': <has the u...
mitodl/open-discussions
open_discussions/constants.py
Python
bsd-3-clause
303
0
"""open_discussions constants""" fro
m rest_framework import status PERMISSION_DENIED_ERROR_TYPE = "PermissionDenied" NOT_AUTHENTICATED_ERROR_TYPE = "NotAuthenticated" DJANGO_PERMISSION_ERROR_TYPES = ( status.HTTP_401_UNAUTHORIZED, s
tatus.HTTP_403_FORBIDDEN, ) ISOFORMAT = "%Y-%m-%dT%H:%M:%SZ"
jl4ge/cs3240-labdemo
places.py
Python
mit
61
0
PLACES
= ["Virginia", "Lexington", "Washington", "N
ew York"]
mozilla/bedrock
bedrock/base/tests/test_urlresolvers.py
Python
mpl-2.0
6,341
0.000789
# 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 https://mozilla.org/MPL/2.0/. from unittest.mock import Mock, patch from django.test import TestCase from django.test.client import RequestFactory f...
"en-GB", "es-us": "es-US"}, CANONICAL_LOCALES={"es": "es-ES", "en": "en-US"}) class TestFindSupported(TestCase): def test_find_supported(self): assert find_supported("en-CA") == "en-US" asse
rt find_supported("en-US") == "en-US" assert find_supported("en-GB") == "en-GB" assert find_supported("en") == "en-US" assert find_supported("es-MX") == "es-ES" assert find_supported("es-AR") == "es-AR" assert find_supported("es") == "es-ES" def test_find_supported_none(self...
IsmoilovMuhriddin/allgo
opencv_samples/color_histogram.py
Python
mit
1,366
0.008053
#!/usr/bin/env python ''' Video histogram sample to show live histogram of video Keys: ESC - exit ''' import numpy as np import cv2 # built-in modules import sys # local modules import video if __name__ == '__main__': hsv
_map = np.zeros((180, 256, 3), np.uint8) h, s = np.indices(hsv_map.shape[:2]) hsv_map[:,:,0] = h hsv_map[:,:,1] = s hsv_map[:,:,2] = 255 hsv_map = cv2.cvtColor(hsv_map, cv2.COLOR_HSV2BGR) cv2
.imshow('hsv_map', hsv_map) cv2.namedWindow('hist', 0) hist_scale = 10 def set_scale(val): global hist_scale hist_scale = val cv2.createTrackbar('scale', 'hist', hist_scale, 32, set_scale) try: fn = sys.argv[1] except: fn = 0 cam = video.create_capture(fn, ...
EndPointCorp/lg_ros_nodes
lg_common/src/lg_common/helpers.py
Python
apache-2.0
35,903
0.001894
import os import sys import json import rospy import base64 import urllib.request, urllib.parse, urllib.error import hashlib import urllib.parse import random import string from lg_common import ManagedWindow from interactivespaces_msgs.msg import GenericMessage from lg_msg_defs.msg import ApplicationState, WindowGeom...
nce.geometry.y) and int(adhoc_browser_message.geometry.width) == int(managed_adhoc_browser_instance.geometry.width) and int(adhoc_browser_message.geometry.height) == int(managed_adhoc_browser_instance.geometry.height)) return geometry_match def url_compare(a0, b0): """ Compare two urls fo...
b0 (str) Returns: True if the urls are equivalent. """ a = urllib.parse.urlparse(a0) b = urllib.parse.urlparse(b0) if a.scheme != b.scheme: return False if a.netloc != b.netloc: return False if a.path != b.path: return False if a.params != b.params: ...
akx/lepo
lepo_doc/views.py
Python
mit
373
0
from django.http import JsonResponse from django.shortcuts import render from django.urls import reverse def get_swagger_json(request, router): return JsonResponse(router.api.doc) def render_docs(request, router, json_ur
l_name): return render(request, 'lepo_doc/swagger-ui.html', { 'json_url': request.build_absolute
_uri(reverse(json_url_name)), })
Hemisphere-Project/Telemir-DatabitMe
Telemir-EEG/TeleMir/analyses/__init__.py
Python
gpl-2.0
110
0
#
-*- coding: utf-8 -*- from .TransmitFeatures import TransmitFeatures from .GetFeatures import GetFeature
s
code-for-india/sahana_shelter_worldbank
private/templates/EVASS/config.py
Python
mit
38,128
0.011305
# -*- coding: utf-8 -*- try: # Python 2.7 from collections import OrderedDict except: # Python 2.6 from gluon.contrib.simplejson.ordered_dict import OrderedDict from gluon import current from gluon.storage import Storage from gluon.validators import IS_NOT_EMPTY, IS_EMPTY_OR, IS_IN_SET from s3 import...
nt_lenght_km = {1: "Km", 2: "mi", 3: "naut mi", } settings.L10n.measurement_area_m = {1: "m²", 2: "yd²", 3: "ac", ...
3: "ac", } settings.L10n.measurement_vol_l = {1: "l", 2: "US_gal", 3: "Uk_gal", }
manjeetk09/GoogleScrapper
rake_tutorial.py
Python
gpl-2.0
2,623
0.014868
from __future__ import absolute_import from __future__ import print_function import six __author__ = 'a_medelyan' import rake import operator import
io import sys # EXAMPLE ONE - SIMPLE stoppath
= "SmartStoplist.txt" # 1. initialize RAKE by providing a path to a stopwords file rake_object = rake.Rake(stoppath, 3,4,1) # 2. run on RAKE on a given text # sample_file = io.open("data/docs/fao_test/w2167e.txt", 'r',encoding="iso-8859-1") # text = sample_file.read() # keywords = rake_object.run(text) # # 3. print...
Lucas-C/pre-commit
tests/store_test.py
Python
mit
5,138
0
from __future__ import absolute_import from __future__ import unicode_literals import io import os.path import sqlite3 import mock import pytest import six from pre_commit.store import _get_default_directory from pre_commit.store import Store from pre_commit.util import cmd_output from pre_commit.util import cwd fro...
rigger a call to create store.require_created() assert not os.path.exists(store.directory) def test_does_not_recreate_if_directory_already_exists(store): assert not os.path.exists(store.directory) # We manually create the directory. # Note: we're intentionally leaving out the README file. This is...
quire_created, this should not call create store.require_created() assert not os.path.exists(os.path.join(store.directory, 'README')) def test_clone(store, tempdir_factory, log_info_mock): path = git_dir(tempdir_factory) with cwd(path): cmd_output('git', 'commit', '--allow-empty', '-m', 'foo')...
mdecourse/2017springvcp
data/w15/vcpw15-5.py
Python
agpl-3.0
11,365
0.006423
# vcpw15-5.py # Memory Puzzle # Original By Al Sweigart al@inventwithpython.com # http://inventwithpython.com/pygame # Released under a "Simplified BSD" license import random, pygame, sys from pygame.locals import * FPS = 30 # frames per second, the general speed of the program WINDOWWIDTH = 640 # size of w...
# Icons don't match. Re-cover up both selections. pygame.time.wait(1000) # 1000 milliseconds = 1 sec coverBoxesAnimation(mainBoard, [(firstSelection[0], firstSelection[1]), (boxx, boxy)]) revealedBoxes[firstSelection[0]][firstS...
[boxx][boxy] = False elif hasWon(revealedBoxes): # check if all pairs found gameWonAnimation(mainBoard) pygame.time.wait(2000) # Reset the board mainBoard = getRandomizedBoard() ...
JuPeg/tools-artbio
unstable/local_tools/includeScore.py
Python
mit
1,223
0.026165
#!/usr/bin/env python #By, drosofff@gmail.com # command: includeScore.py <tabulated_score_file> <GFF> <score_enriched_GFF> id_column score_column filter_limit import sys def get_foldchanges (file, id_column=1, score_column=5, skipline=200, limit=1E-5): scoredic = {} # a dic of scores with gene_id as keys id_colum...
core_column -= 1 linecount = 0 F = open (file, "r") for line in F: if line[:4] == "gene" : continue fields = line[:-1].split("\t") ID = fields[id_column] if fields[-1]=="NA" or float(fields[-1]) > limit: continue try: score = float(fields[score_column]) except: score = 0 scoredic[ID] =...
sys.argv[-1]) ) F_in = open (sys.argv[2], "r") F_out = open (sys.argv[3], "w") for line in F_in: if line[0] == "#": print >> F_out, line[:-1] else: GFF_fields = line[:-1].split("\t") GFF_attribute = GFF_fields[8] GFF_id = GFF_attribute.split(";")[0].split("ID=")[-1] print GFF_id if GFF_i...
ddboline/hangups
hangups/conversation.py
Python
mit
40,461
0
"""Conversation objects.""" import asyncio import datetime import logging from hangups import (parsers, event, user, conversation_event, exceptions, hangouts_pb2) logger = logging.getLogger(__name__) CONVERSATIONS_PER_REQUEST = 100 MAX_CONVERSATION_PAGES = 100 async def build_user_conversatio...
at(e)) # Build list of conversation part
icipants. conv_part_list = [] for conv_state in conv_states: conv_part_list.extend(conv_state.conversation.participant_data) # Retrieve self entity. get_self_info_response = await client.get_self_info( hangouts_pb2.GetSelfInfoRequest( request_header=client.get_request_header...
xzturn/tensorflow
tensorflow/python/eager/memory_tests/memory_test.py
Python
apache-2.0
5,041
0.006943
# Copyright 2018 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...
es), but for now they are helpful for finding memory leaks since not all PyObject leaks are found by introspection (test_util decorators). Please be careful adding new tests here. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python im...
test from tensorflow.python.eager.memory_tests import memory_test_util from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import test_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import gradients as gradient...
82Flex/DCRM
manage.py
Python
agpl-3.0
247
0
#!
/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "DCRM.settings") from django.core.management import execute_from_command_line execute_from_command_lin
e(sys.argv)
jgyates/genmon
genmonlib/mymail.py
Python
gpl-2.0
22,978
0.012664
#!/usr/bin/env python #------------------------------------------------------------------------------- # FILE: mymail.py # PURPOSE: send mail messages and receive commands via email # # AUTHOR: Jason G Yates # DATE: 18-Nov-2016 # # MODIFICATIONS: #-----------------------------------------------------------------...
self.Threads["EmailCommandThread"] = MyThread(self.EmailCommandThread, Name = "EmailCommandThread", start = start) self.LogError("IMAP enabled")
else: self.FatalError("ERROR: incoming_callback, incoming_folder and processed_folder are required if receive IMAP is used") #---------- MyMail.TestSendSettings ---------------------------------------- @staticmethod def TestSendSettings( smtp_server = None, smtp_port = 5...
kambysese/mne-python
mne/commands/mne_browse_raw.py
Python
bsd-3-clause
5,212
0
#!/usr/bin/env python r"""Browse raw data. This uses :func:`mne.io.read_raw` so it supports the same formats (without keyword arguments). Examples -------- .. code-block:: console $ mne browse_raw sample_audvis_raw.fif \ --proj sample_audvis_ecg-proj.fif \ --eve sample_a...
n("-s", "--show_options", dest="show_options", help="Show projection options dialog", defaul
t=False) parser.add_option("--allowmaxshield", dest="maxshield", help="Allow loading MaxShield processed data", action="store_true") parser.add_option("--highpass", dest="highpass", type="float", help="Display high-pass filter corner frequency", ...
dimagi/commcare-hq
corehq/pillows/base.py
Python
bsd-3-clause
2,290
0.00262
from corehq.apps.change_feed.data_sources import SOURCE_COUCH VALUE_TAG = '#value' def map_types(item, mapping, override_root_keys=None): if isinstance(item, dict): return convert_property_dict(item, mapping, override_root_keys=override_root_keys) elif isinstance(item, list): return [map_type...
inue dynamic_mapping = mapping.get('dynamic', True) sub_mapping = mapping.get('properties', {}).get(k, {}) if dynamic_mapping is not False: sub_dict[k] = map_types(v, sub_mapping, o
verride_root_keys=override_root_keys) return sub_dict def restore_property_dict(report_dict_item): """ Revert a converted/retrieved document from Report<index> and deconvert all its properties back from {#value: <val>} to just <val> """ restored = {} if not isinstance(report_dict_item, dic...
qsnake/gpaw
gpaw/transport/intctrl.py
Python
gpl-3.0
7,054
0.007372
import numpy as np class PathInfo: def __init__(self, type, nlead): self.type = type self.num = 0 self.lead_num = nlead self.energy = [] self.weight = [] self.nres = 0 self.sigma = [] for i in range(nlead): self.sigma.append([]) if...
= [ min_energy, min_energy + (10 + dkt)*1.j, #-nkt + (10 + dkt) * 1.j, -nkt + dkt * 1.j, dkt *1.j +nkt] self.eqdelta = dkt nRes = 8 if abs( nRes - (np.round((nRes - 1) //...
1e-3 : print 'Warning: Residue Point too close to IntPath!' self.eqresz = range(1, nRes, 2) for i in range(len(self.eqresz)): self.eqresz[i] *= 1.j * np.pi * self.kt if verbose: print '--eqIntCtrl: Tol = ', self.eqinttol, 'Delta =', \ ...
imageworks/OpenShadingLanguage
testsuite/hashnoise/run.py
Python
bsd-3-clause
294
0.006803
#!/usr/bin/env python # Copyright Contributors to the Open Shading Language project. # SPDX-License-Identifier: BSD-3-Clause # https://github
.com/AcademySoftwareFoundation/OpenShadingLanguage command = testshade("-g 128 128 -
od uint8 -o Cout out.tif test") outputs = [ "out.txt", "out.tif" ]
sagnik17/Movie-Recommendation-System
site/id_generator.py
Python
gpl-3.0
204
0.034314
import pickle if __name__ == '__main__': with open('id_generator.bin', 'rb') as f: _id = pickle.load(
f) print(_id) with open('id_generator.bin', 'wb') as f: _id += 1
pickle.dump(_id, f)
rpavlik/jhbuild-vrjuggler
jhbuild/commands/sanitycheck.py
Python
gpl-2.0
6,633
0.00392
# jhbuild - a build script for GNOME 1.x and 2.x # Copyright (C) 2001-2006 James Henstridge # # sanitycheck.py: check whether build environment is sane # # This program is free software; you can redistribute it and/or modify # it un
der 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, # but WITHOUT ANY WARRANTY; without even the implied warranty
of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 US...
ViaFerrata/DL_pipeline_TauAppearance
scraps/multi_gpu/multi_gpu.py
Python
agpl-3.0
39,536
0.000481
# -*- coding: utf-8 -*- """ Multi-gpu code for Keras/TF. From https://github.com/avolkov1/keras_experiments """ # MODIFIED. Inspiration taken from the ref link below. # ref: https://raw.githubusercontent.com/kuza55/keras-extras/master/utils/multi_gpu.py @IgnorePep8 # The inspirational one carried license: # Apache ...
rror: # raise RuntimeError('Keyword argument "model_creator" required '
# 'for ModelMGPU.') try: smodel = kwargs.pop('serial_model') except KeyError: raise RuntimeError('Keyword argument "serial_model" required ' 'for ModelMGPU.') # SET STATE: Instance of serial model for checkpointing...
Cophy08/ggplot
ggplot/geoms/geom_blank.py
Python
bsd-2-clause
363
0
from __future__ import (absolute_import, division, print_function, unicode_literals) from .geom import geom class geom_
blank(geom): DEFAULT_AES = {} REQUIRED_AES = set()
DEFAULT_PARAMS = {'stat': 'identity', 'position': 'identity'} _aes_renames = {} _units = set() def _plot_unit(self, pinfo, ax): pass
saeki-masaki/cinder
cinder/volume/drivers/blockbridge.py
Python
apache-2.0
21,533
0
# Copyright 2013-2015 Blockbridge Networks, 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 on an "AS IS"...
erning permissions and limitations # under the License. """ Blockbridge EPS iSCSI Volume Driver """ import base64 import httplib import socket import urllib from oslo_config import cfg from oslo_log import log as logging from oslo_serialization import jsonutils from oslo_utils import units from cinder import cont...
jmesteve/saas3
openerp/addons/crm_claim/crm_claim.py
Python
agpl-3.0
9,712
0.00453
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-today OpenERP SA (<http://www.openerp.com>) # # This program is free software: you can redistribute it and/or modify # it under the terms o...
return self.stage_find(cr, uid, [], section_id, [('sequence', '=', '1')], context=context) _columns = { 'id': fields.integer('ID', readonly=True), 'name': fields.char('Claim S
ubject', size=128, required=True), 'active': fields.boolean('Active'), 'action_next': fields.char('Next Action', size=200), 'date_action_next': fields.datetime('Next Action Date'), 'description': fields.text('Description'), 'resolution': fields.text('Resolution'), 'create...
dddomodossola/remi
examples/examples_from_contributors/camera.py
Python
apache-2.0
2,815
0.012433
#!/usr/bin/python3.7 import ssl import remi.gui as gui from remi import start, App class Camera(App): def __init__(self, *args, **kwargs): super(Camera, self).__init__(*args) def video_widgets(self): width = '300' height = '300' self.video = gui.Widget(_type='video') s...
enable_file_cache=True, start_bro
wser=False, debug=False) # certfile='./ssl_keys/fullchain.pem', # keyfile='./ssl_keys/privkey.pem', # ssl_version=ssl.PROTOCOL_TLSv1_2,
yxping/leetcode
solutions/226.Invert_Binary_Tree/AC_stack_n.py
Python
gpl-2.0
730
0.005479
#!/usr/bin/python # -*- coding: utf-8 -*- # Author:
illuz <iilluzen[at]gmail.com> # File: AC_stack_n.py # Create Date: 2015-07-26 10:53:38 # Usage: AC_stack_n.py # Descripton: # Defi
nition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param {TreeNode} root # @return {TreeNode} def invertTree(self, root): stack = [root] while stack: node = stack.po...
ESOedX/edx-platform
lms/djangoapps/verify_student/management/commands/manual_verifications.py
Python
agpl-3.0
3,303
0.002725
""" Django admin commands related to verify_student """ from __future__ import absolute_import import logging import os from pprint import pformat from django.contrib.auth.models import User from django.core.management.base import BaseCommand, CommandError from lms.djangoapps.verify_student.models import ManualVerif...
Example usage: $ ./manage.py lms manual_verifications --email-ids-file <absolute path of file with email ids (one per line)> """ help = 'Manually verifies one or more users passed as an argument list.' def add_arguments(self, parser): parser.add_argument( '--email-ids-file', ...
dest='email_ids_file', default=None, help='Path of the file to read email id from.', type=str, required=True ) def handle(self, *args, **options): email_ids_file = options['email_ids_file'] if email_ids_file: if not os.path...
maru/fiubar
fiubar/users/forms.py
Python
mit
4,831
0
# -*- coding: utf-8 -*- from crispy_forms.bootstrap import FormActions from crispy_forms.helper import FormHelper from crispy_forms.layout import HTML, Div, Field, Layout, Submit from django import forms from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from .mo...
label for="id_status" class="control-label ">'), HTML(_('Occupation')), HTML('</label>'), Div('student', 'assistant', 'professional', 'professor', css_class='users-update-status'), Field('bio', rows="3", css_class='input-xlarge'), FormActions( Submit('subm...
'user', 'avatar'] DELETE_CONFIRMATION_PHRASE = _('delete my account') class UserDeleteForm(forms.ModelForm): confirmation_phrase_en = _('To verify, type "<span class=' '"confirmation-phrase do-not-copy-me">' 'delete my account</span>" below:') f...
Zahajamaan/Fudulbank
exams/migrations/0059_session_has_finished.py
Python
agpl-3.0
474
0
# -
*- coding: utf-8 -*- # Generated by Django 1.11.8 on 2017-12-18 07:22 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('exams', '0058_fill_explanation_is_contribution'), ] operations = [ migrations....
name='has_finished', field=models.NullBooleanField(default=None), ), ]
tboyce1/home-assistant
tests/components/zha/test_device_action.py
Python
apache-2.0
3,876
0.000516
"""The test for zha device automation actions.""" from unittest.mock import patch import pytest import zigpy.profiles.zha import zigpy.zcl.clusters.general as general import zigpy.zcl.clusters.security as security import zigpy.zcl.foundation as zcl_f import homeassistant.components.automation as automation from homea...
"domain": DOMAIN, "device_id": reg_device.id, "type": "warn", }, } ] }, ) await hass.async_block_till_done() calls = async_mock_service(hass, DOMAIN...
sync_block_till_done() assert len(calls) == 1 assert calls[0].domain == DOMAIN assert calls[0].service == "warning_device_warn" assert calls[0].data["ieee"] == ieee_address