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
saltstack/salt
salt/modules/mine.py
Python
apache-2.0
19,294
0.00114
""" The function cache system allows for data to be stored on the master so it can be easily read by other minions """ import logging import time import traceback import salt.channel.client import salt.crypt import salt.payload import salt.transport import salt.utils.args import salt.utils.dictupdate import salt.util...
This feature can be used when updating the mine for functions that require a refresh at different intervals than the rest of the functions specified under `mine_functions` in the minion/ma
ster config or pillar. A potential use would be together with the `scheduler`, for example: .. code-block:: yaml schedule: lldp_mine_update: function: mine.update kwargs: mine_functions: net.lldp: [] ...
cloudify-cosmo/tosca-vcloud-plugin
system_tests/vcloud_handler.py
Python
apache-2.0
5,843
0.000342
# Copyright (c) 2015-2020 Cloudify Platform Ltd. 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 b...
ST_VDC) if status: wait_for_task(vca, task) else: raise RuntimeError("Can't delete test VDC") if vca: task = vca.create_vdc(T
EST_VDC) wait_for_task(vca, task) else: raise RuntimeError("Can't create test VDC") handler = VcloudHandler def login(env): vca = vcloudair.VCA( host=env['vcloud_url'], username=env['vcloud_username'], service_type=env['vcloud_service_type'], versi...
solus-project/ypkg
ypkg2/sources.py
Python
gpl-3.0
12,925
0
#!/bin/true # -*- coding: utf-8 -*- # # This file is part of ypkg2 # # Copyright 2015-2017 Ikey Doherty <ikey@solus-project.com> # # 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...
xdigest() if hash != self.hash: console_ui.emit_error("Source", "Incorrect hash for {}". format(self.filename)) print("Found hash : {}".format(hash)) print("Expected hash : {}".format(self.hash)) return False return Tru...
diropt = "-d" if targe
jigarkb/CTCI
LeetCode/036-M-ValidSudoku.py
Python
mit
1,045
0.004785
# Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules (http://sudoku.com.au/TheRules.aspx). # # The Sudoku board could be partially filled, where empty cells are filled with the character '.'. # # Note: # A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells nee...
] :rtype: bool """ row = {} column = {} box = {} for i in range(len(board)): for j in range(len(board[i])): if board[i][j] != '.': num = int(board[i][j]) if row.get((i, num)) or column.get((j, num)) or bo...
num] = box[i/3, j/3, num] = True return True # Note: # We maintain 3 hash maps for rows(i), column(j) and box((i/3,j,3)) and return false if anyone has value true
Rogentos/rogentos-anaconda
timezone.py
Python
gpl-2.0
2,650
0.004151
# # timezone.py - timezone install data # # Copyright (C) 2001 Red Hat, Inc. All rights reserved. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at yo...
nda_log import PROGRAM_LOG_FILE import log
ging log = logging.getLogger("anaconda") class Timezone: def writeKS(self, f): f.write("timezone") if self.utc: f.write(" --utc") f.write(" %s\n" % self.tz) def write(self, instPath): fromFile = "/usr/share/zoneinfo/" + self.tz tzfile = instPath + "/etc/loc...
lowfatcomputing/amforth
core/devices/atmega8535/device.py
Python
gpl-2.0
4,349
0.07404
# Partname: ATmega8535 # generated automatically, do not edit MCUREGS = { 'ADMUX': '&39', 'ADMUX_REFS': '$C0', 'ADMUX_ADLAR': '$20', 'ADMUX_MUX': '$1F', 'ADCSRA': '&38', 'ADCSRA_ADEN': '$80', 'ADCSRA_ADSC': '$40', 'ADCSRA_ADATE': '$20', 'ADCSRA_ADIF': '$10', 'ADCSRA_ADIE': '$08', 'ADCSRA_A...
UCSRA_RXC': '$80', 'UCSRA_TXC': '$40', 'UCSRA_UDRE': '$20', 'UCSRA_FE': '$10', 'UCSRA_DOR': '$08', 'UCSRA_UPE': '$04', 'UCSRA_U2X': '$02', 'UCSRA_MPCM': '$01
', 'UCSRB': '&42', 'UCSRB_RXCIE': '$80', 'UCSRB_TXCIE': '$40', 'UCSRB_UDRIE': '$20', 'UCSRB_RXEN': '$10', 'UCSRB_TXEN': '$08', 'UCSRB_UCSZ2': '$04', 'UCSRB_RXB8': '$02', 'UCSRB_TXB8': '$01', 'UCSRC': '&64', 'UCSRC_URSEL': '$80', 'UCSRC_UMSEL': '$40', 'UCSRC_UPM': '$30', 'UCSRC_USBS...
gpostelnicu/fin_data
fin_data/stat/correlation/random_matrix.py
Python
mit
2,722
0.003306
import numpy as np def empirical_rmt(input_returns): """ Empirical RMT computes an empirical correlation matrix and then filters using Random Matrix Theory. THIS FUNCTION TAKES AS INPUT A CLEAN NUMPY ARRAY (please remove n/a first !) To compute a correlation matrix, and then apply Wishart RMT, it is ...
ndex_eig] * cur_vect * np.transpose(cur_vect) # print(correlation_matrix) # Fill the remaining eigen-vectors for index_eig in range(correlation_matrix.shape[0]): corre
lation_matrix[index_eig, index_eig] = 1. return correlation_matrix
arborworkflows/ProjectManager
tangelo/projmgr.py
Python
apache-2.0
7,996
0.009005
import tangelo import pymongo import bson.json_util from ArborFileManagerAPI import ArborFileManager api = ArborFileManager() api.initDatabaseConnection() @tangelo.restful def get(*pargs, **query_args): if len(pargs) == 0: return tangelo.HTTPStatusCode(400, "Missing resource type") resource_type = pa...
resource type '%s' - allowed types are: project") if resource == "project": if datasetname is None: api.newProject(projname) else: if filename is None: return tangelo.HTTPStatusCode(400, "Missing argument 'filename'") if filetype is None: ...
ssing argument 'filetype'") if data is None: return tangelo.HTTPStatusCode(400, "Missing argument 'data'") if datasetname is None: return tangelo.HTTPStatusCode(400, "Missing argument 'datasetname'") # user wants to upload a tree or a character matr...
ypkang/keras
keras/constraints.py
Python
mit
1,069
0.012161
from __future__ import absolute_import import theano import theano.tensor as T import numpy as np class Constraint(object): def __call__(self, p): return p def get_config(self): return {"name":self.__class__.__name__} class MaxNorm(Constraint): def __init__(self, m=2): self.m = m ...
"m":self.m} class NonNeg(Constraint): def __call__(self, p): p *= T.ge(p, 0) return p class UnitNorm(Constraint): def __call__(self, p): return p / T.sqrt(T.sum(p**2, axis=-1, keepdims=True)) identity = Constraint maxnorm = MaxNorm nonneg = NonNeg unitnorm = UnitNorm from .uti...
return get_from_module(identifier, globals(), 'constraint', instantiate=True, kwargs=kwargs)
google-research/google-research
tft/script_hyperparam_opt.py
Python
apache-2.0
7,859
0.006489
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # 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 applicab...
e(data_formatter))) default_keras_session = tf.keras.backend.get_session() if use_gpu: tf_config = utils.get_default_tensorflow_config(tf_device="gpu", gpu_id=0) else: tf_config = utils.get_default_tensorflow_config(tf_device="cpu") print("### Running hyperparameter optimization for {} ###".format(e...
data(raw_data) train_samples, valid_samples = data_formatter.get_num_samples_for_calibration( ) # Sets up default params fixed_params = data_formatter.get_experiment_params() param_ranges = ModelClass.get_hyperparm_choices() fixed_params["model_folder"] = model_folder print("*** Loading hyperparm manage...
sseering/ytdlWrapper
urlfind.py
Python
unlicense
1,923
0.00208
#!/usr/bin/env python3 import re import os import os.path import sys def main(): already_found = [] url_matcher = re.compile(r'(https?://(www.)?)?((youtu.be|youtube.(com|de|ch|at))/watch\?v=[-_0-9A-Za-z]{11}|youtu.be/[-_0-9A-Za-z]{11})') backup_matcher = re.compile(r'youtu') argc = len(sys.argv) ...
int('found {0} unmatched candidates and created {1} URL files'.format(num_backup_candidates, num_found)) print('done')
if __name__ == "__main__": main()
jcfr/mystic
examples/cg_rosenbrock.py
Python
bsd-3-clause
1,478
0.023004
#!/usr/bin/env python # # Author: Mike McKerns (mmckerns @caltech and @uqfoundation) # Copyright (c) 1997-2015 California Institute of Technology. # License: 3-clause BSD. The full license text is available at: # - http://trac.mystic.cacr.caltech.edu/project/mystic/browser/mystic/LI
CENSE """ See test_rosenbrock.py. This one uses Scipy's CG (Polak-Ribiere) plus viz via matplotlib cg works well on this problem. """ import pylab from test_rosenbrock import * from numpy import log from mystic._scipyoptimize import fmin_cg import numpy from mystic.tools import getch def show(): import
pylab, Image pylab.savefig('cg_rosenbrock_out',dpi=72) im = Image.open('cg_rosenbrock_out.png') im.show() return def draw_contour(): import numpy x, y = numpy.mgrid[-1:2.1:0.02,-0.1:2.1:0.02] c = 0*x s,t = x.shape for i in range(s): for j in range(t): xx,yy = ...
mcgill-robotics/compsys
scripts/bag/bag/__main__.py
Python
mit
1,110
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """McGill Robotics ROS Bagger. This tool can: 1. Record the specified topics into 15 second bags to the specified directory. 2. Merge previously recorded bags from the specified directory. By default, all the topics defined in your project's 'topics' f...
il import Parser, TopicList __version__ = "1.3.1" def main(): """Runs the CLI.""" try: topics_path = os.environ["TOPICS_PATH"] except KeyError: print("E: TOPICS_PATH environment variable not set") sys.exit(2) topics = TopicList(topics_path) args = Parser(topics, __doc__,...
n()
swenger/glitter
glitter/contexts/glx.py
Python
mit
1,256
0.002389
"""GLX context creation and management. Depends on the binary glxcontext module. @todo: Include glxcontext in distribution as an optional module.
@author: Stephan Wenger @date: 2012-08-28 """ try: from glxcontext import GLXContext as _GLXContext from glitter.contexts.context import Context from glitter.contexts.contextmanager import context_manager class GLXContext(_GLXContext, Context): """Offscreen GLX cont
ext.""" def __init__(self, **kwargs): _GLXContext.__init__(self, **kwargs) Context.__init__(self) # TODO the lines below should not be necessary, or should at least be performed automatically by context_manager # XXX I would have expected it worked without these...
lferr/charm
charm/schemes/ibenc/ibenc_ckrs09.py
Python
lgpl-3.0
4,080
0.017157
''' Jan Camenisch, Markulf Kohlweiss, Alfredo Rial, and Caroline Sheedy (Pairing-based) | From: "Blind and Anonymous Identity-Based Encryption and Authorised Private Searches on Public Key Encrypted Data". | Published in: PKC 2009 | Available from: http://www.iacr.org/archive/pkc2009/54430202/54430202.pdf | Notes: s...
.hash(ID) hashID1 = mpk['g_l'][0] * dotprod2(range(1,mpk['n']), lam_func, mpk['g_l'], hID) c = {} c_pr = (mpk['omega'] ** s) * msg c[0] = hashID1 ** s c[1] = mpk['v1'] ** (s - s1) c[2] = mpk['v2'] ** s1 c[3] = mpk['v3'] **
(s - s2) c[4] = mpk['v4'] ** s2 return {'c':c, 'c_prime':c_pr } def decrypt(self, mpk, sk, ct): c, d = ct['c'], sk['d'] msg = ct['c_prime'] * pair(c[0], d[0]) * pair(c[1], d[1]) * pair(c[2], d[2]) * pair(c[3], d[3]) * pair(c[4], d[4]) return msg de...
OpenTherapeutics/transcode
tests/test_config.py
Python
mit
1,153
0.005204
import pytest import transcode.conf import transcode.render def my_callback(source, *args, **kws): pass CFG_GOOD = { 'TEXT': {'transcoder': my_callback}, } CFG_BAD = { 'MARK': {'transcoder': 42} } class TestConf: def test_default_config(self): for fmt,
expected in ( (transcode.conf.HTML_FORMAT, transcode.render.render_html), (transcode.conf.SIMPLE_TEXT_FORMAT, transcode.render.render_simple), (transcode.conf.MARKDOWN_FORMAT, transcode.render.render_markdown), (transcode.conf.RST_FORMAT, transcode.render.render_restruct...
handler, args, kwargs = transcode.conf.get_transcoder('TEXT', CFG_GOOD) assert handler == my_callback assert args == () assert kwargs == {} def test_config_with_bad_callback(self): try: transcode.conf.load_config(CFG_BAD) except TypeError: asse...
pgmmpk/pypatgen
patgen/tests/test_dictionary.py
Python
mit
1,321
0.009084
''' Created on Mar 7, 2016 @author: mike ''' from patgen.dictionary import parse_dictionary_word, format_dictionary_word,\ Dictionary import unittest from patgen.margins import Margins class TestDictionary(unittest.TestCase): def
test_parse(self): text, hyphens, missed, false, weights = parse_dictionary_word('hy-phe-2n-a-tion') self.assertEqual(text, 'hyphenation') self.assertEqual(hyphens, {2, 5, 6, 7}) self.assertEqual(missed, set()) self.assertEqual(
false, set()) self.assertEqual(weights, {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 2, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1, 11: 1}) def test_format(self): s = format_dictionary_word('hyphenation', {2, 5, 6, 7}) self.assertEqual(s, 'hy-phe-n-a-tion') def test_format_weights(self): ...
eltonkevani/tempest_el_env
tempest/api/orchestration/stacks/test_server_cfn_init.py
Python
apache-2.0
6,500
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # 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...
- {Ref: SmokeKeys} - ' ' - AWSSecretKey= - Fn::GetAtt: [SmokeKeys, SecretAccessKey] - ' ' mode: '000400' owner: root group: root Properties: image: {...
key_name: {Ref: key_name} security_groups: - {Ref: SmokeSecurityGroup} networks: - uuid: {Ref: network} user_data: Fn::Base64: Fn::Join: - '' - - |- #!/bin/bash -v /opt/aws/bin/cfn-init - |- ...
sebdah/markdown-docs
markdowndocs/__init__.py
Python
apache-2.0
4,970
0.004024
#!/usr/bin/env python # -*- coding: utf-8 -*- """ markdown-docs markdown documentation reader APACHE LICENSE 2.0 Copyright 2013 Sebastian Dahlgren 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 ...
fault=False, help='Generate HTML') parser.add_argument('serve', nargs='?', default=True, help='Start a local web ser
ver to serve the documentation') args = parser.parse_args() if args.version: print_version() sys.exit(0) if args.directory: source_dir = os.path.expandvars(os.path.expanduser(args.directory)) if not os.path.exists(source_dir): logger.error('{} does not exist'.f...
kvar/ansible
lib/ansible/modules/storage/purestorage/_purefa_facts.py
Python
gpl-3.0
32,021
0.000999
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2018, Simon Dodsley (simon@purestorage.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.1',...
nt: - purestorage.fa ''' EXAMPLES = r''' - name: collect default set of facts purefa_facts: fa_url:
10.10.10.2 api_token: e31060a7-21fc-e277-6240-25983c6c4592 - name: collect configuration and capacity facts purefa_facts: gather_subset: - config - capacity fa_url: 10.10.10.2 api_token: e31060a7-21fc-e277-6240-25983c6c4592 - name: collect all facts purefa_facts: gather_subset: ...
silly-wacky-3-town-toon/SOURCE-COD
toontown/safezone/SafeZoneLoader.py
Python
apache-2.0
9,369
0.001814
from panda3d.core import * from panda3d.direct import * from toontown.toonbase.ToonBaseGlobal import * from toontown.distributed.ToontownMsgTypes import * from toontown.hood import ZoneUtil from direct.directnotify import DirectNotifyGlobal from toontown.hood import Place from direct.showbase import DirectObject from d...
', 'toonInterior']), State.State('playground', self.enterPlayground, self.exitPlayground, ['quietZone']), State.State('toonInterior', self.enterToonInterior, self.exitToonInterior, ['quietZone']), State.State('quietZone', self.enterQuietZone, self.exitQuietZone, ['playground', 'toonInterior']...
nal, self.exitFinal, ['start'])], 'start', 'final') self.placeDoneEvent = 'placeDone' self.place = None self.playgroundClass = None return def load(self): self.music = base.loadMusic(self.musicFile) self.activityMusic = base.loadMusic(self.activityMusicFile) ...
cloud9ers/gurumate
environment/share/doc/ipython/examples/parallel/interengine/bintree.py
Python
lgpl-3.0
7,132
0.008833
""" BinaryTree inter-engine communication class use from bintree_script.py Provides parallel [all]reduce functionality """ import cPickle as pickle import re import socket import uuid import zmq from IPython.parallel.util import disambiguate_url #-----------------------------------------------------------------...
parent`, default: None. >>> tree = bintree(range(7)) >>> tree {0: None, 1: 0,
2: 1, 3: 1, 4: 0, 5: 4, 6: 4} >>> print_bintree(tree) 0 1 2 3 4 5 6 """ parents = {} n = len(ids) if n == 0: return parents root = ids[0] parents[root] = parent if len(ids) == 1: return parents else: ids = ids[1:...
progdupeupl/pdp_website
doc/conf.py
Python
agpl-3.0
7,983
0.00714
# -*- coding: utf-8 -*- # # Progdupeupl documentation build configuration file, created by # sphinx-quickstart on Sat Dec 07 17:25:18 2013. # # T
his file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated
file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path....
amdeb/amdeb-integrator
amdeb_integrator/shared/model_names.py
Python
gpl-3.0
549
0
# -*- coding: utf-8 -*- """ contains definition of models names """ PRODUCT_TEMPLATE_TABLE = 'product.template' PRODUCT_PRODUCT_TABLE = 'product.product' PRODUCT_TEMPLATE_ID_FIELD = 'product_tmpl_id' PRODUCT_VIRTUAL_AVAILABLE_FIELD = 'virtual_available' PRODUCT_OPERA
TION_TABLE = 'amdeb.product.operation' MODEL_NAME_FIELD = 'model_name' RECORD_ID_FIELD
= 'record_id' TEMPLATE_ID_FIELD = 'template_id' OPERATION_TYPE_FIELD = 'operation_type' WRITE_FIELD_NAMES_FIELD = 'write_field_names' FIELD_NAME_DELIMITER = ', ' TIMESTAMP_FIELD = 'timestamp'
bedekelly/pysh
setup.py
Python
gpl-2.0
340
0
#
!/usr/bin/python3 from distutils.core import setup setup(name='PySh', version='0.0.1', py_modules=['pysh'], description="A tiny interface to intu
itively access shell commands.", author="Bede Kelly", author_email="bedekelly97@gmail.com", url="https://github.com/bedekelly/pysh", provides=['pysh'])
UWCS/uwcs-website
uwcs_website/search/__init__.py
Python
agpl-3.0
1,310
0.003817
registry = {} def register(model, fields, order='pk', filter=False, results=5): registry[str(model)] = (model, fields, results, order, filter) class LoopBreak(Exception): pass def search_for_string(search_string): search_string = search_string.lower() matches = [] for key in registry: model, ...
ass if callable(searchee): searchee = searchee() if search_string in searchee.lower(): matches.append(object) coun
ter += 1 if counter >= results: raise LoopBreak() except LoopBreak: pass return matches
code4futuredotorg/reeborg_tw
src/python/editor.py
Python
agpl-3.0
145
0
from
browser import window from preprocess import transform from reeborg_en import * # NOQA src
= transform(window.editor.getValue()) exec(src)
coderbone/SickRage-alt
sickchill/views/api/webapi.py
Python
gpl-3.0
118,111
0.002879
# coding=utf-8 # Author: Dennis Lutter <lad1337@gmail.com> # Author: Jonathon Saine <thezoggy@gmail.com> # URL: h
ttps://sickchill.github.io # # This file is part of SickChill. # # SickChill is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either
version 3 of the License, or # (at your option) any later version. # # SickChill 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 shoul...
o-kei/design-computing-aij
ch4_1/nearest_liner.py
Python
mit
491
0.002037
from math import sqrt def sq_dist(p, q): return((p[0] - q[0])**2 + (p[1] - q[1])**2) def linear_search(points, query): sqd = float("inf") for point in points:
d = sq_dist(point, query) if d < sqd: nearest = point sqd = d return(nearest, sqd) point_list = [(2, 3), (5, 4), (9, 6), (4, 7), (8, 1), (7, 2)] n = linear_search(point_list, (9, 2)) print('nearest:', n[0], 'dist:', sqrt(n
[1])) # nearest: (8, 1) dist: 1.4142135623730951
Learningtribes/edx-platform
openedx/core/lib/block_structure/tests/test_manager.py
Python
agpl-3.0
6,900
0.002464
""" Tests for manager.py """ from nose.plugins.attrib import attr from unittest import TestCase from ..block_structure import BlockStructureBlockData from ..exceptions import UsageKeyNotInBlockStructure from ..manager import BlockStructureManager from ..transformers import BlockStructureTransformers from .helpers impo...
Asserts the block
structure was transformed. """ cls._assert_block_values(block_structure, cls.transform_data_key) @classmethod def _set_block_values(cls, block_structure, data_key): """ Sets a value for each block in the given structure, using the given data key. """ for ...
cutoffthetop/zeit.content.image
src/zeit/content/image/variant.py
Python
bsd-3-clause
6,899
0.00029
import UserDict import copy import grokcore.component as grok import sys import zeit.cms.content.sources import zeit.content.image.interfaces import zeit.edit.body import zope.schema class Variants(grok.Adapter, UserDict.DictMixin): grok.context(zeit.content.image.interfaces.IImageGroup) grok.implements(zeit...
urn float(xratio) / float(yratio) @property def max_width(self): if self.max_size is None: return sys.maxint width, height =
self.max_size.split('x') return int(width) @property def max_height(self): if self.max_size is None: return sys.maxint width, height = self.max_size.split('x') return int(height) @property def is_default(self): return self.id == self.DEFAULT_NAME ...
epitron/youtube-dl
youtube_dl/extractor/naver.py
Python
unlicense
5,293
0.001171
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor from ..utils import ( ExtractorError, int_or_none, update_url_query, ) class NaverIE(InfoExtractor): _VALID_URL = r'https?://(?:m\.)?tv(?:cast)?\.naver\.com/v/(?P<id>\d+)' _TESTS = [{ 'url': 'http:/...
'abr': int_or_none(bitrate.get('audio')), 'filesize': int_or_none(stream.get('size')), 'protocol': 'm3u8_native' if stream_type == 'HLS' else None, })
extract_formats(video_data.get('videos', {}).get('list', []), 'H264') for stream_set in video_data.get('streams', []): query = {} for param in stream_set.get('keys', []): query[param['name']] = param['value'] stream_type = stream_set.get('type') vi...
ExsonumChain/ProtoServer
voks/settings.py
Python
mit
3,423
0.001753
""" Django settings for voks project. Generated by 'django-admin startproject' using Django 1.11. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os # B...
duction! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1'] # Application definition INSTALLED_APPS = [ 'blockchain.apps.BlockchainConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.
sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'graphene_django' ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ # 'rest_framework.permissions.IsAdminUser', ], # 'PAGE_SIZE': 2 } MIDDLEWARE = [ 'django.middleware.security.SecurityMidd...
Kiganshee/Flip-Sign
TransitionFunctions.py
Python
cc0-1.0
14,898
0.006511
from PIL import Image from PIL import ImageDraw from PIL import ImageChops import random def message_transition(func): func.is_message_transition = True func.is_display_transition = False def display_transition(func): func.is_message_transition = False func.is_display_transition = True def FlashStars...
display state :param desired_state: a PIL image object representing the eventual desired display state :return: a list of PIL image objects representing a transition of display states to get from current to desired """ assert isinstance(current_state, Image.Image) assert isinstance(desired_state, Im...
-1 desired_state_y_val = current_state.size[1] # while the desired image has not reached the top while desired_state_y_val >= 0: # initialize next image next = Image.new("1", current_state.size, color=0) # paste current state at its y valute next.paste(current_state, (0, cur...
miooim/project_hours
src/config.py
Python
mit
1,076
0.009294
from tornado.options import define, options define('mongodb', default='localhost:27017', help='mongodb host name or ip address +port', type=str) define('mongod_name', default='project_hours', help='Project hours database name', type=str) define('auth_db', default='project_hours', help='authentication database', type=...
ive directory password", type=str) define("active_directory_search_def", default='ou=Crow,dc=Crow,dc=local', help="active directory search
definition", type=str) #user cookie define("auth_cookie_name", default='project_hours', help="name of the cookie to use for authentication", type=str)
googleapis/python-appengine-admin
samples/generated_samples/appengine_v1_generated_instances_delete_instance_sync.py
Python
apache-2.0
1,530
0.000654
# -*- 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...
r express or implied. # See the License for the specific
language governing permissions and # limitations under the License. # # Generated code. DO NOT EDIT! # # Snippet for DeleteInstance # 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...
evgenyz/meson
modules/gnome.py
Python
apache-2.0
10,923
0.003662
# Copyright 2015 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 ...
if deps: for dep in deps:
girdir = dep.held_object.get_variable ("girdir") if girdir: typelib_cmd += ["--includedir=%s" % girdir] kwargs['output'] = typelib_output kwargs['command'] = typelib_cmd # Note that this can't be libdir, because e.g. on Debian it points to # l...
smurfix/HomEvenT
modules/bool.py
Python
gpl-3.0
2,922
0.044781
# -*- coding: utf-8 -*- ## ## Copyright © 2007, Matthias Urlichs <matthias@urlichs.de> ## ## This program is free software: you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your...
r(b) class GreaterCheck(Check): name="greater" doc="check if the first argument is larger." de
f check(self,*args): assert len(args)==2,u"The ‹greater› check requires two arguments" a,b = args if a is None or b is None: return False try: return float(a) > float(b) except (ValueError,TypeError): return str(a) > str(b) class BoolModule(Module): """\ This module implements basic boolean conditio...
gioGats/GeneticText
generation_functions.py
Python
gpl-3.0
6,538
0.002906
from ga_utils import * from random import randint, gauss, random, seed import unittest def generate_xover(population, midpoint_dist='uniform'): """ Generates a new value using crossover mutation :param population: sorted iterable of current population :param midpoint_dist: 'uniform' or 'normal' distr...
'uniform': midpoint = randint(0, len(population[0])) elif midpoint_dist is 'normal': midpoint = max(min(int(gauss(0.5 * len(population[0]), 0.5 * len(population[0]))), len(population[0])), 0) else: raise ValueError('Midpoint distribution must be uniform or normal') mom, dad = ranked...
_lmutate(population, locate_dist='uniform'): """ Generates a new value using location mutation :param population: sorted iterable of current population :param locate_dist: 'uniform' or 'normal' distributions for selecting locations :return: new value """ if locate_dist is 'uniform': ...
ytsapras/robonet_site
scripts/rome_fields_dict.py
Python
gpl-2.0
1,964
0.071792
field_dict={'ROME-FIELD-01':[ 267.835895375 , -30.0608178195 , '17:51:20.6149','-30:03:38.9442' ], 'ROME-FIELD-02':[ 269.636745458 , -27.9782661111 , '17:58:32.8189','-27:58:41.758' ], 'ROME-FIELD-03':[ 268.000049542 , -28.8195573333 , '17:52:00.0119','-28:49:10.4064' ], 'ROME-FIE...
3' ], 'ROME-FIELD-16':[ 270.074981708 , -28.5375585833 , '18:00:17.9956','-28:32:15.2109' ], 'ROME-FIELD-17':[ 270.81 , -28.0978333333 , '18:03:14.4','-28:05:52.2' ], 'ROME-FIELD-18':[ 270.290886667 , -27.9986032778 , '18:01:09.8128','-27:5
9:54.9718' ], 'ROME-FIELD-19':[ 270.312763708 , -29.0084241944 , '18:01:15.0633','-29:00:30.3271' ], 'ROME-FIELD-20':[ 270.83674125 , -28.8431573889 , '18:03:20.8179','-28:50:35.3666' ]}
synteny/AuroraBot
sessioncontroller/settings.py
Python
mit
256
0
import os
TELEGRAM_TOKEN = os.environ['TELEGRAM_TOKEN'] DATABASE = { 'HOST': os.getenv('DB_PORT_3306_TCP_ADDR', 'localhost'), 'USER': os.getenv('DB_MYSQL_USER', 'root'), 'PASSWORD': os.getenv('DB_MYSQL_PASSWORD', ''), 'NAME':
'aurora', }
JavierGarciaD/banking
definitions.py
Python
mit
279
0
import os
def root_dir(): """ :return: root folder path """ return os.path.dirname(os.path.abspath(__file__)) def db_path(db_name): i
f db_name == 'forecast': return os.path.join(root_dir(), "data", "forecast.sqlite") else: return None
f-andrey/sprutio
app/modules/webdav/actions/files/read.py
Python
gpl-3.0
4,120
0.002205
from core import FM import traceback class ReadFile(FM.BaseAction): def __init__(self, request, path, session, **kwargs): super(ReadFile, self).__init__(request=request, **kwargs) self.path = path self.session = session def run(self): request = self.get_rpc_request() ...
r[key]) elif isinstance(answer[key], int): decoded[unicode_key] = answer[key] elif isinstance(answer[key], float): decoded[unicode_key] = answer[key] elif isinstance(answer[key], str): decoded[unicode_key] = answer[key] elif...
code_key] = answer[key].decode("utf-8") except UnicodeDecodeError: # Костыль для кракозябр decoded[unicode_key] = answer[key].decode("ISO-8859-1") return decoded def byte_to_unicode_list(self, answer): decoded = [] for item in answer: ...
metabolite-atlas/metatlas
metatlas/tools/formula_generator.py
Python
bsd-3-clause
4,342
0.066099
from __future__ import absolute_import from __future__ import print_function from copy import deepcopy from six.moves import range def get_formulae(mass,tol=5,charge=0,tol_type='ppm',max_tests=1e7, min_h=0,max_h=200, min_c=0,max_c=200, min_n=0,max_n=6, min_o=0,max_o=20, min_p=0,max_p=4, min_s=0,max_s=4, min_na=0...
nd('%s%d'%(element['symbol'],element['guess'])) formulae.append((hit[0]
,''.join(formula))) return formulae def calc_mass(elements): """ ? """ sum = 0.0 for el in elements: sum += el['mass'] * el['guess'] return sum def do_calculations(mass,tol,elements,max_tests): """ ? """ limit_low = mass - tol limit_high = mass + tol test_counter = 0 hits = [] for n8 in range(ele...
ninjaotoko/djblog
djblog/forms.py
Python
bsd-3-clause
1,755
0.011966
# *-* coding=utf-8 *-* from django.conf import settings from django import forms from django.utils.translation import ugettext_lazy as _ from django.template.defaultfilters import slugify from django.forms.widgets import flatatt from django.utils.encoding import smart_unico
de, force_unicode from django.template.loader import render_to_string from django.utils.html import escape, conditional_escape from django.utils.safestring
import mark_safe from djblog.models import Post, Category class PreviewContentWidget(forms.Textarea): def render(self, name, value, attrs=None): if value is None: value = '' value = smart_unicode(value) final_attrs = self.build_attrs(attrs, name=name) context = { ...
sketchturnerr/WaifuSim-backend
resources/middlewares/body_checker.py
Python
cc0-1.0
1,251
0.003457
import json import sys import falcon def body_checker(required_params=(), documentation_link=None): def hook(req, resp, resource, params): if req.content_length in (None, 0, ): raise falcon.HTTPBadRequest('Bad request', 'В запросе деолжны быть парамет...
s: if key not in body: raise falcon.HTTPBadRequest('Bad request', description
% key, href=documentation_link) params[key] = body[key] req.context['parsed_body'] = params return hook
ping/instagram_private_api
instagram_web_api/__init__.py
Python
mit
337
0.002967
# flake8: noqa from .client import Client from .compatpatch import ClientCompatPatch from .errors import (
ClientError, ClientLoginError, ClientCookieExpiredError, ClientConnectionError, ClientForbiddenError, ClientThrottledError,ClientBadRequestError, ) from .common
import ClientDeprecationWarning __version__ = '1.6.0'
wuan/bo-server
tests/test_influxdb.py
Python
apache-2.0
989
0
import datetime import unittest from assertpy import assert_that from blitzortung_server.influxdb import DataPoint class TestAS(unittest.TestCase): def testEmptyDataPoint(self): timestamp = datetime.datetime.utcnow() data_point = DataPoint("meas", time=timestamp) json_repr = data_point....
data_point = DataPoint("meas", time=timestamp) data_point.fields['foo'] = 1.5 data_point.tags['bar'] = "qux" da
ta_point.tags['baz'] = 1234 json_repr = data_point.get() assert_that(json_repr).is_equal_to({ "measurement": "meas", "time": timestamp, "tags": {'bar': 'qux', 'baz': 1234}, "fields": {'foo': 1.5} })
plotly/plotly.py
packages/python/plotly/plotly/validators/surface/colorbar/_thicknessmode.py
Python
mit
506
0.001976
import _plotly_utils.basevalidators class ThicknessmodeValidator(_plotly_uti
ls.basevalidators.EnumeratedValidator): def __init__( self, plotly_name="thicknessmode", parent_name="surface.colorbar", **kwargs ): super(ThicknessmodeValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type...
n", "pixels"]), **kwargs )
Hydrosys4/Master
interruptmod.py
Python
gpl-3.0
29,482
0.054949
from __future__ import print_function from __future__ import division from builtins import str from past.utils import old_div import logging from datetime import datetime , time ,timedelta import _strptime import hardwaremod import os import subprocess import emailmod import interruptdbmod import sensordbmod import act...
a,PIN,"InterruptCount",sensorinterruptcount) #if refsensor!="": # x = threading.Thread(target=savedata, args=(refsensor,reading)) # x.start() def setinterruptevents(): hardwaremod.removeallinterruptevents() print("load interrupt list ") interruptlist=interruptdbmod.sensorlist() print("len interrupt list ...
=item keytosearch=hardwaremod.HW_CTRL_PIN PINstr=hardwaremod.searchdata(recordkey,recordvalue,keytosearch) print("set event for the PIN ", PINstr) if not PINstr=="": keytosearch=hardwaremod.HW_CTRL_LOGIC logic=hardwaremod.searchdata(recordkey,recordvalue,keytosearch) # set Sw pull up / down mode ...
pulse-project/mss
mss/www/wizard/transaction.py
Python
gpl-3.0
7,120
0.000702
import logging from django.core.urlresolvers import reverse from django.utils.translation import ugettext as _, ungettext from mss.lib.xmlrpc import XmlRpc xmlrpc = XmlRpc() logger = logging.getLogger(__name__) class Steps: PREINST = "preinst" DOWNLOAD = "download" MEDIAS_AUTH = "medias_auth" MEDIA...
not module['installed'] or not module["downloaded"]: self.todo_step(Steps.INSTALL) if not module["downloaded"]: self.todo_step(Steps.DOWNLOAD) if module["has_reposito
ries"]: self.todo_step(Steps.MEDIAS_ADD) if module["has_restricted_repositories"]: self.todo_step(Steps.MEDIAS_AUTH) if module["has_configuration"] or module["has_configuration_script"] or not module["downloaded"]: self.todo_step(Steps.CONFIG) ...
pakozm/DNNJ
HyperoptScripts/hyperopt_mlp.py
Python
mit
1,224
0.007353
import math import os import sys sys.path.append(os.path.dirname(sys.argv[0])+"/../TensorFlowScripts") import train_GED from hyperopt import hp, fmin, rand, tpe, STATUS_OK, Trials space = { 'lr': hp.loguniform('lr', math.log(1e-5), math.log(30)), 'wd' : hp.choice('wd', [1e-1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-6, 1e...
return { 'loss': train_loss, 'loss_variance': train_loss * (1.0 - train_loss), 'true_loss': val_loss, 'true_loss_variance': val_loss * (1.0 - val_loss), 'status': STATUS_OK, # # -- store other results like this # 'eval_time': time.time(), # 'other_stuff'...
ls() best = fmin(objective, space=space, algo=tpe.suggest, max_evals=100) print best
supercheetah/diceroller
pyinstaller/buildtests/import/error_during_import2.py
Python
artistic-2.0
48
0
import os os.
environ["qwiejioqwjeioqwjeioqw
je"]
ezrosent/iterators-etc
hash/runTests.py
Python
mit
722
0.018006
from subprocess import Popen, PIPE import itertools ITERATORS_NUM = [0, 1, 4] UPDATERS_NUM = [1, 2, 4, 8] DURATION = [2] PERCENTAGES = [(25, 25)] KEY_RANGE = [65536] INIT_SIZE = [1024] PARAMETER_COMBINATIONS = [ITERATORS_NUM, UPDATERS_NUM, DURATION, PERCENTAGES, KEY_RANGE, INIT_SIZE] for param in itertools.product(*...
AMETER_COMBINATIONS): args = ["java", "-cp", ".:lib/java-getopt-1.0.13.jar" , "IteratorTest"] args += ["-i", str(param[0])] args += ["-u", str(param[1])] args += ["-d", str(param[2])] args += ["
-I", str(param[3][0])] args += ["-R", str(param[3][1])] args += ["-M", str(param[4])] args += ["-s", str(param[5])] pTest = Popen(args, stdout=PIPE) result = pTest.communicate()[0] print result
tiffanyj41/hermes
src/data_prep/jester_vectorize.py
Python
apache-2.0
3,684
0.001629
from src.utils import glove import numpy as np import string class jester_vectorize(): def __init__(self, user_interactions, content, user_vector_type, content_vector_type, **support_files): """Set up the Jester Vectorizer. Args: user_interactions (rdd): The raw data of users interac...
elf.support_files["glove_model"] # Transformation function def joke_to_glove(row, glove): vector = np.zeros(glove.vector_size) for chunk in row.joke_text.split(): word = chunk.lower().strip(string.punctuation) vector += glo...
return self.content.map(lambda row: joke_to_glove(row, glove_model)) elif self.content_vector_type == 'none' or self.content_vector_type is None: return None else: print "Please choose a content_vector_type between 'glove' or None" return None
boothead/karl
karl/views/__init__.py
Python
gpl-2.0
864
0.001157
# Copyright (C) 2008-2009 Open Society Institute # Thomas Moroz: tmoroz@sorosny.org # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU Genera
l Public License Version 2 as published # by the Free Software Foundation. You may not use, modify or distribute # this program under any other version of the GNU General Public License. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the im
plied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 59 Temple Place - Suite 330, Boston, M...
egetzel/wecrow
truehand2014/temboo/Library/Twilio/AvailablePhoneNumbers/TollFreeList.py
Python
apache-2.0
4,256
0.007519
# -*- coding: utf-8 -*- ############################################################################### # # TollFreeList # Returns a list of toll-free available phone numbers that match the specified filters. # # Python version 2.6 # ############################################################################### from...
'*' and [0-9a-zA-Z]. The '*' character will match any single digit.) """
InputSet._set_input(self, 'Contains', value) def set_IsoCountryCode(self, value): """ Set the value of the IsoCountryCode input for this Choreo. ((optional, string) The country code to search within. Defaults to US.) """ InputSet._set_input(self, 'IsoCountryCode', value) d...
mmolero/pyqode.python
runtests.py
Python
mit
236,912
0.000038
#! /usr/bin/env python # Hi There! # You may be wondering what this giant blob of binary data here is, you might # even be worried that we're up to something nefarious (good for you for being # paranoid!). This is a base64 encoding of a zip file, this zip file contains # a fully functional basic pytest script. # # Pyt...
Pg91x65iQAkNXqSOrYhUNWkvxMl/YxB6fmoUtcCc7p43Pt0AQrHCJyO9r 2fmUgx2jiEyqmuFdFFi98leJCAd+GeJUIO2YzmE9AL/rSiEmUpMkARJewjaosvn5wNrgDKH/9ZIq PAROgZ+g5wwDJl5gWuRNH/nBc+78myxbER8CEKdFOQuK80CO4Ht4yN2D0+eeHCfB9DJdXmRVrCko 9xCofN3sIf6ME4Fl6IPzCVto+zS9mtE4lllPt6MYAywxdDaGHIwTngDvfDQdwlG/hAkyq0TVgmKp oS2yRVHmv8YJwSOlgF1NZWIN5Nsb7Ey...
N0GVSrbIosVCpUGXYpnJzcQeDGYBtOLzUQdRLmSzhA4bCv4TiE8mkwK2p8toj8EArDEmLn AClqIk0azlmmhmw6jjMLTOjedbpYzS3K4fCHml3rA2cHPYSFA5o0TxdnszS4Hgf9e/2BHPfUXyKU iKU1MQRcQ5hMPrjP5VNRwWtgRNbzzJo1j4+QFXT5B2EGCO2qS2oR92vPOgnckeYVrVA6L7N0doNc WZUt6yCShSbG1qEGtAiALClwR3nNq0DYMIhtbOttTV5kneDsh9Wve3ZXeYTcxco/sppcg8Jkm2Fo 0rsGe7Cu9JxFLVuLeY...
shirtsgroup/InterMol
intermol/forces/proper_periodic_dihedral_type.py
Python
mit
1,984
0.006552
import parmed.unit as units from intermol.decorators import accepts_compatible_units from intermol.forces.abstract_dihedral_type import AbstractDihedralType class ProperPeriodicDihedralType(AbstractDihedralType): __slots__ = ['phi', 'k', 'multiplicity', 'weight', 'improper'] @accepts_compatible_units(None, ...
s.dimensionless, improper=None) def __init__(self, bondingtype1, bondingtype2, bondingtype3, bondingtype4, phi=0.0 * units.degrees, k=0.0 * units.kilojoules_per_mole,
multiplicity=0.0 * units.dimensionless, weight=0.0 * units.dimensionless, improper=False): AbstractDihedralType.__init__(self, bondingtype1, bondingtype2, bondingtype3, bondingtype4, improper) self.phi = phi self.k = k self.multiplicity = multiplici...
privacyidea/privacyidea
privacyidea/api/validate.py
Python
agpl-3.0
27,219
0.001397
# -*- coding: utf-8 -*- # # http://www.privacyidea.org # (c) cornelius kölbel, privacyidea.org # # 2020-01-30 Jean-Pierre Höhmann <jean-pierre.hohemann@netknights.it> # Add WebAuthn token # 2018-01-22 Cornelius Kölbel <cornelius.koelbel@netknights.it> # Add offline refill # 2016-12-20 Cornelius Kö...
ort json log = logging.getLogger(__name__) validate_blueprint = Blueprint('validate_blueprint', __name__) @validate_blueprint.before_request @register_blueprint.before_request @recover_blueprint.before_request def
before_request(): """ This is executed before the request """ ensure_no_config_object() request.all_data = get_all_params(request) request.User = get_user_from_param(request.all_data) privacyidea_server = current_app.config.get("PI_AUDIT_SERVERNAME") or \ request.hos...
CodeLionX/CommentSearchEngine
cse/WpApiParser.py
Python
mit
1,919
0.00938
from cse.util import Util fr
om collection
s import OrderedDict from cse.pipeline import Handler class WpApiParser(Handler): def __init__(self): super() def parse(self, comments, url, assetId, parentId): data = self.__buildDataSkeleton(url, assetId) data["comments"] = self.__iterateComments(comments, parentId) retu...
MagicSolutions/cmsplugin-carousel
example/example/urls.py
Python
mit
582
0
from django.conf.urls.defaults import * from django.conf.urls.i18n import i18n_patterns from django.contrib import admin
from django.conf import s
ettings admin.autodiscover() urlpatterns = i18n_patterns( '', url(r'^admin/', include(admin.site.urls)), url(r'^', include('cms.urls')), ) if settings.DEBUG: urlpatterns = patterns( '', url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.ME...
SeattleCentral/ITC110
examples/lecture04b.py
Python
mit
508
0
def change_counter(): print("Determine the value of your pocket change.") quarters = int(input("E
nter the number of quarters: ")) dimes = int(input("Enter the number of dimes: ")) nickels = int(input("Enter the number of nickels: ")) pennies = int(input("Enter the number of pennies: ")) value = quarters * 0.25 + dimes * 0.10 + nickels * 0.05
+ pennies * 0.01 print("You have ${0} in pocket change!".format(round(value, 2))) if __name__ == '__main__': change_counter()
rvsingh011/NitK_Assignments
Sem1/Algorithm/Factorial_iter.py
Python
mit
1,055
0.001896
def fact_iter(n): """This function will find the Factorial of the given number by iterative method. This function is coded in Pyhton 3.5.""" # check for integer if not isinstance(n, int): raise TypeError("Please only enter integer") if n <= 0: raise ValueError("Kindly Enter posi...
emp def fact_recu(n): # check for integer if not isinstance(n, int): raise TypeError("Please only enter integer") if n <= 0: raise ValueError("Kindly Enter positive integer only ") if n == 1: return 1 else:
return n * fact_recu(n-1) if __name__ == "__main__": print("""Enter your choice 1 - factorial Iterative 2 - factorial Recursive""") choice = int(input()) print("Enter the number") number = int(input()) if choice == 1: number = fact_iter(number) if choi...
gutooliveira/progScript
tekton/backend/apps/quero_app/model.py
Python
mit
346
0.00289
# -*- coding: utf-8 -*- from __future__ import absolute_im
port, unicode_literals from google.appengine.ext imp
ort ndb from gaegraph.model import Node from gaeforms.ndb import property class Quero(Node): item = ndb.StringProperty(required=True) nome = ndb.StringProperty(required=True) descricao = ndb.StringProperty(required=True)
leppa/home-assistant
homeassistant/components/season/sensor.py
Python
apache-2.0
4,134
0.000242
"""Support for tracking which astronomical or meteorological season it is.""" from datetime import datetime import logging import ephem import voluptuous as vol from homeassistant import util from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import CONF_NAME, CONF_TYPE import homeas...
) @property def name(self): """Return the name.""" return self._name @property def state(self): """Return the current season.""" return self.season @property def icon(self): """Icon to use in the frontend, if any."""
return SEASON_ICONS.get(self.season, "mdi:cloud") def update(self): """Update season.""" self.datetime = dt_util.utcnow().replace(tzinfo=None) self.season = get_season(self.datetime, self.hemisphere, self.type)
Irides-Chromium/cipher
scale_strict.py
Python
gpl-3.0
1,750
0.013714
#!/usr/bin/python3 ### rev: 5.0 ### author: <zhq> ### features: ### errors included ### up to 63 bases (2 to 64) ### caps recognition and same output format (deprecated) ### for the function parameters, `cur` represents the current (input) base, `res` represents the result (output) base, and `num` represen...
iscaps = False positive = True # Input if cur == res: return num if num == "0": return "0" assert cur in range(2, 65) and res in range(2, 65), "Base not defined." if num[0] == "-": positive = Fa
lse num = num[1:] result = 0 unit = 1 if cur != 10: for i in num[::-1]: value = ord(i) if value in range(48, 58): value -= 48 elif value in range(65, 92): value -= 55 elif value in range(97, 123): value -= 61 elif value == 64: valu...
xingyepei/edx-platform
lms/djangoapps/mobile_api/users/serializers.py
Python
agpl-3.0
4,342
0.001152
""" Serializer for user API """ from rest_framework import serializers from rest_framework.reverse import reverse from django.template import defaultfilters from courseware.access import has_access from student.models import CourseEnrollment, User from certificates.models import certificate_status_for_student, Certif...
ializers.ReadOnlyField(source='profile.name') course_enrollments = serializers.HyperlinkedIdentityField( view_name='courseenrollment-detail', lookup_field='username' ) class Me
ta(object): model = User fields = ('id', 'username', 'email', 'name', 'course_enrollments') lookup_field = 'username'
odubno/microblog
venv/lib/python2.7/site-packages/migrate/tests/versioning/test_cfgparse.py
Python
bsd-3-clause
1,112
0.004496
#!/usr/bin/python # -*- coding: utf-8 -*- from migrate.versioning import cfgparse from migrate.versioning.repository import * from migrate.versioning.template import Template from migrate.tests import fixture class TestConfigParser(fixture.Base): def test_to_dict(self): """Correctly interpret config res...
) self.assertEqual(parser.get('section', 'option'), 'value') self.assertEqual(parser.to_dict()['section']['option'], 'value') def test_table_config(self): """We should be able to specify the table to be used with a repository"""
default_text = Repository.prepare_config(Template().get_repository(), 'repository_name', {}) specified_text = Repository.prepare_config(Template().get_repository(), 'repository_name', {'version_table': '_other_table'}) self.assertNotEqual(default_text, specified_text)
saeki-masaki/cinder
cinder/volume/drivers/srb.py
Python
apache-2.0
33,594
0.000179
# Copyright (c) 2014 Scality # # 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...
LOG.exception(_LE('Error activating Volume Group')) LOG.error(_LE('Cmd :%s'), err.cmd) LOG.error(_LE('StdOut :%s'), err.stdout) LOG.error(_LE('StdErr :%s'), err.stderr) raise def deactivate_vg(self): """Deactivate the Volume Group associate...
e to the device. :raises: putils.ProcessExecutionError """ cmd = ['vgchange', '-an', self.vg_name] try: self._execute(*cmd, root_helper=self._root_helper, run_as_root=True) except putils.ProcessExecutionError as er...
halexan/Headquarters
src/headquarters/packet/stream_parser.py
Python
mit
2,384
0
# Copyright (C) 2013 Nippon Telegraph and Telephone Corporation. # Copyright (C) 2013 YAMAMOTO Takashi <yamamoto at valinux co jp> # # 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:...
"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. from abc import ABCMeta, abstractmethod import six @six.add_metaclass(ABCMeta) class StreamParser(object): """Stream...
essages from a raw byte stream. It's designed to be used for data read from a transport which doesn't preserve message boundaries. A typical example of such a transport is TCP. """ class TooSmallException(Exception): pass def __init__(self): self._q = bytearray() def...
BurntSushi/pdoc
test/testdata/demopackage2.py
Python
unlicense
70
0
"""I'm a different package, but I'm in demopack
age.__all__!""" x = 42
pkimber/compose
compose/migrations/0011_auto_20151026_1203.py
Python
apache-2.0
401
0
# -*- coding: utf-8 -*- from __future__ im
port unicode_literals from django.db
import migrations, models class Migration(migrations.Migration): dependencies = [ ('compose', '0010_auto_20151026_1126'), ] operations = [ migrations.RenameField( model_name='slideshow', old_name='slideshow', new_name='temp_slideshow', ), ...
nttks/edx-platform
lms/djangoapps/ga_instructor_task/api.py
Python
agpl-3.0
1,136
0.001761
# -*- coding: utf-8 -*- """ API for submitting background tasks by an instructor for a course. Also includes methods for getting information about tasks that have already been submitted, filtered either by running state or input arguments. """ from ga_instructor_task.tasks import ( generate_score_detail_report, ...
sk_class, course_key, task_input, task_key) def submit_generate_playback_status_report(request, course_key): """ Submits a task to generate a
CSV playback status report. """ task_type = 'generate_playback_status_report' task_class = generate_playback_status_report task_input = {} task_key = "" return submit_task(request, task_type, task_class, course_key, task_input, task_key)
simonreich/coffeedatabase
lib/ckeyboard.py
Python
gpl-3.0
17,891
0.00218
# -*- coding: utf-8 -*- """ This file is part of coffeedatabase. coffeedatabase is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later versi...
# Completer Class # For further reference please see # https://stackoverflow.com/questions/7821661/how-to-code-autocompletion-in-python class MyCompleter(object): # Cus
tom completer def __init__(self, options): self.options = sorted(options) def complete(self, text, state): if state == 0: # on first trigger, build possible matches if text: # cache matches (entries that start with entered text) self.matches = [s for s in self.opt...
tommy-u/enable
kiva/pdf.py
Python
bsd-3-clause
25,949
0.000077
# Copyright (c) 2005-2014, Enthought, Inc. # some parts copyright 2002 by Space Telescope Science Institute # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in enthought/LICENSE.txt and may be redistributed only # under the conditions described in the a...
icsContext(GraphicsContextBase): """ Simple wrapper around a PDF graphics context. """ def __init__(self, pdf_canvas, *args, **kwargs): from .image import GraphicsContext as GraphicsContextImage self.gc = pdf_canvas self.current_pdf_path = None self.current_point = (0, 0)...
f._agg_gc = GraphicsContextImage((1, 1)) super(GraphicsContext, self).__init__(self, *args, **kwargs) # ---------------------------------------------------------------- # Coordinate Transform Matrix Manipulation # ---------------------------------------------------------------- def scale_ctm(s...
Chibin/gpdb
src/test/tinc/tincrepo/mpp/gpdb/tests/storage/walrepl/load/__init__.py
Python
apache-2.0
1,772
0.005643
""" Copyright (c) 2004-Present Pivotal Software, Inc. This program and the accompanying materials are made available under the terms of the 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....
p.models import MPPTestCase from mpp.gpdb.tests.storage.walrepl.lib.pg_util import GpUtility from mpp.gpdb.tests.storage.walrepl.gpinitstandby import GpinitStandby clas
s LoadClass(MPPTestCase): def __init__(self,methodName): self.gp =GpinitStandby() super(LoadClass,self).__init__(methodName) def run_skip(self, type): tinctest.logger.info("skipping checkpoint") cmd_str = 'gpfaultinjector -p %s -m async -H ALL -r primary -f checkpoint -y %...
voidcc/POXPOF
pox.py
Python
apache-2.0
1,289
0
#!/bin/sh - # Copyright 2011-2012 James McCauley # # 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 ...
/null; then exec python2.7 $OPT "$0" $FLG "$@" fi exec python $OP
T "$0" $FLG "$@" ''' from pox.boot import boot if __name__ == '__main__': boot()
trachelr/mne-python
examples/visualization/plot_evoked_topomap_delayed_ssp.py
Python
bsd-3-clause
2,301
0
""" =============================================== Create topographic ERF maps in delayed SSP mode =============================================== This script shows how to apply SSP projectors delayed, that is, at the evoked stage. This is particularly useful to support decisions related to the trade-off between deno...
gmail.com> # Christian Brodbeck <christianbrodbeck@nyu.edu> # Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # # License: BSD (3-clause) import numpy as np import mne from mne import io from mne.datasets import sample print(__doc__) data_path = sample.data_path() ####################...
e/sample_audvis_filt-0-40_raw-eve.fif' ecg_fname = data_path + '/MEG/sample/sample_audvis_ecg_proj.fif' event_id, tmin, tmax = 1, -0.2, 0.5 # Setup for reading the raw data raw = io.Raw(raw_fname) events = mne.read_events(event_fname) # delete EEG projections (we know it's the last one) raw.del_proj(-1) # add ECG pro...
adrianholovaty/django
tests/modeltests/validation/models.py
Python
bsd-3-clause
4,204
0.00785
from datetime import datetime from django.core.exceptions import ValidationError from django.db import models def validate_answer_to_universe(value): if value != 42: raise ValidationError('This is not the answer to life, universe and everything!', code='not42') class ModelToValidate(models.Model): n...
date_answer_to_universe] ) class Author(models.Model): name = models.CharField(max_length=100) class Article(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author) pub_date = models.DateTimeField(blank=True) def clean(self): if self.pub_date is None...
) class Post(models.Model): title = models.CharField(max_length=50, unique_for_date='posted', blank=True) slug = models.CharField(max_length=50, unique_for_year='posted', blank=True) subtitle = models.CharField(max_length=50, unique_for_month='posted', blank=True) posted = models.DateField() def _...
peterwharrison/SWAMP
SWAMP.py
Python
gpl-3.0
27,840
0.000647
#!/usr/bin/env python ''' ____ _ _ _ ____ _______ ____ / ___)| | | | | |/ _ \ / _ _ \| _ \ \___ \| | | | | | (_) | | | | | | |_) ) ___) | |_| |_| | ___ | | | | | | __/ (____/ \_______/|_| |_|_| |_| |_|_| Sliding Win...
======================================================= #Functions===================================================================== #============================================================================== def print_alignment_summary(infil
e): '''Prints out a summary of the given alignment file''' seq_dict = read_phylip(infile) aln_length = len(seq_dict.values()[0]) print "%15s Alignment length: %d codons" % ('', aln_length) total_masked_sites = 0 for species in seq_dict: seq = seq_dict[species] codons = get_co...
BradleyMoore/Snake
game_objects.py
Python
mit
3,550
0.006761
from game_state import BOX, COLS, ROWS, SCREEN import levels from random import randint import pygame from time import sleep class Level(object): def __init__(self): self.size = 1 self.color = 255,120,0 self.x = 0 self.y = 0 self.layout = [] self.wall = [] ...
self.turn('up', 'down') # snake body values self.body = [] self.color = 0,0,255 self.length = 1 def draw(self): for x, y in self.body: pygame.draw.rect(SCREEN, self.color,
(x*BOX, y*BOX, self.size*BOX, self.size*BOX)) def eat(self, amount, state, wall): self.grow(amount) state.foodleft = state.foodleft - 1 state.score_reset() state.increase_food_count(self, wall) def grow(self, amount): self.grow_to = self.grow_to + amount d...
yikelu/nfl_fantasy_data
htmls2csvs.py
Python
gpl-2.0
2,265
0.004415
# pylint: disable = C0301 from bs4 import BeautifulSoup from urllib2 import urlopen import pandas as pd pos_idx_map = { 'qb': 2, 'rb': 3, 'wr': 4, 'te': 5, } def make_url(pos, wk): ii = pos_idx_map[pos] fstr = "http://fantasydata.com/nfl-stats/nfl-fantasy-football-stats.aspx?fs=1&stype=0&sn=1...
r() for header in table.find_all('th')] rows = [] for row in table.find_all('tr'): rows.append([val.text.encode('utf8') for val in row.find_all('td')]) rows = [rr for rr in rows if len(rr) > 0] df = pd.DataFrame.from_records(rows) df.columns = headers return df def position_html_local...
n range(1, 17): fname = '%s%s.html' % (posn, ii) with open(fname) as f: df = html2df(BeautifulSoup(f)) df['wk'] = ii df.columns = header_clean(df.columns, posn) dflist.append(df) return pd.concat(dflist) def position_html(posn): dflist = [] for ii in rang...
workflo/dxf2gcode
source/Gui/myCanvasClass.py
Python
gpl-3.0
26,794
0.014109
# -*- coding: utf-8 -*- """ Special purpose canvas including all required plotting function etc. @newfield purpose: Purpose @newfield sideeffect: Side effect, Side effects @purpose: Plotting all @author: Christian Kohl�ffel @since: 22.04.2011 @license: GPL """ from copy import copy from PyQt4 import...
if(self.dragMode())==1: super(MyGraphicsView, self).mousePressEvent(event) elif event.button() == QtCore.Qt.LeftButton: self.mppos=ev
ent.pos() else: pass def mouseReleaseEvent(self, event): """ Right Mouse click shall have no function, Therefore pass only left click event @purpose: Change inherited mousePressEvent @param event: Event Parameters passed to function ...
concurrence/concurrence
test/testtimer.py
Python
bsd-3-clause
2,659
0.015795
from __future__ import with_statement import time from concurrence import unittest, Tasklet, Channel, TimeoutError from concurrence.timer import Timeout class TimerTest(unittest.TestCase): def testPushPop(self): self.assertEquals(-1, Timeout.current()) Timeout.push(30) s...
out.pop() self.assertEquals(-1, Timeout.current()) Timeout.push(30) self.assertAlmostEqual(30, Timeout.current(), places = 1) Tasklet.sleep(1.0) self.assertAlmostEqual(29, Timeout.current(), places = 1) #push a temporary short timeout Timeout.push(5) self....
), places = 1) Timeout.pop() self.assertAlmostEqual(29, Timeout.current(), places = 1) #try to push a new longer timeout than the parent timeout #this should fail, e.g. it will keep the parent timeout Timeout.push(60) self.assertAlmostEqual(29, Timeout.current(),...
proyectos-analizo-info/pyanalizo
src/app-ape/deprecated/get-propuestas-electorales-v5.py
Python
gpl-3.0
2,267
0.014116
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ...
ta ' + answer + crlf + '---------------------------------------')
f.append(output, 'Hora de inicio: ' + f.formatTime(answers[answ]['answer_end_date']) + crlf + 'Hora de fin: ' + f.formatTime(answers[answ]['answer_start_date'])) for item in answers[answ]['answer'].split('\n'): if item.replace(' ', '...
dmalatesta/spaceterm
entities/star.py
Python
gpl-3.0
729
0
from entities.base import Base import game.constants class Star(Base): """The Star objects represents a star (or a blackhole!)""" symbol = 'O' decoration = game.constants.STYLE_BOLD color = game.constants.COLOR_WK isCollider = True def setClass(self, cl): """ Sets the star c...
TODO:
do some validation? self.color = game.constants.STAR_COLORS[cl]
systemsoverload/codeeval
easy/132_major_element/solution.py
Python
mit
359
0.008357
import sys def
solve(l): numbers = l.split(',') row_hash = {} for num in numbers: count = row_hash.setdefault(num, 0) row_hash[num] = count + 1 if row_hash[num] > len(numbers) / 2: return num return None with open(sys.argv[1], 'r') as f: for
line in f.readlines(): print solve(line.strip())
qedsoftware/commcare-hq
corehq/apps/app_manager/tests/test_profile.py
Python
bsd-3-clause
4,112
0.001217
# coding: utf-8 from django.test import SimpleTestCase from corehq.apps.app_manager.commcare_settings import get_commcare_settings_lookup, get_custom_commcare_settings from corehq.apps.app_manager.models import Application from corehq.apps.app_manager.tests.util import TestXmlMixin import xml.etree.ElementTree as ET f...
ngs(): if se
tting['id'] == 'users': continue for value in setting.get('values', []): self.app.profile = { setting['type']: { setting['id']: value } } self._test_profile(self.app) # cu...
fairbird/OpenPLI-TSimage
lib/python/Screens/StreamingClientsInfo.py
Python
gpl-2.0
4,194
0.030281
from Screen import Screen from Screens.MessageBox import MessageBox from Components.MenuList import MenuList from Components.ActionMap import ActionMap from Components.Sources.StreamService import StreamServiceList from Components.Sources.StaticText import StaticText from Components.Label import Label from enigma impor...
y_red"] = StaticText(_("Close")) self["key_green"] = StaticText("") self["key_yellow"] = StaticText("") self["info"] = Label() self.updateClients() self["actions"] = ActionMap(["ColorActions", "SetupActions"], { "canc
el": self.close, "ok": self.stopCurrentStream, "red": self.close, "green": self.stopAllStreams, "yellow": self.stopCurrentStream }) def updateClients(self): self["key_green"].setText("") self["key_yellow"].setText("") self.setTitle(_("Streaming clients info")) self.clients = [] if self.streamS...
axiak/py-rangeset
rangeset/__init__.py
Python
mit
11,032
0.002085
""" This module provides a RangeSet data structure. A range set is, as the name implies, a set of ranges. Intuitively, you could think about a range set as a subset of the real number line, with arbitrary gaps. Some examples of range sets on the real number line: 1. -infinity to +infinity 2. -1 to 1 3. 1 to 4, 10 to 2...
s __version__ = (0, 0, 11) __all__ = ('INFINITY', 'NEGATIVE_INFINITY', 'RangeSet') class _Indeterminate(object): def timetuple(self): return () def __eq__(self, other): return other is self class _Infinity(_Indeterminate): def __lt__(self, other): return False def ...
__(self): return 'inf' __repr__ = __str__ class _NegativeInfinity(_Indeterminate): def __lt__(self, other): return True def __gt__(self, other): return False def __str__(self): return '-inf' __repr__ = __str__ INFINITY = _Infinity() NEGATIVE_INFINITY = _NegativeInfi...
estaban/pyload
module/plugins/accounts/StahnuTo.py
Python
gpl-3.0
1,610
0.001863
# -*- coding: utf-8 -*- """ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in...
t plugin""" __author_name__ = "zoidberg" __author_mail__ = "zoidberg@mujmail.cz" def loadAccountInfo(self, user,
req): html = req.load("http://www.stahnu.to/") m = re.search(r'>VIP: (\d+.*)<', html) trafficleft = parseFileSize(m.group(1)) * 1024 if m else 0 return {"premium": trafficleft > (512 * 1024), "trafficleft": trafficleft, "validuntil": -1} def login(self, user, data, req): ...
clever-crow-consulting/otm-core
opentreemap/treemap/lib/udf.py
Python
agpl-3.0
2,743
0
import json from django.db import transaction from django.core.exceptions import ValidationError from django.utils.translation import ugettext as _ from treemap.audit import Role, FieldPermission from treemap.udf import (UserDefinedFieldDefinition) def udf_exists(params, instance): """ A little helper funct...
eldPermission.
objects.get_or_create( model_name=model_type, field_name=field_name, permission_level=FieldPermission.NONE, role=role, instance=role.instance) return udf def _parse_params(params): name = params.get('udf.name', None) model_type = params.get('udf...
MaxTyutyunnikov/lino
obsolete/docs/examples/sprl2.py
Python
gpl-3.0
1,300
0.011538
from lino.apps.ledger.ledger_tables import LedgerSchema from lino.reports import Report from lino.adamo.rowattrs import Field, Pointer, Detail class SchemaOverview(Report): def __init__(self,schema): self.schema=schema Report.__init__(self) def getIterator(self): return self.sc...
, ".join([fld.name for fld in row.item.getFields() if isinstance(fld,Pointer)]),
width=15) self.addVurtColumn( label="Details", meth=lambda row:\ ", ".join([fld.name for fld in row.item.getFields() if isinstance(fld,Detail)]), width=25) sch=LedgerSchema() rpt=SchemaOverview(sch) rpt.show()
lavjain/incubator-hawq
tools/bin/gppylib/programs/verify.py
Python
apache-2.0
11,749
0.010043
# 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...
cation messages to the backend. """ if self.results: self._do_results(self.token, self.batch_default) elif self.clean: self._do_clean(self.token, self.batch_default) elif self.abort: AbortVerification(token = self.token, b...
batch_default = self.batch_default).run() elif self.suspend: SuspendVerification(token = self.token, batch_default = self.batch_default).run() else: if self.token is None: self.token = datetime.now().strftime("%Y%m%d%H%M%S") ...
rtucker-mozilla/WhistlePig
vendor-local/lib/python/tastypie/admin.py
Python
bsd-3-clause
582
0.001718
from django.conf import settings from django.contrib import admin if 'django.contrib.auth' in setting
s.INSTALLED_APPS: from tastypie.models import ApiKey class ApiKeyInline(admin.StackedInline): model = ApiKey extra = 0 ABSTRACT_APIKEY = getattr(settings, 'TASTYPIE_ABSTRACT_APIKEY', False) if ABSTRACT_APIKEY and not isinstance(ABSTRACT_APIKEY, bool): raise TypeError("'TASTYPI...
if not ABSTRACT_APIKEY: admin.site.register(ApiKey)
PMantovani/road-irregularity-detector
classification_algorithm/src/svm_training.py
Python
apache-2.0
4,872
0.001437
import sys import csv import pickle import numpy as np from sklearn import svm from sklearn.metrics import f1_score from sklearn.metrics import confusion_matrix from sklearn.preprocessing import StandardScaler training_data = [] training_classes = [] test_data = [] test_classes = [] path = '../../data/' filename = pa...
e number of classes if '-t' in sys.argv or '--two' in sys.argv: two_classes = True else: two_classes = False # parse axis independence if '-a' in sys.argv or '--axis-independent' in sys.argv: axi
s_indep = True else: axis_indep = False c_parameter = 1 # parse value of C if '-c' in sys.argv: ind = sys.argv.index('-c') c_parameter = float(sys.argv[ind+1]) # parse value of gamma gamma_parameter = 1 if '-g' in sys.argv: ind = sys.argv.index('-g') gamma_parameter = float(sys.argv[ind+1]) # par...
vileopratama/vitech
src/addons/account_check_printing/account_journal_dashboard.py
Python
mit
1,200
0.004167
# -*- coding: utf-8 -*- from openerp import models, api, _ class account_journal(models.Model): _inherit = "account.journal" @api.multi def get_journal_dashboard_datas(self): domain_checks_to_print = [ ('journal_id', '=', self.id), ('payment_method_id.code', '=', 'check_pr...
nal, self).get_journal_dashboard_datas(), num_checks_to_print=len(self.env['account.payment'].search(domain_checks_to_print)) ) @api.multi def action_checks_to_print(self): return {
'name': _('Checks to Print'), 'type': 'ir.actions.act_window', 'view_mode': 'list,form,graph', 'res_model': 'account.payment', 'context': dict( self.env.context, search_default_checks_to_send=1, journal_id=self.id, ...
wagnerand/addons-server
src/olympia/amo/views.py
Python
bsd-3-clause
8,643
0.000694
import json import os import re import sys import django from django.conf import settings from django.contrib.auth.models import AnonymousUser from django.contrib.sitemaps.views import x_robots_tag from django.core.exceptions import PermissionDenied, ViewDoesNotExist from django.core.paginator import EmptyPage, PageNo...
nces) or not. frontend_view.is_frontend_view = True def fake_fxa_authorization(request):
"""Fake authentication page to bypass FxA in local development envs.""" if not use_fake_fxa(): raise Http404() interesting_accounts = UserProfile.objects.exclude(groups=None).exclude( deleted=True )[:25] return TemplateResponse( request, 'amo/fake_fxa_authorization.html',...
cchurch/ansible-modules-core
cloud/openstack/_keystone_user.py
Python
gpl-3.0
14,116
0.001063
#!/usr/bin/python # -*- coding: utf-8 -*- # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # ...
n (False, role.id) except KeyError: # Role doesn't exist yet pass role = keystone.roles.create(role_name) return (True, role.id) def ensure_user_role_exists(keystone, user_name, tenant_name, role_name, check_mode): """ Check if role exis
ts Return (True, id) if a new role was created or if the role was newly assigned to the user for the tenant. (False, id) if the role already exists and was already assigned to the user ofr the tenant. """ # Check if the user has the role in the tenant user = get_user(keystone, user...