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
czcorpus/kontext
lib/plugins/mysql_subcmixer/metadata_model.py
Python
gpl-2.0
10,170
0.003147
# Copyright (c) 2022 Institute of the Czech National Corpus # Copyright (c) 2022 Martin Zimandl <[email protected]> # Copyright (c) 2015 Martin Stepan <[email protected]>, # Tomas Machalek <[email protected]> # # This program is free software; you can redistribute it and/or # mod...
corpus_name = %s AND a{i}.item_id
= t_tuple.item_id' for i in range(len(self.category_tree.aligned_corpora)) ] sql = f''' SELECT MIN(tuple_ids.value_tuple_id) AS db_id, SUM(t_tuple.poscount) AS poscount FROM ( {sql_intersect} ) as tuple_ids ...
minlex/django-socialregistration
socialregistration/contrib/openid/migrations/0001_initial.py
Python
mit
2,204
0.002269
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import socialregistration.models from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('sites', '0001_initial'), migrations.swappable_dependency(settings.A...
fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('identity', models.TextField()), ('site', models.ForeignKey(default=socialregistration.models.get_default_site, to='sites.Site')), ('user', mod
els.ForeignKey(to=settings.AUTH_USER_MODEL)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='OpenIDStore', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=Tr...
tensorflow/tfx
tfx/dsl/input_resolution/strategies/latest_blessed_model_strategy_test.py
Python
apache-2.0
2,902
0.001378
# Copyright 2021 Google 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/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
_PROPERTY_BLESSED_KEY].int_value = is_blessed artifact.mlmd_artifact.custom_properties[ model_validator .ARTIFACT_PROPERTY_CURRENT_MODEL_ID_KEY].int_value = model_id def testStrategy(self): #
Model with id 1, will be blessed. model_one = standard_artifacts.Model() model_one.uri = 'model_one' model_one.id = 1 # Model with id 2, will be blessed. model_two = standard_artifacts.Model() model_two.uri = 'model_two' model_two.id = 2 # Model with id 3, will not be blessed. model...
rralcala/random-scripts
py/lc/6/1496.py
Python
gpl-2.0
784
0
import unittest class Solution: def isPathCrossing(self, path: str) -> bool: fullpath = {"0-0": 1} x = 0 y = 0 for move in path: if move == "N": x += 1 elif m
ove == "S": x -= 1 elif move == "E": y -= 1 else: y += 1 pos = f"{x}-{y}" if pos in fullpath: return True else: fullpath[pos] = 1 return False class TestCase(unittest.Tes...
als(Solution().isPathCrossing("NESWW"), True) self.assertEquals(Solution().isPathCrossing("N"), False)
openstack/oslo.context
doc/source/user/examples/usage_user_identity.py
Python
apache-2.0
1,507
0
#!/usr/bin/env python3 # # Copyright (c) 2015 OpenStack Foundation # # 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 appl...
language governing permissions and limitations # under the License. """A usage example of Oslo Context with user_identity This example requires the following modules to be installed. $ pip install oslo.context oslo.log More information can be found at: https://docs.ope
nstack.org/oslo.context/latest/user/index.html """ from oslo_config import cfg from oslo_context import context from oslo_log import log as logging CONF = cfg.CONF DOMAIN = "demo" logging.register_options(CONF) CONF.logging_user_identity_format = "%(user)s/%(tenant)s@%(project_domain)s" logging.setup(CONF, DOMAIN) ...
abenassi/amtrak-trip
amtrak.py
Python
mit
5,392
0.000185
#!/usr/bin/env python # -*- coding: utf-8 -*- """ amtrak Parse a trip itinerary of amtrak services copied into a text file. Running the file will take a trip.txt file and output a .json with one record for each amtrak service in the trip. You can also use the main method of the module. Both cases, the first paramete...
is supported for the parsers in this repo. """ from __future__ import unicode_literals import copy import json import arrow import sys from modules impor
t parsers class AmtrakServiceParser(object): """Parse Amtrak service information from confirmation email lines. Attributes: name (str): Name of the service. departure_station (str): Station where the service starts. departure_state (str): State where the service starts. depar...
inovtec-solutions/OpenERP
openerp/addons/mail/tests/test_mail_base.py
Python
agpl-3.0
4,516
0.00155
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Business Applications # Copyright (c) 2012-TODAY OpenERP S.A. <http://openerp.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of ...
r.mod
el.data') self.ir_attachment = self.registry('ir.attachment') self.mail_alias = self.registry('mail.alias') self.mail_thread = self.registry('mail.thread') self.mail_group = self.registry('mail.group') self.mail_mail = self.registry('mail.mail') self.mail_message = self.r...
l0k1-smirenski/steemportal
src/web.py
Python
unlicense
1,995
0.009023
#!/usr/bin/python3 # # web.py # # Interface frontend for a webserver interface module # # Here's your stinkin' licence: http://unlicense.org/ # # - l0k1 # # Contact details for l0k1 # steemit.com - https://steemit.com/@l0k1 # bitmessage - BM-2cXWxTVaXJbNyMxv5tAjNg87xS98hrAg8P # torchat - xq6xcvqc2vy34qtx # email - l0k1...
calls back through the core, to get the configuration, to load the initial interface. The configuration tells the interface what to set up in the initial startup. """ print ("starting interface") self.config = config_obj self.core = core_obj ...
""" This opens up the main window, places all the widgets, and from the configuration, loads the content that belongs in them. """ pass def persist (): """ This collects the current interface status for shutdown of the app and """ ...
vqw/frappe
frappe/integration_broker/doctype/integration_service/test_integration_service.py
Python
mit
293
0.006826
# -*- coding: utf-8 -*- # Copyri
ght (c) 2015, Frappe Technologies and Contributors # See license.txt from __future__ import unicode_literals import frappe import unittest # test_records
= frappe.get_test_records('Integration Service') class TestIntegrationService(unittest.TestCase): pass
labero/kupfer
waflib/Options.py
Python
gpl-3.0
7,752
0.025284
#!/usr/bin/env python # encoding: utf-8 # Scott Newton, 2005 (scottn) # Thomas Nagy, 2006-2010 (ita) """ Support for waf command-line options Provides default command-line options, as well as custom ones, used by the ``options`` wscript function. """ import os, tempfile, optparse, sys, re from waflib import Logs, U...
t=default_prefix, help='installation prefix [default: %r]' % default_prefix) gr.add_option('--download', dest='download', default=False, action='store_true', help='try to download the tools if missing') gr = optparse.OptionGroup(self, 'build and install options') self.add_option_group(gr) gr.add_option('-p',...
ss bar; -pp: ide output') gr.add_option('--targets', dest='targets', default='', action='store', help='task generators, e.g. "target1,target2"') gr = optparse.OptionGroup(self, 'step options') self.add_option_group(gr) gr.add_option('--files', dest='files', default='', action='store', help='fil...
TaskEvolution/Task-Coach-Evolution
taskcoach/taskcoachlib/persistence/autosaver.py
Python
gpl-3.0
2,170
0.001843
''' Task Coach - Your friendly task manager Copyright (C) 2004-2013 Task Coach developers <[email protected]> Task Coach 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 ...
settings, *args, **kwargs): super(AutoSaver, self).__init__(*args, **kwargs) self.__settings = settings self.__task_files = set() pub.subscribe(self.onTaskFileDirty, 'taskfile.dirty') wx.GetApp().Bind(wx.EVT_IDLE, self.on_idle) def onTaskFileDirty(self, ta
skFile): ''' When a task file gets dirty and auto save is on, note it so it can be saved during idle time. ''' if self._needSave(taskFile): self.__task_files.add(taskFile) def _needSave(self, task_file): ''' Return whether the task file needs to be saved. ''' ...
zzcclp/carbondata
python/pycarbon/tests/core/test_carbon_tf_dataset.py
Python
apache-2.0
10,899
0.010643
# 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 use ...
thetic_dataset, reader_factory): ngram = NGram({0: list(_EXCLUDE_FIELDS), 1: [TestSchema.id]}, 100, TestSchema.id) with reader_factory(carbon_synthetic_dataset.url, schema_fie
lds=ngram) as reader: with pytest.raises(NotImplementedError): make_pycarbon_dataset(reader) @pytest.mark.forked def test_non_unischema_with_many_colums_with_one_shot_iterator(carbon_many_columns_non_unischema_dataset): """Just a bunch of read and compares of all values to the expected values""" with ma...
asazo/ANN
tarea3/Pregunta2/model_64.py
Python
mit
1,302
0.002304
import numpy as np from theano.tensor.shared_randomstreams import RandomStreams from matplotlib import pyplot from keras.preprocessing import sequence from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from keras.layers.embeddings import Embedding from keras.datasets impor...
p_words, embedding_vector_length, input_length=500)) model.add(LSTM(100)) model.add(Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(X_train, y_train,
validation_data=(X_test, y_test), nb_epoch=3, batch_size=64) model.save('LSTM-64.h5')
paramsingh/codechef-solutions
src/long/sep15/question5.py
Python
mit
310
0
# Author: Param Singh <[email protected]> # Cracking the
code i, k, s = map(int, raw_input().split()) ai, bi = map(int, raw_input().split()) diff = k - i v = diff / 2 if diff % 2 == 0: val = (2 ** (4*v-s)) * (
ai + bi) else: val = (2 ** (4*v - s + 1.5) * (ai + (3 ** 0.5) * bi)) print "%f" % val
zzcclp/carbondata
python/setup.py
Python
apache-2.0
3,483
0.001148
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agr
eements. 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 use this file except in compliance with # the License. You may obtain a copy of the License at # ...
BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import io import re import setuptools from setuptools import setup PACKAGE_NAME = 'pycarbon' with open('README.md') as f: lo...
gacarrillor/QGIS
tests/src/python/test_authmanager_pki_postgres.py
Python
gpl-2.0
5,746
0.001568
# -*- coding: utf-8 -*- """ Tests for auth manager PKI access to postgres. This is an integration test for QGIS Desktop Auth Manager postgres provider that checks if QGIS can use a stored auth manager auth configuration to access a PKI protected postgres. From build dir, run: ctest -R PyQgsAuthManagerPKIPostgresTest ...
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. """ import os import time import signal import stat import subprocess import tempfile import glob from shutil import rmtree from utilities import unitTestDataPath from qgis.core import ( QgsApplication, QgsAuthManager, QgsAuthMethodConfig, QgsVector...
dwesa/muhw
app.py
Python
artistic-2.0
729
0.006859
__author__ = 'dalewesa' import flask from flask import Flask from flask import render_template import json from werkzeug.serving import run_simple app = Flask(__name__) @app.route("/") def home(): return render_template('index.html') @app.route("/new") def sendembed():
embedHTML = {'embed': '<iframe width="100%" height=
"80%" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/users/12006695&amp;color=ff5500&amp;auto_play=false&amp;hide_related=false&amp;show_comments=true&amp;show_user=true&amp;show_reposts=false"></iframe>'} return flask.jsonify(embedHTML) if __name__ == "__mai...
rushiagr/keystone
keystone/contrib/ec2/controllers.py
Python
apache-2.0
17,344
0
# Copyright 2013 OpenStack Foundation # # 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...
credentials = ec2credentials if 'access' not in credentials: raise exception.Unauthorized(message='EC2 signature not supplied.') creds_ref = self._get_credentials(credentials['access']) self.check_signature(creds_ref, credentials) # TODO(termie): don't create new tokens...
nController.authenticate tenant_ref = self.resource_api.get_project(creds_ref['tenant_id']) user_ref = self.identity_api.get_user(creds_ref['user_id']) metadata_ref = {} metadata_ref['roles'] = ( self.assignment_api.get_roles_for_user_and_project( user_ref['id...
NoctuaNivalis/qutebrowser
tests/unit/utils/test_qtutils.py
Python
gpl-3.0
32,541
0.000061
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2014-2017 Florian Bruhin (The Compiler) <[email protected]> # # This file is part of qutebrowser. # # qutebrowser 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 S...
elf._error is None: raise AttributeError else: return self._error def isValid(self): return self._valid def isNull(self): return self._null @pytest.mark.parametrize('obj,
raising, exc_reason, exc_str', [ # good examples (QtObject(valid=True, null=True), False, None, None), (QtObject(valid=True, null=False), False, None, None), # bad examples (QtObject(valid=False, null=True), True, None, '<QtObject> is not valid'), (QtObject(valid=False, null=False), True, None, ...
njsmith/codetrawl
codetrawl/dump.py
Python
gpl-3.0
587
0
# This file is part of Codetrawl # Copyright (C) 2015 Nathaniel Smith <[email protected]> # See file LICENSE.txt for license information. """Usage: codetrawl.dump PATTERN FILE [FILE...] where PATTERN is a Python format string like "{raw_url}", with allowed keys: - service - query - repo - path - raw_url - c...
stdout.write(args["PATTERN"].format(**match)) sys
.stdout.write("\n")
brunobergher/dotfiles
sublime/pymdownx/st3/pymdownx/magiclink.py
Python
mit
10,950
0.002648
""" Magic Link. pymdownx.magiclink An extension for Python Markdown. Find http|ftp links and email address and turn them to actual links MIT license. Copyright (c) 2014 - 2017 Isaac Muse <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associate...
rl.""" if link_type is self.COMMIT: # user/repo@`hash` text = '' if my_repo else user_repo + '@' link.text = md_util.AtomicString(text) # Need a root with an element for things to get processed. # Send
the `value` through and retreive it from the p element. # Pop it off and add it to the link. el = md_util.etree.Element('div') p = md_util.etree.SubElement(el, 'p') p.text = '`%s`' % value[0:hash_size] el = self.markdown.treeprocessors['inline'].run(el) ...
faribas/RMG-Java
source/cclib/parser/mm4parser.py
Python
mit
11,929
0.00964
""" gmagoon 05/03/10: new class for MM4 parsing, based on mopacparser.py, which, in turn, is based on gaussianparser.py from cclib, described below: cclib (http://cclib.sf.net) is (c) 2006, the cclib development team and licensed under the LGPL (http://www.gnu.org/copyleft/lgpl.html). """ __revision__ = "$Revisi...
#Example: FORMULA WEIGHT : 86.112 if line[0:33] == ' FORMULA WEIGHT :': self.updateprogress(inputfile, "Attributes", self.fupdate) molmass = self.float(line.split()[-1]) if hasattr(self, "molmass"): assert self.molmass == molmass ...
equent occurences match the original value else: self.molmass = molmass #rotational constants (converted to GHZ) #Example: # THE MOMENTS OF INERTIA CALCULATED FROM R(g), R(z) VALUES # (also from R(e), R(alpha), R(s) VALUES) # # No...
weichweich/Pi-Timeswitch
Flask-Server/timeswitch/auth/schema.py
Python
mit
1,110
0.005405
import logging from marshmallow import ValidationError, post_load from marshmallow_jsonapi import Schema, fields from timeswitch.auth.dao import User class NullHandler(logging.Handler): def emit(self, record): pass logging.getLogger(__name__).addHandler(NullHandler()) LOGGER = logging.getLogger(__name_...
text.replace('_', '-') class UserSch
ema(Schema): id = fields.String(dump_only=True, required=True) name = fields.String(required=True) password = fields.String(load_only=True, required=False, attribute="password_clear") new_password = fields.String(load_only=True, required=False) email = fields.Email(required=False) last_loggin =...
openstack/octavia
octavia/tests/unit/amphorae/backends/utils/test_interface.py
Python
apache-2.0
33,169
0
# Copyright 2020 Red Hat, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
ts.RULES], iface.rules) test_utils.assert_script_lists_equal( self, expected_dict[consts.SCRIPTS], iface.scripts) def test__ipr_command(self): mock_ipr_addr = mock.MagicMock() controller = interface.InterfaceController() contr
oller._ipr_command(mock_ipr_addr, controller.ADD, arg1=1, arg2=2) mock_ipr_addr.assert_called_once_with('add', arg1=1, arg2=2) def test__ipr_command_add_eexist(self): mock_ipr_addr = mock.MagicMock() mock_ipr_addr.side_effect ...
ellipses/Yaksha
src/commands/voting.py
Python
mit
7,274
0.000825
#!/usr/bin/python from commands.utilities import register import asyncio import re class Voting(): def __init__(self, config=None): # regex to match a number at the start of the message. # Being a float is optional. self.length_re = r'--((\d*)?(\.\d*)?)' # regex to atch and capture...
he vote is finished. del self.active_votes[channel] @register('
!vote') async def start_vote(self, msg, user, channel, client, *args, **kwargs): ''' Main function that handles the vote function. Makes sure that only vote is going at a time in a channel. Calls from a channel that has a vote going on are considered to be a vote for the ong...
QuLogic/meson
mesonbuild/scripts/clangformat.py
Python
apache-2.0
3,260
0.002147
# Copyright 2018 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to ...
fnmatch.fnmatch(strf, i) for i in ignore): continue futures.append(e.submit(run_clang_format, exelist, f, check)) returncode = max([x.result().returncode for x in futures]) return returncode def run(args: T.List[str]) -> int: parser = argparse.ArgumentParser() parser.add...
parser.add_argument('sourcedir') parser.add_argument('builddir') options = parser.parse_args(args) srcdir = Path(options.sourcedir) builddir = Path(options.builddir) exelist = detect_clangformat() if not exelist: print('Could not execute clang-format "%s"' % ' '.join(exelist)) ...
amagdas/eve-elastic
eve_elastic/elastic.py
Python
gpl-3.0
13,856
0.001371
import ast import json import arrow import elasticsearch from bson import ObjectId from flask import request from eve.utils import config from eve.io.base import DataLayer try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse def parse_date(date_str): """Parse elastic...
return int(self.hits['hits']['total']) def extra(self, response): """Add extra info to response.""" if 'facets' in self.hits: response['_facets'] = self.hits['facets'] if 'aggregations' in self.hits: response['_aggregations'] = self.hits['aggregations'] def ...
y being constructed :param base_filters: all filters set outside of query (eg. resource config, sub_resource_lookup) """ filters = [f for f in base_filters if f is not None] query_filter = query['query']['filtered'].get('filter', None) if query_filter is not None: if 'and' in query_filter: ...
rstens/gwells
gwells/models/BCGS_Numbers.py
Python
apache-2.0
996
0.003012
""" 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 distri...
, verbose_name="BCGS Mapsheet Number") class Meta: db_table = 'bcgs_number' ordering = ['bcgs_number'] def __str__(self):
return self.description
dmnfarrell/peat
PEATDB/plugins/biodatabaseplugin.py
Python
mit
4,663
0.01587
#!/usr/bin/env python # # Protein Engineering Analysis Tool DataBase (PEATDB) # Copyright (C) 2010 Damien Farrell & Jens Erik Nielsen # # 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 ver...
# You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Contact information: # Email: Jens.Nielsen_at_gmail.com # Normal mail: # Jens Nielsen # SBBS, Conway Institute # University College Dublin # Dublin 4, Ireland # from Plugin...
n from Tkinter import * import Pmw from GUI_helper import * from Bio import Entrez class BioDBQuery(Plugin, GUI_help): """Bio database query plugin for PEAT""" capabilities = ['gui','uses_sidepane'] requires = ['biopython'] menuentry = 'Bio DB Query' gui_methods = {'quit':'Quit'} about = 'This ...
firmadyne/scraper
firmware/spiders/foscam.py
Python
mit
1,854
0.005394
from scrapy import Spider from scrapy.http import Request from firmware.items import FirmwareImage from firmware.loader import FirmwareLoader class FoscamSpider(Spider): name = "foscam" allowed_domains = ["foscam.com"] start_urls = [ "http://www.foscam.com/download-center/firmware-downloads.html"]...
ef parse(self, response): for i in range(0, len(response.xpath("//div[@id='main_r
ight']/span[1]/p")), 7): prods = response.xpath("//div[@id='main_right']/span[1]//p[%d]/text()" % (i + 2)).extract()[0].split("\r\n") for product in [x for x in prods]: item = FirmwareLoader(item=FirmwareImage(), response=response) item.add_xpath("version", "//di...
dmlc/tvm
python/tvm/topi/generic/image.py
Python
apache-2.0
1,606
0
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
ge operators""" from .default import default_schedule as _default_schedule def schedule_dilation2d_nchw(outs): """Schedule for dilation2d Parameters ---------- outs : Array of Tensor The computation graph description of dilati
on2d in the format of an array of tensors. Returns ------- sch : Schedule The computation schedule for the op. """ return _default_schedule(outs, False) def schedule_dilation2d_nhwc(outs): """Schedule for dilation2d Parameters ---------- outs : Array of Tensor ...
arth-co/shoop
shoop_tests/admin/test_product_variation.py
Python
agpl-3.0
2,122
0.002356
# -*- coding: utf-8 -*- from django.forms import formset_factory import pytest from shoop.admin.modules.products.views.variation.simple_variation_forms import SimpleVariationChildForm, SimpleVariationChildFormSet from shoop.admin.modules.products.views.variation.variable_variation_forms import VariableVariationChildren...
hild = create_product(printable_gibberish()) child.link_to_parent(parent, variables={var1: a, var2: b}
) assert parent.variation_children.count() == 4 * 3 form = VariableVariationChildrenForm(parent_product=parent) assert len(form.fields) == 12 # TODO: Improve this test?
Loodoor/UrWorld-Alpha-3.x
server/gentest.py
Python
gpl-2.0
6,381
0.004861
#C:\Python34\python.exe # -*- coding: utf-8 -*- import random from structs import * BLOCK, VOID = True, False foret = { 'stone': ['s'], 'snow': ['I'], 'grass': ['h'], 'dirt': ['U'] } desert = { 'stone': ['s'], 'snow': ['d'], 'grass': ['d'], 'dirt': ['d'] } noman_land = { 'stone': ...
x, y = item try: self[y][x] = value except IndexError: pass else: super().__setitem__(item, value) def __add__(self, other): new = self[:] for y, line in enumerate(other): new[y] += line ret...
rep += elt.rep rep += '\n' print(rep) if __name__ == '__main__': import sys length, flatness, height = map(int, sys.argv[1:4]) headstart, deniv = height//2, 1 try: headstart = int(sys.argv[4]) deniv = int(sys.argv[5]) except IndexError: pass noise ...
mpeuster/son-emu
src/emuvim/dcemulator/son_emu_simple_switch_13.py
Python
apache-2.0
5,519
0.000181
# 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...
ofproto.OFPCML_NO_BUFFER)] actions = [parser.OFPActionOutput(ofproto.OFPCML_NO_BUFFER)] self.add_flow(dat
apath, 0, match, actions) def add_flow(self, datapath, priority, match, actions, buffer_id=None, table_id=0): ofproto = datapath.ofproto parser = datapath.ofproto_parser inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS, ...
sofianehaddad/ot-svn
python/test/t_PiecewiseHermiteEvaluationImplementation_std.py
Python
mit
726
0
#! /usr/bin/env python from openturns import * ref = NumericalMathFunction("x", "sin(x)") size = 12 locations
= NumericalPoint(size) values = NumericalPoint(size) derivatives = NumericalPoint(size) # Build locations/values/derivatives with non-increasing locations for i in range(size): locations[i] = 10.0 * i * i / (size - 1.0) / (size - 1.0) values[i] = ref([locations[i]])[0] derivatives[i] = ref.gradient([locati...
n( locations, values, derivatives) print "evaluation=", evaluation # Check the values for i in range(2 * size): x = [-1.0 + 12.0 * i / (2.0 * size - 1.0)] print "f( %.12g )=" % x[0], evaluation(x), ", ref=", ref(x)
ireapps/coding-for-journalists
2_web_scrape/completed/fun_with_regex_done.py
Python
mit
3,044
0.010184
# Regular expressions are a powerful tool for pattern matching when you # know the general format of what you're trying to find but want to keep # it loose in terms of actual content: think finding email addresses or # phone numbers based on what they have in common with each other. Python # has a standard library that...
ay 4, 2
013 Sam Fuzz, Inc. $6,850.50 939 Walnut St, San ' 'Carlos, CA 94070 (408) 555-0304 [email protected] January 28' ', 2016 February 15, 2016'] # Find the word 'Sunnyvale' in the first record with re.search() re.search('Sunnyvale', records[0]).group() # Find the first date in the first record. Let's pi...
andreif/heroku_django
project/views.py
Python
mit
49
0
fro
m .apps.page import views as page assert p
age
serratoro/timesheet-analyser
TimeSheetAnalyser/presenters/daily_attendance_plot_presenter.py
Python
gpl-3.0
3,657
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Time-sheet Analyser: Python library which allows to analyse time-sheets. # Copyright (C) 2017 Carlos Serra Toro. # # 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 S...
OSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not,
see <http://www.gnu.org/licenses/>. import math import matplotlib.pyplot as plt from matplotlib.dates import MONDAY from matplotlib.dates import MonthLocator, WeekdayLocator, DateFormatter from TimeSheetAnalyser.utils.misc import time_to_float_time, normalise_number,\ average...
jbedorf/tensorflow
tensorflow/python/kernel_tests/ctc_loss_op_test.py
Python
apache-2.0
31,093
0.004567
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
ramework import errors_impl from tensorflow.python.framework import ops from tensorflow.python.framework import random_seed from tensorflow.python.framework import sparse_tensor from tensorflow.python.framework import test_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import ctc_ops from t...
impl from tensorflow.python.ops import math_ops from tensorflow.python.ops import random_ops from tensorflow.python.ops import sparse_ops from tensorflow.python.platform import test def SimpleSparseTensorFrom(x): """Create a very simple SparseTensor with dimensions (batch, time). Args: x: a list of lists of ...
matthewoliver/swift
test/unit/common/middleware/s3api/helpers.py
Python
apache-2.0
6,907
0
# Copyright (c) 2013 OpenStack Foundation # # 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 ...
ta around, but # register_unconditionally() keeps nothing. self._responses[(method, path)] = (response_class, headers, body) def clear_calls(self): del self._calls[:] class UnreadableInput(object): # Some clients will se
nd neither a Content-Length nor a Transfer-Encoding # header, which will cause (some versions of?) eventlet to bomb out on # reads. This class helps us simulate that behavior. def __init__(self, test_case): self.calls = 0 self.test_case = test_case def read(self, *a, **kw): self...
toobaz/pandas
pandas/tests/io/json/test_readlines.py
Python
bsd-3-clause
5,700
0.001053
from io import StringIO import pytest import pandas as pd from pandas import DataFrame, read_json import pandas.util.testing as tm from pandas.util.testing import assert_frame_equal, assert_series_equal, ensure_clean from pandas.io.json._json import JsonReader @pytest.fixture def lines_json_df(): df = pd.DataF...
l(chunked, unchunked) def test_readjson_each_chunk(lines_json_df): # Other tests check that the final result of read_json(chunksize=True) # is correct. This checks the intermediate chunks. chunks = list(pd.read_json(StringIO(lines_json_df), lines=True, chunksize=2)) assert chunks[0].shape == (2, 2) ...
with ensure_clean("test.json") as path: df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) df.to_json(path, lines=True, orient="records") chunked = pd.concat(pd.read_json(path, lines=True, chunksize=1)) unchunked = pd.read_json(path, lines=True) assert_frame_equal(unchunked, ...
undefinedv/Jingubang
sqlmap/lib/controller/controller.py
Python
gpl-3.0
30,449
0.003481
#!/usr/bin/env python """ Copyright (c) 2006-2016 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import os import re from lib.controller.action import action from lib.controller.checks import checkSqlInjection from lib.controller.checks import checkDynParam from lib.cont...
AULT_GET_POST_DELIMITER)) else: retVal = retVal.replace(item, "%s%s" % (item, randomStr())) return retVal def _saveToHash
DB(): injections = hashDBRetrieve(HASHDB_KEYS.KB_INJECTIONS, True) if not isListLike(injections): injections = [] injections.extend(_ for _ in kb.injections if _ and _.place is not None and _.parameter is not None) _ = dict() for injection in injections: key = (injection.place, inje...
akuks/pretix
src/pretix/control/views/orders.py
Python
apache-2.0
13,510
0.001776
from datetime import timedelta from itertools import groupby from django import forms from django.contrib import messages from django.core.urlresolvers import reverse from django.db.models import Q from django.http import HttpResponse from django.shortcuts import redirect, render from django.utils.functional import ca...
ownload_button_icon or 'fa-download', 'text': provider.download_button_text or 'fa-download', 'identifier': provider.identifier, }) return buttons def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) ctx['items'] = self.g...
ctx['download_buttons'] = self.download_buttons ctx['can_download'] = ( self.request.event.settings.ticket_download and self.order.status == Order.STATUS_PAID ) ctx['payment'] = self.payment_provider.order_control_render(self.request, self.object) return ...
toobaz/pandas
pandas/tests/tslibs/test_period_asfreq.py
Python
bsd-3-clause
2,130
0.000939
import pytest from pandas._libs.tslibs.frequencies import get_freq from pandas._libs.tslibs.period import period_asfreq, period_ordinal @pytest.mark.parametrize( "freq1,freq2,expected", [ ("D", "H", 24), ("D", "T", 1440), ("D", "S", 86400), ("D", "L", 86400000), ("D", ...
00000000), ("L", "U", 1000), ("L", "N", 1000000), ("U", "N", 1000), ], ) def test_intra_day_conversion_factors(freq1, freq2, expected): assert period_asfreq(1, get_freq(freq1), get_freq(freq2), False) == expected @pytes
t.mark.parametrize( "freq,expected", [("A", 0), ("M", 0), ("W", 1), ("D", 0), ("B", 0)] ) def test_period_ordinal_start_values(freq, expected): # information for Jan. 1, 1970. assert period_ordinal(1970, 1, 1, 0, 0, 0, 0, 0, get_freq(freq)) == expected @pytest.mark.parametrize( "dt,expected", [ ...
biggihs/python-pptx
tests/test_api.py
Python
mit
1,552
0
# encoding: utf-8 """ Test suite for pptx.api module """ from __future__ import ( absolute_import, division, print_function, unicode_literals ) import os import pytest from pptx.api import Presentation from pptx.opc.constants import CONTENT_TYPE as CT from pptx.parts.presentation import PresentationPart from ...
ation = prs_ return Package_, path, prs_ # fixture components --------------------------------------------- @pytest.fixture def Package_(self, request): return class_mock(request, 'pptx.api.Package') @pytest.fixture def
prs_(self, request): return instance_mock(request, Presentation) @pytest.fixture def prs_part_(self, request): return instance_mock(request, PresentationPart)
bjornwallner/proq2-server
apps/modeller9v8/modlib/modeller/topology.py
Python
gpl-3.0
2,065
0.002906
"""Classes to handle information from residue topology files""" import _modeller __docformat__ = "epytext en" class Topology(object): """All information from a residue topology file. You should never need to create a L{Topology} object yourself - one is created for you by the L{environ} class, e.g....
r.mod_topology_in_memory(self._modpt) submodel = property(__get_submodel, __set_submodel, doc="Topology sub-model, an integer from 1 to 10, " + \ "as defined in C{models.lib}") in_memory = property(__get_in_memory,
doc="True if information has been read into memory")
stevec7/gpfs
gpfs/mmpmon.py
Python
mit
1,059
0.016053
class mmpmon(object): def __init__(self): self.name = 'mmpmon' self.nodefields = { '_n_': 'nodeip', '_nn_': 'nodename', '_rc_': 'status', '_t_': 'seconds', '_tu_': 'microsecs', '_br_': 'bytes_read', '_bw_': 'bytes_written', '_oc_': 'opens', '_cc_': 'closes', '_r...
self.nodelabels = {} self
.fsfields = { '_n_': 'nodeip', '_nn_': 'nodename', '_rc_': 'status', '_t_': 'seconds', '_tu_': 'microsecs', '_cl_': 'cluster', '_fs_': 'filesystem', '_d_': 'disks', '_br_': 'bytes_read', '_bw_': 'bytes_written', '_oc_': 'opens', '_cc_': 'closes', '_rdc_': 'reads', ...
ttreeagency/PootleTypo3Org
pootle/apps/staticpages/managers.py
Python
gpl-2.0
1,705
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 20
13 Zuza Software Foundation # # This file is part of Pootle. # # Pootle 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 ver
sion. # # translate 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 # a...
singer-io/singer-python
tests/test_catalog.py
Python
apache-2.0
5,436
0.002943
import unittest from singer.schema import Schema from singer.catalog import Catalog, CatalogEntry, write_catalog class TestWriteCatalog(unittest.TestCase): def test_write_empty_catalog(self): catalog = Catalog([]) write_catalog(catalog) def test_write_catalog_with_streams(self): catal...
'id': {'type': 'integer', 'selected': True}, 'amount': {'type': 'number', 'selected': True} } } }
] } obj_form = Catalog(streams=[ CatalogEntry( stream='users', tap_stream_id='prod_users', stream_alias='users_alias', database='prod', table='users', schema=Schema( type='object', selected=T...
PseudoAj/MyInsightRepo
data/examples/consumer/comsumeMsgs.py
Python
mit
1,513
0.00727
#!/usr/bin/env python #title :comsumeMsgs.py #description :The class is a simple cosumer to print message #author :Ajay Krishna Teja Kavuri #date :01252017 #version :0.1 #============================================================================== # Libraries from kafka impor...
c = 'electricity' # Initialize the consumer here self.consumer = KafkaConsumer(self.topic, group_id=self.grpId, bootstrap_servers=self.cnctnAddr) # Actual method to start consuming def consumeMsgs(self): # Loop through the consumer for message in self.consumer: # ...
consumer print "Message topic: "+str(message.topic)+" Message partition: "+str(message.partition)+" Message offset: "+str(message.offset)+" Message key: "+str(message.key)+" Message value: "+str(message.value) # Main method for triggering consumptiom if __name__ == '__main__': # Define the address ...
gangadharkadam/saloon_frappe
frappe/patches/v5_0/move_scheduler_last_event_to_system_settings.py
Python
mit
215
0.027907
import frappe def execute(): frappe.rel
oad_doctype('System Settings') last = frappe.db.get_global('scheduler_last_event') frappe.db.set_value('System
Settings', 'System Settings', 'scheduler_last_event', last)
lsommerer/worms
ui_new_world_dialog.py
Python
gpl-3.0
6,133
0.001141
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'new_world.ui' # # Created by: PyQt5 UI code generator 5.5.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjec...
.height.setObjectName("height") self.width = QtWidgets.QSpinBox(self.worldSize) self.width.setGeometry(QtCore.QRect(100, 60, 42, 22)) self.width.setButtonSymbols(QtWidge
ts.QAbstractSpinBox.UpDownArrows) self.width.setMinimum(5) self.width.setMaximum(999) self.width.setSingleStep(5) self.width.setProperty("value", 30) self.width.setObjectName("width") self.heightLabel = QtWidgets.QLabel(self.worldSize) self.heightLabel.setGeometry...
ruar18/competitive-programming
algorithms-data-structures/sorting/insertion-sort.py
Python
mit
493
0.002028
# Impleme
ntation of the insertion-sort sorting algorithm # O(N^2) # Insertion sort def insertionSort(a): final = a # Loop through every integer to be sorted for i in range(1, len(a)): key = a[i] j = i - 1 # Find ideal location while j >= 0 and final[j] > key: final[j+1] =...
y))
malb/pyme
pyme/errors.py
Python
gpl-2.0
1,710
0.008772
# $Id$ # Copyright (C) 2004 Igor Belyi <[email protected]> # Copyright (C) 2002 John Goerzen <[email protected]> # # 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; e...
e # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA import pygpgme class GPGMEEr
ror(Exception): def __init__(self, error = None, message = None): self.error = error self.message = message def getstring(self): message = "%s: %s" % (pygpgme.gpgme_strsource(self.error), pygpgme.gpgme_strerror(self.error)) if self.message != No...
consultit/Ely
ely/direct/data_structures_and_algorithms/ch02/sequence_iterator.py
Python
lgpl-3.0
1,665
0.000601
# Copyright 2013, Michael H. Goldwasser # # Developed for use with the book: # # Data Structures and Algorithms in Python # Michael T. Goodrich, Roberto Tamassia, and Michael H. Goldwasser # John Wiley & Sons, 2013 # # This program is free software: you can redistribute it and/or modify # it under the terms of...
: """An iterator for any of Python's sequence types.""" def __init__(self, sequence): """Create an iterator for the given sequence.""" self._seq = sequence # keep a reference to the underlying data self._k = -1 # will increment to 0 on first call to next d...
r else raise StopIteration error.""" self._k += 1 # advance to next index if self._k < len(self._seq): return(self._seq[self._k]) # return the data element else: raise StopIteration() # there are no more elements def __iter__(self): ""...
open-synergy/opnsynid-hr
hr_attendance_overtime_request_tier_validation/models/__init__.py
Python
agpl-3.0
192
0
# -*- coding: utf-8
-*- # Copyright 2018 OpenSynergy Indonesia # Li
cense AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from . import hr_overtime_request from . import tier_definition
blueboxgroup/neutron
neutron/plugins/ml2/driver_api.py
Python
apache-2.0
35,825
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 ...
perations are cached so that other MechanismDrivers can freely access the same information. """ @abc.abs
tractproperty def current(self): """Return the subnet in its current configuration. Return the subnet, as defined by NeutronPluginBaseV2. create_subnet and all extensions in the ml2 plugin, with all its properties 'current' at the time the context was established. ""...
uraxy/imozzle
api/migrations/0007_auto_20170105_2339.py
Python
mit
446
0
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 o
n 2017-01-05 14:39 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0006_auto_20161229_1650'), ] operations = [ migrations.AlterField( model_name='feed', name='meta',...
), ]
Mikescher/Project-Euler_Befunge
compiled/Python2/Euler_Problem-020.py
Python
mit
1,973
0.058287
#!/usr/bin/env python2 # transpiled with BefunCompile v1.3.0 (c) 2017 import sys import zlib, base64 _g = ("AR+LCAAAAAAABAC9jz0KAjEQha+SnZhmh5hMhogECbZeYrcR0qZK6dkddxVEEGOzrxjmD977mt9AbQMPynCFTDYNus3Jc/XEFW4XwMA1By5yNoRr4wp4sJ7LSFwwxYjm" + "cFRNdWla6k5/rOdJD5VDslQ4VCaHMVYnZjIimWcznvpMVuUFgAUm84uA3whQKRkTWXnpjf9N5/2D...
return (6)if(sp()!=0)else(2) def _2(): sa(sr()); gw(0,3,sp()) gw(1,3,0) gw(2,3,199) return 3 def _3(): global t0 t0=(((gr((gr(2,3)%100)+1,gr(2,3)/100)-48)*gr(0,3))+gr(1,3))/10 gw((gr(2,3)%100)+
1,gr(2,3)/100,((((gr((gr(2,3)%100)+1,gr(2,3)/100)-48)*gr(0,3))+gr(1,3))%10)+48) gw(1,3,t0) t0=gr(2,3)-1 gw(2,3,gr(2,3)-1) return 4 def _4(): global t0 return (3)if((t0)!=0)else(5) def _5(): sa(sp()-1) sa(sr()); sa((0)if(sp()!=0)else(1)) return 1 def _6(): global t0 gw(3,...
dvdmena/BioFormatsRead
test_get_timeseries.py
Python
bsd-2-clause
2,218
0.003607
import bfimage as bf from matplotlib import pyplot as plt, cm import os import numpy as np filename = r'testdata/T=5_Z=3_CH=2_CZT_All_CH_per_Slice.czi' imgbase = os.path.basename(filename) imgdir = os.path.dirname(filename) # specify bioformats_package.jar to use if required #bf.set_bfpath(insert path to bioformats_...
nel, :, :] fig1 = plt.figure(figsize=(10, 8), dpi=100) ax1 = fig1.add_subplot(111) cax = ax1.imshow(img2show, interpolation='nearest', cmap=cm.gray, aspect='equal') ax1.set_title('T=' + str(timepoint+1) + ' Z=' + str(zplane+1) + ' CH=' + str(channel+1), fontsize=12
) ax1.set_xlabel('X-dimension [pixel]', fontsize=10) ax1.set_ylabel('Y-dimension [pixel]', fontsize=10) cbar = fig1.colorbar(cax) # show plots plt.show()
deuscoin-org/deuscoin-core
qa/rpc-tests/timestampindex.py
Python
mit
1,959
0.001021
#!/usr/bin/env python2 # Copyright (c) 2014-2015 The Deuscoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Test timestampindex generation and fetching # import time from test_framework.test_framework im
port DeuscoinTestFramework from test_framework.util import * class TimestampIndexTest(DeuscoinTestFramework): def setup_chain(self): print("Initializing test directory "+self.options.tmpdir) initialize_chain_clean(self.options.tmpdir, 4) def setup_network(self): self.nodes = [] ...
self.nodes.append(start_node(1, self.options.tmpdir, ["-debug", "-timestampindex"])) # Nodes 2/3 are used for testing self.nodes.append(start_node(2, self.options.tmpdir, ["-debug"])) self.nodes.append(start_node(3, self.options.tmpdir, ["-debug", "-timestampindex"])) connect_nodes...
SamuelLongchamps/grammalecte
gc_core/py/gc_engine.py
Python
gpl-3.0
17,150
0.008464
# -*-
encoding: UTF-8 -*- import re import sys import os import traceback from ..ibdawg import IBDAWG from ..echo import echo from . import gc_options __all__ = [ "lang", "locales", "pkg", "name", "version", "author", \ "load", "parse", "get
Dictionary", \ "setOptions", "getOptions", "getOptionsLabels", "resetOptions", \ "ignoreRule", "resetIgnoreRules" ] __version__ = u"${version}" lang = u"${lang}" locales = ${loc} pkg = u"${implname}" name = u"${name}" version = u"${version}" author = u"${author}" # commons regexes _zEndOfSen...
evan-erdos/cboe
pkg/win/gen-data.py
Python
gpl-2.0
1,087
0.015639
from os.path import normpath as makepath from glob import glob import sys root = makepath(sys.argv[1]) # To add directories to the list of sources to generate file lists from, # simply edit this dictionary. The key is the directory path (relative to # the build output directory), and the value is either a glob patte...
ers': ['mask.frag', 'mask.vert'], 'data/graphics': '*.png', 'data/cursors': '*.gif', 'data/sounds': '*.WAV', } for path, pattern in files.items(): print 'SetOutPath', '"' + makep
ath("$INSTDIR/" + path + '/') + '"' if type(pattern) == list: check_files = [root + '/' + path + '/' + x for x in pattern] else: check_files = glob(makepath(root + '/' + path + '/' + pattern)) for fname in check_files: print 'File', '"' + makepath(fname.replace(root, '${RELEASE_DIR}')) + '"'
google-code-export/cocoslive
cocoslive/configuration.py
Python
gpl-3.0
1,082
0.000924
#!/usr/bin/python2.5 # # Copyright 2008 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 or...
os Live v0.3.6 - &copy; 2009 <a href="http://www.sapusmedia.com">Sapus Media</a>' ) # File caching controls FILE_CACHE_CONTROL = 'private, max-age=86400' FILE_CACHE_TIME = datetime.timedelta(days=1) # Title for the website SYSTEM_TITLE = 'cocos Live' # Un
ique identifier from Google Analytics ANALYTICS_ID = 'UA-871936-6'
certik/sympy-oldcore
sympy/plotting/pyglet/media/avbin.py
Python
bsd-3-clause
16,204
0.00253
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2007 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistribu...
self.data = (ctypes.c_uint8 * packet.size)() self.size = packet.size ctypes.memmove(self.data, packet.data, self.size)
class BufferedImage(object): def __init__(self, image, timestamp): self.image = image self.timestamp = timestamp class AVbinSource(StreamingSource): def __init__(self, filename, file=None): if file is not None: raise NotImplementedError('TODO: Load from file stream') ...
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-2.1/Lib/nntplib.py
Python
mit
18,078
0.002157
"""An NNTP client class based on RFC 977: Network News Transfer Protocol. Example: >>> from nntplib import NNTP >>> s = NNTP('news') >>> resp, count, first, last, name = s.group('comp.lang.python') >>> print 'Group', name, 'has', count, 'articles, range', first, 'to', last Group comp.lang.python has 51 articles, rang...
to enable 'reader' mod
e. # However, the order in which 'mode reader' and 'authinfo' need to # arrive differs between some NNTP servers. Try to send # 'mode reader', and if it fails with an authorization failed # error, try again after sending authinfo. readermode_afterauth = 0 if readermode: ...
dudunato/ywam-cerrado
demo/migrations/0008_auto_20150509_0023.py
Python
bsd-3-clause
922
0.002169
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.db.models.deletion class
Migration(migrations.Migration): dependencies = [ ('wagtailimages', '0005_make_filter_spec_unique'), ('demo', '0007_auto_20150508_1856'), ] operations = [ migrations.AddField( model_name='formpage', name='feed_image', field=models.ForeignKey(rel...
nk=True, to='wagtailimages.Image', null=True), preserve_default=True, ), migrations.AddField( model_name='formpage', name='header_image', field=models.ForeignKey(related_name='+', on_delete=django.db.models.deletion.SET_NULL, blank=True, to='wagtailimages....
a10networks/acos-client
acos_client/v30/dns.py
Python
apache-2.0
1,880
0
# Copyright (C) 2016, A10 Networks Inc. All rights reserved. # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
addr_spec} return self._post(self.url_prefix + precedence, payload) def _set_suffix(self, suffix): payload = {'suffix': {'domain-name': suffix}} return self._post(self.url_prefix
+ 'suffix', payload) def set(self, primary=None, secondary=None, suffix=None): if primary is not None: self._set_dns('primary', primary) if secondary is not None: self._set_dns('secondary', secondary) if suffix is not None: self._set_suffix(suffix) ...
facetothefate/contrail-controller
src/opserver/analytics_db.py
Python
apache-2.0
14,728
0.004753
# # Copyright (c) 2014 Juniper Networks, Inc. All rights reserved. # # # analytics_db.py # Implementation of database purging # import redis import pycassa from pycassa.pool import ConnectionPool from pycassa.columnfamily import ColumnFamily from pycassa.types import * from pycassa import * from sandesh.viz.constants...
2 import time import json import
datetime import pdb import argparse import socket import struct class AnalyticsDb(object): def __init__(self, logger, cassandra_server_list, redis_query_port, redis_password, cassandra_user, cassandra_password): self._logger = logger self._cassandra_server_li...
Geoion/pomegranate
tests/test_profile_hmm.py
Python
mit
17,293
0.059099
from __future__ import (division, print_function) from pomegranate import * from nose.tools import with_setup from nose.tools import assert_equal from nose.tools import assert_not_equal import random import numpy as np def setup(): ''' Build a model that we want to use to test sequences. This model will be somewh...
on( d1, d2, 0.15 ) model.add_transition( d1, i1, 0.15 ) model.add_transition( d1, m2, 0.70 ) model.add_transition( d2, d3, 0.15 ) model.add_transition( d2, i2, 0.15 ) model.add_transition( d2, m3, 0.70 ) model.add_transition( d3, i3, 0.30 ) model.add_transition( d3, model.end, 0.70 ) # Call bake to finalize...
above model, except that it uses the multiple transition methods for building. ''' random.seed(0) global model model = HiddenMarkovModel( "Global Alignment") # Define the distribution for insertions i_d = DiscreteDistribution( { 'A': 0.25, 'C': 0.25, 'G': 0.25, 'T': 0.25 } ) # Create the insert states i0 = ...
guker/spear
config/tools/isv/isv_512g_u100.py
Python
gpl-3.0
542
0.001845
#!/usr/bin/env python import spear # 1/ The tool tool = spear.tools.ISVTool # 2/ GMM Training n_gaussians = 512 iterk = 25 iterg_train = 25 end_acc = 0.0001 var_thd = 0.0001 update_weights = True update_means = True update_variances = True norm_KMeans = True # 3/ JFA Training ru = 100 # The dimensionality of the su...
vance_factor = 4 n_iter_train = 10 n_iter_enrol = 1 # 4/ JFA Enrolment and scoring iterg_enrol = 1 convergence_threshold = 0.0001 variance_threshold = 0.0001 relevance_factor = 4 re
sponsibilities_threshold = 0
unreal666/outwiker
src/outwiker/pages/wiki/wikiconfig.py
Python
gpl-3.0
5,052
0
# -*- coding: utf-8 -*- from outwiker.core.config import (BooleanOption, IntegerOption, StcStyleOption, StringOption) from outwiker.gui.stcstyle import StcStyle class WikiConfig (object): """ Класс, хранящий...
E_COMMENT_PARAM = u"comment" STYLE_COMMENT_DEFAULT = StcStyle.parse(u"fore:#12B535") COLORIZE_SYNTAX_PARAM = u'ColorizeSyntax' COLORIZE_SYNTAX_DEFAULT = True RECENT_STYLE_NAME_PARAM = 'RecentStyleName' RECENT_STYLE_NAME_DEFAULT = '' def __init__(self, config): self.config = config ...
ig, WikiConfig.WIKI_SECTION, WikiConfig.SHOW_HTML_CODE_PARAM, True) # Размер превьюшек по умолчанию self.thumbSizeOptions = IntegerOption(self.config, WikiConfig.WIKI_SECTION, ...
mrquim/mrquimrepo
script.module.nanscrapers/lib/nanscrapers/scraperplugins/projectfreetv.py
Python
gpl-2.0
2,949
0.015259
import re import requests import xbmc from ..scraper import Scraper class projectfreetv(Scraper): domains = ['project-free-tv.ag'] name = "ProjectFree" sources = [] def __init__(self): self.base_link = 'http://project-free-tv.ag' self.search_movie = self.base_link+'/movies/search-form/...
print 'hi' # start_url= self.search_movie+title.replace(' ','%20') # html = requests.get(start_url).content # match = re
.compile('<div style="float:left.+?href="(.+?)" title="(.+?)"',re.DOTALL).findall(html) # for url,name in match: # movie_year = re.findall('\((.+?)\)',str(name))[0] # url = self.base_link+url # if movie_year == year: # print year # ...
epruesse/ymp
src/ymp/cli/init.py
Python
gpl-3.0
3,545
0
"Implements subcommands for ``ymp init``" import logging import os import shutil import subprocess as sp import click import ymp from ymp.cli.shared_options import command, group log = logging.getLogger(__name__) # pylint: disable=invalid-name @group() def init(): """Initialize YMP workspace""" def have_co...
ue, help="Confirm every prompt") def project(name,
yes): cfg = ymp.get_config()._config if not name: name = click.prompt("Please enter a name for the new project", type=str) if name in cfg.projects and not yes: click.confirm("Project '{}' already configured. " "Do you want to overwrite this...
ericlink/adms-server
playframework-dist/play-1.1/python/Lib/distutils/sysconfig.py
Python
mit
19,643
0.001527
"""Provide access to Python's configuration information. The specific configuration variables available depend heavily on the platform and configuration. The values may be retrieved using get_config_var(name), and the list of variables is available via get_config_vars().keys(). Additional convenience functions a...
x, "Lib") else: return os.path.join(prefix, "Lib", "site-packages") elif os.name == "os2": if standard_lib: return os.path.join(PREFIX, "Lib") else: return os.path.join(PREFIX, "Lib", "site-packages") else: raise DistutilsP...
rm '%s'" % os.name) def customize_compiler(compiler): """Do any platform-specific customization of a CCompiler instance. Mainly needed on Unix, so we can plug in the information that varies across Unices and is stored in Python's Makefile. """ if compiler.compiler_type == "unix": ...
akabos/NearPy
nearpy/utils/utils.py
Python
mit
2,882
0.000694
# -*- coding: utf-8 -*- # Copyright (c) 2013 Ole Krause-Sparmann # 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 rights # to use, copy,...
tors): """ Returns numpy array representation of argument. Argument maybe numpy array (input is returned) or a list of numpy vectors. """ # If vectors is not a numpy matrix, create one if not isinstance(vectors, numpy.ndarray): V = numpy.zeros(
(vectors[0].shape[0], len(vectors))) for index in range(len(vectors)): vector = vectors[index] V[:, index] = vector return V return vectors def unitvec(vec): """ Scale a vector to unit length. The only exception is the zero vector, which is returned back unchan...
pbrod/numpy
numpy/linalg/tests/test_linalg.py
Python
bsd-3-clause
74,497
0.00055
""" Test functions for linalg module """ import os import sys import itertools import traceback import textwrap import subprocess import pytest import numpy as np from numpy import array, single, double, csingle, cdouble, dot, identity, matmul from numpy import multiply, atleast_2d, inf, asarray from numpy import lin...
array( [[1. + 1j, 2. + 2j], [3. - 3j, 4. - 9j], [5. - 4j, 6. + 8j]], dtype=csingle), array([2. + 1j, 1. + 2j, 3.
- 3j], dtype=csingle)), LinalgCase("cdouble_nsq_1", array( [[1. + 1j, 2. + 2j, 3. - 3j], [3. - 5j, 4. + 9j, 6. + 2j]], dtype=cdouble), array([2. + 1j, 1. + 2j], dtype=cdouble)), LinalgCase("cdouble_nsq_2", array( [[1. + 1j, 2. +...
gobstones/PyGobstones-Lang
tests/utils.py
Python
gpl-3.0
3,644
0.005488
import importlib import os import subprocess import math import itertools import random def eqValue(gbsv, pyv): return gbsv == str(pyv) def delete_files_in_dir(dir, exceptions=[]): for f in os.listdir(dir): if not f in exceptions: os.remove(os.path.join(dir, f)) def group(lst, n): ...
mbda x, y: x % y, } binop = lambda op, x, y: BINOPS[op](x,y) # Gbs syntax isEmpty = lambda xs: len(xs) == 0 head = lambda xs: xs[0] tail = lambda xs: xs[1:] # Test scripts def combine_args(args): prod = itertools.product(*args.values()) return [dict(zip(args.keys(),pargs)) for pargs in prod] COLORS = [...
este"] BOOLS = ["True", "False"]
Andrwe/py3status
py3status/modules/wanda_the_fish.py
Python
bsd-3-clause
5,569
0.001437
# -*- coding: utf-8 -*- """ Display a fortune-telling, swimming fish. Wanda has no use what-so-ever. It only takes up disk space and compilation time, and if loaded, it also takes up precious bar space, memory, and cpu cycles. Anybody found using it should be promptly sent for a psychiatric evaluation. Configuration ...
e behavior of motion to prevent modules from shifting Optional: fortune-mod: the fortune cookie program from bsd games Examples: ``` # disable motions when not in use wanda_the_fish { format = '[\?if=fortune {nomotion}][{fortune} ]' format += '{wanda}[\?if=fortune
{motion}]' } # no updates, no motions, yes fortunes, you click wanda_the_fish { format = '[{fortune} ]{wanda}' cache_timeout = -1 } # wanda moves, fortunes stays wanda_the_fish { format = '[{fortune} ]{nomotion}{wanda}{motion}' } # wanda is swimming too fast, slow down wanda wanda_the_fish { cache_t...
macloo/web-scraper-steps
MLS_scraper_4.py
Python
mit
1,865
0.009115
from urllib.request import urlopen from bs4 import BeautifulSoup import time # time will allow a delay in program execution # added 2 time delays: One for each page while scraping the URLs, # and one for each page while scraping the text about each player # also added get_text() in the get_player_details() function ...
a", {"title":"Go to next page"} ) if next_page and ('href' in next_page.attrs):
partial = str(next_page.attrs['href']) new_url = "http://www.mlssoccer.com" + partial html = urlopen(new_url) bsObj = BeautifulSoup(html, "html.parser") get_player_pages(html, bsObj) else: print("Done collecting URLs ...") # run this on each page to get player detail pa...
jumpstarter-io/nova
nova/objects/base.py
Python
apache-2.0
28,219
0.000035
# Copyright 2013 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
ed or instantiated
via RPC
Everley1993/Laky-Earo
setup.py
Python
apache-2.0
608
0.004934
#!/usr/bin/python # -*- coding:utf-8 -*- from setuptools import setup setup( name='Earo', version='0.1.0', url='https://github.com/Everley1993/Laky-Earo', lic
ense='Apache', author='Everley', author_email='[email protected]', description='A microframework based on EDA for business logic development.', packages=['earo'], package_data={'earo':['static/css/*.css', 'static/fonts/*', 'static/js/*.js', 'static/*.html']}, include_packag
e_data=True, zip_safe=False, platforms='any', install_requires=[ 'flask', 'enum', 'atomic', ] )
Bolt64/my_code
Rosalind/edit_distancev3.py
Python
mit
2,389
0.030557
#!/usr/bin/python3 """ A script to determine the edit distance between 2 strings http://introcs.cs.princeton.edu/java/assignments/sequence.html """ from memoize import Memoize penalties={'gap':2,'mismatch':1,'match':0} def break_into_chunks(func): chunksize=100 def wrapper(string1,string2): for i i...
al_edit_distance(string1[1:],string2[1:])+penalties[match], optimal_edit_distance(string1[0:],string2[1:])+penalties['gap'], optimal_edit_distance(string1[1:],string2[0:])+penalties['gap'] ) def optimal_alignment(string1,str
ing2): opt=optimal_edit_distance edit_dist=opt(string1,string2) new_string1='' new_string2='' while (string1!='') or (string2!=''): if (opt(string1,string2)-opt(string1[1:],string2[0:])==penalties['gap']): new_string1+=string1[0] new_string2+='-' string1...
pgexperts/patroni-compose
patroni/patroni/exceptions.py
Python
mit
547
0.001828
class Pat
roniException(Exception): """Parent class for all kind of exceptions related to selected distributed configuration store""" def __init__(self, value): self.value = value def __str__(self): """
>>> str(PatroniException('foo')) "'foo'" """ return repr(self.value) class PatroniCtlException(Exception): pass class PostgresException(PatroniException): pass class DCSError(PatroniException): pass class PostgresConnectionException(PostgresException): pass
richard-willowit/odoo
addons/l10n_eu_service/wizard/__init__.py
Python
gpl-3.0
121
0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details.
from . import wizard
william-richard/moto
moto/support/responses.py
Python
apache-2.0
3,039
0.000658
from __future__ import unicode_literals from moto.core.responses import BaseResponse from .models import support_backends import json class SupportResponse(BaseResponse): SERVICE_NAME = "support" @property def support_backend(self): return support_backends[self.region] def describe_trusted_a...
ecks}) def refresh_trusted_advisor_check(self): chec
k_id = self._get_param("checkId") status = self.support_backend.refresh_trusted_advisor_check(check_id=check_id,) return json.dumps(status) def resolve_case(self): case_id = self._get_param("caseId") resolve_case_response = self.support_backend.resolve_case(case_id=case_id,) ...
ramalho/eagle-py
tests/slider.py
Python
lgpl-2.1
611
0.003273
#!/usr/bin/env python2 from eagle import * def callback(app, entry, value): print app, entry, value App(title="Slider test", left=Slider(id="hslider", label="Slider:", value_pos=Slider.POS_NONE,
horizontal=True, min=0, max=10, callback=callback), right=Slider(id="vslider", label=None, horizontal=False, value_pos=Slider.POS_LEFT, min=0, max=100,
callback=callback, expand_policy=ExpandPolicy.All()), ) run()
vparitskiy/data-importer
data_importer/readers/xml_reader.py
Python
bsd-2-clause
463
0
#!/usr/bin/env python # -*- coding: utf-8 -*- import xml.etree.ElementTree as et class XMLReader(object): def __init__(self, instance): self.instance = instance def read(self): "Convert XML to Dict" tree = et.fromstring(self.instance.source) elements = tree.f
indall(self.
instance.root) for elem in elements: items = list(elem) content = [i.text for i in items] yield content
ros/ros
tools/rosunit/test/test_dotname.py
Python
bsd-3-clause
1,950
0.004615
#!/usr/bin/env python # This file should be run using a non-ros unit test framework such as nose using # nosetests test_dotname.py. Alternative
ly, just run with python test_dotname.py. # You will get the output from rostest as well. import unittest from dotname_cases import DotnameLoadingTest, NotTestCase import rosunit class TestDotnameLoading(unittest.TestCase): def test_class_basic(self): rosunit.unitrun('test_rosunit', 'test_class_basic'...
ethod_dotname(self): rosunit.unitrun('test_rosunit', 'test_method_dotname', 'test.dotname_cases.DotnameLoadingTest.test_a') def test_suite_dotname(self): rosunit.unitrun('test_rosunit', 'test_suite_dotname', 'test.dotname_cases.DotnameLoadingSuite') def test_class_basic_nottest(self): ...
chrisdickinson/nojs
build/android/gyp/jinja_template.py
Python
bsd-3-clause
5,601
0.007856
#!/usr/bin/env python # # Copyright 2014 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. """Renders one or more template files using the Jinja template engine.""" import codecs import argparse import os import sys from u...
is g
iven.') parser.add_argument('--loader-base-dir', help='Base path used by the ' 'template loader. Must be a common ancestor directory of ' 'the inputs. Defaults to DIR_SOURCE_ROOT.', default=host_paths.DIR_SOURCE_ROOT) parser.add_argument('--variables...
janneke/schikkers-list
scripts/genicon.py
Python
agpl-3.0
833
0.032413
#! /usr/bin/python import os import sys import tempfile base = os.path.splitext (os.path.split (sys.argv[1])[1])[0] input = os.path.abspath (sys.argv[1]) output = os.path.abspath (sys.argv[2]) program_name = os.path.split (sys.argv[0])[1] print program_name dir = tempfile.mktemp (program_name) os.mkdir (dir, 0777) o...
c): print c if os.system (c): raise 'barf' outputs = [] for sz in [256,128,64,48,32,16] : for depth in [24,8]: out = '%(base)s-%(sz)d-%(depth)d.png' % locals() system ('convert -depth %(depth)d -sample %(sz)d %(input)s %(out)s' % locals ()) outputs.append (ou...
system ('icotool --output %s --create %s' % (output, ' '.join (outputs))) system('rm -rf %(dir)s' % locals())
jorisvandenbossche/pandas
pandas/compat/pyarrow.py
Python
bsd-3-clause
705
0
""" support pyarrow compatibility across versions """ from pandas.util.version import Version try: import pyarrow as pa _pa_version = pa.__version__ _palv = Version(_pa_version) pa_version_under1p0 = _palv < Version("1.0.0") pa_version_under2p0 = _palv < Version("2.0.0") pa_version_under3p0 =...
rsion_under1p0 = True
pa_version_under2p0 = True pa_version_under3p0 = True pa_version_under4p0 = True pa_version_under5p0 = True pa_version_under6p0 = True
CityofPittsburgh/pittsburgh-purchasing-suite
migrations/versions/16e5b0c1ffc8_contact_zip_code_to_text_field.py
Python
bsd-3-clause
1,648
0.01335
"""contact zip code to text field Revision ID: 16e5b0c1ffc8 Revises: 8ac7c042469 Create Date: 2015-10-12 15:23:39.600694 """ # revision identifiers, used by Alembic. revision = '16e5b0c1ffc8' down_revision = '8ac7c042469' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generate...
, 'created_by_id', existing_type=sa.INTEGER(), nullable=True, existing_server_default=sa.text(u'1')) op.create_foreign_key('opportunity_created_from_id_contract_id_fkey', 'opportunity', 'contract', ['created_from_id'], ['id'] ) op.alter_column(u'company_c...
cute( sa.sql.text( ''' UPDATE company_contact SET zip_code = rpad('0', 5, zip_code) where char_length(zip_code) < 5 ''' ) ) def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.execute( sa.sql.text(...
zozo123/buildbot
master/buildbot/test/unit/test_buildslave_libvirt.py
Python
gpl-3.0
10,089
0.000892
# This file is part of Buildbot. Buildbot 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, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
_effect = lambda: defer.succeed(0) self.patch(bs, "_prepare_base_image", prep) create = mock.Mock() create.side_effect = lambda sel
f: defer.fail( failure.Failure(RuntimeError('oh noes'))) self.patch(libvirtbuildslave.Connection, 'create', create) yield bs._find_existing_deferred started = yield bs.start_instance(mock.Mock()) self.assertEqual(bs.domain, None) self.assertEqual(started, False) ...
XXLRay/libreshot
libreshot/classes/project.py
Python
gpl-3.0
13,790
0.034083
# LibreShot Video Editor is a program that creates, modifies, and edits video files. # Copyright (C) 2009 Jonathan Thomas, TJ # # This file is part of LibreShot Video Editor (http://launchpad.net/libreshot/). # # LibreShot Video Editor is free software: you can redistribute it and/or modify # it under the terms of t...
ributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with LibreShot Video E...
oject, save_project, state_project, restore_state, sequences, video, theme # init the foreign language from language import Language_Init ######################################################################## class project(): """This is the main project class that contains all the details of a project, such as na...
romeubertho/USP-IntroPython
django/learning_log/learning_log/learning_logs/migrations/0002_teste.py
Python
mit
647
0.001546
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-07-20 14:32 from __future__ import unicode_literals from django.db import migrat
ions, models class Migration(migrations.Migration): dependencies = [ ('learning_logs', '0001_initial'), ] operations = [ migrations.CreateModel( name='Teste', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, ve...
TimeField(auto_now_add=True)), ], ), ]
BubuLK/sfepy
sfepy/solvers/auto_fallback.py
Python
bsd-3-clause
1,594
0
from __future__ import absolute_import from sfepy.base.base import Struct from sfepy.solvers.solvers import Solver, use_first_available class AutoFallback
Solver(Solver): """ Base class for virtual solvers with the automatic fallback. """ _ls_solvers = [] def __new__(cls, conf, **kwargs): """ Choose an available solver from `self._ls_solvers`. Parameters ---------- conf : dict The solver configurat...
for ls, _conf in cls._ls_solvers] return use_first_available(ls_solvers) class AutoDirect(AutoFallbackSolver): """The automatically selected linear direct solver. The first available solver from the following list is used: `ls.mumps <sfepy.solvers.ls.MUMPSSolver>`, `ls...
yandexdataschool/gumbel_lstm
gumbel_softmax.py
Python
mit
3,120
0.010901
# -*- coding: utf-8 -*- """ a bunch of lasagne code implementing gumbel softmax https://arxiv.org/abs/1611.01144 """ import numpy as np import theano import theano.tensor as T from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams from lasagne.random import get_rng from lasagne.layers import Layer clas...
t=0.1, eps=1e-20): assert t != 0 self.temperature=t self.eps=eps self._srng = RandomStreams(get_rng().randint(1, 2147462579)) def __call__(self,logits): """computes a gumbel softmax sample""" #sample from Gumbel(0,...
ribution return T.nnet.softmax((logits + gumbel) / self.temperature) def onehot_argmax(logits): """computes a hard one-hot vector encoding maximum""" return T.extra_ops.to_one_hot(T.argmax(logits,-1),logits.shape[-1]) class GumbelSoftmaxLayer(Layer): """ lasagne.layers.GumbelSoftmaxLayer(incom...
deepmind/lab
python/tests/utils/maze_game_controller_test.py
Python
gpl-2.0
2,542
0.006688
"""Tests maze_game_controller.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from absl.testing import absltest import numpy as np import six import deepmind_lab from python.tests.utils import maze_game_controller from python.tests.utils impo...
self.assertFalse(self._controller.move_to(3, 4)) def testFollowPat
hToReachablePos(self): path = self._controller.find_path(2, 5) self.assertTrue(self._controller.follow_path(path)) pos = self._controller.maze_position() self.assertTrue(np.array_equal(pos, [2, 5])) def testFollowSparsePathToReachablePos(self): self.assertTrue(self._controller.follow_path([(2, 5)...
SandstoneHPC/OIDE
sandstone/lib/ui_methods.py
Python
mit
647
0.01391
from sandstone import settings def get_app_descriptions(*args,**kwargs): desc_list = [] for app_spec in settings.APP_SPECIFICATIONS:
desc_list.append(app_spec['APP_DESCRIPTION']) return desc_list def get_ng_module_spec(*args,**kwargs): mod_list = [] for app_spec in settings.APP_SPECIFICATIONS: mod_list.append({ 'module_name':app_spec['NG_MODULE_NAME'], 'stylesheets':app_spec['NG_MODULE_STYLESHEET...
refix