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
hkariti/ansible
lib/ansible/modules/system/systemd.py
Python
gpl-3.0
18,087
0.002764
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2016, Brian Coca <bcoca@ansible.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_version': '1...
"ExecMainExitTimestampMonotonic": "0", "
ExecMainPID": "595", "ExecMainStartTimestamp": "Sun 2016-05-15 18:28:49 EDT", "ExecMainStartTimestampMonotonic": "8134990", "ExecMainStatus": "0", "ExecReload": "{ path=/bin/kill ; argv[]=/bin/kill -HUP $MAINPID ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pi...
sgarrity/bedrock
bedrock/newsletter/redirects.py
Python
mpl-2.0
432
0.009259
from bedrock.redirects.util import redirect redirectpatterns = ( # bug 926629 redirect(r'^newsletter/abou
t_mobile(?:/(?:index\.html)?)?$', 'newsletter.subscribe'), redirect(r'^newsletter/about_mozilla(?:/(?:index\.html)?)?$', 'mozorg.contribute.index'), redirect(r'^newsletter/new(?:/(?:index\.html)?)?$', 'newsletter.subscribe'), redirect(r'^newsl
etter/ios(?:/(?:index\.html)?)?$', 'firefox.mobile.index'), )
jason-weirather/py-seq-tools
seqtools/cli/legacy/fastq_bgzf_index.py
Python
apache-2.0
6,010
0.030283
#!/usr/bin/python import sys, argparse, StringIO, re, gzip from multiprocessing import Pool, cpu_count, Queue from Bio.Format.BGZF import is_bgzf, reader as BGZF_reader, get_block_bounds from Bio.Format.Fastq import FastqEntry # Create an index for bgzf zipped fastq files. # Pre: A fastq file that has been compress...
if not m:
sys.stderr.write("Problem overlap\n") sys.exit() else: if m.group(1)[0] != '@': sys.stderr.write("failed to parse last\n") sys.exit() of.write(m.group(1)[1:]+"\t"+str(block)+"\t"+str(starts[i])+"\t"+str(len(m.group(1))+len(m.group(2))+len(m.group(3...
alexissmirnov/donomo
donomo_archive/lib/reportlab/pdfbase/_fontdata.py
Python
bsd-3-clause
61,719
0.04992
#Copyright ReportLab Europe Ltd. 2000-2004 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/pdfbase/_fontdata.py #$Header $ __version__=''' $Id: _fontdata.py 3052 2007-03-07 14:04:49Z rgbecker $ ''' __doc__=""" database of font related thi...
XMap[y] if y in self.keys(): raise IndexError, 'Encoding %s is already set' % y self.data[y] = v def __getitem__(self,x): y = x.lower() if y[-8:]=='encoding': y = y[:-8] y = self._XMap[y] return self.data[y] encodings = _Name2StandardEncodingMap() encodings['WinAnsi...
None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'perio...
Zyell/home-assistant
tests/components/test_rfxtrx.py
Python
mit
4,095
0
"""Th tests for the Rfxtrx component.""" # pylint: disable=too-many-public-methods,protected-access import unittest import time from homeassistant.bootstrap import _setup_component from homeassistant.components import rfxtrx as rfxtrx from tests.common import get_test_home_assistant class TestRFXTRX(unittest.TestCas...
self.hass = get_test_home_assistant(0) def tearDown(self): """Stop everything that was started.""" rfxtrx.RECEIVED_EVT_SUBSCRIBERS = [] rfxtrx.RFX_DEVICES = {} if rfxtrx.RFXOBJECT: rfxtrx.RFXOBJECT.close_connection() self.hass.stop() def test_default_co...
, 'rfxtrx', { 'rfxtrx': { 'device': '/dev/serial/by-id/usb' + '-RFXCOM_RFXtrx433_A1Y0NJGR-if00-port0', 'dummy': True} })) self.assertTrue(_setup_component(self.hass, 'sensor', { 'sensor': {'platform': 'rfxtrx', ...
seraphln/wheel
wheel/modules/posts/commands/listposts.py
Python
gpl-3.0
316
0
# -*- coding: utf-8 -*- import click from ..models import Post @click.command() @click.option('--title', default=None,
help='Title of the Post') def cli(title): "Prints a list of posts" posts = Post.objects if title: posts = posts(title=title
) for post in posts: click.echo(post)
AndrewSallans/osf.io
framework/exceptions/__init__.py
Python
apache-2.0
2,900
0.007241
# -*- coding: utf-8 -*- '''Custom exceptions for the framework.''' import copy import httplib as http from
flask import request class FrameworkError(Exception): """Base class from which framework-related errors inherit.""" pass class HTTPError(FrameworkError): error_msgs = { http.BAD_REQUEST: { 'message_short': 'Bad request',
'message_long': ('If this should not have occurred and the issue persists, ' 'please report it to <a href="mailto:support@osf.io">support@osf.io</a>.'), }, http.UNAUTHORIZED: { 'message_short': 'Unauthorized', 'message_long': 'You must <a href="/login/">log in</a> to...
matk86/pymatgen
pymatgen/io/tests/test_adf.py
Python
mit
10,190
0.000196
from __future__ import print_function, absolute_import from pymatgen.io.adf import AdfKey, AdfTask, AdfOutput, AdfInput from pymatgen.core.structure import Molecule import unittest import os from os.path import join __author__ = 'Xin Chen, chenxin13@mails.tsinghua.edu.cn' test_dir = os.path.join(os.path.dirname(__f...
-0.103309 0.887485 1.655272 B 0.436856 0.371367 3.299887 B 0.016593 -0.854959 1.930982 B 0.563233 -1.229713 3.453066 B 0.445855 -2.
382027 2.415013 B 0.206283 2.604044 -1.459430 B 0.404410 1.880136 -2.866764 B -0.103309 0.887485 -1.655272 B 0.436856 0.371367 -3.299887 B 0.563233 -1.229713 -3.453066 B 0.016593 -0.854959 -1.930982 B 0.200456 -2.309538 -0.836316 ...
erh3cq/hyperspy
hyperspy/tests/component/test_exponential.py
Python
gpl-3.0
3,100
0.000323
# -*- coding: utf-8 -*- # Copyright 2007-2021 The HyperSpy developers # # This file is part of HyperSpy. # # HyperSpy 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...
t_value / g.tau.value) np.testing.assert_allclose(g.function(0.), g.A.value) np.testing.assert_allclose(g.function(test_value), test_result)
@pytest.mark.parametrize(("lazy"), (True, False)) @pytest.mark.parametrize(("uniform"), (True, False)) @pytest.mark.parametrize(("only_current", "binned"), TRUE_FALSE_2_TUPLE) def test_estimate_parameters_binned(only_current, binned, lazy, uniform): s = Signal1D(np.empty((100,))) s.axes_manager.signal_axes[0...
scheib/chromium
third_party/blink/web_tests/external/wpt/webdriver/tests/refresh/refresh.py
Python
bsd-3-clause
3,290
0.000608
import pytest from webdriver.error import NoSuchElementException, StaleElementReferenceException from tests.support.asserts import assert_error, assert_success def refresh(session): return session.transport.send( "POST", "session/{session_id}/refresh".format(**vars(session))) def test_null_response_va...
history.pushState({foo: "bar"}, "", "#pushstate"); } </script> <a onclick="javascript:pushState();">click</a> """) session.url = pushstate_page session.find.css("a", all=False).click() assert session.url == "{}#pushstate".format(pushstate_page) assert session.execute_scrip...
Element('div'); window.document.body.appendChild(elem); """) element = session.find.css("div", all=False) response = refresh(session) assert_success(response) assert session.url == "{}#pushstate".format(pushstate_page) assert session.execute_script("return history.state;") == {"foo": "ba...
ddm/pcbmode
pcbmode/utils/excellon.py
Python
mit
4,661
0.00708
#!/usr/bin/python import os import re from lxml import etree as et import pcbmode.config as config from . import messages as msg # pcbmode modules from . import utils from .point import Point def makeExcellon(manufacturer='default'): """ """ ns = {'pcbmode':config.cfg['ns']['pcbmode'], 'svg...
getExcellon(): f.write(line) class Excellon(): """ """ def __init__(self, svg): """ """ self._svg = svg self._ns = {'pcbmode':config.cfg['ns']['pcbmode'],
'svg':config.cfg['ns']['svg']} # Get all drill paths except for the ones used in the # drill-index drill_paths = self._svg.findall(".//svg:g[@pcbmode:type='component-shapes']//svg:path", namespaces=self._ns) drills_dict = {} ...
mementum/backtrader
backtrader/feeds/rollover.py
Python
gpl-3.0
6,892
0
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2020 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
been met ... check other factors only if 2 datas # still there if self._ds and self._checkcondition(self._d, self._ds[0]): # Time to switch to next data self._dexp = self._d self._d = self._ds.pop(0) self._d...
ines.datetime[0] self.lines.open[0] = self._d.lines.open[0] self.lines.high[0] = self._d.lines.high[0] self.lines.low[0] = self._d.lines.low[0] self.lines.close[0] = self._d.lines.close[0] self.lines.volume[0] = self._d.lines.volume[0] self.lines.o...
jeffshek/betterself
events/migrations/0004_auto_20171223_0859.py
Python
mit
1,984
0.00252
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2017-12-23 08:59 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('events', '0003_auto_20171221_0336'), ] operations = [ migrations.AlterField...
Text_Message')], max_length=50), ), migrations.AlterField( model_name='sleeplog', name='source', field=models.CharField(choices=[('api', 'Api'), ('ios', 'Ios'), ('android', 'Android'), ('mobile', 'Mobile'), ('web', 'Web'), ('user_excel', 'User_Excel'), ('text_message'...
_length=50), ), migrations.AlterField( model_name='supplementlog', name='source', field=models.CharField(choices=[('api', 'Api'), ('ios', 'Ios'), ('android', 'Android'), ('mobile', 'Mobile'), ('web', 'Web'), ('user_excel', 'User_Excel'), ('text_message', 'Text_Message...
shelag/piggybank
saving/migrations/0001_initial.py
Python
mit
1,468
0.004087
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.Create...
ngs.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Tag', fields=[ ('id', models.AutoField(serialize=False, verbose_name='ID', primary_key=True, auto_created=True)),
('word', models.CharField(max_length=50)), ('slug', models.CharField(max_length=100)), ], ), migrations.AddField( model_name='movement', name='tag', field=models.ManyToManyField(to='saving.Tag'), ), ]
beiko-lab/gengis
bin/Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/ed_cmdbar.py
Python
gpl-3.0
43,285
0.000924
###########################################
#################################### # Name: ed_cmdbar.py
# # Purpose: Creates a small slit panel that holds small controls for searching # # and other actions. # # Author: Cody Precord <cprecord@editra.org> # # Copyright: (c) 2008 Cody Preco...
winterDroid/android-drawable-importer-intellij-plugin
json_generator/__init__.py
Python
apache-2.0
30
0
__author
__ = 'marcprengemann'
starwels/starwels
test/functional/wallet_hd.py
Python
mit
5,199
0.003847
#!/usr/bin/env python3 # Copyright (c) 2016-2019 The Starwels developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test Hierarchical Deterministic wallet function.""" from test_framework.test_framework import StarwelsTest...
om test_framework.util import ( assert_equal, connect_nodes_bi, ) import shutil import os class WalletHDTest(StarwelsTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 2 sel
f.extra_args = [[], ['-keypool=0']] def run_test (self): tmpdir = self.options.tmpdir # Make sure can't switch off usehd after wallet creation self.stop_node(1) self.assert_start_raises_init_error(1, ['-usehd=0'], 'already existing HD wallet') self.start_node(1) con...
eternnoir/pyTelegramBotAPI
examples/asynchronous_telebot/callback_data_examples/simple_products_example.py
Python
gpl-2.0
2,831
0.003535
# -*- coding: utf-8 -*- """ This Example will show you how to use CallbackData """ from telebot.callback_data import CallbackData, CallbackDataFilter from telebot import types from telebot.async_telebot import AsyncTeleBot from telebot.asyncio_filters import AdvancedCustomFilter API_TOKEN = 'TOKEN' PRODUCTS = [ {...
config=products_factory.filter(product_id='2')) async def product_one_callback(call: types.CallbackQuery): await bot.answer_callback_query(callback_query_id=call.id, text='Not available :(', show_alert=True) # Any other products @bo
t.callback_query_handler(func=None, config=products_factory.filter()) async def products_callback(call: types.CallbackQuery): callback_data: dict = products_factory.parse(callback_data=call.data) product_id = int(callback_data['product_id']) product = PRODUCTS[product_id] text = f"Product name: {produc...
shailcoolboy/Warp-Trinity
ResearchApps/Measurement/warpnet_coprocessors/phy_logger/examples/twoNode_cfoLogging.py
Python
bsd-2-clause
6,164
0.034069
from warpnet_framework.warpnet_client import * from warpnet_framework.warpnet_common_params import * from warpnet_experiment_structs import * from twisted.internet import reactor from datetime import * from numpy import log10, linspace import time import sys mods = [[2,2,2100,78-1]] pktLens = [1412]; #range(1412, 91,...
lStruct.channel = 9 controlStruct.txPower = txGain controlStruct.modOrderHeader = mods[0][0] controlStruct.modOrderPayload = mods[0][1] #P
HYCtrol params: #param0: txStartOut delay #param1: artificial txCFO #param2: minPilotChanMag #param3: # [0-0x01]: PHYCTRL_BER_EN: enable BER reporting # [1-0x02]: PHYCTRL_CFO_EN: enable CFO reporting # [2-0x04]: PHYCTRL_PHYDUMP_EN: enable Rx PHY dumping # [3-0x08]: PHYTRCL_EXTPKTDET_EN: use only ext pk...
SciLifeLab/scilifelab
tests/pm/test_default.py
Python
mit
2,421
0.008674
import os from cement.core import backend, handler, output from cement.utils import test, shell from scilifelab.pm import PmApp from data import setup_data_files from empty_files import setup_empty_files ## Set default configuration filedir = os.path.abspath(os.path.dirname(os.path.realpath(__file__))) config_defaults...
g_defaults['config']['ignore'] = ["slurm*", "tmp*"] config_defaults['log']['level'] = "INFO" config_defaults['log']['file'] = os.path.join(filedir, "data", "log", "pm.log") config_defaults['db']['url'] = "localhost" config_defaults['db']['
user'] = "u" config_defaults['db']['password'] = "p" config_defaults['db']['samples'] = "samples-test" config_defaults['db']['flowcells'] = "flowcells-test" config_defaults['db']['projects'] = "projects-test" def safe_makedir(dname): """Make directory""" if not os.path.exists(dname): try: ...
williamFalcon/pytorch-lightning
tests/loggers/test_wandb.py
Python
apache-2.0
9,157
0.001747
# Copyright The PyTorch Lightning 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 i...
"" Verify that pickling trainer with wandb logger works. Wandb doesn't work well with pytest so we have to mock it out here. """ class Experiment: id = "the_id" step = 0 dir = "wandb" def project_name(self): return "the_project_name" wandb.run = None ...
turn_value = Experiment() logger = WandbLogger(id="the_id", offline=True) trainer = Trainer(default_root_dir=tmpdir, max_epochs=1, logger=logger) # Access the experiment to ensure it's created assert trainer.logger.experiment, "missing experiment" assert trainer.log_dir == logger.save_dir pkl_b...
cga-harvard/worldmap
worldmap/management/commands/fix_migrated_layers.py
Python
gpl-3.0
4,316
0.001854
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2017 OSGeo # # 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 ...
end(layer) if options['remove']: print 'Removing this layer...' layer.delete() except: print("Unexpected error:", sys.exc_info()[0]) print '\n***** Layers with errors: %s in a total of %s *****' % (len(layer_errors)...
er.owner.username)
Gilbert88/mesos
src/python/cli_new/lib/cli/util.py
Python
apache-2.0
13,337
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...
".".join(import_path[1:])) except Exception as exception: raise CLIException("Un
able to get module: {error}" .format(error=str(exception))) return module def completions(comp_words, current_word, argv): """ Helps autocomplete by returning the appropriate completion words under three conditions. 1) Returns `comp_words` if the completion word is ...
dr4ke616/LazyTorrent
application/lib/the_pirate_bay/utils.py
Python
gpl-3.0
2,327
0
from collections import Order
edDict from purl import URL as PURL def URL(base, path, segments=None, defaults=None): """ URL segment handler ca
pable of getting and setting segments by name. The URL is constructed by joining base, path and segments. For each segment a property capable of getting and setting that segment is created dinamically. """ # Make a copy of the Segments class url_class = type(Segments.__name__, Segments.__bases_...
offbye/PiBoat
pyboat/gps_test.py
Python
apache-2.0
604
0.003333
#!/usr/bin/python2.7 # -*- encoding: UTF-8 -*- # gps_test created on 15/8/22 上午12:44 # Copyright 2014 offbye@gmail.com """ """
__author__ = ['"Xitao":<offbye@gmail.com>'] import gps3 gps_connection = gps3.GPSDSocket() gps_fix = gps3.Fix() try: for new_data in gps_connection: if new_data: gps_fix.refresh(new_data) print(gps_fix.TPV['time']) print(gps_fix.TPV['lat']) print(gps_fix.T...
t('\nTerminated by user\nGood Bye.\n')
pannkotsky/groupmate
backend/apps/users/login_backend.py
Python
mit
618
0
from .models import EmailUser class EmailOrPhoneModelBackend: def authenticate(self, username=None, password=None): if '@' in username: kwarg
s = {'email__iexact': username} else: kwargs = {'phone': username} try: user = EmailUser.objects.get(**kwargs) if user.check_password(password): return user except EmailUser.DoesNotExist: return None def get_user(self, user_id)...
DoesNotExist: return None
AcroManiac/AcroLink
Server/DjangoServer/manage.py
Python
gpl-3.0
810
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "DjangoServer.s
ettings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: im...
"Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
EricSchles/python-route53
tests/test_util.py
Python
mit
916
0.009825
import unittest from tests.test_basic import BaseTestCase from datetime import timedelta, datetime, tzinfo class UTC(tzinfo): """UTC""" def utcoffset(self, dt): return timedelta(0) def tzname(self, dt): return "UTC" def dst(self, dt): return timedelta(0) class UtilTestCase(...
self.assertEqual(parse_iso_8601_time_str('2013-07-28T
01:00:01Z'), datetime.datetime(2013, 7, 28, 1, 0, 1, 0, \ tzinfo=UTC())) self.assertEqual(parse_iso_8601_time_str('2013-07-28T01:00:01.001Z'), datetime.datetime(2013, 7, 28, 1, 0, 1, 1000, \ tzinfo=UTC()))
suutari/shoop
shuup_setup_utils/parsing.py
Python
agpl-3.0
928
0
# This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. import os def get_test_requirements_from_tox_ini(path): result = [] between_begin...
p: for line in fp: if line.strip() == '# BEGIN testing deps': between_begin_and_end = True elif line.strip() == '# END testing deps' or not line[0].isspace(): between_begin_and_end = False elif between_begin_and_end: result.appe...
with open(path, 'rt') as fp: return fp.read() return None
jianghuaw/nova
nova/api/openstack/placement/handler.py
Python
apache-2.0
9,268
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/LIC
ENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
the # License for the specific language governing permissions and limitations # under the License. """Handlers for placement API. Individual handlers are associated with URL paths in the ROUTE_DECLARATIONS dictionary. At the top level each key is a Routes compliant path. The value of that key is a dictionary ma...
joergdietrich/astropy
astropy/utils/console.py
Python
bsd-3-clause
33,248
0.000211
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Utilities for console input and output. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import codecs import locale import re import math import multiprocessing i...
hon(object): """Singleton class given access to IPython streams, etc.""" @classproperty def get_ipython(cls): try: from IPython import get_ipython except ImportError: pass return get_ipython @classproperty def Out
Stream(cls): if not hasattr(cls, '_OutStream'): cls._OutStream = None try: cls.get_ipython() except NameError: return None try: from ipykernel.iostream import OutStream except ImportError: ...
yanheven/ceilometer
ceilometer/alarm/evaluator/combination.py
Python
apache-2.0
4,511
0
# # Copyright 2013 eNovance <licensing@enovance.com> # # Authors: Mehdi Abaakouk <mehdi.abaakouk@enovance.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/l...
larm_state == state] reason_data = cls._reason_data(alarms_to_report) if transition: return (_('Transition to %(state)s due to alarms' ' %(alarm_ids)s
in state %(state)s') % {'state': state, 'alarm_ids': ",".join(alarms_to_report)}), reason_data return (_('Remaining as %(state)s due to alarms' ' %(alarm_ids)s in state %(state)s') % {'state': state, 'alarm_ids': ",".jo...
daicang/Leetcode-solutions
487-max-consecutive-ones-ii.py
Python
mit
773
0.006468
class Solution(object): def findMaxConsecutiveOnes(self, nums): """ :type nums: List[int] :rtype: int """
# sliding window max_len = 0 li = 0 ri = 0 l = 0 inserted = False for ri, rval in enumerate(nums): if rval == 1: l += 1 max_len = max(max_len, l)
else: if not inserted: inserted = True l += 1 max_len = max(max_len, l) else: while nums[li] == 1: li += 1 li += 1 l = ri-li+1 ...
chris48s/UK-Polling-Stations
polling_stations/apps/data_collection/management/commands/import_bradford.py
Python
bsd-3-clause
408
0.009804
from data_collection.management.commands import Bas
eXpressDemocracyClubCsvImporter class Command(BaseXpressDemocracyClubCsvImporter): council_id = 'E08000032' addresses_name = 'parl.2017-06-08/Version 1/Democracy_Club__08June2017.tsvJune2017.tsv' stations_name = 'parl.2017-06-08/Version 1/Democracy_Club__08June2017.tsvJune2017.tsv' elections = ['parl.2...
_delimiter = '\t'
noemis-fr/custom
account_banking_natixis_direct_debit/__openerp__.py
Python
gpl-3.0
1,248
0
# -*- coding: utf-8 -*- ############################################################################## ############################################################################## { 'name': 'Account Banking Netixis Direct Debit', 'summary': 'Create Natixis files for Direct Debit', 'version': '7.0.0.2.0',...
: 'Banking addons', 'depends': [ 'account_direct_debit', 'account_banking_pain_base', 'account_payment_partner', 'account' ], 'external_dependencies': { 'python': ['unidecode', 'lxml'], }, 'data': [ 'views/account_banking_natixis_view.xml', 'vi...
'security/ir.model.access.csv', 'views/invoice.xml', 'data/payment_type_natixis.xml', 'views/account_payment_view.xml', 'views/partner.xml', 'views/natixis_file_sequence.xml', ], 'demo': ['sepa_direct_debit_demo.xml'], 'description': ''' Module to export dire...
0x0all/scikit-learn
sklearn/preprocessing/label.py
Python
bsd-3-clause
28,286
0
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Mathieu Blondel <mathieu@mblondel.org> # Olivier Grisel <olivier.grisel@ensta.org> # Andreas Mueller <amueller@ais.uni-bonn.de> # Joel Nothman <joel.nothman@gmail.com> # Hamzeh Alsalhi <ha258@cornell.edu> # Licens...
s', 'tokyo'] >>> le.transform(["tokyo", "tokyo", "paris"]) #doctest: +ELLIPSIS array([2, 2, 1]...) >>> list(le.inverse_transform([2, 2, 1])) ['tokyo', 'tokyo', 'paris'] """ def _check_fitted(self): if not hasattr(self, "classes_"): raise ValueError("LabelEncoder was not fit...
") def fit(self, y): """Fit label encoder Parameters ---------- y : array-like of shape (n_samples,) Target values. Returns ------- self : returns an instance of self. """ y = column_or_1d(y, warn=True) _check_numpy_unico...
mhaessig/servo
tests/wpt/web-platform-tests/tools/webdriver/webdriver/transport.py
Python
mpl-2.0
3,140
0.001274
import httplib import json import urlparse import error class Response(object): """Describes an HTTP response received from a remote en"Describes an HTTP response received from a remote end whose body has been read and parsed as appropriate.""" def __init__(self, status, body): self.status = s...
"no-cache"
if body: try: body = json.loads(body) except: raise error.UnknownErrorException("Failed to decode body as json:\n%s" % body) return cls(status, body) class ToJsonEncoder(json.JSONEncoder): def default(self, obj): return getattr(obj.__clas...
googleapis/python-tasks
samples/generated_samples/cloudtasks_v2beta2_generated_cloud_tasks_get_task_async.py
Python
apache-2.0
1,437
0.000696
# -*- 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...
rning permissions and # limitations under the License. # # Generated code. DO NOT EDIT! # # Snippet for GetTask # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in your environment. # To install the latest published package dependency, execute...
sample_get_task(): # Create a client client = tasks_v2beta2.CloudTasksAsyncClient() # Initialize request argument(s) request = tasks_v2beta2.GetTaskRequest( name="name_value", ) # Make the request response = await client.get_task(request=request) # Handle the response pri...
openstack/cinder
cinder/tests/unit/policies/test_default_volume_types.py
Python
apache-2.0
12,078
0.000662
# 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...
context.project_id response = self._get_request
_response(system_admin_context, path, 'DELETE', microversion= mv.DEFAULT_TYPE_OVERRIDES) self.assertEqual(HTTPStatus.NO_CONTENT, response.status_int) def test_project_a...
syncloud/platform
src/test/snap/test_snap.py
Python
gpl-3.0
1,740
0.000575
from syncloud_platform.snap.models import App, AppVersions from syncloud_platform.snap.snap import join_apps def test_join_apps(): installed_app1 = App() installed_app1.id = 'id1' installed_app_version1 = AppVersions() installed_app_version1.installed_version = 'v1' installed_app_version1.current...
= 'v1' installed_app_version2.current_version = None installed_app_version2.app = installed_app2 installed_apps = [installed_app_version1, installed_app_version2] store_app2 = App() store_app2.id = 'id2' store_app_versi
on2 = AppVersions() store_app_version2.installed_version = None store_app_version2.current_version = 'v2' store_app_version2.app = store_app2 store_app3 = App() store_app3.id = 'id3' store_app_version3 = AppVersions() store_app_version3.installed_version = None store_app_version3.curren...
plaidml/plaidml
plaidbench/plaidbench/cli.py
Python
apache-2.0
3,879
0.002578
# Copyright 2018 Intel 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 applicable law or agreed to in writi...
'--examples', type=int, default=None,
help='Number of examples to use (over all epochs)') @click.option( '--blanket-run', is_flag=True, help='Run all networks at a range of batch sizes, ignoring the --batch-size and --examples ' 'options and the choice of network.') @click.option('--results', type=click.Path(exists=False,...
hcarvalhoalves/SublimeHaskell
util.py
Python
mit
2,159
0.012043
import sublime if int(sublime.version()) < 3000: import ghci import ghcmod
import haskell_docs import hdevtools import sublime_haskell_common as common import symbols else: import SublimeHaskell.ghci as ghci import SublimeHaskell.ghcmod as ghcmod import SublimeHaskell.haskell_docs as haskell_docs import SublimeHaskell.hdevtools as hdevtools import SublimeH...
common import SublimeHaskell.symbols as symbols def symbol_info(filename, module_name, symbol_name, cabal = None, no_ghci = False): result = None if hdevtools.hdevtools_enabled(): result = hdevtools.hdevtools_info(filename, symbol_name, cabal = cabal) if not result and ghcmod.ghcmod_enabled():...
tanium/pytan
BUILD/doc/source/examples/export_resultset_csv_sensor_false_code.py
Python
mit
3,040
0.002303
# import the basic python packages we need import os import sys import tempfile import pprint import traceback # disable python from generating a .pyc file sys.dont_write_bytecode = True # change me to the path of pytan if this script is not running from EXAMPLES/PYTAN_API pytan_loc = "~/gh/pytan" pytan_static_path =...
e # optional, this saves all re
sponse objects to handler.session.ALL_REQUESTS_RESPONSES # very useful for capturing the full exchange of XML requests and responses handler_args['record_all_requests'] = True # instantiate a handler using all of the arguments in the handler_args dictionary print "...CALLING: pytan.handler() with args: {}".format(hand...
connect1ngdots/AppHtmlME
AppHtmlME.workflow/Scripts/apphtml_settings.py
Python
mit
1,540
0.00411
# vim: fileencoding=utf-8 """ AppHtml settings @author Toshiya NISHIO(http://www.toshiya240.com) """ defaultTemplate = { '1) 小さいボタン': '${badgeS}', '2) 大きいボタン': '${badgeL}', '3) テキストのみ': '${textonly}', "4) アイコン付き(小)": u"""<span class="appIcon"><img class="appIconImg" height="60" src="${icon60url}" style...
nline-block; margin:4px">${badgeL}</span><br style="clear:both;"> """ } settings = { 'phg': "", 'cnt': 8, 'scs': { 'iphone': 320, 'ipad': 320, 'mac': 480 }, 'template': { 'software': defaultTemplate, 'iPadSoftware': defaultTemplate, 'macSoftware': def...
te } }
EmreAtes/spack
var/spack/repos/builtin/packages/cblas/package.py
Python
lgpl-2.1
2,365
0
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
epends_on('blas') pa
rallel = False def patch(self): mf = FileFilter('Makefile.in') mf.filter('^BLLIB =.*', 'BLLIB = %s/libblas.a' % self.spec['blas'].prefix.lib) mf.filter('^CC =.*', 'CC = cc') mf.filter('^FC =.*', 'FC = f90') def install(self, spec, prefix): make('all')...
matrixise/epcon
microblog/dataaccess.py
Python
bsd-2-clause
5,734
0.007499
# -*- coding: UTF-8 -*- from django.core.cache import cache from django.db.models.signals import post_delete, post_save import functools import hashlib WEEK = 7 * 24 * 60 * 60 # 1 week def cache_me(key=None, ikey=None, signals=(), models=(), timeout=WEEK): def hashme(k): if isinstance(k, unicode): ...
.filter(content_type__app_label='microblog', content_type__model='post')\ .filter(object_pk=pid, is_public=True) burl = models.PostContent.build_absolute_url(post, content) return { 'post': post, 'content': content, 'url': dsetting
s.DEFAULT_URL_PREFIX + reverse(burl[0], args=burl[1], kwargs=burl[2]), 'comments': list(comment_list), 'tags': list(post.tags.all()), } def _i_get_reactions(sender, **kw): if sender is models.Trackback: return 'm:reaction:%s' % kw['instance'].content_id else: return 'm:react...
gitlitz/pygame-with-interpreter
drawable.py
Python
gpl-3.0
750
0.064
from static import tools class DrawAble(object): def __init__(self,image,position,zIndex=0,activated=True): self.image=image self.position=position self._zIndex=zIndex self.__activated=Non
e self.activated=activated def _
_del__(self): self.activated=False #zindex def __getZIndex(self): return self._zIndex zIndex=property(__getZIndex) #enabled def _disable(self): tools.spritebatch.remove(self) def _enable(self): tools.spritebatch.add(self) def __setActivated(self,b): if self.__activated!=...
Elvirita/reposelvira
elviraae/ec/edu/itsae/conn/DBcon.py
Python
gpl-2.0
604
0.006623
#-*- coding:utf-8 -*- '
'' Created on 18/2/2015 @author: PC06 ''' from flaskext.mysql import MySQL from flask import Flask c
lass DBcon(): ''' classdocs ''' def __init__(self): ''' Constructor ''' pass def conexion(self): mysql = MySQL() app = Flask(__name__) app.config['MYSQL_DATABASE_USER'] = 'python' app.config['MYSQL_DATABASE_PASSWORD'] = '123456...
juju-solutions/charms.reactive
charms/reactive/flags.py
Python
apache-2.0
9,936
0.000805
from charmhelpers.cli import cmdline from charmhelpers.core import hookenv from charmhelpers.core import unitdata from charms.reactive.bus import FlagWatch from charms.reactive.trace import tracer __all__ = [ 'set_flag', 'clear_flag', 'toggle_flag', 'register_trigger', 'is_flag_set', 'all_fla...
ion(RelationBase): class states(StateList): connected = State('{relation_name}.connected') available = State('{
relation_name}.available') """ pass @cmdline.subcommand() @cmdline.no_output def set_flag(flag, value=None): """set_flag(flag) Set the given flag as active. :param str flag: Name of flag to set. .. note:: **Changes to flags are reset when a handler crashes.** Changes to flags happen i...
dsimandl/teamsurmandl
gallery/tasks.py
Python
mit
1,465
0.001365
import time import zipfile from io import BytesIO from django.utils.image import Image as D_
Image from django.core.files.base import ContentFile
from celery import task from .models import Image @task def upload_zip(to_upload): print("In the zip!") zip = zipfile.ZipFile(to_upload.zip_file) bad_file = zip.testzip() if bad_file: zip.close() raise Exception('"%s" in zip archive is corrupt' % bad_file) count = 1 for file_na...
tensorflow/kfac
kfac/python/kernel_tests/periodic_inv_cov_update_kfac_opt_test.py
Python
apache-2.0
3,178
0.003776
# Copyright 2019 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...
import periodic_inv_cov_update_kfac_opt from kfac.python.ops.tensormatch import graph_search _BATCH_SIZE = 128 def _construct_layer_collection(layers, all_logits, var_list): for idx, logits in enumerate(all_logits): tf.logging.info("Registering logits: %s", logits) with tf.variable_scope(tf.get_variable_sc...
> 0)): layers.register_categorical_predictive_distribution( logits, name="register_logits") batch_size = all_logits[0].shape.as_list()[0] vars_to_register = var_list if var_list else tf.trainable_variables() graph_search.register_layers(layers, vars_to_register, batch_size) class PeriodicInvCov...
qedsoftware/commcare-hq
corehq/apps/app_manager/views/multimedia.py
Python
bsd-3-clause
2,218
0.000451
from django.contrib import messages from django.http import Http404, HttpResponse fr
om django.shortcuts import render from corehq.apps.app_manager.dbaccessors import get_app from corehq.apps.app_manager.decorators import require_deploy_apps, \ require_can_edit_apps from corehq.apps.app_manager.xform import XForm from corehq.util.view_utils import set_file_download from dimagi.utils.logging import ...
(domain, app_id) include_audio = request.GET.get("audio", True) include_images = request.GET.get("images", True) strip_jr = request.GET.get("strip_jr", True) filelist = [] for m in app.get_modules(): for f in m.get_forms(): parsed = XForm(f.source) parsed.validate() ...
mrshelly/openerp71313
openerp/addons/hr_attendance/wizard/hr_attendance_error.py
Python
agpl-3.0
2,918
0.002742
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
m-%d'), 'max_delay': 120, } def print_report(self, cr, uid, ids, context=None): emp_ids = [] data_error = self.read(cr, uid, ids, context=context)[0] date_from = data_error['init_date'] date_to = data_error['end_date'] cr.execute("SELECT id FROM hr
_attendance WHERE employee_id IN %s AND to_char(name,'YYYY-mm-dd')<=%s AND to_char(name,'YYYY-mm-dd')>=%s AND action IN %s ORDER BY name" ,(tuple(context['active_ids']), date_to, date_from, tuple(['sign_in','sign_out']))) attendance_ids = [x[0] for x in cr.fetchall()] if not attendance_ids: ...
zhou13/qtunneler
qtunneler.py
Python
gpl-3.0
16,827
0.002853
#!/bin/env python3 """ Copyright (C) 2014 by Yichao Zhou <broken.zhou AT gmail DOT com> License: http://www.gnu.org/licenses/gpl.html GPL version 3 or higher Any comments are welcome through email and github! """ import codecs import re import random import os import pexpect import sys import string import time from ...
xit now. SSH_UNKNOWN: SSH does not return enough information """ index = self.ssh.expect([ pexpect.TIMEOUT, #0 "ssh: connect t
o host", #1 "Permission denied (publickey)", #2 "The authenticity of host", #3 "s password: ", #4 pexpect.EOF, #5 "execing", #6 "connection ok", ...
TheOstrichIO/tomato-cmd
slugify.py
Python
apache-2.0
4,674
0.001498
# -*- coding: utf-8 -*- """ Copyright © Val Neekman ([Neekware Inc.](http://neekware.com)) [ info@neekware.com, [@vneekman](https://twitter.com/vneekman) ] All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following condition...
text = unicode(text, 'u
tf-8', 'ignore') # character entity reference if entities: text = CHAR_ENTITY_REXP.sub(lambda m: unichr(name2codepoint[m.group(1)]), text) # decimal character reference if decimal: try: text = DECIMAL_REXP.sub(lambda m: unichr(i...
reinforceio/tensorforce
tensorforce/environments/cartpole.py
Python
apache-2.0
8,953
0.002457
# Copyright 2020 Tensorforce Team. 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 la...
) / \ self.pole_length_range[1] / \ (4.0 / 3.0 - self.pole_mass_range[0] / (self.cart_mass_range[1] + self.pole_mass_range[1])) max_loc_acc_in_zero = (self.relative_force_range[1] * self.gravity - \
self.pole_mass_range[0] * self.pole_length_range[0] * min_angle_acc_in_zero) / \ (self.cart_mass_range[0] + self.pole_mass_range[0]) angle_vel_bound = max_angle_acc_in_zero * self.action_timedelta * 10.0 loc_vel_bound = max_loc_acc_in_zero * self.action_timedelta * 10.0 i...
blancltd/django-latest-tweets
latest_tweets/migrations/0011_photo_image_file.py
Python
bsd-3-clause
434
0.002304
# -*- coding: utf-8 -*- from __future_
_ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('latest_tweets', '0010_photo_unique'), ] operations = [ mig
rations.AddField( model_name='photo', name='image_file', field=models.ImageField(blank=True, upload_to='latest_tweets/photo'), ), ]
botswana-harvard/microbiome
microbiome/apps/mb_maternal/tests/test_maternal_locator.py
Python
gpl-2.0
847
0.002361
from edc_constants.constants import YES, NEG from .base_test_case import BaseTestCase from .factories import MaternalConsentFactory, MaternalEligibilityFactory, PostnatalEnrollmentFactory class TestMaternalLocator(BaseTestCase): def setUp(self): super(TestMaternalLocator, self).setUp() self.mate...
egistered_subject PostnatalEnrollmentFactory( registered_subject=self.registered_subject, current_hiv_st
atus=NEG, evidence_hiv_status=YES, rapid_test_done=YES, rapid_test_result=NEG) def test_maternal_locator(self): pass
iafan/zing
pootle/core/views/api.py
Python
gpl-3.0
10,141
0.000197
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # Copyright (C) Zing contributors. # # This file is a part of the Zing project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import json...
not None: self.fields = form._meta.fields else
: # Assume all fields by default self.fields = (f.name for f in self.model._meta.fields) self.serialize_fields = (f for f in self.fields if f not in self.sensitive_field_names) def _init_forms(self): if 'post' in self.allowed_methods and self.add_f...
ifduyue/sentry
tests/sentry/models/test_groupresolution.py
Python
bsd-3-clause
2,921
0
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function from datetime import timedelta from django.utils import timezone from sentry.models import GroupResolution from sentry.testutils import TestCase class GroupResolutionTest(TestCase): def setUp(self): super(GroupResolutionTest...
on.objects.create( release=self.new_re
lease, group=self.group, type=GroupResolution.Type.in_release, ) assert GroupResolution.has_resolution(self.group, None) def test_no_release_with_no_resolution(self): assert not GroupResolution.has_resolution(self.group, None)
veikman/cbg
cbg/content/card.py
Python
gpl-3.0
4,586
0.000436
# -*- coding: utf-8 -*- '''A module to represent the text content of a playing card at a high level.''' # This file is part of CBG. # # CBG 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 ...
xcept AttributeError: return self._untitled_base @property def card(self): '''An override of a field method.''' return self @property def _sorting_signature(self): '''Salient properties of self, for sorting purposes. To be overridden for card types with oth...
return str(self.deck), str(self) def __eq__(self, other): '''Used for sorting (as performed by decks).''' try: return self._sorting_signature == other._sorting_signature except AttributeError: return False def __lt__(self, other): '''Used for sorting (a...
mheap/ansible
lib/ansible/module_utils/network/f5/bigip.py
Python
gpl-3.0
3,738
0.001338
# -*- coding: utf-8 -*- # # Copyright (c) 2017 F5 Networks Inc. # 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 import time try: from f5.bigip import ManagementRoot from icontrol.exceptions import iControlUnexpectedHTTPError HAS_F5SDK = True except ImportError: HAS_F5SDK
= False try: from library.module_utils.network.f5.common import F5BaseClient from library.module_utils.network.f5.common import F5ModuleError from library.module_utils.network.f5.icontrol import iControlRestSession except ImportError: from ansible.module_utils.network.f5.common import F5BaseClient ...
theshammy/GenAn
src/concepts/query.py
Python
mit
1,811
0.009939
from textx.exceptions import TextXSemanticError def query_processor(query): if not query.condition is None: query.condition.conditionName = adapter_for_query(query) for query in query.parent.queries: if (not hasattr(query, 'property')) and (query.sortBy not in query.parent.properties): ...
no property named %s." % (line, col, query.parent.object.name, query.parent.
property.name)) elif (not hasattr(query, 'sortBy')) and (query.sortBy not in query.parent.properties): line, col = query.parent._tx_metamodel.parser.pos_to_linecol( object._tx_position) raise TextXSemanticError("ERROR: (at %d, %d) Object %s has no property named %s." % ...
supistar/Botnyan
model/qrcreator.py
Python
mit
520
0
# -*- encoding:utf8 -*- import cStringIO import qrcode class QRCodeCreator(): def __init__(self): pass def create(self, message): qr = qrcode.QRCode( version=1, error_correction=q
rcode.constants.ERROR_CORRECT_L, box_size=10, border=4, ) qr.add_data(message) qr.make(fit=True) img = qr.make_image() img_buf = cStringIO.StringIO() img.save(img_buf) img_buf.seek(0)
return img_buf
jalanb/dotjab
src/python/__init__.py
Python
mit
48
0
#! /us
er/bin/env p
ython __version__ = '0.8.53'
stdgregwar/elve
personaltypes.py
Python
lgpl-3.0
2,750
0.000727
############################################################################ # # Copyright (C) 2016 The Qt Company Ltd. # Contact: https://www.qt.io/licensing/ # # This file is part of Qt Creator. # # Commercial License Usage # Licensees holding valid commercial Qt licenses may use this file in # accordance with the co...
ator/creator-debugging-helpers.html # for more details or look at qttypes.py, stdtypes.py, boosttypes.py # for more complex examples. from dumper import * #def qdump__Pin(d,value): # d.putValue('%s %s' % (value['id'].integer(
), value['index'].integer())) # d.putNumChild(2) # if d.isExpanded(): # with Children(d): # d.putSubItem("id",value["id"]) # d.putSubItem("index",value["index"]) ######################## Your code below #######################
quamilek/django-custard
custard/tests/test.py
Python
mit
13,067
0.004362
from __future__ import unicode_literals import django from django.core.exceptions import ValidationError from django.db.models import Q from django.contrib.contenttypes.models import ContentType from django.test import TestCase, Client from django.test.client import RequestFactory from django.test.utils import override...
etime_f
ield', label="Datetime field", data_type=CUSTOM_TYPE_DATETIME) self.cf7.save() self.cf8 = CustomFieldsModel.objects.create(content_type=self.simple_with_manager_ct, name='time_field', label="Time fie...
trickvi/budgetdatapackage
tests/test_resource.py
Python
gpl-3.0
3,567
0
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import budgetdatapackage import datapackage import datetime from nose.tools import raises from datapackage import compat class TestBudgetResourc...
package.BudgetResource(**self.values) @raises(ValueError) def test_bad_status(self): self.values['status'] = 'batman' budgetdatapackage.BudgetResource(**self.values) @raises(ValueError) def test_bad_type(self): self.values['type'] = 'batma
n' budgetdatapackage.BudgetResource(**self.values) @raises(ValueError) def test_bad_location(self): self.values['location'] = 'batman' budgetdatapackage.BudgetResource(**self.values)
sit/dht
tools/vischat.py
Python
mit
1,908
0.021488
import asynchat import socket import errno class vischat (asynchat.async_chat): def __init__ (self, host, port): self.host = host self.port = port self.outstanding = [] self.lines = [] self.buffer = "" asynchat.async_chat.__init__ (self) def handle_connect (self...
self.lines = [] else: self.lines.append (self.buffer)
self.buffer = "" # Each command here is a front-end to a real message that could get # sent to vis, and a callback that should notify def list (self, cb): self.push ("list\n") self.outstanding.append (cb) def arc (self, a, b): self.push ("arc %s %s\n" % (a, b)) self...
alexsilva/helicon-zoofcgi
zoofcgi.py
Python
mit
34,047
0.001351
# encoding: utf-8 # FastCGI-to-WSGI bridge for files/pipes transport (not socket) # # Copyright (c) 2002, 2003, 2005, 2006 Allan Saddi <allan@saddi.com> # Copyright (c) 2011 - 2013 Ruslan Keba <ruslan@helicontech.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modif...
] self._avail -= self._pos self._pos = 0 assert self._avail >= 0 def _waitForData(self): """Waits for more data to become available.""" self._conn.process_input() def read(self, n=-1): if self._pos == self._avail and self._eof: return ''...
e's no more coming. newPos = self._avail break else: # Wait for more data. self._waitForData() continue else: newPos = self._pos + n break # Mer...
leepa/django-paypal-driver
paypal/driver.py
Python
gpl-2.0
14,675
0.000409
# -*- coding: utf-8 -*- # Pluggable PayPal NVP (Name Value Pair) API implementation for Django. # This file includes the PayPal driver class that maps NVP API methods to such # simple functions. # Feel free to distribute, modify or use any open or closed project without # any permission. # Author: Ozgur Vatansever #...
ENDPOINT, query_string).read() response_dict = parse_qs(response) self.api_response = response_dict state = self._get_value_from_qs(response_dict, "ACK") if state in ["Success", "SuccessWithWarning"]: self.token = self._get_value_from_qs(response
_dict, "TOKEN") return True self.setexpresscheckouterror = GENERIC_PAYPAL_ERROR self.apierror = self._get_value_from_qs( response_dict, "L_LONGMESSAGE0" ) return False """ If SetExpressCheckout is successfull use TOKEN to redirect to the browser to t...
t3dev/odoo
addons/partner_autocomplete/models/res_partner.py
Python
gpl-3.0
7,237
0.001935
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import json from odoo import api, fields, models, exceptions, _ from odoo.addons.iap import jsonrpc from requests.exceptions import ConnectionError, HTTPError from odoo.addons.iap.models.iap import Insuffi...
'|', ('name', '=ilike', state_name),
('code', '=ilike', state_code) ], limit=1) if state: state_id = { 'id': state.id, 'display_name': state.display_name } else: _logger.info('Country code not found: ...
stephenrjones/geoq
geoq/core/managers.py
Python
mit
1,155
0.001732
# -*- coding: utf-8 -*- # This technical data was produced for the U. S. Government under Contract No. W15P7T-13-C-F600, and # is subject to the Rights in Technical Data-Noncommercial Items clause at DFARS 252.227-7013 (FEB 2012) from django.contrib.gis.db import models class AOIManager(models.GeoManager): def ...
def assigned(self): """ Returns assigned AOIs. """ return self.add_filters(status='Assigned') def in_work(self): """ Returns AOIs in work. """ return self.add_filters(status='In Work') def submitted(self): """ Re
turns submitted AOIs. """ return self.add_filters(status='Submitted') def completed(self): """ Returns completed AOIs. """ return self.add_filters(status='Completed')
arnaudsj/pebl
src/pebl/learner/greedy.py
Python
mit
4,765
0.003568
"""Learner that implements a greedy learning algorithm""" import time from pebl import network, result, evaluator from pebl.util import * from pebl.learner.base import * class GreedyLearnerStatistics: def __init__(self): self.restarts = -1 self.iterations = 0 self.unimproved_iterations = ...
ill the restarting_criteria is met, at whic
h point we begin again with a new random network (step 1) Any config param for 'greedy' can be passed in via options. Use just the option part of the parameter name. For more information about greedy learning algorithms, consult: 1. http://en.wikipedia.org/wiki/Greedy_algo...
dmayle/YAMLTrak
yamltrak/commands.py
Python
gpl-3.0
11,746
0.004001
# Copyright 2009 Douglas Mayle # This file is part of YAMLTrak. # YAMLTrak is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or (at your # option) any later version. # ...
Aborting' import sys sys.exit(1) def unpack_new(issuedb, args): # We should be able to avoid this somehow by using an object dictionary. skeleton_new = issuedb.skeleton_new issue = {} for field in skeleton_new: issue[field] = getattr(args, field, None) if issue[field] is None: ...
print 'Added new issue: %s' % newid def unpack_list(issuedb, args): issues = issuedb.issues(status=args.status) for id, issue in issues.iteritems(): # Try to use color for clearer output color = None if 'high' in issue.get('priority',''): color = 'red' elif 'normal' ...
dana-i2cat/felix
optin_manager/src/python/openflow/optin_manager/sfa/methods/Update.py
Python
apache-2.0
1,376
0.009448
from openflow.optin_manager.sfa.util.method import Method from openflow.optin_manager.sfa.trust.credential import Credential from openflow.optin_manager.sfa.util.parameter import Parameter class Update(Method): """ Update an object in the registry. Currently, this only updates the PLC information associa...
ccessful") def call(self, record_dict, creds): # validate the cred valid_creds = self.api.auth.checkCredentials(creds, "update") # verify permissions hrn = record_dict.get('hrn', '') self.api.auth.verify_object_permission(hrn) # log origin...
: %s"%(self.api.interface, origin_hrn, hrn, self.name)) return self.api.manager.Update(self.api, record_dict)
scowcron/ImagesOfNetwork
images_of/entrypoints/discord_announce_bot.py
Python
mit
1,599
0.005629
import click from images_of import command, settings, Reddit from images_of.discord_announcer import DiscordBot, DiscordBotSettings @command @click.option('-G', '--no-github', is_flag=True, help='Do not process github events') @click.option('-M', '--no-modlog', is_flag=True, help='Do not process network modlog events...
Settings() botsettings.DO_GITHUB = not no_github botsettings.DO_MODLO
G = not no_modlog botsettings.DO_OC = not no_oc botsettings.DO_INBOX = not no_inbox botsettings.DO_FALSEPOS = not no_falsepositives botsettings.RUN_INTERVAL = run_interval botsettings.STATS_INTERVAL = stats_interval discobot.run(botsettings) if __name__ == '__main__': main()
bebraw/speccer
speccer/__init__.py
Python
mit
86
0.011905
# -*- coding: utf-8 -*- __aut
hor__ = 'Juho Vepsäläinen' __version__ = '0.7.5-dev'
hugombarreto/credibility_allocation
allocators/optimization_allocation.py
Python
mit
3,025
0.000661
import numpy as np import scipy.optimize as opt import unittest def allocate(a, c, initial_guess): def sum_positives(x): return sum(i for i in x if i > 0) def sum_negatives(x): return -sum(i for i in x if i < 0) pareto_ref = min(sum_positives(a), sum_negatives(a)) def sqr_sum(o,c):...
qual(output, [-1, 0, -2, 2, 2, -1]) def test_lack_resources_float_reputation(self): desire = [1, 3, 2, 2, -3, 1, -5, 3, 0] reputation = [-6.2, -3.1, -3.1, -2.2, 8.6, 12.2, -4.3, 6.0, -7.9] output = desire[:] allocate(desire, reputation, output) self.assertEqual(output, [1, ...
12] output = desire[:] allocate(desire, reputation, output) self.assertEqual(output, [1, -1, 2, -1, -2, 1]) def test_efficient(self): # sum a = 0 desire = [1, -3, 2, -1, -2, 3] reputation = [-10, -3, -5, 2, 4, 12] output = desire[:] allocate(desire, reputa...
AgusRumayor/pypriorapi
order.py
Python
gpl-3.0
6,154
0.039812
import falcon import msgpack import json from btree import BinaryTree import ZODB, ZODB.FileStorage import transaction from persistent import Persistent import uuid import urllib import btree from pprint import pprint class Collection (object): def on_post(self, req, resp): # req.stream corresponds to the WSGI wsgi....
{"order":"/order
/%s"%(urllib.quote(token))}, {"lt":"/order/%s/%s/%s"%(urllib.quote(token), tree.current.getNodeValue(), tree.next)}, {"gt":"/order/%s/%s/%s"%(urllib.quote(token), tree.next, tree.current.getNodeValue())}]} transaction.commit() connection.close() db.close() storage.c...
oaraque/sentiment-analysis
pattern/run.py
Python
mit
639
0.001565
import csv import sys import codecs from pattern.en import sentiment input_, output_ = str(sys.argv[1]), str(sys.argv[2]) with codecs.open('/output.txt', 'w') as fout: writer = csv.writer(fout, delimiter='\t') with codecs.open('/input.txt', 'r') as fin: for l_i, line i
n enumerate(fin): line = line.strip() result = sentiment(line)[0] prediction = None if result > 0: prediction = 1 elif result < 0: prediction = -1 elif result == 0: prediction = 0
writer.writerow([l_i, prediction])
dbbhattacharya/kitsune
vendor/packages/sqlalchemy/lib/sqlalchemy/sql/expression.py
Python
bsd-3-clause
152,008
0.003592
# expression.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 """Defines the base components of SQL expression trees. All components are derived...
'except_', 'except_all', 'exists', 'extract', 'func', 'modifier', 'collate', 'insert', 'intersect', 'intersect_all', 'join', 'label', 'literal', 'literal_column', 'not_', 'null', 'or_', 'outparam', 'outerjoin', 'select', 'subquery', 'table', 'text', 'tuple_', 'union', 'union_all', 'update', ] PARSE_AU...
lement. e.g.:: order_by = [desc(table1.mycol)] """ return _UnaryExpression(column, modifier=operators.desc_op) def asc(column): """Return an ascending ``ORDER BY`` clause element. e.g.:: order_by = [asc(table1.mycol)] """ return _UnaryExpression(column, modifier=operators....
AllieDeford/radremedy
remedy/admin_views/reviewview.py
Python
bsd-3-clause
4,932
0.00588
""" reviewview.py Contains administrative views for working with reviews. """ from admin_helpers import * from flask import flash from flask.ext.admin.actions import action from flask.ext.admin.contrib.sqla import ModelView from wtforms import IntegerField, validators import remedy.rad.reviewservice from remedy.rad....
ets up the review form to ensure that the rating field behaves on a 1-5 scale. """ form_class = super(ReviewView, self).scaffold_form() form_class.rating = IntegerField('Provider Rating', validators=[ validators.Optional(), validators.NumberRange(min=1, max=5) ...
validators.Optional(), validators.NumberRange(min=1, max=5) ]) form_class.intake_rating = IntegerField('Intake Rating', validators=[ validators.Optional(), validators.NumberRange(min=1, max=5) ]) return form_class def delete_model(...
jlaine/django-timegraph
timegraph/tests/test_timegraph.py
Python
bsd-2-clause
13,243
0.003248
# -*- coding: utf-8 -*- # # django-timegraph - monitoring graphs for django # Copyright (c) 2011-2012, Wifirst # Copyright (c) 2013, Jeremy Lainé # All rights reserved. # # See AUTHORS file for a full list of contributors. # # Redistribution and use in source and binary forms, with or without modification, # are permit...
') self.assertEquals(format_value(0.00000000000001, 's'), u'10.0 fs') self.assertEquals(format_value(0.0000000000001, 's'), u'100.0 fs') self.assertEquals(format
_value(0.000000000001, 's'), u'1.0 ps') self.assertEquals(format_value(0.00000000001, 's'), u'10.0 ps') self.assertEquals(format_value(0.0000000001, 's'), u'100.0 ps') self.assertEquals(format_value(0.000000001, 's'), u'1.0 ns') self.assertEquals(format_value(0.00000001, 's'), u'10.0 ns'...
voriux/Flexget
flexget/plugins/plugin_change_warn.py
Python
mit
3,389
0.002951
from __future__ import unicode_literals, division, absolute_import import logging import sys import os from flexget import plugin from flexget.event import event log = logging.getLogger('change') found_deprecated = False class ChangeWarn(object): """ Gives warning if user has deprecated / changed config...
_clean = True if 'resolver' in name: require_clean = True if 'filter_torrent_size' in name: require_clean = True if 'filter_nzb_size' in name: require_clean = True if 'module_priority' in name: require_cl...
_clean = True if 'module_manual' in name: require_clean = True if 'output_exec' in name: require_clean = True if 'plugin_adv_exec' in name: require_clean = True if 'output_transmissionrpc' in name: requir...
dbbhattacharya/kitsune
vendor/packages/logilab-common/db.py
Python
bsd-3-clause
2,037
0.003436
# copyright 2003-2010 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-common. # # logilab-common is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as publ...
nalities such as listing existing users or databases, creating database... Get the helper for your database using the `get_adv_func_helper` function. """ __docformat__ = "restructuredtext en" from warnings import warn warn('this module is deprecated, use logilab.database instead', DeprecationWarning, stackle
vel=1) from logilab.database import (get_connection, set_prefered_driver, get_dbapi_compliant_module as _gdcm, get_db_helper as _gdh) def get_dbapi_compliant_module(driver, *args, **kwargs): module = _gdcm(driver, *args, **kwargs) module.adv_func_helper = _gdh(d...
xavierdutreilh/robots.midgar.fr
services/crawler/tests/conftest.py
Python
mit
564
0.001773
from concurrent.futures import ThreadPoolExecutor import grpc import pytest from crawler.services import Library im
port crawler_pb2_grpc @pytest.fixture(name='grpc_client', scope='session', autouse=True) def setup_grpc_client(): server = grpc.server(ThreadPoolExecutor(max_workers=4)) crawler_pb2_grpc.add_LibraryServicer_to_server(Libr
ary(), server) port = server.add_insecure_port('[::]:0') server.start() with grpc.insecure_channel(f'localhost:{port}') as channel: yield crawler_pb2_grpc.LibraryStub(channel) server.stop(0)
josh-perry/NDSHomebrewDownloader
main.py
Python
mit
3,662
0.001638
__author__ = "Josh Perry" import os import shutil import urllib2 import zipfile import rarfile from bs4 import BeautifulSoup dumping_directory = "W:\Plugin repo\dump" def save_file(url, filename): filename = "out/" + filename # Check if we already have it if os.path.isfile(filename + ".zip") or os.pat...
out/ndshb_games"): os.mkdir("out/ndshb_games") for i in range(0, 10): page = page_template.format(i * 10) f = u
rllib2.urlopen(page) soup = BeautifulSoup(f.read(), "html.parser") for link in soup.find_all(class_="jd_download_url"): url = link["href"] filename = url.split('/')[-1].split("?")[0] save_file(base_url + url, "ndshb_games/" + filename) def process_files(directory):...
Rivares/MyBlog
blog/urls.py
Python
apache-2.0
446
0.002242
__author__ = 'Conscience' from django.conf.urls import url from django.contrib import admin from . import views urlpatter
ns = [ url(r'^$', views.post_list, name='post_list'), url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'), url(r'^post/$', views.post_list, name='post_list'), url(r'^post/new/$', views.post_new, name='post_new'), url(r'^post/(
?P<pk>[0-9]+)/edit/$', views.post_edit, name='post_edit'), ]
lcoandrade/DsgTools
gui/CustomWidgets/BasicInterfaceWidgets/buttonPropWidget.py
Python
gpl-2.0
27,350
0.00106
# -*- coding: utf-8 -*- """ /*************************************************************************** DsgTools A QGIS plugin Brazilian Army Cartographic Production Tools ------------------- begin : 2017-08-24 git sha ...
k, v in \ CustomFeatureButton().supportedTools().items()} return tools[self.toolComboBox.currentText()] def setUseColor(self, useColor): """ Sets whether button
will have a custom color set as read from GUI. :param useColor: (bool) whether button should use a custom color palette. """ self.colorCheckBox.setChecked(useColor) def useColor(self): """ Reads whether button will have a custom color from GUI. ...
tradebyte/paci
paci/helpers/__init__.py
Python
mit
37
0
"""
Init file for the paci h
elpers"""
pegasus-isi/pegasus
packages/pegasus-python/src/Pegasus/service/_serialize.py
Python
apache-2.0
1,770
0.00113
import logging from json import JSONEncoder, dumps from flask import current_app, make_response, request __all__ = ( "serialize", "jsonify", ) log = logging.getLogger(__name__) def serialize(rv): log.debug("Serializing output") if rv is None or (isinstance(rv, str) and not len(rv)): log.in...
"pretty-print", current_app.config["JSONIFY_PRETTYPRINT_REGULAR"] ) ) indent = None separators = (",", ":") cls = current_app.json_encoder or JSONEncoder if pretty_print is True and request.is_xhr is False: indent = 2 separators = (", ", ": ") if hasattr(request, ...
YPE" in current_app.config: mime_type = current_app.config["JSONIFY_MIMETYPE"] else: mime_type = "application/json; charset=utf-8" json_str = dumps(data, indent=indent, separators=separators, cls=cls) + "\n" json_str.encode("utf-8") return current_app.response_class(json_str, mimetype=...
zzzzrrr/openmelee
ai/ai.py
Python
gpl-3.0
2,647
0.005667
# # Copyright (c) 2009 Mason Green & Tom Novelli # # This file is part of OpenMelee. # # OpenMelee 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 # any later version. # # O...
if angle > 0.05 and angle < 6.233: if angle >= 0.05 and angle < pi: self.ship.turn_right() else: self.
ship.turn_left() else: self.ship.body.angular_velocity = 0.0 if self.range > 5.0: self.ship.thrust() def avoid(self, st): k = self.ship.body.get_local_point(st) angle = atan2(k.x, k.y) + pi t = self.ship.body.linear_velocity.cross(st) ...
thiagopena/PySIGNFe
pysignfe/nfe/manual_300/__init__.py
Python
lgpl-2.1
1,984
0.017713
# -*- coding: utf-8 -*- ESQUEMA_ATUAL = u'pl_005f' # # Envelopes SOAP # from .soap_100 import SOAPEnvio as SOAPEnvio_110 from .soap_100 import SOAPRetorno as SOAPRetorno_110 # # Emissão de NF-e # from .nfe_110 import NFe as NFe_110 from .nfe_110 import NFRef as NFRef_110 from .nfe_110 import Det as Det_110 from .nf...
e_107 import
CancNFe as CancNFe_107 from .cancnfe_107 import RetCancNFe as RetCancNFe_107 from .cancnfe_107 import ProcCancNFe as ProcCancNFe_107 # # Inutilização de NF-e # from .inutnfe_107 import InutNFe as InutNFe_107 from .inutnfe_107 import RetInutNFe as RetInutNFe_107 from .inutnfe_107 import ProcInutNFe as ProcInutNFe_107 ...
Azure/azure-sdk-for-python
sdk/keyvault/azure-keyvault-certificates/samples/import_certificate_async.py
Python
mit
3,725
0.005101
# ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ import asyncio import os from azure.identity.aio import DefaultAzureCredential from azure.keyvault.certificates import CertificateContentType, CertificatePolicy, WellKno...
/github.com/Azure/azure-sdk-for-python/tree/main/sdk/keyvault/azure-keyvault-admin
istration#authenticate-the-client) # # 4. A PFX certificate on your machine. Set an environment variable, PFX_CERT_PATH, with the path to this certificate. # # 5. A PEM-formatted certificate on your machine. Set an environment variable, PEM_CERT_PATH, with the path to this # certificate. # # ------------------------...
jos4uke/getSeqFlankBlatHit
lib/python2.7/site-packages/pybedtools/test/tfuncs.py
Python
gpl-2.0
462
0.004329
import pybedtools import os testdir = os.path.dirname(__file__) test_tempdir = os.path.join(os.path.abspath(testdir), 'tmp') unwriteable = os.path.join(os.path.abspath(testdir), 'unwriteable
') def setup(): if not os.path.exists(test_tempdir): os.system('mkdir -p %s' % test_tempdir) pybedtools.set_tempdir(test_tempdir) def teardown():
if os.path.exists(test_tempdir): os.system('rm -r %s' % test_tempdir) pybedtools.cleanup()
djorda9/Simulated-Conversations
vagrant/simcon/templatetags/generatelink_extras.py
Python
mit
376
0.007979
from djang
o import template register = template.Library() # Used to create the generated link url for the templates @register.filter def get_link_filter(obj, arg): base = obj.get_link(arg) return base # Used to create the base url of the generated link for the templates @register.filter def get_base_link_filter(obj): ...
k() return base
rcbops/glance-buildpackage
glance/registry/db/migration.py
Python
apache-2.0
3,992
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/...
) sql_connection = conf.sql_connection try: return versioning_api.db_version(sql_connection, repo_path) except versioning_exceptions.DatabaseNotControlledError, e: msg = (_("database '%(sql_connection)s' is not under " "migration control") % locals()) raise
exception.DatabaseMigrationError(msg) def upgrade(conf, version=None): """ Upgrade the database's current migration level :param conf: conf dict :param version: version to upgrade (defaults to latest) :retval version number """ db_version(conf) # Ensure db is under migration control ...
LarsBV/kate_plugin_template
my_plugin.py
Python
bsd-2-clause
1,396
0.012894
# -*- coding: utf-8 -*- # Author: <Your name> # License see LICENSE from PyKDE4.kdecore import i18n from PyKDE4.kdeui import KAction, KIcon from PyQt4.QtCore import QObject from PyQt4.QtGui import QMenu from libkatepate.errors import showOk, showError import kate class MyPlugin(QObject): def __init__(self): ...
on[self.act.objectName()]) # self.act.setCheckable(True) # self.act.setChecked(False) # self.act
.changed.connect(self.onActionChange) # self.act.toggled.connect(self.toggle) # kate.mainInterfaceWindow().viewChanged.connect(self.onViewChanged) def onActionChange(self): kate.configuration[self.sender().objectName()] = self.sender().shortcut().toString() kate.configuration.save() ...
saltstack/salt
salt/utils/preseed.py
Python
apache-2.0
2,707
0.002586
""" Utilities for managing Debian preseed .. versionadded:: 2015.8.0 """ import shlex import salt.utils.files import salt.utils.stringutils import salt.utils.yaml def mksls(src, dst=None): """ Convert a preseed file to an SLS file """ ps_opts = {} with salt.utils.files.f
open(src, "r") as fh_: for line in fh_: line = salt.utils.stringutils.to_u
nicode(line) if line.startswith("#"): continue if not line.strip(): continue comps = shlex.split(line) if comps[0] not in ps_opts.keys(): ps_opts[comps[0]] = {} cmds = comps[1].split("/") pointer = ...