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
dplarson/Mocha.jl
docs/conf.py
Python
mit
8,570
0.006301
# -*- coding: utf-8 -*- # # Mocha documentation build configuration file, created by # sphinx-quickstart on Thu Nov 13 00:43:40 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All...
.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'Mochadoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '...
List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'Mocha.tex', u'Mocha Documentation', u'pluskid', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_lo...
CptDemocracy/Python
MITx-6.00.1x-EDX-Introduction-to-Computer-Science/Week-4/PSET-4/game.py
Python
mit
2,366
0.005917
""" PSET-4 Word Game Part 9: You and your Computer """ PROMPT_STR = "Enter n to deal a new hand, r to replay the last hand, or e to end game: " NO_REPL_AVAIL_STR = "You have not played a hand yet. Please play a new hand first!" INVALID_CMD = "Invalid command." CHOOSE_PLAYER_STR = "Enter u to have yourself play, c to h...
a 'u' or a 'c'. * If the user inputs anything that's not 'c' or 'u', keep asking them again. 3) Switch functionality based on the above choices: * If the user inputted 'n', play a new (random) hand. * Else, if the user inputted 'r', play the last hand again. But if no hand
was played, output "You have not played a hand yet. Please play a new hand first!" * If the user inputted 'u', let the user play the game with the selected hand, using playHand. * If the user inputted 'c', let the computer play the game with the selected hand, u...
j5shi/Thruster
pylibs/test/test_peepholer.py
Python
gpl-2.0
9,096
0.001539
import dis import sys from cStringIO import StringIO import unittest def disassemble(func): f = StringIO() tmp = sys.stdout sys.stdout = f dis.dis(func) sys.stdout = tmp result = f.getvalue() f.close() return result def dis_single(line): return disassemble(compile(l...
oor divide ('a = 14%4', '(2)'), # binary modulo ('a = 2+3', '(5)'),
# binary add ('a = 13-4', '(9)'), # binary subtract ('a = (12,13)[1]', '(13)'), # binary subscr ('a = 13 << 2', '(52)'), # binary lshift ('a = 13 >> 2', '(3)'), # binary rshift ...
conejoninja/xbmc-seriesly
servers/nowdownload.py
Python
gpl-3.0
2,851
0.025614
# -*- coding: utf-8 -*- #------------------------------------------------------------ # seriesly - XBMC Plugin # Conector para nowdownload # http://blog.tvalacarta.info/plugin-xbmc/seriesly/ #------------------------------------------------------------ import urlparse,urllib2,urllib,re import os from core import scra...
f="([^"]*)" class="btn btn-danger"><i class="icon-white icon-download"></i> Download Now</a>') except: #$.get("/api/token.php?token=7e1ab09df2775dbea02
506e1a2651883"); token = scrapertools.get_match(data,'(/api/token.php\?token=[^"]*)') logger.debug("[nowdownload.py] token:" + token) d= scrapertools.cache_page( "http://www.nowdownload.co"+ token ) url = scrapertools.get_match(data,'expiryText: \'<a class="btn btn-danger" href="([^"]*)') logge...
schleichdi2/OPENNFR-6.1-CORE
opennfr-openembedded-core/meta/lib/oeqa/runtime/cases/df.py
Python
gpl-2.0
493
0.006085
from oeqa.runtime.case import OERuntimeTestCase from oeqa.co
re.decorator.depends import OETestDep
ends from oeqa.core.decorator.oeid import OETestID class DfTest(OERuntimeTestCase): @OETestID(234) @OETestDepends(['ssh.SSHTest.test_ssh']) def test_df(self): cmd = "df / | sed -n '2p' | awk '{print $4}'" (status,output) = self.target.run(cmd) msg = 'Not enough space on image. Curr...
thomasem/nova
nova/virt/netutils.py
Python
apache-2.0
6,132
0.000163
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # Copyright (c) 2010 Citrix Systems, Inc. # Copyright 2013 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use th...
tr(net.ip), str(net.netmask)
def get_net_and_prefixlen(cidr): net = netaddr.IPNetwork(cidr) return str(net.ip), str(net._prefixlen) def get_ip_version(cidr): net = netaddr.IPNetwork(cidr) return int(net.version) def _get_first_network(network, version): # Using a generator expression with a next() call for the first elem...
fp7-netide/Engine
tests/of13-parallel-priority-3firewalls/firewall_13-3.py
Python
epl-1.0
5,948
0.003362
# Copyright (C) 2011 Nippon Telegraph and Telephone Corporation. # # 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 appli...
ch_features_handler(self, ev): datapath = ev.msg.datapath ofproto = datapath.ofproto parser = datapath.ofproto_parser # install table-miss flow entry # # We specify NO BUFFER to max_len of the output action due to # OVS bug. At this moment, if we specify a lesser...
acket data. In that case, we cannot output packets # correctly. The bug has been fixed in OVS v2.1.0. match = parser.OFPMatch() actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER, ofproto.OFPCML_NO_BUFFER)] self.add_flow(datapath, 0, matc...
aothms/hdf5_bim_sparql_query
src/query.py
Python
gpl-3.0
22,647
0.00892
from __future__ import print_function import operator import functools import collections import ifc2x3_schema as schema import prefixes import rdflib.plugins.sparql as sparql from rdflib.namespace import RDF, XSD from rdflib.term import Variable, Literal, URIRef, BNode from rdflib.paths import Path, SequencePath, M...
self.fn = lambda t: opfn(getattr(t, s0), a1) self.s = "F(%s) -> {0,1} { ?%s %s %s }" % (varnames_c, s0, ex
pr.op, a1) elif is_var[1]: self.fn = lambda t: opfn(a0, getattr(t, s1)) self.s = "F(%s) -> {0,1} { %s %s ?%s }" % (varnames_c, a0, expr.op, s1) else: raise Exception("Not supported") def __init__(self, q, expr): ...
jespino/django-rest-framework-apidoc
rest_framework_apidoc/apidoc.py
Python
bsd-3-clause
2,342
0.002989
from django.conf import settings from rest_framework.settings import import_from_string from .mixins import FileContentMixin, DocStringContentMixin, MarkupProcessMixin, NoProcessMixin, SafeProcessMixin APIDOC_DEFAULT_DOCUMENTER_CLASSES = getattr( settings, 'APIDOC_DEFAULT_DOCUMENTER_CLASSES', ['rest_fra...
cStringsDocumenter'] ) def get_view_description(view_cls, html=False, request=None): documenters = [] if hasattr(view_cl
s, 'documenter_classes'): for cls in view_cls.documenter_classes: documenters.append(cls()) else: for cls in APIDOC_DEFAULT_DOCUMENTER_CLASSES: documenter_class = import_from_string(cls, "APIDOC_DEFAULT_DOCUMENTER_CLASS") documenters.append(documenter_class()) ...
dmach/dnf
dnf/logging.py
Python
gpl-2.0
7,178
0.002786
# logging.py # DNF Logging Subsystem. # # Copyright (C) 2013-2016 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program ...
ndlers to the preferred level self.stdout_handler.setLevel(verbose_level) self.stderr_handler.setLevel(error_level) logging.raiseExceptions = False def _setup_from_dnf_conf(self, conf): verbose_level_r = _cfg_verbose_val2level(conf.debuglevel) error_level_r = _cfg_err_val2le...
se_level_r, error_level_r, logdir) class Timer(object): def __init__(self, what): self.what = what self.start = time.time() def __call__(self): diff = time.time() - self.start msg = 'timer: %s: %d ms' % (self.what, diff * 1000) logging.getLogger("dnf").log(DDEBUG, msg)...
epronk/pyfit2
examples/chat/User.py
Python
gpl-2.0
75
0
class User(object): def _
_init__(self, name): self.name = na
me
openwns/wrowser
openwns/wrowser/playgroundPlugins/SimulationCampaign/simcontrol.py
Python
gpl-2.0
23,950
0.013946
#! /usr/bin/env python ############################################################################### # This file is part of openWNS (open Wireless Network Simulator) # _____________________________________________________________________________ # # Copyright (C) 2004-2007 # Chair of Communication Networks (ComNets) ...
Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not,
see <http://www.gnu.org/licenses/>. # ############################################################################### import os import pwd import sys import shutil import subprocess import optparse import re import datetime import time import openwns.wrowser.Configuration as conf import openwns.wrowser.simdb.Databas...
envycontent/msd.rdfexport
msd/rdfexport/researcher/helper/webpresence.py
Python
gpl-2.0
1,575
0.013333
#!/usr/bin/env python """ For the moment we're not using this, but it would be nice to do so at some point. It isn't really relevant to the researcher RDF export, the idea would be to export details of a web-presence, to compile a complete directory of websites in the Medical Sciences Division. """ ...
<foaf:Organization rdf:about="http://www.psy.ox.ac.uk/"> <foaf:homepage> <res:WebPresence> <dc:title>Department of Experimental Psychology Website</dc:title> <dc:creator> <foaf:Person> <foaf:mbox>anne.bowtell@medsci.ox.ac.uk</foaf:mbox> </foaf:Person> ...
</res:WebPresence> </foaf:homepage> """ #TODO - this will be real data in the future standardWebmaster = 'webmaster@medsci.ox.ac.uk' homepageProp = rdf.createElement('foaf:homepage') deptElement.appendChild(homepageProp) wpElem = rdf.createElement('res:WebPresence')...
leonth/elude
elude/proxy.py
Python
mit
3,517
0.004834
import logging import re import asyncio from functools import partial import aiohttp from pandas.io.html import read_html from elude import config logger = logging.getLogger(__name__) class Proxy(object): test_semaphore = None def __init__(self, ip=None, port=None, country=None, source=None): self...
(self): self.new_proxy_callbacks = [] @asyncio.coroutine def start_getting_proxies(self): return asyncio.async(asyncio.gather(self._grab_proxies_from_checkerproxy(), self._grab_proxies_from_letushide())) @asyncio.coroutine def _grab_proxies_from_checkerproxy(self): dfs = yield ...
f_filtered = df[(df['proxy type'] == 'HTTP') & (df['proxy status'].str.contains('Elite proxy'))].drop_duplicates(subset=['ip:port']) i = 0 for _, row in df_filtered.iterrows(): m = re.match(r'([0-9.]+):([0-9]+)', row['ip:port']) if m: ip, port = m.group(1), m.gro...
dls-controls/pymalcolm
tests/test_modules/test_scanning/test_attributeprerunpart.py
Python
apache-2.0
3,395
0.001473
import unittest from mock import Mock, call from malcolm.modules.scanning.hooks import ( AbortHook, PauseHook, PostRunReadyHook, PreRunHook, ) from malcolm.modules.scanning.parts import AttributePreRunPart class TestAttributePreRunPartConstructor(unittest.TestCase): def setUp(self): self...
faultNamePutMethods(un
ittest.TestCase): def setUp(self): # Create our part name = "AttributePart" mri = "ML-ATTR-01" self.pre_run_value = "Set" self.reset_value = "Reset" self.part = AttributePreRunPart( name, mri, self.pre_run_value, self.reset_value, attribute_name="togglePar...
jmesmon/layman
layman/__init__.py
Python
gpl-2.0
1,585
0.005047
#!/usr/bin/python # -*- coding: utf-8 -*- """Layman is a complete library for the operation and maintainance on all gentoo repositories and overlays """ import sys try: from layman.api import LaymanAPI from layman.config import BareConfig from layman.output import Message except ImportError: sys.stde...
=True, quiet=False, quietness=4, verbose=False, nocolor=False, width
=0, root=None ): """Input parameters are optional to override the defaults. sets up our LaymanAPI with defaults or passed in values and returns an instance of it""" self.message = Message(out=stdout, err=stderr) self.config = BareConfig( output=self.messag...
Jokiva/Computational-Physics
lecture 15/1a_init.py
Python
gpl-3.0
927
0.005394
from particle import RandomParticle import numpy as np import matplotlib.pyplot as plt from time import time t0 = time() num_of_paths = (50, 500, 5000) max_num_of_collisions = 1000 particle = RandomParticle(1) rms = np.zeros((3, max_num_of_collisions)) for n in range(3): path = num_of_paths[n] data = np.ze...
np.savetxt('rm
s_1a.txt', rms) """ x = np.linspace(0, 1000) y = np.sqrt(x) plt.figure() for n in range(3): l = str(num_of_paths[n]) + ' paths' plt.scatter(list(range(1000)), rms[n], marker='+', label=l) plt.plot(x, y) plt.legend() plt.grid() plt.show() """
csdms/packagebuilder
setup.py
Python
mit
1,488
0.004032
from ez_setup import use_setuptools # https://pypi.python.org/pypi/setuptools use_setuptools() from setuptools import setup, find_packages from packager import __version__ # Get the long description from the README file. def get_long_description(): from codecs import open from os import path here = path.a...
'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Programmin
g Language :: Python :: 2.7', ], keywords='CSDMS, earth system modeling, packaging, Linux, rpm, deb', packages=find_packages(exclude=['*test']), install_requires=['nose'], package_data={ 'packager': ['repositories.txt'], }, entry_points={ 'console_scripts': [ ...
dbbhattacharya/kitsune
vendor/packages/sqlalchemy/lib/sqlalchemy/orm/util.py
Python
bsd-3-clause
23,666
0.003085
# mapper/util.py # Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010 Michael Bayer # mike_mp@zzzcomputing.com # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php import sqlalchemy.exceptions as sa_exc from sqlalchemy import sql, util from sql...
The dictionary interface provides containment for implemented method names mapped to a callable which executes that method for participating extensions. """ interface = set(method for method in dir(MapperExtension) if not method.startswith('_')) def __init__(
self, extensions=None): self._extensions = [] for ext in extensions or (): self.append(ext) def copy(self): return ExtensionCarrier(self._extensions) def push(self, extension): """Insert a MapperExtension at the beginning of the collection.""" self._register...
carquois/blobon
blobon/punns/migrations/0028_auto__add_unique_cat_slug__add_field_punn_publish_on_facebook.py
Python
mit
8,119
0.008006
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding unique constraint on 'Cat', fields ['slug'] db.create_unique('punns_cat', ['slug']) # Addi...
db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_n...
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),...
watsonyanghx/CS231n
assignment3/cs231n/classifiers/rnn.py
Python
mit
13,249
0.008378
import numpy as np from cs231n.layers import * from cs231n.rnn_layers import * class CaptioningRNN(object): """ A CaptioningRNN produces captions from image features using a recurrent neural network. The RNN receives input vectors of size D, has a vocab size of V, works on sequences of length T, has an RN...
vocabulary at every timestep using the hidden state
s, giving an # # array of shape (N, T, V). # # (5) Use (temporal) softmax to compute loss using captions_out, ignoring # # the points where the output word is <NULL> using the mask above. # # ...
alirizakeles/zato
code/zato-server/src/zato/server/service/internal/pubsub/__init__.py
Python
gpl-3.0
12,954
0.004477
# -*- coding: utf-8 -*- """ Copyright (C) 2014 Dariusz Suchojad <dsuch at zato.io> Licensed under LGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib from httplib import FORBIDDEN, INTERNAL_SERVER_ERROR, OK from json impor...
spawn # huTools from huTools.structured import dict2xml # Zato from zato.common import DATA_FORMAT, PUB_SUB, ZATO_ERROR, ZATO_NONE, ZATO_OK from zato.common.pubsub import ItemFull, PermissionDenied from zato.common.util import get_basic_auth_credentials from zato.server.connection.http_soap import BadRequest, Forbidd...
, Unauthorized from zato.server.service import AsIs, Bool, Int, Service from zato.server.service.internal import AdminService logger_overflown = getLogger('zato_pubsub_overflown') # ################################################################################################################################ class ...
Canpio/Paddle
python/paddle/fluid/tests/unittests/test_smooth_l1_loss_op.py
Python
apache-2.0
3,483
0
# Copyright (c) 2018 PaddlePaddle 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 app...
'X': np.random.random(dims).astype("float32"), 'Y': np.random.random(dims).astype("float32"), 'InsideWeight': np
.random.random(dims).astype("float32"), 'OutsideWeight': np.random.random(dims).astype("float32") } sigma = 3.0 self.attrs = {'sigma': sigma} sigma2 = sigma * sigma diff = self.inputs['X'] - self.inputs['Y'] diff = diff * self.inputs['InsideWeight'] lo...
lqez/korean
koreantests.py
Python
bsd-3-clause
20,731
0.000232
# -*- coding: utf-8 -*- from __future__ import unicode_literals, with_statement import contextlib import sys import textwrap from pytest import deprecated_call, raises from korean import * @contextlib.contextmanager def disable_imports(*names): """Stolen from Attest.""" import __builtin__ import_ = __bu...
를)을', '(을)를') assert Particle('로').naive() == ('(으)로',) def test_pick_allomorph_with_noun(self): pick_allomorph = morphology.pick_allomorph P, N = Particle, Noun assert pick_allomorph(P('가'), suffix_of=N('받침')) == '이' assert pick_allomorph(P('가'), suffix_of=N('나비')) == '가' ...
assert pick_allomorph(P('로'), suffix_of=N('파이썬')) == '으로' assert pick_allomorph(P('다'), suffix_of=N('파이썬')) == '이다' assert pick_allomorph(P('일랑'), suffix_of=N('게임')) == '일랑' assert pick_allomorph(P('일랑'), suffix_of=N('서버')) == 'ㄹ랑' def test_pick_allomorph_with_number_word(self): ...
napjon/moocs_solution
robotics-udacity/1.3.py
Python
mit
626
0.036741
p=[0.2,0.2,0.2,0.2,0.2] world=['green', 'red', 'red', 'green',
'green'] measurements = ['red','green'] Z = 'red' pHit = 0.6 pMiss = 0.2 def sense(p, Z): q=[] for i in range(len(p)): hit = (Z == world[i]) #hit return zero if false q.append(p[i] * (hit * pHit + (1-hit) * pMiss)) #if hit zero then miss s=sum(q) for i in ra
nge (len(p)): q[i] = q[i]/s #q[i] = q[i]/sum(q)-->WRONG. The Sum then different everytime it goes to loop return q #def move(p,U) for k in range(len(measurements)): p = sense (p,measurements[k]) print p print sense(p,Z)
aadithyamd/QandA
QA/forms.py
Python
mit
4,443
0.011479
from django import forms from .models import Question, Answer, Categories, Customuser from django.contrib import auth from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ class add_Question_Form(forms.ModelForm): # just a regular form question_text = forms.CharField(l...
assword confirmation"), widget=forms.PasswordInput, help_text=_("Enter the same password as before, for verification.")) # User's username field and our own 2 fields pass1 and pass2 are used. Later # we shall set the User's password by user.set_password. class Meta: model = Customu...
rd1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) ...
inferrna/neurolabcl
replacer.py
Python
lgpl-3.0
407
0.034398
import re s = open("neurolab/tool.py", "r").read() s = re.sub('^([ \t\r\f\v]*)(.+?)\.shape = (.*?), (.*?)$', '\g<1>\g<2> = \g<2>.reshape((\g<3>, \g<
4>,)) #replacement for \"\\g<0>\"', s, flags=re.MULTILINE) s = re.sub('^([ \t\r\f\v]*)(.+?)\.shape = (\S+?)$', '\g<1>\g<2> = \g<2>.reshape(\g<3>) #replacement for \"\\g<0>\"', s, flags=re.MULTILINE) f = open("neuro
lab/newtool.py", "w") f.write(s) f.close()
dobbscoin/dobbscoin-source
qa/rpc-tests/getblocktemplate_proposals.py
Python
mit
6,302
0.004919
#!/usr/bin/env python2 # Copyright (c) 2014 The Dobbscoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework import DobbscoinTestFramework from dobbscoinrpc.authproxy import AuthServiceProxy, JSONR...
ff\xff\xff\xff' assert_template(node, tmpl, txlist, 'bad-txns-nonfinal') txlist[0][-4:] = b'\0\0\0\0' # Test 7: Bad tx count txlist.append(b'') try: assert_template(node, tmpl, txlist, 'n/a'
) except JSONRPCException: pass # Expected txlist.pop() # Test 8: Bad bits realbits = tmpl['bits'] tmpl['bits'] = '1c0000ff' # impossible in the real world assert_template(node, tmpl, txlist, 'bad-diffbits') tmpl['bits'] = realbits # Test 9...
roderickvd/nzbToMedia
nzbtomedia/linktastic/linktastic.py
Python
gpl-3.0
4,080
0.004902
# Linktastic Module # - A python2/3 compatible module that can create hardlinks/symlinks on windows-based systems # # Linktastic is distributed under the MIT License. The follow are the terms and conditions of using Linktastic. # # The MIT License (MIT) # Copyright (c) 2012 Solipsis Development # # Permission is here...
_link_windows(src, dest) else: os.link(src, dest) # Create a symlink to src named as de
st, but don't fail if you're on nt def symlink(src, dest): if os.name == 'nt': _symlink_windows(src, dest) else: os.symlink(src, dest) # Create a symlink to src named as dest, but don't fail if you're on nt def dirlink(src, dest): if os.name == 'nt': _dirlink_windows(src, dest) ...
pelucid/salesforce_bulk
test_salesforce_bulk.py
Python
mit
4,845
0.008462
import re import unittest import salesforce_oauth_request from salesforce_bulk import SalesforceBulk class SalesforceBulkTest(unittest.TestCase): def __init__(self, testName, endpoint, sessionId): super(SalesforceBulkTest, self).__init__(testName) self.endpoint = endpoint self.sessionId =...
= unittest.TestSuite() suite.addTest(SalesforceBulkTest("test_csv_u
pload", endpoint, sessionId)) unittest.TextTestRunner().run(suite)
evelkey/vahun
experiment_FINAL.py
Python
apache-2.0
4,608
0.021267
import sys import tensorflow as tf from vahun.Text import Text import numpy as np from vahun.tools import Timer from vahun.tools import explog from vahun.autoencoder import Autoencoder_ffnn from vahun.variational_autoencoder import Variational_autoencoder from vahun.genetic import evolution from vahun.genetic import ex...
/store/velkey/mnsz2/filt.200k.maxlen20.digraph_repl',size=size), Text(corpus_path='/mnt/store/velkey/mnsz2/filt.200k_random.maxlen20.digraph_repl',size=size)] print("Corpus list ready") exps = [] ranger=range(args.low,args.high) i=0 with open('/mnt/store/velkey/experiments') as f:...
exps: exper=[int(item) for item in exper] layerlist=exper[3:] settings=Settings(layerlist) typ=0 if exper[1]==0 and exper[2]==0: corpus_path='/mnt/store/velkey/mnsz2/filt.200k.maxlen20' typ=0 if exper[1]==1 and exper[2]==0: corpus_path...
googleapis/python-aiplatform
samples/generated_samples/aiplatform_v1_generated_job_service_delete_model_deployment_monitoring_job_async.py
Python
apache-2.0
1,687
0.001778
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
me_value", ) # Make the request operation = client.delete_model_deployment_monitoring_job(request=request) print("Waiting for operation to complet
e...") response = await operation.result() # Handle the response print(response) # [END aiplatform_v1_generated_JobService_DeleteModelDeploymentMonitoringJob_async]
nikesh-mahalka/cinder
cinder/tests/unit/api/contrib/test_availability_zones.py
Python
apache-2.0
2,932
0
# Copyright (c) 2013 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless ...
cinder.context': cinder.context.get_admin_context()} GET = {} class ControllerTestCase(cinder.test.TestCase): def setUp(self): super(ControllerTestCase, self).setUp() self.controller = cinder.api.contrib.availability_z
ones.Controller() self.req = FakeRequest() self.stubs.Set(cinder.volume.api.API, 'list_availability_zones', list_availability_zones) def test_list_hosts(self): """Verify that the volume hosts are returned.""" actual = self.controller.ind...
ruchee/vimrc
vimfiles/bundle/vim-python/submodules/pylint/tests/functional/u/use/used_before_assignment_488.py
Python
mit
251
0.003984
# pyl
int: disable=missing-docstring def func(): """Test that a variable defined in a finally clause does not trigger a false positive""" try: variable = 1 yield variable fin
ally: variable = 2 yield variable
khalidm/ExAC_genes
src/annotations.py
Python
mit
3,862
0.009063
''' A tool to annotate and print variants in tabular format. Author: Khalid Mahmood (khalid.mahmood@unimelb.edu.au). Copyright: 2015 ''' #!/usr/bin/python #from utils import findlist import sys import os import argparse import getopt #import vcf import array import pysam #class Error(Exception): # """Base-class...
ent_chr, current_pos, current_ref, current_alt): current_chr = current_chr.translate(None, 'chr') data = cadd_tbx.fetch(current_chr, current_pos-1, current_pos) cadd_phred, cadd_priPhCons, cadd_GerpRS = '','','' cadd_polysift, cadd_test1, cadd_t
est2 = '','','' if data is not None: for row in data: row_info = row.split("\t") cadd_ref = row_info[2] cadd_alt = row_info[4] if(cadd_ref == current_ref and cadd_alt == current_alt): cadd_phred = row_info[115] cadd_priPhCons =...
galaxyproject/pulsar
pulsar/client/transport/ssh.py
Python
apache-2.0
1,799
0.000556
import os import subprocess SSH_OPTIONS = ['-o', 'StrictHostKeyChecking=no', '-o', 'PreferredAuthentications=publickey', '-o', 'PubkeyAuthentication=yes'] def rsync_get_file(uri_from, uri_to, user, host, port, key): cmd = [
'rsync', '-e', 'ssh -i {} -p {} {}'.format(key, port, ' '.join(SSH_OPTIONS)), '{}@{}:{}'.format(user, host, uri_from), uri_to, ] _call(cmd) def rsync_post_file
(uri_from, uri_to, user, host, port, key): _ensure_dir(uri_to, key, port, user, host) cmd = [ 'rsync', '-e', 'ssh -i {} -p {} {}'.format(key, port, ' '.join(SSH_OPTIONS)), uri_from, '{}@{}:{}'.format(user, host, uri_to), ] _call(cmd) def scp_get_file(uri_from, u...
simion/django-trampoline
tests/test_paginator.py
Python
mit
2,454
0
""" Test paginator for trampoline. """ from elasticsearch_dsl import Index from elasticsearch_dsl import Search from trampoline.paginator import ESSearchPaginator from tests.base import BaseTestCase from tests.models import Token from tests.views import PaginatedContentView class TestPaginator(BaseTestCase): d...
) self.assertIsNotNone(page) self.assertIsNotNone(view.page) self.assertEqual(view.get_context_data()['page'], view.
page)
uwekamper/flutterspark
flutterbrain_web/mapview/clustering.py
Python
mit
3,178
0.003776
# -*- coding: utf-8 -*- import re import requests import base64 import struct import random from sklearn.cluster import KMeans from sklearn.preprocessing import scale from dateutil.parser import parse class Tweet(object): def __init__(self, status): self.screen_name = status['screen_name'] self.tex...
}]>'.format(self.screen_name, self.text[:20], self.classification) def get_tweets(hashtag): url = u'http://loklak.org:9000/api/search.json?q={}&minifi
ed=true'.format(hashtag) resp = requests.get(url) data = resp.json()['statuses'] tweets = [] for status in data: tweets.append(Tweet(status)) return tweets def extract_brainstate(text): match = re.search(r' [A-Za-z0-9+/=]{24,32} ', text) if not match: return None else: ...
bpeschier/reek-pages
pages/apps.py
Python
mit
265
0
from django.apps import AppConfig from django.utils.module_load
ing import autodiscover_modules class PagesAppConfig(AppConfig): name = 'pages' def ready(self): #
Walk over all views-modules to discover views autodiscover_modules('views')
Thortoise/Super-Snake
Blender/animation_nodes-master/node_link_conversion.py
Python
gpl-3.0
11,610
0.008183
import bpy from . import tree_info from mathutils import Vector from . utils.nodes import idToSocket from . sockets.info import toBaseIdName, isList from . tree_info import getAllDataLinkIDs, getDirectlyLinkedSocket def correctForbiddenNodeLinks(): for dataOrigin, target in iterLinksThatNeedToBeCorrectedOrRemoved(...
urn origin.dataType == "Object" and target.dataType == "Shape Key" def insert(self, nodeTree, origin, target, dataOrigin): getShapeKeys, getListElement = insertNodes(nodeTree, ["an_ShapeKeysFromObjectNode", "an_GetListElementNode"], origin, target) getListElement.inputs[1].val
ue = 1 nodeTree.links.new(getShapeKeys.inputs[0], origin) nodeTree.links.new(getListElement.inputs[0], getShapeKeys.outputs[0]) nodeTree.links.new(getListElement.outputs[0], target) class ConvertSeparatedMeshDataToBMesh(LinkCorrection): separatedMeshDataTypes = ["Vector List", "Edge Indices...
marcusmoller/pyorpg-client
src/pgu/gui/test.py
Python
mit
226
0.00885
class Test(object): @
property def something(self): return 12 @something.setter def something(self, value): self.other = value t = Test() print t.something t.something =
123 print t.other
dw9694/django_blog
blog/templatetags/image_tags.py
Python
gpl-3.0
2,209
0.000453
#!/usr/bin/env python # -*- coding: utf8 -*- import os.path from django import template FMT = 'JPEG' EXT = 'jpg' QUAL = 75 register = template.Librar
y() def resized_path(path, size, method): "Returns the path for the resized image." dir, name = os.path.split(path) image_name, ext = name.rsplit('.', 1) return os.path.join(dir, '%s_%s_%s.%s' % (image_name, method, size, EXT)) def scale(imagefield, size, method='scale'): "
"" Template filter used to scale an image that will fit inside the defined area. Returns the url of the resized image. {% load image_tags %} {{ profile.picture|scale:"48x48" }} """ # imagefield can be a dict with "path" and "url" keys if imagefield.__class__.__name__ == 'dict': ...
lordakshaya/pyexcel
examples/basics/read_cell_by_cell.py
Python
bsd-3-clause
1,031
0.00291
""" read_cell_by_cell.py :copyright: (c) 2014-2015 by Onni Software Ltd. :license: New BSD License, see LICENSE for more details This shows how to use **Reader** class to go through a single page spreadsheet, The
output is:: 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 """ import os import pyexcel as pe def main(base_dir): # Simple give the file name to **Reader** # "example.xls","example.xlsx","example.ods", "example.xlsm" spreadsheet = pe.load(os.path.join(base_dir,"example.csv")) ...
nge(): # cell_value(row_index, column_index) # return the value at the specified # position # please note that both row_index # and column_index starts from 0 print(spreadsheet.cell_value(r, c)) if __name__ == '__main__': main(os.getcwd())
crossbario/crossbarexamples
exclude_subscribers/carol.py
Python
apache-2.0
2,561
0.000781
import random from os import environ, urandom from os.path import exists from functools import partial from twisted.internet.defer import inlineCallbacks from autobahn.twisted.util import sleep from autobahn.twisted.wamp import ApplicationSession, ApplicationRunner from autobahn.wamp import cryptosign from autobahn....
ounter += 1 yield sleep(3) def onConnect(self): extra = { 'pubkey': self.key.pu
blic_key(), 'channel_binding': 'tls-unique' } # now request to join .. self.join(self.config.realm, authmethods=['cryptosign'], authid='carol', authextra=extra) def onChallenge(self, challenge): self.log.info("authen...
namili/blueman
blueman/gui/MessageArea.py
Python
gpl-3.0
5,072
0.043573
# Copyright (
C) 2008 Valmantas Paliksa <walmis at balticum-tv dot lt> # # Licensed under the GNU General Public License Version 3 # # 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 Lic...
his 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 wit...
monodokimes/pythonmon
controller/component/__init__.py
Python
gpl-3.0
403
0
from controller.component.component import Compon
ent from controller.component.graphics_component import GraphicsComponent from controller.component.movement_component import MovementComponent from controller.component.input_component import InputComponent from controller.component.pla
yer_input_component import PlayerInputComponent from controller.component.tile_map_component import TileMapComponent
laffra/pava
pava/implementation/natives/jdk/management/resource/__init__.py
Python
mit
215
0.009302
""" This is the Python implementation for the Java package "jdk.management.resource.internal", compiled by Pava.
""" import pava from pava import nan, inf pava_classes = {} pava.module(__name__) impor
t internal
franciscod/python-telegram-bot
tests/test_inlinequeryresultvideo.py
Python
gpl-2.0
3,826
0.001307
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2016 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # 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 ...
legram.InlineKeyboardButton('reply_markup') ]]) self.json_dict = { 'type': self.type, 'id': self.id, 'video_url': self.video_url, 'mime_type': self.mime_type, 'video_width': self.video_width, 'video_height': self.video_height, ...
n': self.description, 'input_message_content': self.input_message_content.to_dict(), 'reply_markup': self.reply_markup.to_dict(), } def test_video_de_json(self): video = telegram.InlineQueryResultVideo.de_json(self.json_dict) self.assertEqual(video.type, self.type) ...
psiinon/addons-server
src/olympia/lib/crypto/signing.py
Python
bsd-3-clause
9,286
0
import hashlib import os import zipfile from base64 import b64decode, b64encode from django.db import transaction from django.conf import settings from django.core.files.storage import default_storage as storage from django.core.exceptions import ObjectDoesNotExist from django.utils.encoding import force_bytes, force...
ch to that without breaking backwards # compatibility" # https://github.com/mozilla/addons-server/issues/9308 # This means, the pkcs7 sha1 signature is used for backwards # compatibility and cose sha256 will be used for newer # Firefox versions. # ...
n Firefox is # "security.signed_app_signatures.policy" # where it's set to COSEAndPKCS7WithSHA1OrSHA256 to match # these settings. 'pkcs7_digest': 'SHA1', 'cose_algorithms': ['ES256'] }, } hawk_auth = HawkAuth(id=conf['user_id'], key=conf['key...
Venturi/oldcms
env/lib/python2.7/site-packages/tests/config.py
Python
apache-2.0
31,993
0.00175
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import copy import os import sys from argparse import Namespace from mock import patch from six import StringIO, text_type from tzlocal import get_localzone import six from djangocms_installer import config from djangocm...
:pwd@host/dbname', '--cms-version=stable',
'--django-version=1.4', '--cms-version=3.0', '--i18n=no', '--reversion=no', '--permissions=no', '--use-tz=no', '-tEurope/Rome', '-len', '-lde', '-lit', '-p'+self.project_dir, 'example_prj']) s...
PiotrZakrzewski/steamweb
steamweb/actions/auction_actions.py
Python
mit
4,727
0.003385
from steamweb.actions_base import PlayerAction from steamweb.db_utils import get_tender, get_tile, get_resource from steamweb.utils import InsufficientFunds, get_capacity from steamweb.database import db_session from steamweb.models import * class BidAction(PlayerAction): def resolution(self, game, player, argum...
ist_auction_victory"] def domain(self, game, player): specs = Specialist.query.filter(Specialist.game == game.id).all() specs = [spec.id for spec in specs if spec.player is None] bonus_res = ['None'] # player can always pick no bonus, for instance when there is none to be taken if...
nd('energy') if game.bonus_ore: bonus_res.append('ore') if game.bonus_quartz: bonus_res.append('quartz') if game.bonus_water: bonus_res.append('water') pick_spec_domain = [] for spec_id in specs: for bonus in bonus_res: ...
myhearter/dianping
ddp/app/merchants/migrations/0007_auto_20171119_0852.py
Python
mit
807
0.001239
# -*- coding: utf-8 -*- from
__future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('merchants', '0006_classfy'), ] operations = [ migrations.CreateModel( name='RegionItem', fields=[ ('name', model...
tions={ 'db_table': 'T_region', }, ), migrations.RenameModel( old_name='Classfy', new_name='ClassfyItem', ), migrations.RenameModel( old_name='MerchantInfo', new_name='MerchantItem', ), ]
DirectXMan12/nova-hacking
nova/tests/virt/baremetal/test_driver.py
Python
apache-2.0
14,537
0.001376
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # coding=utf-8 # Copyright 2012 Hewlett-Packard Development Company, L.P. # Copyright (c) 2012 NTT DOCOMO, INC. # Copyright (c) 2011 University of Southern California / ISI # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may ...
f.assertEqual( expected, self.driver.macs_for_instance(node['instance'])) def test_macs_for_instance(self): node = self._create_node() expected = set(['01:23:45:67:89:01', '01:23:45:67:89:02']) self.assertEqual( expected, self.driver.macs_for_instance(node['instance'...
macs_for_instance_no_interfaces(self): # Nodes cannot boot with no MACs, so we raise an error if that happens. node = self._create_node(nic_info=[]) self.assertRaises(exception.NovaException, self.driver.macs_for_instance, node['instance']) def test_spawn_node_already_associated...
dims/heat
heat/engine/resources/openstack/keystone/user.py
Python
apache-2.0
9,242
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 # ...
prps or []) - set(stored_prps or []))] removed_group_ids = [self.client_p
lugin().get_group_id(group) for group in (set(stored_prps or []) - set(updated_prps or []))] return new_group_ids, removed_group_ids def handle_create(self): user_name = (self.properties[self.NAME] or ...
shaneknapp/spark
python/pyspark/tests/test_context.py
Python
apache-2.0
13,901
0.001511
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
llo() with QuietTest(self.sc): self.assertRaises(Exception, self.sc.parallelize(range(2)).map(func).first) # Add the file, so the job should now succeed: path = os.pat
h.join(SPARK_HOME, "python/test_support/userlibrary.py") self.sc.addPyFile(path) res = self.sc.parallelize(range(2)).map(func).first() self.assertEqual("Hello World!", res) def test_add_file_locally(self): path = os.path.join(SPARK_HOME, "python/test_support/hello/hello.txt") ...
sdpython/pyquickhelper
src/pyquickhelper/loghelper/buffered_flog.py
Python
mit
844
0
""" @file @brief Buffer as a logging function. """ from io import StringIO class BufferedPrint: """ Buffered display. Relies on :epkg:`*py:io:StringIO`. Use it as follows: .. runpython:: :showcode: def
do_something(fLOG=None): if fLOG: fLOG("Did something.") return 3 from pyquickhelper.loghelper import BufferedPrint buf = BufferedPrint() do_something(fLOG=buf.fprint) print(buf) """
def __init__(self): "constructor" self.buffer = StringIO() def fprint(self, *args, **kwargs): "print function" mes = " ".join(str(_) for _ in args) self.buffer.write(mes) self.buffer.write("\n") def __str__(self): "Returns the content." return ...
michaelyou/One-piece-forum
forum/migrations/0001_initial.py
Python
mit
12,680
0.005205
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.contrib.auth.models import django.utils.timezone from django.conf import settings import django.core.validators import forum.models class Migration(migrations.Migration): dependencies = [ ...
odels.Au
toField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('title', models.CharField(max_length=200, null=True, blank=True)), ('slug', models.SlugField(max_length=200, null=True, blank=True)), ('content', forum.models.NormalTextField(null=True, bl...
lsolanka/gridcells
tests/unit/test_analysis_signal.py
Python
gpl-3.0
10,163
0.000197
'''Test the analysis.signal module.''' from __future__ import absolute_import, print_function, division import pytest import numpy as np import gridcells.analysis.signal as asignal from gridcells.analysis.signal import (local_extrema, local_maxima, local_minima, ExtremumTypes, ...
minima) # 2 minima for n_extrema
in [4, 5]: sig, extrema_idx, extrema_types = generate_sin(n_extrema)
Empire-of-Code-Puzzles/checkio-empire-most-numbers
verification/src/tests.py
Python
gpl-2.0
2,790
0.001792
TESTS = { "Level_1": [ { "input": [1, 2, 3], "answer": 2, "explanation": "3-1=2" }, { "input": [5, -5], "answer": 10, "explanation": "5-(-5)=10" }, { "input": [10.2, -2.2, 0, 1.1, 0.5], ...
, -0.025, -28.0, -4.7, -2.9, -8.0, -0.093, -13.0, -73.0], "answer": 72.975, "explanation": "-0.025-(-73.0)"}, {"inpu
t": [-0.015, 7.6], "answer": 7.615, "explanation": "7.6-(-0.015)"}, {"input": [-46.0, 0.19, -0.08, -4.0, 4.4, 0.071, -0.029, -0.034, 28.0, 0.043, -97.0], "answer": 125.0, "explanation": "28.0-(-97.0)"}, {"input": [32.0, -0.07, -0.056, -6.4, 0.084], "answer"...
CODAIT/graph_def_editor
tests/function_graph_test.py
Python
apache-2.0
6,316
0.006966
# Copyright 2021 Google. All Rights Reserved. # Copyright 2019 IBM. 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 # #...
x = tf.placeholder(name="x", dtype=tf.float32, shape=[]) y = tf.placeholder(name="y", dtype=tf.float32, shape=[]) result_op = tf.add(x, y, name="add") _ = multiplier_function(result_op) return tf_g def run_tf_graph(self, tf_g
, x, y): with tf.Session(graph=tf_g) as sess: x_tensor = tf_g.get_tensor_by_name("x:0") y_tensor = tf_g.get_tensor_by_name("y:0") output_tensor = tf_g.get_tensor_by_name("PartitionedCall:0") return sess.run(output_tensor, {x_tensor: x, y_tensor: y}) def save_tf_graph(self, tf_g, model_dir...
piotras/midgard-core
tests/GIR/test_query_select.py
Python
lgpl-2.1
9,821
0.020772
# coding=utf-8 import sys import struct import unittest from test_000_config import TestConfig from test_001_connection import TestConnection from gi.repository import Midgard from gi.repository import GObject class TestQuerySelect(unittest.TestCase): mgd = None def setUp(self): if self.mgd == None: s...
ass = "midgard_person") storage_two = Midgard.QueryStorage(dbclass = "midgard_person") qs = Midgard.QuerySelect(connection = self.mgd, storage = storage_one) group = Midgard.QueryConstraintGroup(grouptype = "AND") constraint_one =
Midgard.QueryConstraint( property = Midgard.QueryProperty(property = "firstname"), operator = "=", holder = Midgard.QueryValue.create_with_value("Alice") ) constraint_two = Midgard.QueryConstraint( property = Midgard.QueryProperty(property = "firstname", storage = storage_two), op...
JoaquimPatriarca/senpy-for-gis
gasp/fromtxt/pnd.py
Python
gpl-3.0
272
0.014706
""" Te
xt files to Pandas """ import pandas def txt_to_pandas(csvFile, _delimiter, encoding_='utf8'): """ Text file to Pandas Dataframe """ return pandas.read_csv( csvFile, sep=_delimiter, low_memory=False, #encoding=encoding_ )
comocheng/RMG-Py
rmgpy/rmg/input.py
Python
mit
22,111
0.007281
#!/usr/bin/python # -*- coding: utf-8 -*- ################################################################################ # # RMG - Reaction Mechanism Generator # # Copyright (c) 2002-2010 Prof. William H. Green (whgreen@mit.edu) and the # RMG Team (rmg_dev@mit.edu) # # Permission is hereby granted, free of c...
tyThreshold=1e-3): logging.debug('Found LiquidReactor reaction system') T = Quantity(temperature) for spec,conc in initialConcentrations.iteritems(): concentration = Quantity(conc) # check the dimensions are ok # convert to mol/m^3 (or something numerically nice? or must it be S...
for spec, conv in terminationConversion.iteritems(): termination.append(TerminationConversion(speciesDict[spec], conv)) if terminationTime is not None: termination.append(TerminationTime(Quantity(terminationTime))) if len(termination) == 0: raise InputError('No termination condition...
zqfan/leetcode
algorithms/664. Strange Printer/solution.py
Python
gpl-3.0
657
0.001522
class Solution(object): def strangePrinter(self, s): """ :type s: str :rtype: int """ n = len(s) dp = [[0] * n for i in xrange(n + 1)] for i in xrange(n): dp[i][i] = 1 for l in xrange(1
, n): for i in xrange(n-l): e = i + l dp[i][e] = dp[i+1][e] + 1 for j in xrange(i+1, e+1): if s[i] == s[j] and dp[i][j-1] + dp[j+1][e] < dp[i][e]: dp[i][e] = dp[i][j-1] + dp[j+1][e] return dp[0][-1] if s else...
sed. # Status: Accepted # Runtime: 852 ms
ganesh-95/python-programs
thoughtworks/strrev.py
Python
mit
109
0.036697
#reversing the words in a string s = raw_input(
'enter the string:') print '
'.join(s.split(' ')[::-1])
supertom/ansible-modules-core
cloud/digital_ocean/digital_ocean_block_storage.py
Python
gpl-3.0
11,293
0.00487
#!/usr/bin/python # -*- coding: utf-8 -*- # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. #...
ATION = ''' --- module: digital_ocean_block_storage short_description: Create/destroy or attach/detach Block Storage volumes in DigitalOcean description: - Create/destroy Block Storage volume in DigitalOcean, or attach/detach Block Storage volume to a droplet. version_added: "2.2" author: "Harnek Sidhu"
options: command: description: - Which operation do you want to perform. choices: ['create', 'attach'] required: true state: description: - Indicate desired state of the target. choices: ['present', 'absent'] required: true api_token: description: - DigitalOcean api tok...
hfeeki/django-guardian
guardian/mixins.py
Python
bsd-2-clause
6,473
0.002935
from collections import Iterable from django.conf import settings from django.contrib.auth.decorators import REDIRECT_FIELD_NAME from django.contrib.auth.decorators import login_required from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import PermissionDenied from guardian.utils...
""" Checks if *request.user* has all permissions returned by *get_required_permissions* method. :param request: Original request. """ obj = hasattr(self, 'get_object') and self.get_obje
ct() \ or getattr(self, 'object', None) forbidden = get_403_or_None(request, perms=self.get_required_permissions(request), obj=obj, login_url=self.login_url, redirect_field_name=self.redirect_field_name, return_403=self.return_403,...
kobejean/tensorflow
tensorflow/python/framework/random_seed.py
Python
apache-2.0
5,902
0.003219
# Copyright 2015 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...
determinism is (None, None). if seeds == (0, 0): return (0, _MAXINT32) return seeds @tf_export('set_random_seed') def set_random_seed(seed): """Sets the graph-level random seed. Operations that rely on a random seed actually derive it from two seeds: the graph-level and operation-level seeds. This sets...
e operation seed is set: A random seed is used for this op. 2. If the graph-level seed is set, but the operation seed is not: The system deterministically picks an operation seed in conjunction with the graph-level seed so that it gets a unique random sequence. 3. If the graph-level seed is no...
lferr/charm
charm/test/schemes/dabenc_test.py
Python
lgpl-3.0
3,191
0.015042
from charm.schemes.dabe_aw11 import Dabe from charm.adapters.dabenc_adapt_hybrid import HybridABEncMA from charm.toolbox.pairinggroup import PairingGroup, GT import unittest debug = False class DabeTest(unittest.TestCase): def testDabe(self): groupObj = PairingGroup('SS512') dabe = Dabe(groupObj)...
) if debug: groupObj.debug(CT) orig_m = dabe.decrypt(GP, K, CT) assert m == orig_m, 'FAILED Decryp
tion!!!' if debug: print('Successful Decryption!') class HybridABEncMATest(unittest.TestCase): def testHybridABEncMA(self): groupObj = PairingGroup('SS512') dabe = Dabe(groupObj) hyb_abema = HybridABEncMA(dabe, groupObj) #Setup global parameters for al...
fras2560/Baseball-Simulator
simulator/__init__.py
Python
apache-2.0
5,251
0.003047
""" ------------------------------------------------------- Simulator a package that helps simulate a baseball game based on previous batting history ------------------------------------------------------- Author: Dallas Fraser ID: 110242560 Email: fras2560@mylaurier.ca Version: 2014-09-11 -----------...
%(message)s') logger = logging.getLogger(__name__) self.logger = logger self.import_players(file) self.pp = PrettyPrinter(indent=4) def import_players(self, file): # assuming csv self.girls = [] self.boys = [] with open(file) as f: ...
data[0] gender = data[1] hits = data[2:] if gender.strip().upper() == "F": self.girls.append(Player(name, hits, gender, ...
MOOCworkbench/MOOCworkbench
marketplace/migrations/0011_auto_20170526_1215.py
Python
mit
462
0
# -*- codin
g: utf-8 -*- # Generated by Django 1.11.1 on 2017-05-26 12:15 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('marketplace', '0010_packageresource_recommend
ed'), ] operations = [ migrations.AlterField( model_name='packageresource', name='resource', field=models.TextField(), ), ]
ostree/plaso
plaso/cli/hexdump.py
Python
apache-2.0
2,539
0.006302
# -*- coding: utf-8 -*- """Class to represent binary data as hexadecimal.""" class Hexdump(object): """Class that defines a hexadecimal representation formatter (hexdump).""" @classmethod def _FormatDataLine(cls, data, data_offset, data_size): """Formats binary data in a single line of hexadecimal represen...
taining a hexadecimal representation of the binary data. Raises:
ValueError: if the data offset is out of bounds. """ if data_offset < 0 or data_offset >= data_size: raise ValueError(u'Data offset value out of bounds.') if data_size - data_offset > 16: data_size = data_offset + 16 word_values = [] for byte_offset in range(data_offset, data_siz...
dougli1sqrd/yamldown
setup.py
Python
bsd-3-clause
555
0.003604
from setuptools import setup, find_packages setup( name="yamldown", version="0.1.8", packages=["yamldown"], author="edou
glass", author_email="edouglass@lbl.gov", url="https://github.com/dougli1sqrd/yamldown", download_url="https://github.com/dougli1sqrd/yamldown/archive/0.1.8.tar.gz", description="Python library for loading and dumping \"yamldown\" (markdown with embedded yaml) files.", long_description=ope
n("README.md").read(), keywords=["yaml", "markdown"], install_requires=[ "pyYaml", ], )
uq-eresearch/uqam
location/views.py
Python
bsd-3-clause
4,790
0.003549
from django.http import HttpResponse, Http404 from django.core.exceptions import ObjectDoesNotExist from django.shortcuts import render, get_object_or_404 from django.core.urlresolvers import reverse from django.utils.xmlutils import SimplerXMLGenerator from models import Place, Region from models import Locality fr
om models import GlobalRegion from utils.utils import do_paging, split_list from django.db.models import Count from django.contrib.contenttypes.models import ContentType import json def place_detail(request, place_id): """ Lookup a ``Place`` based on its id. Pagination its objects. """ place = get_obj...
ce_objects = place.museumobject_set.filter(public=True) objects = do_paging(request, place_objects) return render(request, "location/place_detail.html", {'place': place, 'objects': objects, 'region': region}) def place_json(request, encoding='utf-8', mimetype='text/plain'): plac...
Lcaracol/ideasbox.lan
ideasbox/fields.py
Python
mit
778
0
from select_multiple_field.models import SelectMultipleField class CommaSeparatedCharField(SelectMultipleField): def contribute_to_class(self, cls, name, **kwargs): """Contribute to the Model subclass. We just set our custom get_FIELD_display(), which returns a comma-separated list of di...
**kwargs) def _get_FIELD_display(instance): choices = dict(self.choices) values = getattr(instance, self.attname) return ", ".join(unicode(ch
oices.get(c, c)) for c in values if c) setattr(cls, 'get_%s_display' % self.name, _get_FIELD_display)
paulrouget/servo
tests/wpt/web-platform-tests/tools/third_party/hyper/hyper/common/headers.py
Python
mpl-2.0
8,888
0
# -*- coding: utf-8 -*- """ hyper/common/headers ~~~~~~~~~~~~~~~~~~~~~ Contains hyper's structures for storing and working with HTTP headers. """ import collections from hyper.common.util import to_bytestring, to_bytestring_tuple class HTTPHeaderMap(collections.MutableMapping): """ A structure that contains...
o ensure that it is always possible to # reproduce the original header structure if necessary. This leads to # some unfortunate performance costs on structure access
where it is # often necessary to transform the data into canonical form on access. # This cost is judged acceptable in low-level code like `hyper`, but # higher-level abstractions should consider if they really require this # logic. self._items = [] for arg in args: ...
frankrousseau/weboob
modules/allocine/module.py
Python
agpl-3.0
8,218
0.001583
# -*- coding: utf-8 -*- # Copyright(C) 2013 Julien Veyssier # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your op...
umbnail_url' in fields\ or 'biography' in fields\ or 'gender' in fields or fields is None: per = self.get_person(person.id) person.real_name = per.real_name person.birth_date = per.birth_date person.death_date = per.death_date perso...
iography person.short_description = per.short_description person.roles = per.roles person.biography = per.biography person.thumbnail_url = per.thumbnail_url return person def fill_movie(self, movie, fields): if 'other_titles' in fields or 'release_da...
zerolab/wagtail
wagtail/admin/forms/tags.py
Python
bsd-3-clause
1,354
0.001477
from taggit.forms import TagField as TaggitTagField from taggit.models import Tag from wagtail.admin.widgets import AdminTagWidget class TagField(TaggitTagField): """ Extends taggit's TagField with the option to prevent creating tags that do not already exist """ widget = AdminTagWidget def __in...
Otherwise, set default values for clean() to use if self.tag_model is None: self.tag_model = Tag else: self.widget.tag_model = self.tag_model if self.free_tagging is None: self.free_tagging = getattr(self.tag_model, 'free_tagging', True) else: ...
# filter value to just the tags that already exist in tag_model value = list( self.tag_model.objects.filter(name__in=value).values_list('name', flat=True) ) return value
pgmillon/ansible
lib/ansible/module_utils/network/common/network.py
Python
gpl-3.0
8,128
0.002461
# This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete wo...
n(msg='Unknown transport or no default transport specified') except (TypeError, NetworkError) as exc: self.fail_json(m
sg=to_native(exc), exception=traceback.format_exc()) if connect_on_load: self.connect() @property def cli(self): if not self.connected: self.connect() if self._cli: return self._cli self._cli = Cli(self.connection) return self._cli ...
lmazuel/azure-sdk-for-python
azure-mgmt-compute/setup.py
Python
mit
2,784
0.001078
#!/usr/bin/env python #------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. #----------------------------------------------------------------...
-', '/') # a-b-c => a.b.c namespace_name = PACKAGE_NAME.replace('-', '.') # azure v0.x is not compatible with this package # azure v0.x used to have a __version__ attribute (newer versions don't) try: import azure try: ver = azure.__version__ raise Exception( 'This package is incomp...
zure".' ) except AttributeError: pass except ImportError: pass # Version extraction inspired from 'requests' with open(os.path.join(package_folder_path, 'version.py'), 'r') as fd: version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).gro...
thaim/ansible
lib/ansible/modules/network/cumulus/nclu.py
Python
mit
7,641
0.001309
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2016-2018, Cumulus Networks <ce-ceng@cumulusnetworks.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_v...
y json register: output - name: Print BGP Status In JSON debug: var: output["msg"] ''' RETURN = ''' changed: description: whether the interface was changed returned: changed type: bool sample: True msg: description: human-readable report of success or failure
returned: always type: str sample: "interface bond0 config updated" ''' from ansible.module_utils.basic import AnsibleModule def command_helper(module, command, errmsg=None): """Run a command, catch any nclu errors""" (_rc, output, _err) = module.run_command("/usr/bin/net %s" % command) if _rc ...
OCA/l10n-brazil
l10n_br_fiscal/wizards/__init__.py
Python
agpl-3.0
252
0
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from . import base_wizard_mixin from . import document_cancel_wizard from . import docume
nt_correction_wizar
d from . import document_status_wizard from . import invalidate_number_wizard
vijayendrabvs/ssl-neutron
neutron/plugins/ml2/plugin.py
Python
apache-2.0
35,120
0.000028
# Copyright (c) 2013 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless ...
() self.conn.create_consumer(self.topic, self.dispatcher, fanout=False) return self.conn.consume_in_thread() def _process_provider_segment(self, segment): network_type = self._get_attribute(segment, provider.NETWORK_TYPE) physical_network = self._ge...
provider.PHYSICAL_NETWORK) segmentation_id = self._get_attribute(segment, provider.SEGMENTATION_ID) if attributes.is_attr_set(network_type): segment = {api.NETWORK_TYPE: network_type, ...
CropCircleSys/bsd-cloudinit
cloudbaseinit/metadata/services/ec2service.py
Python
apache-2.0
3,464
0
# Copyright 2014 Cloudbase Solutions Srl # Copyright 2012 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # ...
self._metadata_version) def get_public_keys(self): ssh_keys = [] keys_info = self._get_cache_data( '%s/meta-data/public-keys' % self._metadata_version).split("\n") for key_info in keys_info: (idx, key_name) = key_info.split('=') ssh_key = s...
idx)s/openssh-key' % {'version': self._metadata_version, 'idx': idx}) ssh_keys.append(ssh_key) return ssh_keys def get_network_details(self): # TODO(cpoieana): add static network config support pass
murphyke/avocado
tests/cases/query/tests/parsers.py
Python
bsd-2-clause
19,203
0
from copy import deepcopy from django.test import TestCase from django.core.exceptions import ValidationError from django.core import management from avocado.query import oldparsers as parsers from avocado.models import DataConcept, DataField, DataConceptField from ....models import Employee class DataContextParserTe...
', 'title', 'name'], 'operator': 'exact', 'value': 'CEO', 'cleaned_value': {'value': 'CEO', 'label': 'CEO'}, 'language': 'Name is CEO' } self.assertEqual( parsers.datacontext.validate(deepcopy(attrs), tree=Employee), attrs)
# Single by field attrs = { 'field': title.pk, 'operator': 'exact', 'value': 'CEO', 'cleaned_value': {'value': 'CEO', 'label': 'CEO'}, 'language': 'Name is CEO' } self.assertEqual( parsers.datacontext.validate(deepcopy(att...
ratnania/pyccel
tests/internal/scripts/blas/ex2.py
Python
mit
611
0.036007
from pyccel.stdlib.internal.blas import dgemv from numpy import zeros n = 4 m = 5 a = zeros((n,m), 'double') x = zeros(m, 'double') y = zeros(n, 'double') # ... a[0,0] = 1.0
a[1,0] = 6.0 a[2,0] = 11.0 a[3,0] = 16.0 a[0,1] = 2.0 a[1,1] = 7.0 a[2,1] = 12.0 a[3,1] = 17.0 a[0,2] = 3.0 a[1,2] = 8.0 a[2,2] = 13.0 a[3,2] = 18.0 a[0,3] = 4.0 a[1,3] = 9.0 a[2,3] = 14.0 a[3,3] = 19.0
a[0,4] = 5.0 a[1,4] = 10.0 a[2,4] = 15.0 a[3,4] = 20.0 # ... # ... x[0] = 2.0 x[1] = 3.0 x[2] = 4.0 x[3] = 5.0 x[4] = 6.0 # ... alpha = 2.0 beta = 0.0 incx = 1 incy = 1 dgemv('N', n, m, alpha, a, n, x, incx, beta, y, incy)
DevangS/CoralNet
images/tests/__init__.py
Python
bsd-2-clause
144
0
# Import test
s from each test file. #
e.g. if we have tests/sources.py, then "from sources import *" from sources import * from tasks import *
ESOedX/edx-platform
cms/djangoapps/contentstore/views/tests/utils.py
Python
agpl-3.0
3,337
0.004195
""" Utilities for view tests. """ from __future__ import absolute_import import json from contentstore.tests.utils import CourseTestCase from contentstore.views.helpers import xblock_studio_url from xmodule.modulestore.tests.factories import ItemFactory class StudioPageTestCase(CourseTestCase): """ Base cl...
name) self.validate_html_for_action_button( html, '<div class="add-xblock-component new-component-item adding"></div>', can_add ) self.validate_html_for_action_button( html, '<span data-tooltip="Drag to reorder" class="drag-handle actio...
btn-default move-button action-button">', can_move ) self.validate_html_for_action_button( html, 'button class="btn-default edit-button action-button">', can_edit ) self.validate_html_for_action_button( html, '<butto...
botswana-harvard/edc-map
edc_map/mapper.py
Python
gpl-2.0
2,309
0.000433
import sys from geopy import Point from django.apps import apps as django_apps from django.core.exceptions import ImproperlyConfigured from django.core.management.color import color_style from .geo_mixin import GeoMixin LANDMARK_NAME = 0 LATITUDE = 2 LETTERS = list(map(chr, range(65, 91))) LONGITUDE = 1 style = co...
Return True if point is within mapper area radius.""" return self.point_in_radius( point, self.area_center_point, self.area_radius) def raise_if_not_in_map_area(self, poi
nt): self.raise_if_not_in_radius( point, self.area_center_point, self.area_radius, units='km', label=self.map_area)
moagstar/python-uncompyle6
test/simple_source/bug26/04_comp_for.py
Python
mit
156
0
#
From python2.6/_abcoll.py # Bug was wrong code for "comp_for" giving # "for in x" instead of: "for x in y" chain = (e for s in (self, other) for x in y)
cjaymes/pyscap
src/scap/model/xnl_2_0/TitleElement.py
Python
gpl-3.0
946
0.001057
# Copyright 2016 Casey Jaymes # This file is part of PySCAP. # # PySCAP is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # PySCAP is ...
; 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 PySCAP. If not, see <http://www.gnu.org/licenses/>. from scap.Model import Model impo...
DEL_MAP = { 'tag_name': 'Title', 'attributes': { 'Type': {}, 'Code': {}, '*': {}, } }
aaxelb/osf.io
api_tests/metaschemas/views/test_metaschemas_detail.py
Python
apache-2.0
2,170
0.004608
import pytest from api.base.settings.defaults import API_BASE from osf.models import MetaSchema from osf_tests.factories import ( AuthUserFactory, ) from website.project.metadata.schemas import LATEST_SCHEMA_VERSION @pytest.mark.django_db class TestMetaSchemaDetail: def test_metaschemas_detail_visibility(se...
assert res.status_code == 200 assert res.json['data']['attributes']['name'] == 'OSF-Standard Pre-Data Collection Registrati
on' assert res.json['data']['attributes']['schema_version'] == 1 #test_invalid_metaschema_not_found url = '/{}metaschemas/garbage/'.format(API_BASE) res = app.get(url, auth=user.auth, expect_errors=True) assert res.status_code == 404
Psycojoker/HamlPy
hamlpy/parser/filters.py
Python
mit
5,088
0.001769
from __future__ import unicode_literals """ Core HamlPy filters. The implementation of these should match https://github.com/haml/haml/blob/master/lib/haml/filters.rb as closely as possible. Where we differ is that we don't compile Stylus, Coffeescript etc into CSS or Javascript - but place the content into suitable <...
]>\n' % comment) if options.cdata else ('', '') return '<script%s>\n%s%s%s\n%s</script>' % (type_attr, before, indent, text, after) # ---------------------------------------------------------------------------------- # Filter registration # ------------------------------------------------------------------------...
n, 'preserve': preserve, 'escaped': escaped, 'cdata': cdata, 'css': css, 'stylus': stylus, 'less': less, 'sass': sass, 'javascript': javascript, 'coffee': coffee, 'coffeescript': coffee, 'markdown': markdown, 'highlight': highlight, 'python': python } def register_f...
taras1k/finance
server/utils.py
Python
gpl-2.0
237
0.004219
from
collections import OrderedDict class SerializableModel(object): def _asdict(self): result = OrderedDict() for key in self.__mapper__.c.keys(): result[key] = getattr(self, key) return resul
t
ThinkboxSoftware/Deadline
Examples/DeadlineCommand/JobTaskTimes/GetJobTaskTimes.py
Python
apache-2.0
6,747
0.006966
''' This script shows an example of working with the output of the GetJobTasks subcommand. The script takes a single argument, which is the JobID of the job. When calculating the elapsed time for rendering tasks, the script does not account for daylight savings time differences or time zone differences. Elapsed ...
ASSUMPTION: Assume zero for all other TaskStatus values. TaskDict["RenderTime"] = "00:00:00.0000000" TaskDict
["TaskRenderTime"] = TaskDict["RenderTime"] return def ParseGetJobTasksOutput(output): """ Parses the output of the call to GetJobTasks. The result is a "TaskList", mean a list of "TaskDict"s, where a "TaskDict" is a dictionary of key,value pairs of information about the Task. "...
ktan2020/jpype
jpype/_jcollection.py
Python
apache-2.0
8,284
0.003621
#***************************************************************************** # Copyright 2004-2008 Steve Menard # # 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...
i): return self.remove(i) def _colAddAll(self, v): if isPythonSequence(v): r = False for i in v: r = self.add(i) or r return r else: return self._addAll(v) def _colRemoveAll(self, v):
if isPythonSequence(v): r = False for i in v: r = self.remove(i) or r return r else: return self._removeAll(v) def _colRetainAll(self, v): if isPythonSequence(v): r = _jclass.JClass("java.util.ArrayList")(len(v)) for i in v: ...
h4ck3rm1k3/ansible
lib/ansible/module_utils/basic.py
Python
gpl-3.0
60,500
0.004496
# This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete wo...
n()[1] if not distribution_version and os.path.isfile('/etc/system-release'): distribution_version = platform.linux_distribution(supported_dists=['system'])[1] except: # FIXME: MethodMissing, I assume? distribution_version = platform.dist()[1] else: ...
s(cls, *args, **kwargs): ''' used by modules like User to have different implementations based on detected platform. See User module for an example. ''' this_platform = get_platform() distribution = get_distribution() subclass = None # get the most specific superclass for this platfor...
ericmjl/bokeh
tests/unit/bokeh/util/test_version.py
Python
bsd-3-clause
3,274
0.00733
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #-------------------------------------------------------------------...
("1.2.3dev2", "1.4.5rc3", "junk")) def test_mock_not_full(self, monkeypatch, v) -> None: monkeypatch.setattr(buv, '__version__', v) assert not buv.is_full_release() #----------------------------------------------------------------------------- # Dev API #-------------------------------------------...
------------------------ # Private API #----------------------------------------------------------------------------- class Test__base_version_helper(object): def test_release_version_unchanged(self) -> None: assert buv._base_version_helper("0.2.3") == "0.2.3" assert buv._base_version_helper("1.2....
r-castro/Python
NewList.py
Python
gpl-3.0
1,219
0.001641
# Simple class SimgleList class SingleList: """Documentation for SingleList """ def __init__(self, initial_list=None): self.__list = [] if initial_list: for value in initial_list: if value not in self.__list: self.__list.append(value) ...
def __setitem__(self, index, value): if value in
self.__list: raise ValueError("List already contains value %s" % str(value)) self.__list[index] = value def __eq__(self, other): if len(self) != len(other): return 0 for i in range(0, len(self)): if self.__list[i] != other.__list[i]: re...
vileopratama/vitech
src/addons/sale_order_dates/__init__.py
Python
mit
124
0
# -*- coding: utf-
8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import sale_ord
er_dates