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
mfraezz/osf.io
osf/migrations/0049_preprintprovider_preprint_word.py
Python
apache-2.0
579
0.001727
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-08-09 17:56 from __future__ import unicode_literals from django.db impo
rt migrations, mo
dels class Migration(migrations.Migration): dependencies = [ ('osf', '0048_merge_20170804_0910'), ] operations = [ migrations.AddField( model_name='preprintprovider', name='preprint_word', field=models.CharField(choices=[('preprint', 'Preprint'), ('pap...
NoBodyCam/TftpPxeBootBareMetal
nova/image/glance.py
Python
apache-2.0
14,223
0.000492
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 OpenStack LLC. # 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/...
mages.append(self._translate_from_glance(image)) return _images def _extract_query_params(self, params): _params = {} accepted_params = ('filters', 'ma
rker', 'limit', 'sort_key', 'sort_dir') for param in accepted_params: if param in params: _params[param] = params.get(param) # ensure filters is a dict params.setdefault('filters', {}) # NOTE(vish): don't filter out private images ...
MingfeiPan/leetcode
backtracking/79.py
Python
apache-2.0
1,039
0.010587
class Solution: def exist(self, board, word): """ :type board: List[List[str]] :type word: str :rtype: bool """ for i in range(0, len(board)): if not board: return False for j in range(0, len(board[0])): ...
j] = '.' ret = self.dfs(i-1,j,board, wo
rd, index+1) or self.dfs(i+1,j,board, word, index+1) or self.dfs(i,j-1,board, word, index+1) or self.dfs(i,j+1,board, word, index+1) board[i][j] = tmp return ret else: return False
ychen820/microblog
y/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.2/webapp2_extras/security.py
Python
bsd-3-clause
6,834
0
# -*- coding: utf-8 -*- """ webapp2_extras.security ======================= Security related helpers such as secure password hashing tools and a random token generator. :copyright: (c) 2010 by the Werkzeug Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. :co...
:returns: True if both strings are equal, False otherwise. """ if len(a) != len(b): return False result = 0 for x
, y in zip(a, b): result |= ord(x) ^ ord(y) return result == 0 # Old names. create_token = generate_random_string create_password_hash = generate_password_hash
teeple/pns_server
work/install/Python-2.7.4/Lib/test/test_urllib.py
Python
gpl-2.0
35,463
0.002143
"""Regresssion tests for urllib""" import urllib import httplib import unittest import os import sys import mimetools import tempfile import StringIO from test import test_support from base64 import b64encode def hexescape(char): """Escape char as RFC 2396 specifies""" hex_repr = hex(ord(char))[2:].upper() ...
for line in self.returned_obj.__iter__(): self.assertEqual(line, self.text) def test_relativelocalfile(self): self.assertRaises(ValueError,urllib.urlo
pen,'./' + self.pathname) class ProxyTests(unittest.TestCase): def setUp(self): # Records changes to env vars self.env = test_support.EnvironmentVarGuard() # Delete all proxy related env vars for k in os.environ.keys(): if 'proxy' in k.lower(): self.env....
Open-Plus/opgui
lib/python/Components/Sources/List.py
Python
gpl-2.0
3,424
0.033586
from Source import Source from Components.Element import cached class List(Source, object): """The datasource of a listbox. Currently, the format depends on the used converter. So if you put a simple string list in here, you need to use a StringList converter, if you are using a "multi content list styled"-list, you ...
Changed(self, index): if self.disable_callbacks: return # update all non-master targets for x in self.downstream_elements: if x is not self.master: x.index = index for x in self.onSelectionChanged: x() @cached def getCurrent(self): return self.master is not None and self.mas
ter.current current = property(getCurrent) def setIndex(self, index): if self.master is not None: self.master.index = index self.selectionChanged(index) @cached def getIndex(self): if self.master is not None: return self.master.index else: return None setCurrentIndex = setIndex index = prop...
goodking-bq/golden-note
source/_static/socks5_server/udp_c.py
Python
mit
1,286
0.00311
# coding:utf-8 from __future__ import absolute_import, unicode_literals __author__ = "golden" __date__ = '2017/10/12' import asyncio class EchoClientProtocol: def __init__(self, message, loop): self.message = message self.loop = loop self.transport = None def connection_made(self, t...
event_loop() message = "Hell
o World!" connect = loop.create_datagram_endpoint( lambda: EchoClientProtocol(message, loop), remote_addr=('127.0.0.1', 2222)) transport, protocol = loop.run_until_complete(connect) loop.run_forever() transport.close() loop.close()
rbdavid/DENV-NS3h
RMSD_analyses/sel_list.py
Python
gpl-3.0
529
0.020794
### Paper RMSD selections ### sel = [] sel.append(['a2_subdomain1_backbone','backbone
and resid 57:68 and not name H*']) sel.append(['mo
tif_2_backbone','backbone and resid 117:124 and not name H*']) sel.append(['aligned_CAs','protein and (resid 20:25 50:55 73:75 90:94 112:116 142:147 165:169 190:194 214:218 236:240 253:258 303:307) and name CA']) sel.append(['aligned_betas','protein and (resid 20:25 50:55 73:75 90:94 112:116 142:147 165:169 190:194 214...
simphony/simphony-openfoam
edmsetup.py
Python
gpl-2.0
1,743
0.001721
import sys import click import os import subprocess from packageinfo import BUILD, VERSION, NAME if "WM_PROJECT" not in os.environ: print("To run this command you must source edmenv.sh first") sys.exit(1) # The version of the buildcommon to checkout. BUILDCOMMONS_VERSION="v0.1" def bootstrap_devenv(): ...
interface/wrapper"): common.run("python edmsetup.py egg") @cli.command() def upload_egg(): egg_path = "endist/{NAME}-{VERSION}-{BUILD}.egg".format( NAME=NAME, VERSION=VERSION, BUILD=BUILD) click.echo("Uploading {} to EDM repo".format(egg_path)) commo
n.upload_egg(egg_path) with common.cd("openfoam-interface/internal-interface/wrapper"): try: common.run("python edmsetup.py upload_egg") except subprocess.CalledProcessError as e: print("Error during egg upload of submodule: {}. Continuing.".format(e)) click.echo("Done"...
cacraig/grib-inventory
gribinventory/models/NonNCEPModel.py
Python
mit
1,819
0.018692
import time from bs4 import BeautifulSoup import sys if (sys.version_info > (3, 0)): # Python 3 code in this block import urllib.request as urllib2 else: # Python 2 code in this block import urllib2 import datetime, re, os class NonNCEPModel: ''''' Base Class for all Non-NCEP models. ''''' def __init_...
f.defaultTimes ''''' Intia
lze all of our models hour stamp data to defaults. ''''' def getDefaultHours(self): # Default times. modelTimes = self.defaultTimes return modelTimes def getName(self): return self.name def getAlias(self): if self.modelAliases != "": return self.modelAlias else: return...
hackerspace-ntnu/website
applications/migrations/0009_applicationperiod_name.py
Python
mit
471
0.002123
# Generate
d by Django 2.0.10 on 2019-01-14 11:39 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('applications', '0008_applicationperiod'), ] operations = [ migrations.AddField( model_name='applicationperiod', name='name', ...
), ]
andrewyoung1991/abjad
abjad/tools/timespantools/CompoundInequality.py
Python
gpl-3.0
7,680
0.002214
# -*- encoding: utf-8 -*- from abjad.tools import durationtools from abjad.tools.datastructuretools.TypedList import TypedList class CompoundInequality(TypedList): '''A compound time-relation inequality. :: >>> compound_inequality = timespantools.CompoundInequality([ ... timespantools.Com...
truth_value = inequality.evaluate_offset_inequality( timespan_start, timespan_stop, offset) truth_values.append(truth_value) else: message = 'unknown inequality: {!r}.' message = message.format(inequality) rai...
sert truth_values, repr(truth_values) if self.logical_operator == 'and': truth_value = all(truth_values) elif self.logical_operator == 'or': truth_value = any(truth_values) elif self.logical_operator == 'xor': truth_value = bool(len([x for x in truth_values if...
ryanjoneil/docker-image-construction
ipynb/examples/example2-3-sub.py
Python
mit
7,365
0.003802
from mosek.fusion import Model, Domain, Expr, ObjectiveSense import sys # TODO: need a way to determine if we're adding something in front of an # existing clique, or intersecting with it, etc. # Example 2. Column generation approach. # Iteration 2, subproblem. # Output: # # Images: # w_1 = 1 # ...
, Expr.sub(0.0, Ex
pr.add([w_3, y_a])), Domain.greaterThan(-1.0)) m.constraint('c_3_b_1', Expr.sub(z_3_b, w_3), Domain.lessThan(0.0)) m.constraint('c_3_b_2', Expr.sub(z_3_b, y_b), Domain.lessThan(0.0)) m.constraint('c_3_b_3', Expr.sub(z_3_b, Expr.add([w_3, y_b])), Domain.greaterThan(-1.0)) m.constraint('c_3_c_1', Expr.sub(z_3_c, w_3), ...
smallyear/linuxLearn
salt/salt/states/lvs_server.py
Python
apache-2.0
6,440
0.004503
# -*- coding: utf-8 -*- ''' Management of LVS (Linux Virtual Server) Real Server ==================================================== ''' def __virtual__(): ''' Only load if the lvs module is available in __salt__ ''' return 'lvs_server' if 'lvs.get_rules' in __salt__ else False def present(name, ...
ress=service_address, server_address=server_address) if server_check is True: if __opts__['test']: ret['result'] = None ret['comment'] = 'LVS Server {0} in service {1}({2}) is present and needs to be removed'.format(name, service_addres...
dress=service_address, server_address=server_address) if server_delete is True: ret['comment'] = 'LVS Server {0} in service {1}({2}) has been removed'.format(name, service_address, protocol) ret['changes'][name] = 'Absent' ...
Brightgalrs/con-lang-gen
maketree.py
Python
mit
2,237
0.007599
from ete3 import Tree, TreeStyle, Tree, TextFace, NodeStyle, add_face_to_node import sys from collections import OrderedDict import os # build list of filenames filenames = [] for d in os.listdir('out/'): filenames.append('out/' + d + '/') # roman numeral thing just incase things get crowded... def write_roman(nu...
= -180 # 0 degrees = 3 o'clock #ts.arc_span = 180 def my_layout(node): F = TextFace(node.name, tight_text=False) F.margin_top = 1 F.margin_right = 5 F.margin_left = 5 add_face_to_node(F, node, column=0, position="branch-bottom") ts.la...
le["vt_line_width"] = 2 i = 1 for n in t.traverse(): n.set_style(nstyle) #ts.legend.add_face(TextFace(write_roman(i).lower() + ". "), column=0) #ts.legend.add_face(TextFace(n.name), column=1) #n.name = write_roman(i).lower() i += 1 #t.rend...
truetug/django-admin-helper
test_proj/test_proj/wsgi.py
Python
mit
395
0
""" WSGI config for test_proj project. It exposes the WSGI callable as a module-level variable
named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_proj.settings") applicatio
n = get_wsgi_application()
Stanford-Online/edx-platform
lms/djangoapps/support/tests/test_views.py
Python
agpl-3.0
17,238
0.002147
# coding: UTF-8 """ Tests for support views. """ import itertools import json import re from datetime import datetime, timedelta import ddt import pytest from django.contrib.auth.models import User from django.urls import reverse from django.db.models import signals from nose.plugins.attrib import attr from pytz impo...
ontains(response, "courseFilter: '" + unicode(self.course.id) + "'") @ddt.ddt class SupportViewEnrollmentsTests(SharedModuleStoreTestCase, SupportViewTestCase): """Tests for the enrollment support view.""" def setUp(self): super(SupportViewEnrollmentsTests, self).setUp() SupportStaffRole().ad...
est') for mode in ( CourseMode.AUDIT, CourseMode.PROFESSIONAL, CourseMode.CREDIT_MODE, CourseMode.NO_ID_PROFESSIONAL_MODE, CourseMode.VERIFIED, CourseMode.HONOR ): CourseModeFactory.create(mode_slug=mode, course_id=self.course.id) # pylint: disable=no-member...
wooey/Wooey
wooey/models/mixins.py
Python
bsd-3-clause
1,643
0
from django.db.models.query_utils import DeferredAttribute from django.forms.models import model_to_dict from ..backend import utils class UpdateScriptsMixin(object): pass class WooeyPy2Mixin(object): def __unicode__(self): return unicode(self.__str__()) # from # http://stackoverflow.com/question...
A model mixin that tracks model fields' values and provide some useful api to know what fields have been changed. """ def __init__(self, *args, **kwargs): super(ModelDiffMixin, self).__init__(*args, **kwargs) self.__initial = self._dict @property def diff(self): d1 = self...
d2[k])) for k, v in d1.items() if v != d2[k]] return dict(diffs) @property def has_changed(self): return bool(self.diff) @property def changed_fields(self): return self.diff.keys() def get_field_diff(self, field_name): """ Returns a diff for field if it's c...
ritchiewilson/majormajor
tests/document/test_document_missing_changesets.py
Python
gpl-3.0
3,226
0.00155
# MajorMajor - Collaborative Document Editing Library # Copyright (C) 2013 Ritchie Wilson # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option)...
s(self): doc = Document(snapshot='') doc.HAS_EVENT_LOOP = False assert doc.missing_changesets == set([]) assert doc.pending_new_changesets == [] root = doc.get_root_changeset() A = Changeset(doc.get_id(), "dummyuser", [root]) doc.receive_changeset(A) ...
sets == set([]) assert doc.pending_new_changesets == [] # Just one Changeset gets put in pending list B = Changeset(doc.get_id(), "user1", ["C"]) B.set_id("B") doc.receive_changeset(B) assert doc.get_ordered_changesets() == [root, A] assert doc.missing_changesets...
scifiswapnil/Project-LoCatr
LoCatr/LoCatr/apps.py
Python
mit
152
0
# -*- coding: utf-8 -
*- from __future__ import unicode_literals from django.apps import A
ppConfig class LoCatrConfig(AppConfig): name = 'LoCatr'
omf2097/pyomftools
omftools/pyshadowdive/palette.py
Python
mit
1,805
0
from validx import Dict, List, Tuple import typing from .protos import DataObject from .utils.validator import UInt8 from .utils.types import Color, Remapping class Palette(DataObject): __slots__ = ("data",) schema = Dict({"data": List(Tuple(UInt8, UInt8, UInt8))}) def __init__(self): self.data...
.data[m]) def serialize(self) -> dict: return { "data": self.data, } def unserialize(self, da
ta: dict): self.data = data["data"] return self
opentrials/opentrials-airflow
tests/dags/operators/test_postgres_to_s3_transfer.py
Python
mpl-2.0
2,927
0.001367
try: import unittest.mock as mock except ImportError: import mock import subprocess import dags.utils.helpers as helpers from dags.operators.postgres_to_s3_transfer import PostgresToS3Transfer class TestPostgresToS3Transfer(object): def test_its_created_successfully(self): operator = PostgresToS3T...
ssert_called_with(expected_command, stdout=subprocess.PIPE) @mock.patch('subprocess.Popen') @mock.patch('boto3.resource', autospec=True) @mock.patch('airflow.hooks.
base_hook.BaseHook.get_connection') def test_execute_dumps_only_whitelisted_tables(self, get_connection_mock, boto3_mock, popen_mock): tables = [ 'users', 'log', ] operator = PostgresToS3Transfer( task_id='task_id', postgres_conn_id='postgres_c...
Juanlu001/CBC.Solve
cbc/swing/fsinewton/utils/timings.py
Python
gpl-3.0
3,415
0.016398
"""Utility Class used to report timings """ import time class Timings(object): def __init__(self): """Key of data dictionary is the name for timings, values are a tuple which is (n,t,st) where n is the number of calls, and t the cumulative time it took, and st the status ('finished',STARTTIME)""" ...
""" assert self._last != None self.stop(self._last) def startnext(self,name): """Will stop whatever measurement has been started most recently, and start the next one with name 'name'.""" if self._last: self.stop(self._last) self.start(name) def get...
return self.data[name][0] def gettime(self,name): return self.data[name][1] def report_str(self,n=10): """Lists the n items that took the longest time to execute.""" msg = "Timings summary, longest items first:\n" #print in descending order of time taken sorted_ke...
portante/sosreport
sos/plugins/sysvipc.py
Python
gpl-2.0
1,199
0.010842
## Copyright (C) 2007-2012 Red Hat, Inc., Bryn M. Reeves <bmr@redhat.com> ### This program is free software; you can redistribute i
t and/or modify ## it under the te
rms 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 FI...
kongji2008/genetify
pygooglechart/examples/helper.py
Python
mit
290
0.013793
import random de
f random_data(points=50, maximum=100): return [random.random() * maximum for a in xrange(points)] def random_colour(min=20, max=200): func = lambda: int(random.random() * (max-min) + min) r, g, b = func(), func(), func() return '%02X%02X%02X' % (r,
g, b)
stephanie-wang/ray
python/ray/tune/examples/nevergrad_example.py
Python
apache-2.0
1,858
0
"""This test checks that Nevergrad is functional. It also checks that it is usable with a separate scheduler. """ import ray from ray.tune import run from ray.tune.schedulers import AsyncHyperBandScheduler from ray.tune.suggest.nevergrad import NevergradSearch def easy_objective(config, reporter): import time ...
entation = inst.Instrumentation( # height=inst.var.Array(1).bounded(0, 200).asfloat(), # width=inst.var.OrderedDiscrete([0, 10, 20, 30, 40, 50])) # parameter_names = None # names are provided by the instrumentation
optimizer = optimizerlib.OnePlusOne(instrumentation) algo = NevergradSearch( optimizer, parameter_names, max_concurrent=4, metric="mean_loss", mode="min") scheduler = AsyncHyperBandScheduler(metric="mean_loss", mode="min") run(easy_objective, name="neverg...
fblupi/master_informatica-SSBW
tarea6/sitio_web/restaurantes/urls.py
Python
gpl-3.0
408
0
from django.conf.urls import url from .
import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^list/$', views.list, name='list'), url(r'^search/$', views.search, name='search'), url(r'^add/$', views.add, name='add'), url(r'^restaurant/(?P<id>[0-9]+)$', views.restaurant, name='restau
rant'), url(r'^images/(?P<id>[0-9]+)$', views.show_image, name='show_image') ]
jakeret/tf_unet
tf_unet/__init__.py
Python
gpl-3.0
101
0
__author__ = 'Joel Akeret' __version__ = '0.1.2' __credits__ = 'ETH Zurich, Inst
itute for Astron
omy'
JarrodCTaylor/vim-shell-executor
autoload/vim_shell_executor.py
Python
mit
1,433
0.002791
import subprocess import os INPUT_FILE = "/tmp/input" ERROR_LOG = "/tmp/error.log" RESULTS_FILE = "/tmp/results" def get_command_from_first_line(line): if line.startswith("#!"): return line[2:] return line def get_program_output_from_buffer_contents(buffer_contents): write_buffer_contents_to_file...
errors = read_file_lines(ERROR_LOG) std_out = read_file_lines(RESULTS_FILE) new_buf = errors + std_out return new_buf def write_buffer_contents_to_file(file_name, contents): with open(file_name, "w") as f: for line in contents: f.write(line + "\n") def execute_file_with_speci...
ell_program(shell_command): try: subprocess.check_call("{0} {1} {2} > {3} 2> {4}".format( shell_command, redirect_or_arg(shell_command), INPUT_FILE, RESULTS_FILE, ERROR_LOG), shell=True ) except: pass def redirect_...
JohnVinyard/zounds
zounds/index/hammingdb.py
Python
mit
7,331
0.000818
import lmdb from zounds.nputil import Growable, packed_hamming_distance import numpy as np from multiprocessing.dummy import Pool as ThreadPool from multiprocessing import cpu_count import os import binascii class HammingDb(object): def __init__(self, path, map_size=1000000000, co
de_size=8, writeonly=False): super(HammingDb, self).__
init__() self.writeonly = writeonly if not os.path.exists(path): os.makedirs(path) self.path = path self.env = lmdb.open( self.path, max_dbs=10, map_size=map_size, writemap=True, map_async=True, metasy...
GuessWhoSamFoo/pandas
pandas/tests/groupby/test_counting.py
Python
bsd-3-clause
7,838
0
# -*- coding: utf-8 -*- from __future__ import print_function import numpy as np import pytest from pandas.compat import product as cart_product, range from pandas import DataFrame, MultiIndex, Period, Series, Timedelta, Timestamp from pandas.util.testing import assert_frame_equal, assert_series_equal class TestCo...
5) assert_series_equal(expected, g.ngroup()) assert_series_equal(expected, sg.ngroup()) def test_ngroup_empty(self): ge = DataFrame().groupby(level=0) se = Series().groupby(level=0) # edge case, as this is usually considered float
e = Series(dtype='int64') assert_series_equal(e, ge.ngroup()) assert_series_equal(e, se.ngroup()) def test_ngroup_series_matches_frame(self): df = DataFrame({'A': list('aaaba')}) s = Series(list('aaaba')) assert_series_equal(df.groupby(s).ngroup(), ...
Callek/build-relengapi
relengapi/lib/logging.py
Python
mpl-2.0
3,196
0.000313
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from __future__ import absolute_import import logging import os import structlog import sys from datetime import datet...
ozdef # move everything to a 'details' sub-key details = event_dict event_dict = {'details': details} # but pull out the summary/event event_dict['summary'] = details.pop('event') if not details: event_dict.pop('details') # and set some other fields based on context event_dict...
format() event_dict['processid'] = os.getpid() event_dict['processname'] = 'relengapi' event_dict['source'] = logger.name event_dict['severity'] = method_name.upper() event_dict['tags'] = ['relengapi'] return event_dict def reset_context(**kwargs): logger.new(**kwargs) def configure_logg...
Air-Fighter/DecomposableAttModel_PyTorch
model.py
Python
gpl-2.0
2,524
0.001981
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable class Bottle(nn.Module): def forward(self, input): if len(input.size()) <= 2: return super(Bottle, self).forward(input) size = input.size()[:2] out = super(Bottle, self).forw...
def forward(self, batch): prem_embed = self.embed(batch.premise.transpose(0, 1)) hypo_embed = self.embed(batch.hypothesis.transpose(0, 1)) if self.config.fix_emb: prem_embed = Variable(prem_embed.data) hypo_embed = Variable(hypo_embed.data) e = torch.bmm(self....
2)) e_ = F.softmax(e) e_t = F.softmax(e.transpose(1, 2)) beta = torch.bmm(e_, hypo_embed) alpha = torch.bmm(e_t, prem_embed) v1 = self.G(torch.cat((prem_embed, beta), 2)).sum(1) v2 = self.G(torch.cat((hypo_embed, alpha), 2)).sum(1) v = F.softmax(self.H(self.dr...
Micronaet/micronaet-mx8
mx_sale_parcels/parcels.py
Python
agpl-3.0
3,131
0.006068
# -*- coding: utf-8 -*- ############################################################################### # # Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License a...
import relativedelta from openerp import SUPERUSER_ID, api from openerp import tools from openerp.tools.translate import _ from openerp.tools.float_utils import float_round as round from openerp.tools import (DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT, DATETIME_FORMATS_MAP, float_compare...
def update_parcels_event(self, cr, uid, ids, context=None): ''' Get total of parcels ''' assert len(ids) == 1, 'Only one element a time' parcels = 0 parcels_note = '' for line in self.browse(cr, uid, ids, context=context)[0].order_line: if line.pro...
RobbieClarken/channelarchiver
channelarchiver/structures.py
Python
mit
703
0
# -*- coding: utf-8 -*- class Codes(object): def __init__(self, **kws): self._reverse
_dict = {} for k, v in kws.items(): self.__setattr__(k, v) def str_value(self, value): return self._reverse_dict[value] def __setattr__(self, name, value): super(Codes, self).__setattr__(name, value) if not name.startswith("_"): self._reverse_dict[value]...
name def __repr__(self): constants_str = ", ".join( f"{v}={k!r}" for k, v in sorted(self._reverse_dict.items()) ) return f"Codes({constants_str})" def __getitem__(self, key): return self.__dict__[key.replace("-", "_").upper()]
axlt2002/script.light.imdb.ratings.update
resources/support/tmdbsimple/search.py
Python
gpl-3.0
6,284
0.003342
# -*- coding: utf-8 -*- """ tmdbsimple.search ~~~~~~~~~~~~~~~~~ This module implements the Search functionality of tmdbsimple. Created by Celia Oakley on 2013-10-31. :copyright: (c) 2013-2018 by Celia Oakley :license: GPLv3, see LICENSE for more details """ from .base import TMDB class Search(TMDB): """ Se...
elf._get_path('keyword') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response def multi(self, **kwargs): """ Search the movie, tv show and person collections with a single query. Args: query: CGI escpaed string. ...
Expected value is an integer. language: (optional) ISO 639-1 code. include_adult: (optional) Toggle the inclusion of adult titles. Expected value is True or False. Returns: A dict respresentation of the JSON returned from the API. """ ...
steveb/heat
heat_integrationtests/common/clients.py
Python
apache-2.0
8,193
0
# 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 # d...
for calling various APIs. Manager that provides access to the official python clients for calling various OpenStack APIs. """ CINDERCLIENT_VERSION = '2' HEATCLIENT_VERSION = '1' NOVACLIENT_VERSION = '2' CEILOMETER_VERSION = '2' def __init__(self, conf): self.c
onf = conf if self.conf.auth_url.find('/v'): self.v2_auth_url = self.conf.auth_url.replace('/v3', '/v2.0') self.auth_version = self.conf.auth_url.split('/v')[1] else: raise ValueError(_('Incorrectly specified auth_url config: no ' 'versi...
junneyang/taskflow
taskflow/tests/unit/test_progress.py
Python
apache-2.0
5,259
0
# -*- coding: utf-8 -*- # Copyright (C) 2012 Yahoo! 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...
d self.assertEqual(2, len(fired_events)) self.assertEqual(1.0, fired_events[-1]) self.assertEqual(0.0, fired_events[0]) def test_storage_progress(self): with contextlib.closing(impl_memory.MemoryBackend({})) as be: flo = lf.Flow("test") flo.add(ProgressTask("...
", 3)) b, fd = p_utils.temporary_flow_detail(be) e = self._make_engine(flo, flow_detail=fd, backend=be) e.run() end_progress = e.storage.get_task_progress("test") self.assertEqual(1.0, end_progress) task_uuid = e.storage.get_atom_uuid("test") ...
Makeystreet/makeystreet
woot/apps/catalog/migrations/0127_auto__add_field_makey_derived_from.py
Python
apache-2.0
64,380
0.007689
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Makey.derived_from' db.add_column(u'catalog_makey', 'deri...
ango.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '200'}) }, 'catalog.cfistoreitem': { 'Meta': {'object_name': 'CfiStoreItem'}, 'added_time': ('django.db.models.fields.DateTimeField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'pri...
o.db.models.fields.BooleanField', [], {'default': 'True'}), 'item': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['catalog.Product']", 'unique': 'True'}), 'likers': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'cfi_store_item_likes'", 'symmetrical...
cojacoo/testcases_echoRD
gen_test2111b.py
Python
gpl-3.0
430
0.044186
mcinif='mcini_gen2' r
unname='gen_test2111b' mcpick='gen_test2b.pickle' pathdir='/beegfs/work/ka_oj4748/echoRD' wdir='/beegfs/work/ka_oj4748/gen_tests' update_prec=0.04 update_mf=Fa
lse update_part=500 import sys sys.path.append(pathdir) import run_echoRD as rE rE.echoRD_job(mcinif=mcinif,mcpick=mcpick,runname=runname,wdir=wdir,pathdir=pathdir,update_prec=update_prec,update_mf=update_mf,update_part=update_part,hdf5pick=False)
Skchoudhary/python_programm
list.py
Python
mit
551
0.029038
#! /usr/bin/env python3 a = [1, 3, 4, 5, 8] a.append(23) #adding element at last position of list. a.insert(0,23) #ins
erting at first position of list. a.insert(2,21) #inserting at second position of list. print("list : ", a) del a[-1] #delete last element. a.remove(3) #delete element from list. print("deletion opeartion on list : ", a) a.append(11) k= a.count(11) print("k : ", k) b = [34, 56, 221, 3] a.append(b) # append list at ...
a.sort() print(a)
coreos/chromite
buildbot/repository_unittest.py
Python
bsd-3-clause
3,059
0.005557
#!/usr/bin/python # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import functools import os import sys import constants sys.path.insert(0, constants.SOURCE_ROOT) from chromite.buildbot import rep...
t) self.assertFalse(repository.IsInternalRepoCheckout('.')) def testInternalRepoCheckout(self): """Test we detect internal checkouts properly.""" self.mox.StubOutWithMock(cros_build_lib, 'RunCommand') tests = [ 'ssh://gerrit-int.chromium.org:29419/chromeos/manifest-internal.git', 's...
nal', 'ssh://gerrit.chromium.org:29418/chromeos/manifest-internal', 'test@abcdef.bla.com:39291/bla/manifest-internal.git', ] for test in tests: cros_build_lib.RunCommand = functools.partial(self.RunCommand_Mock, test) self.assertTrue(repository.IsInternalRepoCheckout('.')) class R...
ActiveState/code
recipes/Python/83048_Dynamic_generatidispatcher/recipe-83048.py
Python
mit
2,283
0.002628
def generate_dispatcher(method_handler, parent_class=None): """ Create a dispatcher class and return an instance of it from a dispatcher definition. The definition is a class with the following attributes: _ EXPORTED_METHOD: dictionary where keys are method names and values class attribute nam...
s def %s(self, *attrs):\n return self.%s.%s(*attrs)\n'%\ (class_str, method, objname, method) # constructor definition attrs = '' for objname in registered: attrs = '%s, %s' % (attrs, objname) statements = '%s self.%s=%s\n' % (statements, objname, objname) # re...
getattr(method_handler, "%s")'%(objname, objname) # assemble all parts class_str = '%s def __init__(self%s):\n%s' % (class_str, attrs, statements) # now we can eval the full class exec class_str # return an instance of constructed class return eval('Dispatcher(%s)'%attrs[2:]) # attrs[2:] for ...
danieldmm/minerva
proc/nlp_query_extraction.py
Python
gpl-3.0
499
0.006012
# should be using spacy for
everything NLP from now on from ml.document_features import en_nlp, selectContentWords from proc.query_extraction import SentenceQueryExtractor, EXTRACTOR_LIST class FilteredSentenceQueryExtractor(SentenceQueryExtractor): def getQueryTextFromSentence(self, sent): doc = en_nlp(sent["text"]) words...
= " ".join(words) return text EXTRACTOR_LIST[ "Sentences_filtered"] = FilteredSentenceQueryExtractor()
goyal-sidd/BLT
website/migrations/0037_auto_20170813_0319.py
Python
agpl-3.0
510
0.001961
# -*- codin
g: utf-8 -*- # Generated by Dja
ngo 1.11.1 on 2017-08-13 03:19 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('website', '0036_auto_20170813_0049'), ] operations = [ migrations.AlterField( model_name='userprofile', ...
vesellov/bitdust.devel
blockchain/pybc/AuthenticatedDictionary.py
Python
agpl-3.0
57,165
0.000875
""" AuthenticatedDictionary.py: Contains an authenticated dictionary
data structure
. Supports O(log n) insert, find, and delete, and maintains a hash authenticating the contents. The data structure is set-unique; if the same data is in it, it always produces the same hash, no matter what order it was inserted in. The data structure is backed by a SQliteShelf database, and exposes a commit() method ...
korovkin/WNNotifier
notifier/sign.py
Python
apache-2.0
2,981
0.015431
#!/usr/bin/python import json import parcon import operator import pprint import os import sys import getopt import re import optparse import md5 import hashlib import version ### def sign_data(data_to_sign): m = hashlib.md5() m.update(data_to_sign) signature = m.hexdigest() return signature #### def source...
file__) #### initial signature toke that i have to use SIGNATURE_TOKEN = '<<SignedSource::*O*zOeWoEQle#+L!plEphiEmie@IsG>>' #### a signature header (prefixed to the signed file): header_template = """// @generated
%s // signed with: https://github.com/korovkin/WNNotifier/notifier/sign.py """ ##### def sign(options, data): """ sign the given, yield a signature that can be verified by phabricator and lint Replaces the followin string in the input file: // @generated <<SignedSource::*O*zOeWoEQle#+L!plEphiEmie@IsG>...
kundan2510/pixelCNN
plot_images.py
Python
mit
1,614
0.042131
import pickle import scipy.misc import numpy as np from sys import argv def plot_25_figure(images, output_name, num_channels = 1): HEIGHT, WIDTH = images.shape[1], images.shape[2] if num_channels == 1: images = images.reshape((5,5,HEIGHT,WIDTH)) # rowx, rowy, height, width -> rowy, height, rowx, width images =...
Exception("You should not be here!! Only 1 or 3 channels allowed for images!!") def plot_100_figure(images, output_name, num_channels = 1): HEIGHT, WIDTH = images.shape[1], images.shape[2] if num_channels == 1: images = images.reshape((10,10,HEIGHT,WIDTH)) # rowx, rowy, height, width -> rowy, height, rowx, wid...
es.reshape((10,10,HEIGHT,WIDTH,3)) images = images.transpose(1,2,0,3,4) images = images.reshape((10*HEIGHT, 10*WIDTH, 3)) scipy.misc.toimage(images).save(output_name) else: raise Exception("You should not be here!! Only 1 or 3 channels allowed for images!!") if __name__ == "__main__": X = pickle.load(open(a...
EmmaIshta/QUANTAXIS
QUANTAXIS_Trade/QA_tradex/QA_Trade_stock_api.py
Python
mit
10,682
0.001387
#!/usr/bin/env python # -*- coding: utf-8 -*- import configparser import msvcrt import os import sys sys.path.append(os.path.dirname(os.path.realpath(__file__))) import TradeX TradeX.OpenTdx() class QA_Stock(): def set_config(self, configs): try: self.sHost = configs['host'] ...
Password)) return client except TradeX.error as e: return ("error: " + e.message) """ nCategory 0 资金 1 股份 2 当日委托 3 当日成交 4 可撤单 5 股东代码 6 融资余额 7 融券余额 8 可融证券 9 10 11 12 可申...
_errinfo, self.result = _client.QueryData(self.nCategory) if _errinfo != "": return (_errinfo) else: accounts = self.result.split('\n')[1].split('\t') account = {} account['account_id'] = accounts[0] account['available'] = accounts[3] ...
xjsender/haoide
salesforce/login.py
Python
mit
7,654
0.005487
import urllib import os import json import time import datetime import sublime from xml.sax.saxutils import escape from .. import requests from .. import util from ..libs import auth # https://github.com/xjsender/simple-salesforce/blob/master/simple_salesforce/login.py def soap_login(settings, session_id_expired=Fals...
:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"> <env:Body> <n1:login xmlns:n1="urn:partner.soap.sforce.com">
<n1:username>{username}</n1:username> <n1:password>{password}</n1:password> </n1:login> </env:Body> </env:Envelope> """.format( username = settings["username"], password = escape(settings["password"]) + settings["security_tok...
kfoss/keras
tests/manual/check_models.py
Python
mit
8,592
0.003841
from __future__ import absolute_import from __future__ import print_function from keras.datasets import mnist from keras.models import Sequential from keras.layers.core import Dense, Activation, Merge from keras.utils import np_utils import numpy as np nb_classes = 10 batch_size = 128 nb_epoch = 1 max_train_samples =...
timizer='rmsprop') model.fit([X_train, X_train], Y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=True, verbose=0, validation_data=([X_test, X_test], Y_test)) model.fit([X_train, X_train], Y_train, batch_si
ze=batch_size, nb_epoch=nb_epoch, show_accuracy=False, verbose=0, validation_data=([X_test, X_test], Y_test)) model.fit([X_train, X_train], Y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=True, verbose=0, validation_split=0.1) model.fit([X_train, X_train], Y_train, batch_size=batch_size, nb_epoch=nb_ep...
tema-mbt/tema-adapterlib
adapterlib/testrunner.py
Python
mit
15,926
0.013939
# -*- coding: utf-8 -*- # Copyright (c) 2006-2010 Tampere University of Technology # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the r...
: float @param delay: Wait-time between consequtive keywords (in seconds) @type record: boolean @param record: Is the test recorded to html-file """ self._targetNames = targets self._targets = [] self.delay = delay self._r...
ywordLogger() self._kw_cache = {} # Special commands listed here for interactive mode completer self._commands = {} self._commands["exit"] = ["quit","q","exit"] self._commands["kws"] = ["list","kws","list full","kws full"] self._commands["info"] = ["info"] self....
lyarwood/bugwarrior
bugwarrior/services/teamlab.py
Python
gpl-3.0
4,419
0
import six import requests from bugwarrior.config import die from bugwarrior.services import Issue, IssueService, ServiceClient import logging log = logging.getLogger(__name__) class TeamLabClient(ServiceClient): def __init__(self, hostname, verbose=False): self.hostname = hostname self.verbose ...
}, FOREIGN_ID: { 'type': 'string', 'label': 'Teamlab ID', }, TITLE: { 'type': 'string', 'label': 'Teamlab Title', }, PROJECTOWNER_ID: { 'type': 'string', 'label': 'Teamlab ProjectOwner ID', }...
UNIQUE_KEY = (URL, ) def to_taskwarrior(self): return { 'project': self.get_project(), 'priority': self.get_priority(), self.TITLE: self.record['title'], self.FOREIGN_ID: self.record['id'], self.URL: self.get_issue_url(), self.PR...
gnarula/eden_deployment
private/templates/NYC/layouts.py
Python
mit
5,177
0.002318
# -*- coding: utf-8 -*- from gluon import * from s3 import * # ============================================================================= class S3MainMenuOuterLayout(S3NavigationItem): """ Main Menu Outer Layout for a Bootstrap-based theme """ @staticmethod def layout(item): """ Cu...
==============
========================
threefoldfoundation/app_backend
plugins/tff_backend/api/rogerthat/documents.py
Python
bsd-3-clause
3,285
0.00274
# -*- coding: utf-8 -*- # Copyright 2017 GIG Technology NV # # 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...
global_stats import ApiCallException from plugins.tff_backend.bizz.iyo.utils import get_username from plugins.tff_backend.models.document import Document, DocumentType from plugins.tff_backend.mod
els.hoster import NodeOrder from plugins.tff_backend.models.investor import InvestmentAgreement from plugins.tff_backend.to.user import SignedDocumentTO @returns([SignedDocumentTO]) @arguments(params=dict, user_detail=UserDetailsTO) def api_list_documents(params, user_detail): try: username = get_username...
jmaas/cobbler
tests/conftest.py
Python
gpl-2.0
1,465
0.002048
import logging import sys import xmlrpc.client as xmlrpcclient import pytest from cobbler.utils import local_get_cobbler_api_url, get_shared_secret # "import xmlrpc.client" does currently not work. No explanation found anywhere. def pytest_addoption(parser): parser.addoption("-E", action="store", metavar="NAME...
er_api_url() remote = xmlrpcclient.Server(api_url, allow_n
one=True) shared_secret = get_shared_secret() token = remote.login("", shared_secret) if not token: sys.exit(1) yield (remote, token)
sh4wn/vispy
vispy/app/canvas.py
Python
bsd-3-clause
26,614
0.000075
# -*- coding: utf-8 -*- # Copyright (c) 2015, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. from __future__ import division, print_function import sys import numpy as np from time import sleep from ..util.event import EmitterGroup, Event, WarningEmitter from ..util...
use. If 'interactive', escape and F11 will close the canvas and toggle full-screen mode, respectively. If dict, maps keys to functions. If dict values are strings, they are assumed to be ``Canvas`` methods, otherwise they should be callable. parent : widget-object
The parent widget if this makes sense for the used backend. dpi : float | None Resolution in dots-per-inch to use for the canvas. If dpi is None, then the value will be determined by querying the global config first, and then the operating system. always_on_top : bool If...
intezer/docker-ida
ida_client/ida_client.py
Python
gpl-3.0
2,196
0.002732
# System imports import itertools import concurrent.futures # Third party imports import requests class Client: """ Used for sending commands to one or more IDA containers over HTTP. """ def __init__(self, urls): """ >>> client = Client(['http://host-1:4001', 'http://host-2:4001']) ...
m timeout: A timeout given for the command (optional) :returns True if the command ran successfully, else false """ data_to_send = dict(command=command) if timeout is not None: data_to_send['timeout'] = timeout response = re
quests.post('%s/ida/command' % next(self._urls), data=data_to_send) return response.status_code == 200 def send_multiple_commands(self, commands, timeout=None, num_of_threads=4): """ Send a batch of commands asynchronously to an IDA container via HTTP :param commands: An iterable o...
maltouzes/sfark-extractor
sample/setup.py
Python
gpl-3.0
3,698
0
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f....
d :: GNU General Public License v3 (GPLv3)", # Specify the Python versions you support here. In particular, ensure # that you indicate whether you support Python 2, Python 3 or both. "Programming Language :: Python", 'Programming Language :: Python :: 3', 'Programming Language :...
ming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', "Operating System :: POSIX :: Linux", "Natural Language :: English", "Topic :: Sound", ], # What does your project relate to? keywords='sfArk to sf2 soundfont', # You can just specify the packages...
jamesob/bitcoin
contrib/signet/getcoins.py
Python
mit
6,271
0.003987
#!/usr/bin/env python3 # Copyright (c) 2020-2021 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. import argparse import io import requests import subprocess import sys DEFAULT_GLOBAL_FAUCET = 'https://...
-cli', help='bitcoin-cli command to use') parser.add_argument('-f', '--faucet', dest='faucet', default=DEFAULT_GLOBAL_FAUCET, help='URL of the faucet') parser.add_argument('-g', '--captcha', dest='captcha', default=DEFAULT_GLOBAL_CAPTCHA, help='URL of the faucet captcha, or e
mpty if no captcha is needed') parser.add_argument('-a', '--addr', dest='addr', default='', help='Bitcoin address to which the faucet should send') parser.add_argument('-p', '--password', dest='password', default='', help='Faucet password, if any') parser.add_argument('-n', '--amount', dest='amount', default='0.001', h...
paul99/clank
tools/grit/grit/format/policy_templates/writers/xml_writer_base_unittest.py
Python
bsd-3-clause
1,025
0.002927
#!/usr/bin/python2.4 # Copyright (c) 2011 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. """Unittests for grit.format.policy_templates.writers.admx_writer.""" import os import sys import unittest from xml.dom import ...
: XML of the chrildren of the parent node. ''' return ''.join( child.toprettyxml(indent=' ') for child in parent.childNodes) def AssertXMLEquals(self, output, expected_output): '''Asserts if the passed XML arguements are equal. Args: output: Actual XML text. expect
ed_output: Expected XML text. ''' self.assertEquals(output.strip(), expected_output.strip())
oostapenko84/python_training
conftest.py
Python
apache-2.0
230
0.004348
__author__ = 'olga.ostapenko' import pytest from fi
xture.application import Application @pytest.fixture(scope="session") def app(request): fixture = Application() request.addfin
alizer(fixture.destroy) return fixture
akshah/netra
Cache/detoursCache.py
Python
apache-2.0
2,309
0.014292
import os import threading from cachetools import LRUCache from customUtilities.logger import logger class Cache(): def __init__(self,cachefilename,CACHE_SIZE,logger=logger('detoursCache.log')): self.lock = threading.RLock() self.cachefilename = cachefilename self.entry = LRUCache(maxsize=...
self.lock.acquire(blocking=1) try: self.hitcount=0 finally: self.lock.release() def push(self,key,val): self.lock.acquire(blocking=1) try:
self.entry[key]=val except: return finally: self.lock.release() def get(self,key): self.lock.acquire(blocking=1) try: return self.entry[key] except: return False finally: self.lock.release()...
orting/emphysema-estimation
Scripts/Util.py
Python
gpl-3.0
538
0.007435
class intersperse: '''Generator that inserts a value before each element of an iterable ''' def __init__(self, value
, iterable): self.value = value self.iterable = iterable self.return_value = True def __iter__(self): return self def __next__(self): if self.return_value: self.next_value = next( self.iterable ) r = self.value else: ...
not self.return_value return r
mekkablue/Glyphs-Scripts
Spacing/Freeze Placeholders.py
Python
apache-2.0
1,053
0.034188
#MenuTitle: Freeze Placeholders # -*- coding: utf-8 -*- from __future__ import division, print_function, unicode_literals __doc__=""" Turn placeholders in current tab into current glyphs. """ try: thisFont = Glyphs.font # frontmost font currentTab = thisFont.currentTab # current edit tab, if any selectedGlyph = thi...
macro window to front and clears its log: Glyphs.clearLog() import traceback print(traceback.format_exc()) Message( title="Freezing Placeholders Failed", message="An error occurred during the execution of the script. Is a font open, a glyph selected? Check the Macro Window for a detailed error messa
ge.", OKButton=None )
nikitanovosibirsk/jj
jj/mock/_mock.py
Python
apache-2.0
3,717
0.001076
from typing import Any, Callable, Tuple, Union from packed import pack, unpack import jj from jj import default_app, default_handler from jj.apps import BaseApp, create_app from jj.http.codes import BAD_REQUEST, OK from jj.http.methods import ANY, DELETE, GET, POST from jj.matchers import LogicalMatcher, RequestMatch...
code(payload) except Exception: return Response(status=BAD_REQUEST, json={"status": BAD_REQUEST}) history = await self._repo.get_by_tag(handler_id) packed = pack(history) return Response(status=OK, body=packed) @jj.match(ANY)
async def resolve(self, request: Request) -> StreamResponse: handler = await self._resolver.resolve(request, self._app) response = await handler(request) handler_id = self._resolver.get_attribute("handler_id", handler, default=None) if handler_id: await self._repo.add(r...
edx-solutions/api-integration
edx_solutions_api_integration/users/urls.py
Python
agpl-3.0
3,599
0.005557
""" Users API URI specification """ from django.conf import settings from django.conf.urls import url from django.db import transaction from edx_solutions_api_integration.users import views as users_views from rest_framework.urlpatterns import format_suffix_patterns COURSE_ID_PATTERN = settings.COURSE_ID_PATTERN url...
users_views.UsersList.as_view(), name='apimgr-users-list'), url(r'mass-details/$', users_views.MassUsersDetailsList.as_view(), name='apimgr-mass-users-detail'), url(r'^(?P<user_id>[a-zA-Z0-9]+)/courses/progress', users_views.UsersCourseProgressList.as_view(), name='users-courses-progress'), url(r'^...
ibutes/', users_views.ClientSpecificAttributesView.as_view(), name='users-attributes'), url(r'validate-token/$', users_views.TokenBasedUserDetails.as_view(), name='validate-bearer-token'), url(r'anonymous_id/$', users_views.UsersAnonymousId.as_view(), name='user-anonymous-id'), ] urlpatt...
w1ll1am23/home-assistant
homeassistant/components/onewire/__init__.py
Python
apache-2.0
2,774
0.001802
"""The 1-Wire component.""" import asyncio import logging from homeassistant.config_entries import ConfigEntry from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers.typing import HomeAssistantType from .const ...
.""" return True async def async_setup_entry(hass: HomeAssistantType, config_entry: ConfigEntry): """Set up a 1-Wire proxy for a config entry."
"" hass.data.setdefault(DOMAIN, {}) onewirehub = OneWireHub(hass) try: await onewirehub.initialize(config_entry) except CannotConnect as exc: raise ConfigEntryNotReady() from exc hass.data[DOMAIN][config_entry.unique_id] = onewirehub async def cleanup_registry() -> None: ...
lupyuen/RaspberryPiImage
usr/share/pyshared/ajenti/plugins/packages/pm_bsd.py
Python
apache-2.0
390
0
from ajenti.api import * from api import PackageInfo, Packa
geManager @plugin @rootcontext @persistent class BSDPackageManager (PackageManager): platforms = ['freebsd'] def init(self): self.upgradeable = [] def get_lists(self): pass def refresh(self): pass def search(self, query): return [] de
f do(self, actions): pass
rgalanakis/practicalmayapython
src/chapter6/mayatestcase.py
Python
mit
1,966
0.002035
"""This is a really rough implementation but demonstrates the core ideas.""" import os import unittest try: import maya ISMAYA = True except ImportError: maya, ISMAYA = None, False from mayaserver.client import start_process, create_client, sendrecv class MayaTestCase(unittest.TestCase): def _setUp(...
self._wrappedTest() finally: self._testMethodName = self.__testMethodName self.setUp = lambda: None self.tearDown = lambda: None self._setUp() setattr(self, self._testMethodName, wrappedTest) unittest.TestCase.run(self, result) def _wrapp...
=self.testalias, testcase=self.__class__.__name__, testfunc=self._testMethodName) teststr = """tc = {testmodule}.{testcase}("{testfunc}") try: tc.setUp() tc.{testfunc}() finally: tc.tearDown()""".format(**strargs) try: sendrecv(self.reqsock, ('exec', tests...
opensvn/test
src/study/python/cpp/ch13/capOpen.py
Python
gpl-2.0
385
0.002597
#!/usr/bin/env python class
CapOpen(object): def __init__(self, fn, mode='r', buf=-1): self.file =
open(fn, mode, buf) def __str__(self): return str(self.file) def __repr__(self): return `self.file` def write(self, line): return self.file.write(line.upper()) def __getattr__(self, attr): return getattr(self.file, attr)
alephu5/Soundbyte
environment/lib/python3.3/site-packages/pandas/tests/test_groupby.py
Python
gpl-3.0
130,215
0.004807
from __future__ import print_function import nose from numpy.testing.decorators import slow from datetime import datetime from numpy import nan from pandas import date_range,bdate_range, Timestamp from pandas.core.index import Index, MultiIndex, Int64Index from pandas.core.common import rands from pandas.core.api im...
'dull', 'shiny', 'shiny', 'dull', 'shiny', 'shiny', 'shiny'], 'D': np.random.randn(11), 'E': np.random.randn(11), 'F': np.rand...
data = Series(np.arange(9) // 3, index=np.arange(9), dtype=dtype) index = np.arange(9) np.random.shuffle(index) data = data.reindex(index) grouped = data.groupby(lambda x: x // 3) for k, v in grouped: self.assertEqual(len(v), 3) ...
Zorro666/renderdoc
util/test/tests/Vulkan/VK_Robustness2.py
Python
mit
3,750
0.002133
import renderdoc as rd import rdtest class VK_Robustness2(rdtest.TestCase): demos_test_name = 'VK_Robustness2' def check_capture(self): action: rd.ActionDescription = self.find_action('vkCmdDraw') self.controller.SetFrameEvent(action.eventId, True) self.check_triangle() rdt...
ent) for i, cb in enumerate(refl.constantBlocks): cbuf = pipe.GetConstantBuffer(rd.ShaderStage.Fragment, i, 0)
var_check = rdtest.ConstantBufferChecker( self.controller.GetCBufferVariableContents(pipe.GetGraphicsPipelineObject(), pipe.GetShader(rd.ShaderStage.Fragment), rd.ShaderStage.Fragment, refl.entryPoint, i, ...
stack-of-tasks/rbdlpy
tutorial/lib/python2.7/site-packages/OpenGLContext/utilities.py
Python
lgpl-3.0
2,924
0.031464
'''Simple utility functions that should really be in a C module''' from math import * from OpenGLContext.arrays import * from OpenGLContext import vectorutilities def rotMatrix( (x,y,z,a) ): """Given rotation as x,y,z,a (a in radians), return rotation matrix Returns a 4x4 rotation matrix for the given rotatio...
create vector for all other points, take vector to second point, calculate cross-product where the cross-product is non-zero (not colinear), if the normalised cross-product is all equal, the points are collinear... """ points = asarray( points, 'f' ) if len(points) < 4: return True ...
rest, vec1, ) vecsNonZero = sometrue(vecs,1) vecs = compress(vecsNonZero, vecs,0) if not len(vecs): return True vecs = vectorutilities.normalise(vecs) return allclose( vecs[0], vecs )
dcramer/sentry-old
sentry/client/celery/tasks.py
Python
bsd-3-clause
396
0.002525
""" sentry.client.celery.tasks ~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c
) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from celery.decorators import task from sentry.client.base import SentryClient from sentry.client.celery impor
t conf @task(routing_key=conf.CELERY_ROUTING_KEY) def send(data): return SentryClient().send(**data)
BitFunnel/BitFunnel
src/Scripts/tail-latency.py
Python
mit
1,033
0.000968
# Note that this is not a valid measurement of tail latency. This uses the execution times we measure because they're convenient, but this does not include queueing time inside BitFunnel nor does it include head-of-line blocking queue waiting time on the queue into BitFunnel. import csv filename = "/tmp/QueryPipeline...
'parse', 'plan', 'match'] for row in reader: total_time = float(row[-1]) + float(row[-2]) + float(row[-3]) times.append(total_time)
times.sort(reverse=True) idx_max = len(times) - 1 idx = [round(idx_max / 2), round(idx_max / 10), round(idx_max / 100), round(idx_max / 1000), 0] tails = [times[x] for x in idx] print(tails)
onyxfish/agate
agate/computations/change.py
Python
mit
2,638
0.000758
#!/usr/
bin/env python from agate.aggregations.has_nulls import HasNulls from agate.computations.base import Computation from agate.data_types import Date, DateTime, Number, TimeDelta from agate.exceptions import DataTypeError from agate.warns import warn_null_calculation class Change(Computation): """ Calculate the...
ied to :class:`.Number` columns to calculate numbers. It can also be applied to :class:`.Date`, :class:`.DateTime`, and :class:`.TimeDelta` columns to calculate time deltas. :param before_column_name: The name of a column containing the "before" values. :param after_column_name: The nam...
youtube/cobalt
starboard/build/application_configuration.py
Python
bsd-3-clause
4,981
0.003212
# Copyright 2017 The Cobalt Authors. All Rights Reserved. # # Licensed under the Apache Li
cense, 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 im...
shimpe/expremigen
expremigen/musicalmappings/dynamics.py
Python
gpl-3.0
904
0
class Dynamics: """ a convenience class containing some dynamics """ ppppp = 10 pppp = 20
ppp = 30 pp = 40 p = 60 mp = 80 mf = 90 f = 100 ff = 110 fff = 1
20 ffff = 127 @classmethod def from_string(cls, thestring): """ :param thestring: a string containing a symbolic volume indication :return: the string mapped to a number """ lut = { 'ppppp': Dynamics.ppppp, 'pppp': Dynamics.pppp, ...
pfmoore/invoke
tests/executor.py
Python
bsd-2-clause
9,278
0.000216
from spec import eq_, ok_ from mock import Mock from invoke import Collection, Config, Context, Executor, Task, call, task from invoke.parser import ParserContext from _util import expect, IntegrationSpec class Executor_(IntegrationSpec): def setup(self): s = super(Executor_, self) s.setup() ...
es Building Deploying Preparing for testing Testing """.lstrip()) def _expect(self, args, expected): expect('-c integration {0}'.format(args), out=expected.lstrip()) class adjacent_hooks: def deduping(self): self._expect('biz', """ foo bar biz post1 post2 """) ...
-dedupe biz', """ foo foo bar biz post1 post2 post2 """) class non_adjacent_hooks: def deduping(self): self._expect('boz', """ foo bar boz post2 post1 """) def no_deduping(self): self._expect('--no-dedupe boz', """ foo bar foo boz post2 post1 post2 """) ...
djedproject/djed.form
djed/form/__init__.py
Python
isc
3,170
0.008833
__all__ = [ 'null', 'Invalid', 'FieldsetErrors', 'Field', 'FieldFactory', 'Fieldset', 'field', 'fieldpreview', 'get_field_factory', 'get_field_preview', 'Term', 'Vocabulary', 'All','Function','Regex','Email','Range', 'Length','OneOf', 'CompositeField', 'CompositeError', 'InputField', 'Op...
n from .interfaces import null from .interfaces import Invalid # field from .field import Field from .field import FieldFactory from .fieldset import Fieldset from .fieldset import FieldsetErrors # field registration from .directives import field from .directives import fieldpreview from .directives import get_field...
import Vocabulary # validators from .validator import All from .validator import Function from .validator import Regex from .validator import Email from .validator import Range from .validator import Length from .validator import OneOf # helper class from .field import InputField # helper field classes from .fields...
rosscdh/twimer
wastingtimer/nprofile/models.py
Python
gpl-3.0
820
0.014634
# -*- coding: UTF-8 -*- from django.conf import settings from django.contrib.auth.models import User from django.db import models from jsonfield import JSONField
PLACEHOLDER_IMAGE = "%simages/placeholder.png"%settings.STATIC_URL class UserProfile(models.Model): user = models.OneToOneField(User, related_name='_profile_cache') twitter_image = models.CharField(max_
length=255) profile_image = models.ImageField(upload_to='profile',blank=True,null=True) twitter_data = JSONField(default={}) def __unicode__(self): return u'%s' % self.user.username @property def location(self): return u'%s' % self.twitter_data.get('location', None) def image_or_placeholder(self)...
ygol/odoo
addons/stock/models/stock_move.py
Python
agpl-3.0
92,248
0.004499
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from collections import defaultdict from datetime import datetime from itertools import groupby from operator import itemgetter from re import findall as regex_findall from re import split as regex_split from dateutil i...
does not generate a " "backorder. Changing this quantity on assigned moves affects " "the product reservation, and should be done with care.") product_uom = fields.Many2one('uom.uom', 'Unit of Measure', required=True, dom
ain="[('category_id', '=', product_uom_category_id)]") product_uom_category_id = fields.Many2one(related='product_id.uom_id.category_id') # TDE FIXME: make it stored, otherwise group will not work product_tmpl_id = fields.Many2one( 'product.template', 'Product Template', related='product_id....
ioan-dragan/python-scripts
loadLeveler/getProblems.py
Python
gpl-2.0
1,175
0.011915
#!/usr/bin/env python # Copyright (C) 2014 Ioan Dragan # 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 progr...
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 rec
eived a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import sys, os, time import re from os import path folderList = [] def getProblems( arg ): fin = open ("ProblemList.txt","...
bringingheavendown/numpy
numpy/core/tests/test_deprecations.py
Python
bsd-3-clause
17,790
0.00163
""" Tests related to deprecation warnings. Also a convenient place to document how deprecations should eventually be turned into errors. """ from __future__ import division, absolute_import, print_function import datetime import sys import operator import warnings import numpy as np from numpy.testing import ( r...
p.zeros(3), [])) a = np.zeros(3, dtype='i,i') # (warning is issued a couple of times here) self.assert_deprecated(op, args=(a, a[:-1]), num=None) # Element comparison error (numpy array can't be compared). a = np.array([1, np.array([1,2,3])], dtype=ob
ject) b = np.array([1, np.array([1,2,3])], dtype=object) self.assert_deprecated(op, args=(a, b), num=None) def test_string(self): # For two string arrays, strings always raised the broadcasting error: a = np.array(['a', 'b']) b = np.array(['a', 'b', 'c']) ass...
taimur97/Feeder
server/flaskapp/setuserpass.py
Python
gpl-2.0
1,570
0
# -*- coding: utf-8 -*- ''' Usage: setuserpass.py [-d] username password Set a user's username/password, creating it if it did not already exist. Specifying -d on the commandline removes the user and in that case a password is not necessary ''' import sys from hashlib import sha1 from werkzeug.security import ge...
gs) == 0 or '-h' in args: exit(__doc__) # Check delete flag should_delete = False if '-d' in args: should_delete = True args.rem
ove('-d') # Make sure enough arguments were specified if not should_delete and len(args) < 2: exit("Not enough arguments specified. Print help with -h") elif should_delete and len(args) < 1: exit("No username specified. Print help with -h") if should_delete: username = args[0] else: username, passwor...
Britefury/scikit-image
skimage/novice/tests/test_novice.py
Python
bsd-3-clause
8,113
0.000247
import os import tempfile import numpy as np from numpy.testing import assert_equal, raises, assert_allclose from skimage import novice from skimage.novice._novice import (array_to_xy_origin, xy_to_array_origin, rgb_transpose) from skimage import data_dir from skimage._shared.utils ...
ir, "chelsea.png") SMALL_IMAGE_PATH = os.path.join(data_dir, "block.png") def _array_2d_to_RGBA(a
rray): return np.tile(array[:, :, np.newaxis], (1, 1, 4)) def test_xy_to_array_origin(): h, w = 3, 5 array = np.arange(h * w).reshape(h, w, 1) out = xy_to_array_origin(array_to_xy_origin(array.copy())) assert np.allclose(out, array) def test_pic_info(): pic = novice.open(IMAGE_PATH) asse...
ftuyama/TEEG
build/lib/mindwave/parser.py
Python
mit
8,344
0.002996
import bluetooth import struct import time import pandas as pd from datetime import datetime """ This interface library is designed to be used from very different contexts. The general idea is that the Mindwave modules in the headset (and other devices) talk a common binary protocol, which is entirely on...
d # This byte should be "\aa" too if byte == 0xaa: # packet synced by 0xaa 0xaa packet_length = yield packet_code = yield if packet_code == 0xd4: # standing by self.state = "s...
data_len = yield headset_id = yield headset_id += yield self.dongle_state = "disconnected" else: self.sending_data = True left = packet_length - 2 ...
endrebak/epic
epic/statistics/compute_window_score.py
Python
mit
501
0
from epic.utils.helper_functions import lru_cache from numpy import log from scipy.stats import poisson @lru_cache() def compute_window_score(i, poisson_parameter): # type: (
int, float) -> float # No enrichment; poisson param also average if i < poisson_parameter: return 0 p_value = poisson.pmf(i, poisson_parameter) if p_value > 0: window_score = -log(p_value) else: # log of zero not defined window_sc
ore = 1000 return window_score
tigwyk/eve-wspace
evewspace/core/models.py
Python
gpl-3.0
9,702
0.004947
# Eve W-Space # Copyright (C) 2013 Andrew Austin and other contributors # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your ...
_unicode__(self): return self.name class ConfigEntry(models.Model): """A configuration setting that may be changed at runtime.""" name = models.CharField(max_length=32, unique=True) value = models.CharField(max_length=255, null=True, blank=True) user = models.ForeignKey(User, related_n...
id = models.IntegerField(primary_key=True, db_column='marketGroupID') name = models.CharField(max_length = 100, null=True, blank=True, db_column='marketGroupName') parentgroup = models.ForeignKey("self", related_name="childgroups", blank=True, null=True, db_column='parentGroupID'...
israelem/aceptaelreto
codes/2017-05-15-triangulos_piedras.py
Python
mit
390
0.010256
def suma_n_numeros(n): return (pow(n,2)+n)/2 if __name__ == '__main__': numero_piedras = int(input()) while(numero_piedras > 0):
i = 1; while(suma_n_numeros(i)<numero_piedras): i += 1 i -= 1 sobran = numero_piedras - suma_n_numeros(i) print(str(i) + " " + str(int(sobran))) numero_piedras = int(in
put())
ritatsetsko/python_training
fixture/group.py
Python
apache-2.0
3,117
0.003529
from model.group import Group class GroupHelper: def __init__(self, app): self.app = app def open_groups_page(self): wd = self.app.wd if not (wd.current_url.endswith("/group.php") and len(wd.find_elements_by_name("new"))>0): wd.find_element_by_link_text("groups").click() ...
up creation wd.find_element_by_name("submit").click() self.return_to_groups_page() self.group_cache = None def fill_group_form(self, group): wd = self.app.wd self.change_field_value("group_name", group.name) self.change_field_value("group_header", group.header) ...
def change_field_value(self, field_name, text): wd = self.app.wd if text is not None: wd.find_element_by_name(field_name).click() wd.find_element_by_name(field_name).clear() wd.find_element_by_name(field_name).send_keys(text) def delete_first_group(self): ...
astronomeara/xastropy-old
xastropy/obs/x_getsdssimg.py
Python
bsd-3-clause
4,509
0.021956
#;+ #; NAME: #; x_getsdssimg #; Version 1.1 #; #; PURPOSE: #; Returns an Image by querying the SDSS website #; Will use DSS2-red as a backup #; #; CALLING SEQUENCE: #; #; INPUTS: #; #; RETURNS: #; #; OUTPUTS: #; #; OPTIONAL KEYWORDS: #; #; OPTIONAL OUTPUTS: #; #; COMMENTS: #; #; EXAMPLES: #; #; PROCEDURES/...
e+='&height=' name+=str(int(ys)) #sett
ing the height #------ Options options = '' if grid != None: options+='G' if label != None: options+='L' if invert != None: options+='I' if len(options) > 0: name+='&opt='+options name+='&query=' url = name1+name return url # Generat...
clearcare/railgun
tests/engines/test_storage_engine.py
Python
mit
1,295
0.001544
from unittest import TestCase from mock
import
patch from railgun.engines.storage_engine import DummyEngine class StorageEngineTestCase(TestCase): def setUp(self): self.config = { 'field1': 'value1', 'field2': 'value2' } def test_init(self): with patch('railgun.engines.storage_engine.DummyEngine.config_f...
twiindan/selenium_lessons
04_Selenium/03_elements_interaction/send_keys.py
Python
apache-2.0
365
0.00274
from selenium import webdriver from time import sleep driver = webdriver.Fi
refox() driver.get('http://www.google.com') sleep(2) loginTextBox = driver.find_e
lement_by_css_selector('.gLFyf.gsfi') searchButton = driver.find_element_by_xpath('//input[@name="btnK"]') loginTextBox.clear() loginTextBox.send_keys("python") sleep(2) searchButton.click() driver.quit()
krathjen/studiolibrary
src/studiolibrary/librarywindow.py
Python
lgpl-3.0
80,070
0.000787
# Copyright 2020 by Kurt Rathjen. All Rights Reserved. # # This library is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. This ...
brary Widget. :type parent: QtWidgets.QWidget or None :type name: str :type path: str """ QtWidgets.QWidget.__init__(self, parent) self.setObjectName("studiolibrary") version = studiolibrary.version() studiolibrary.sendAnalytics("MainWindow", version=ve...
ck")) self._dpi = 1.0 self._path = "" self._items = [] self._name = name or self.DEFAULT_NAME self._theme = None self._kwargs = {} self._isDebug = False self._isLocked = False self._isLoaded = False self._previewWidget = None self....
mikea/appengine-mapreduce
python/src/mapreduce/mock_webapp.py
Python
apache-2.0
6,577
0.006994
#!/usr/bin/env python # # Copyright 2007 Google 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 o...
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. # """Mocks for classes defined in webapp module. Use this classes to test functionality depending on webapp framework. """ imp...
shakamunyi/neutron-vrrp
neutron/tests/unit/cisco/test_network_plugin.py
Python
apache-2.0
53,883
0.00026
# Copyright (c) 2012 OpenStack Foundation. # # Licensed under the Apach
e Licens
e, 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 ...
kkozarev/mwacme
src/fit_powerlaw_spectra_normalized.py
Python
gpl-2.0
4,350
0.030345
import numpy as np import os,sys from scipy import optimize import matplotlib.pyplot as plt import matplotlib.dates as pltdates from astropy.io import ascii from datetime import datetime #This script will fit a power law to the moving source synchrotron spectrum #The new data location #if sys.platform == 'darwin': B...
/MWA_DATA/' if sys.platform == 'darwin': BASEDIR='/Users/kkozarev/Desktop/MWA_CME_project/MWA_DATA/' if sys.platform == 'linux2': BASEDIR='/mnt/MWA_DATA/' avgperiod='10sec' datadir=BASEDIR+'max_spectra/normalized/'+avgperiod+'/' po
larization='XX' #sourcetype={'1':'Moving','2':'Stationary'} sourcetype={'1':'Moving'} #Do not modify! #Read in the data spectrafile='moving_source_normalized_spectra_'+polarization+'_'+avgperiod+'.txt' #frequencies=[79.8,88.76,97.72,107.96,119.48,132.28,145.08] frequencies=np.array([79.8,88.76,97.72,107.96,119.48,145....
OlegPshenichniy/upfavor-mezzanine
bootstrap_helpers/templatetags/bootstrap_messages.py
Python
mit
684
0.002924
from django import template register =
template.Library() @register.inclusion_tag(file_name='bootstrap_messages.html') def bootstrap_messages(messages, icon_remove_class=None): """ Render django.contrib.messages messages as bootstrap alert blocks. Display only info, success, error and warning level messages. messages - django.contrib.mes...
xample of use: {% bootstrap_messages messages 'icon-remove' %} """ return {'messages': messages, 'icon_remove_class': icon_remove_class}