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
haikuginger/beekeeper
test/test_variable_handers.py
Python
mit
3,412
0.005569
from __future__ import unicode_literals import unittest from functools import partial from beekeeper.variable_handlers import render import beekeeper.variable_handlers class VariableReceiver(object): def execute(self, var_type, **kwargs): render(self, var_type, **kwargs) def receive(self, expected...
wargs: self.assertIn(kwargs, expected) else: self.assertIn(args[0], expected) elif kwargs: self.assertEqual(expected, kwargs) else: self.assertEqual(expected, args[0]) class fakeuuid: def __init__(self):
self.hex = 'xxx' class VariableHandlerTest(VariableReceiver, unittest.TestCase): def test_data(self): self.set_headers = partial(self.receive, {'Content-Type': 'text/plain'}) self.set_data = partial(self.receive, b'this is text') self.execute('data', variable={'mimetype': 'text/plain', ...
liqd/a4-meinberlin
tests/ideas/rules/test_rules_view.py
Python
agpl-3.0
4,529
0
import pytest import rules from adhocracy4.projects.enums import Access from adhocracy4.test.helpers import freeze_phase from adhocracy4.test.helpers import freeze_post_phase from adhocracy4.test.helpers import freeze_pre_phase from adhocracy4.test.helpers import setup_phase from adhocracy4.test.helpers import setup_u...
assert project.access == Access.SEMIPUBLIC with freeze_phase(phase): assert rules.has_perm(perm_name, anonymous, item) assert rules.has_perm(perm_name, user, item) assert rules.has_perm(perm_name, participant, item) assert rules.has_perm(perm_name, m
oderator, item) assert rules.has_perm(perm_name, initiator, item) @pytest.mark.django_db def test_phase_active_project_draft(phase_factory, idea_factory, user): phase, _, project, item = setup_phase(phase_factory, idea_factory, phases.CollectPhase, ...
VoiDeD/Sick-Beard
sickbeard/processTV.py
Python
gpl-3.0
9,409
0.004251
# Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/sickbeard/ # # This file is part of Sick Beard. # # Sick Beard 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 t...
d tv_episodes.file_size = ?" sql_results = myDB.select(search_sql, [cur_video_file_path, cur_video_file_path_size]) if len(sql_results): returnStr += logHelper(u"Ignoring file: " + cur_video_file_path + " looks like it's
been processed already", logger.DEBUG) continue try: returnStr += u"\n" processor = postProcessor.Po
ThrawnCA/ckanext-qgov
ckanext/qgov/common/authenticator.py
Python
agpl-3.0
2,108
0.009013
from ckan.lib.authenticator import UsernamePasswordAuthenticator from ckan.model import User, Session from sqlalchemy import Column, types, MetaData, DDL from sqlalchemy.ext.declarative import declarative_base from zope.interface import implements from repoze.who.interfaces import IAuthenticator Base = declarative_b...
None: log.debug('Login failed - username %r not found', identity.get('login')) return None qgovUser = Session.query(QGOVUser).filter_by(name = identity.get('login')).first() if qgovUser.login_attempts >= 10: log.debug('Login as %r failed - account is locked', identit...
tity.get('password')): # reset attempt count to 0 qgovUser.login_attempts = 0 Session.commit() return user.name else: log.debug('Login as %r failed - password not valid', identity.get('login')) qgovUser.login_attempts += 1 Session.comm...
rchristie/mapclientplugins.meshgeneratorstep
mapclientplugins/meshgeneratorstep/model/mastermodel.py
Python
apache-2.0
6,058
0.007098
import os import json from PySide2 import QtCore from opencmiss.zinc.context import Context from opencmiss.zinc.material import Material from mapclientplugins.meshgeneratorstep.model.meshgeneratormodel import MeshGeneratorModel from mapclientplugins.meshgeneratorstep.model.meshannotationmodel import MeshAnnotationMo...
_segmentation_data_model def getScene(self):
return self._region.getScene() def getContext(self): return self._context def registerSceneChangeCallback(self, sceneChangeCallback): self._generator_model.registerSceneChangeCallback(sceneChangeCallback) def done(self): self._saveSettings() self._generator_model.don...
lbarahona/UdacityProject4
conference.py
Python
apache-2.0
37,472
0.005444
#!/usr/bin/env python """ conference.py -- Udacity conference server-side Python App Engine API; uses Google Cloud Endpoints $Id: conference.py,v 1.25 2014/05/24 23:42:19 wesc Exp wesc $ created by wesc on 2014 apr 21 """ __author__ = '[email protected] (Wesley Chun)' from datetime import datetime import ...
ls import ConflictException from models import Profile from models import ProfileMiniForm from models import ProfileForm from models import StringMessage from models import Boole
anMessage from models import Conference from models import ConferenceForm from models import ConferenceForms from models import ConferenceQueryForm from models import ConferenceQueryForms from models import TeeShirtSize from models import Session, SessionForm, SessionForms, SessionTypes from models import Speaker, Spea...
ntt-sic/heat
heat/tests/test_ceilometer_alarm.py
Python
apache-2.0
15,354
0.000065
# 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...
, snippet) self.assertRaises(resource.UpdateReplace, updater) self.m.VerifyAll() @utils.stack_delete_after def test_mem_alarm_s
uspend_resume(self): """ Make sure that the Alarm resource gets disabled on suspend and reenabled on resume. """ self.stack = self.create_stack() self.m.StubOutWithMock(self.fa.alarms, 'update') al_suspend = {'alarm_id': mox.IgnoreArg(), 'en...
jzaremba/sima
sima/motion/dftreg.py
Python
gpl-2.0
31,079
0.000064
""" Motion correction of image sequences by 'efficient subpixel image registration by cross correlation'. A reference image is iteratively computed by aligning and averaging a subset of images/frames. 2015 Lloyd Russell, Christoph Schmidt-Hieber *************************************************************************...
num_channels = sequence.shape
[4] if num_channels > 1: raise NotImplementedError("Error: only one colour channel \ can be used for DFT motion correction. Using channel 1.") for plane_idx in range(num_planes): # load into memory... need to pass numpy array to dftreg. ...
jayceyxc/hue
apps/search/src/search/conf.py
Python
apache-2.0
1,443
0
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Versio
n 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BAS...
ng permissions and # limitations under the License. from django.utils.translation import ugettext_lazy as _ from desktop.lib.conf import Config, coerce_bool SOLR_URL = Config( key="solr_url", help=_("URL of the Solr Server."), default="http://localhost:8983/solr/") EMPTY_QUERY = Config( key="empty_query", ...
sgiavasis/nipype
nipype/interfaces/tests/test_auto_MeshFix.py
Python
bsd-3-clause
3,030
0.024092
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from ...testing import assert_equal from ..meshfix import MeshFix def test_MeshFix_inputs(): input_map = dict(args=dict(argstr='%s', ), cut_inner=dict(argstr='--cut-inner %d', ), cut_outer=dict(argstr='--cut-outer %d', ), decouple_inin=...
yield assert_equal, getattr(inputs.traits()[key], metakey), value def test_MeshFix_outputs(): output_map = dict(mesh_file=dict(), ) outputs = MeshFix.output_spec() for key, metadata in list(output_map.items()): for metakey,
value in list(metadata.items()): yield assert_equal, getattr(outputs.traits()[key], metakey), value
MadManRises/Madgine
shared/bullet3-2.89/examples/pybullet/gym/pybullet_envs/deep_mimic/learning/ppo_agent.py
Python
mit
15,708
0.006175
import numpy as np import copy as copy import tensorflow as tf from pybullet_envs.deep_mimic.learning.pg_agent import PGAgent from pybullet_envs.deep_mimic.learning.solvers.mpi_solver import MPISolver impo
rt pybullet_envs.deep_mimic.learning.tf_util as TFUtil import pybullet_envs.deep_mimic.learning.rl_util as RLUtil from pybullet_utils.logger import Logger import pybullet_utils.mpi_util as MPIUtil import pybullet_utils.math_util as MathUtil from pybullet_envs.deep_mimic.env.env import Env ''' Proximal Policy Optimizati...
_KEY = "NormAdvClip" TD_LAMBDA_KEY = "TDLambda" TAR_CLIP_FRAC = "TarClipFrac" ACTOR_STEPSIZE_DECAY = "ActorStepsizeDecay" def __init__(self, world, id, json_data): super().__init__(world, id, json_data) return def _load_params(self, json_data): super()._load_params(json_data) self.epochs = ...
cloudbase/nova-virtualbox
nova/api/openstack/compute/plugins/v3/flavors_extraspecs.py
Python
apache-2.0
6,450
0
# Copyright 2010 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
tent) instead of 200 by v2.1 # +microversions because the flavor extra specs has been deleted # completely when returning a response. @extensions.expected_errors(404) def delete(self, req, flavor_id, id): """Deletes an existing extra spec.""" context = req.environ['nova.context'] ...
del flavor.extra_specs[id] flavor.save() except (exception.FlavorExtraSpecsNotFound, exception.FlavorNotFound) as e: raise webob.exc.HTTPNotFound(explanation=e.format_message()) except KeyError: msg = _("Flavor %(flavor_id)s has no extra specs w...
zbeaver4/python-webpage-monitor-slackbot
rtmbot.py
Python
mit
7,767
0.007596
#!/usr/bin/env python import sys sys.dont_write_bytecode = True import glob import re import yaml import json import os import sys import time import logging import requests import platform import imp from argparse import ArgumentParser from slackclient import SlackClient def dbg(debug_string): if debug: ...
directory = os.path.abspath("{}/{}".format(os.getcwd(), directory )) config = yaml.load(file(args.config or 'rtmbot.conf', 'r')) debug = config["DEBUG"]
bot = RtmBot(config["SLACK_TOKEN"]) site_plugins = [] files_currently_downloading = [] job_hash = {} if config.has_key("DAEMON"): if config["DAEMON"]: import daemon with daemon.DaemonContext(): main_loop() main_loop()
pakit/recipes
parallel.py
Python
bsd-3-clause
883
0
""" Formula for building parallel """ from pakit import Archive, Recipe class Parallel(Recipe): """ GNU parallel executes shell jobs in parallel """ def __init__(self): super(Parallel, self).__init__() self.homepage = 'http://www.gnu.org/software/parallel' self.repos = { ...
'parallel-20181022.tar.bz2', hash='2e84dee3556cbb8f6a3794f5b21549faffb132' 'db3fc68e2e95922963adcbdbec') } self.repos['stable'] = self.repos['un
stable'] def build(self): self.cmd('./configure --prefix={prefix}') self.cmd('make install') def verify(self): lines = self.cmd('parallel --version').output() assert lines[0].find('GNU parallel') != -1
isi-nlp/bolinas
common/hgraph/amr_corpus_reader.py
Python
mit
4,973
0.019706
#!/usr/bin/env python2 from hgraph import Hgraph import amr_graph_description_parser #import tree import re import sys import string from collections import defaultdict as ddict def format_tagged(s): #return [tuple(p.split('/')) for p in s.split()] return [p.rsplit('-',1)[0] for p in s.split()] def format_amr(l)...
%s \n"%l
s_no = int(match.group(1)) text = match.group(2).strip().split(" ") s_id = match.group(3).strip() return s_id, s_no, text def plain_corpus(f): while True: x = read_to_empty(f) if not x: raise StopIteration amr = format_amr(x) yield amr def aligne...
andrenam/Fogger
fogger/FoggerWindow.py
Python
gpl-3.0
10,132
0.002764
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- ### BEGIN LICENSE # Copyright (C) 2012 Owais Lone <[email protected]> # 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 ...
None self.icon_selected = False self.icon_theme = Gtk.IconTheme.get_default() self.setup_drop_targets() self.background_image.set_from_pixbuf(get_chameleonic_pixbuf_from_svg( 'background-app.svg')) def validate_form(self, widg...
et_text() sensitive = url and name self.create_button.set_sensitive(sensitive) def setup_drop_targets(self): self.drag_dest_set(Gtk.DestDefaults.ALL, [], Gdk.DragAction.MOVE) self.connect("drag-data-received", self.on_drag_data_received) self.drag_dest_add_uri_targets() ...
aljim/deploymentmanager-samples
community/cloud-foundation/src/cloud_foundation_toolkit/dm_utils.py
Python
apache-2.0
3,240
0
from collections import namedtuple import io import re from six.moves.urllib.parse import urlparse from apitools.base.py import exceptions as apitools_exceptions from googlecloudsdk.api_lib.deployment_manager import dm_base from ruamel.yaml import YAML DM_OUTPUT_QUERY_REGEX = re.compile( r'!DMOutput\s+(?P<url>\bd...
'"dm://${project}/${deployment}/${resource}/${name}" or' '"dm://${deployment}/${resource}/${name}"' ) parsed_url = urlparse(url) if parsed_url.scheme != 'dm': raise ValueError(error_msg) path = parsed_url.path.split('/')[1:] # path == 2 if project isn't specified in the URL ...
: args = [project] + [parsed_url.netloc] + path elif len(path) == 3: args = [parsed_url.netloc] + path else: raise ValueError(error_msg) return DMOutputQueryAttributes(*args) def parse_dm_output_token(token, project=''): error_msg = ( 'The url must look like ' ...
ojarva/davis-weatherlink-scraper
setup.py
Python
bsd-3-clause
1,407
0.001421
from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.d
irname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='davis-weatherlink-scraper', version='0.1.0', description='Scraper and parser for Davis Weatherlink data', long_description=long_description, url='https://github.com/ojarv...
- Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming ...
javaarchive/PIDLE
ccode.py
Python
mit
846
0.049645
replacing='qwertyuiopasdfghjklzxcvbnm )([]\/{}!@#$%^&*' a='\/abcdefghijklmnopqrstuvwxyz() }{][*%$&^#@!' replacing=list(replacing) a=list(a) d={} e={} if len(replacing)==len(a): for x in range(len(a)): d[replacing[x]]=a[x] e[a[x]]=replacing[x] def encypt(dict,stri...
ode' decode=[] for x in string: decode.append(dict[x]) return ''.join(decode) if __name__=='__main__': c=input('code:') code=encypt(e,c) decode=decypt(d,c)
print('encypts to',code) print('decypt to',decode) input()
unnikrishnankgs/va
venv/lib/python3.5/site-packages/tensorflow/contrib/quantization/python/array_ops.py
Python
bsd-2-clause
1,156
0
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
ray_ops import dequantize from tensorflow.python.ops.gen_array_ops import quantize_v2 from tensorflow.python.ops.gen_array_ops import quantized_concat # pylint: enable=unu
sed-import
babyliynfg/cross
tools/project-creator/Python2.6.6/Lib/test/test_bigmem.py
Python
mit
39,354
0.001347
from test import test_support from test.test_support import bigmemtest, _1G, _2G, _4G, precisionbigmemtest import unittest import operator import string import sys # Bigmem testing houserules: # # - Try not to allocate too many large objects. It's okay to rely on # refcounting semantics, but don't forg...
muse=3) def test_encode(self, size): return self.basic_encode_test(size, 'utf-8') @precisionbigmemtest(size=_4G // 6 + 2, memuse=2) def test_encode_raw_unicode_escape(self, size): try: return self.basic_encode_test(size, 'raw_unicode_escape') except MemoryError: ...
self.basic_encode_test(size, 'utf7') except MemoryError: pass # acceptable on 32-bit @precisionbigmemtest(size=_4G // 4 + 5, memuse=6) def test_encode_utf32(self, size): try: return self.basic_encode_test(size, 'utf32', expectedsize=4*size+4) except Memo...
merfishtools/merfishtools-evaluation
scripts/fig-dataset-correlation.py
Python
mit
311
0
import svgutils.transform as sg from common import load_svg, label_plot
fig = sg.SVGFigure("4.1in", "1.8in") a = load_svg(snakemake.input[1]) b = load_svg(snakemake.input[0]) b.moveto(190, 0) la
= label_plot(5, 10, "a") lb = label_plot(185, 10, "b") fig.append([a, b, la, lb]) fig.save(snakemake.output[0])
r4rdsn/vk-raid-defender
vk_raid_defender/cli/cli.py
Python
mit
7,730
0.007869
from .. import __description__ from ..defender import VkRaidDefender, data, update_data #################################################################################################### LOGO = '''\ _ _ _ _ __ _ __ _| | __ _ __ __ _(_) __| | __| | ___ / _| __...
+ '\n') print('открой в веб-браузере страницу по ссылке выше.') token = None while token is None: user_input = getpass('авторизируйся на открытой странице при необходимости и вставь адресную строку страницы, на которую было осуществлено перенаправление: ') token = re.search(r'(
?:.*access_token=)?([a-f0-9]+).*', user_input) return token.group(1) def run(proxy=None, chat_ids=[], objectives=[], auto_login=False): token = data.get('token') proxies = data.get('proxies') if not token or (not auto_login and not ask_yes_or_no('использовать ранее сохранённые данные для авторизации...
irlabs/BathroomTiles
GradientSliders.py
Python
mit
12,149
0.033254
# Gradient Sliders # Custom ControlP5 Compound Classes for percentage sliders # For Processing in Python import copy add_library('controlP5') class GradientController(object): def __init__(self, colorList, cp5, sliderClass): self.colorList = self.colorListFromColors(colorList) self.cp5 = cp5 self.Slider = sl...
] values = [] for i, cStop in enumerate(self.allStops): # collect stop positions v = cStop['sliders'][colorIndex].getValue() # set inbetween values # if len(stop
Positions) > 0: # # TODO: fix for right position (refactor testLerpSlider) # testLerpPosition = self.testLerpSlider.getValue() / 100.0 # prevStopPosition = stopPositions[-1] # nextStopPosition = cStop['position'] # stopPositions.append(lerp(prevStopPosition, nextStopPosition, testLerpPosition)) #...
pymber/algorithms
algorithms/sorting/bucket_sort.py
Python
mit
730
0.012329
#!/usr/bin/env python from math import (sqrt, ceil) from insertion_sort import * def bucket_sort(L=[]): ''' Unstable implementation of bucket sort. :param L: list of sortable el
ements. ''' if len(L) < 2: return L # create buckets num_bucket = sqrt(len(L)) interval = int(ceil(max(L) / num_bucket)) bucket = [ [] for x in range(int(num_bucket)+1) ] # bucket = [[]] * int(ceil(num_bucket)) if not bucket: return L # place each items in respective bucket for...
to single array bucket = [ x for y in bucket for x in y ] # return optimized insertion sort return insertion_sort(bucket)
npoznans/python_etl
bayes_evening_workshop/Naive_Bayes_Evening_Workshop/classifiers.py
Python
mit
6,290
0.002226
from collections import Counter, defaultdict import math import pprint import functools # Advanced material here, feel free to ignore memoize if you like. # Long story short, it remembers the inputs and outputs to functions, # and if the same input is seen multiple times, then rather than # running the function multi...
if prediction == class_of_interest: tp += 1 else: tn += 1 else: # we got it wrong :( if prediction == class_of_interest: fp += 1 else: fn += 1 precision = float(tp) / (tp + fp) recall = float(tp)...
, precision) print("recall:", recall) print("f1:", f1) return f1, precision, recall class NaiveBayesClassifier(object): def __init__(self, laplace_smoothing_constant=0.01): self.total_counter = 0 self.class_counter = Counter() self.feature_given_class_counter = default...
tartley/pyweek11-cube
source/model/collision.py
Python
bsd-3-clause
1,781
0.003369
from euclid import Vector3 from ..util.vectors import tuple_of_ints class Collision(object): ''' detects if any objects in the world collide ''' def __init__(self, w
orld): world.item_added += self.world_add_item world.item_removed += self.world_remove_item self.occupied = {}
def world_add_item(self, item): if hasattr(item, 'bounds'): position = (0, 0, 0) if hasattr(item, 'position'): position = item.position self.add_item(position, item) def world_remove_item(self, item): if hasattr(item, 'bounds'): ...
BumagniyPacket/mosaic
run.py
Python
apache-2.0
65
0
from mos
aic import app
if __name__ == '__main__': app.run()
CharlesGust/data_structures
sort_quick/test_quick_sort.py
Python
mit
794
0
import py.test import unittest from quick_sort import sort import random class testQuickSort(unittest.TestCase): def test__init__(self): pass def test_sort_inorder(self): arr = [i for i in xrange(0, 10000)] sortarr = sort
(arr) for i in xrange(1, 10000): self.assertGreaterEqual(sortarr[i], sortarr[i-1]) def test_sort_revorder(self): arr = [i for i in xrange(10000, 0, -1)] sortarr = sort(arr) for i in xrange(1, 10000): self.assertGreaterEqual(sortarr[i], sortarr[i-1]) def ...
0): self.assertGreaterEqual(sortarr[i], sortarr[i-1])
deepmind/jraph
jraph/examples/lstm.py
Python
apache-2.0
5,350
0.006168
# Copyright 2020 DeepMind Technologies Limited. # 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 # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed t...
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. """Example of how to use recurrent networks (e.g.`LSTM`s) with `G...
per-node, per-edge or per-graph recurrent state. In this example we show an `InteractionNetwork` that uses an LSTM to keep a memory of the inputs to the edge model at each step of message passing, by using separate "embedding" and "state" fields in the edge features. Following a similar procedure, an LSTM could be ad...
ulfalizer/Kconfiglib
listnewconfig.py
Python
isc
2,619
0
#!/usr/bin/env python3 # Copyright (c) 2018-2019, Ulf Magnusson # SPDX-License-Identifier: ISC """ Lists all user-modifiable symbols that are not given a value in the configuration file. Usually, these are new symbols that have been added to the Kconfig files. The default configuration filename is '.config'. A diffe...
uppress_traceback=True) # Make it possible to filter this message out print(kconf.load_config(), file=sys.stderr) for sym in kconf.unique_defined_syms: # Only sho
w symbols that can be toggled. Choice symbols are a special # case in that sym.assignable will be (2,) (length 1) for visible # symbols in choices in y mode, but they can still be toggled by # selecting some other symbol. if sym.user_value is None and \ (len(sym.assignable) > ...
salas106/irc-ltl-framework
utils/queue.py
Python
mit
352
0.005682
# -*- coding: utf8 -*- """ The ``queue` utils ================== Some op
eration will require a queue. This utils file """ __author__ = 'Salas' __copyright__ = 'Copyright 2014 LTL' __credits__ = ['Salas'] __license__ = 'MIT' __version__ = '0.2.0' __maintainer__ = 'S
alas' __email__ = '[email protected]' __status__ = 'Pre-Alpha'
eroicaleo/LearningPython
interview/leet/713_Subarray_Product_Less_Than_K.py
Python
mit
434
0.009217
#!/usr/bin/
env python3 class Solution(): def numSubarrayProductLessThanK(self, nums, k): lo, prod = 0, 1 ret = 0
for hi, n in enumerate(nums): prod *= n while lo <= hi and prod >= k: prod //= nums[lo] lo += 1 ret += (hi-lo+1) return ret nums = [10,5,2,6] k = 100 sol = Solution() print(sol.numSubarrayProductLessThanK(nums, k))
extremoburo/django-jquery-file-upload
fileupload/serialize.py
Python
mit
1,030
0.001942
# encoding: utf
-8 import mimetypes import re from django.core.urlresolvers import reverse def order_name(name): """order_name -- Limit a text to 20 chars length, if necessary strips the middle of the text and substitute it for an ellipsis. name -- text to be limited. """ name = re.sub(r'^.*/', '', name) if...
a File instance into a dict. instance -- File instance file_attr -- attribute name that contains the FileField or ImageField """ obj = getattr(instance, file_attr) return { 'url': obj.url, 'name': order_name(obj.name), #'type': mimetypes.guess_type(obj.path)[0] or 'image/pn...
sunqm/psi4-cc
psi4/__init__.py
Python
gpl-2.0
434
0
''' ps = psi4.Solver with psi4.quit
e_run(): ps.prepare_chkpt(mo_coeff, fock_on_mo, nelec, e_scf, nuclear_repulsion) ecc = ps.energy('CCSD', c.shape[1], hcore_on_mo, eri_on_mo) rdm1, rdm2 =
ps.density(mo_coeff.shape[1]) eccsdt = ps.energy('CCSD(T)', c.shape[1], hcore_on_mo, eri_on_mo) rdm1, rdm2 = ps.density(mo_coeff.shape[1]) ''' from wrapper import * __all__ = filter(lambda s: not s.startswith('_'), dir())
sbarbett/ip_intelligence
src/check_json.py
Python
apache-2.0
945
0.012698
# Copyright 2017 NeuStar, Inc.All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "Licens
e"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the L
icense 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. class CheckJSON: def __init__(self, key, obj, ip_info=False): self.key_error = 'Field is not ap...
crmccreary/openerp_server
openerp/addons/product_manufacturer/__openerp__.py
Python
agpl-3.0
1,833
0.004364
############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public L...
penERP SA", 'category': 'Purchase Management', 'complexity': "easy", "depends" : ["stock"], "init_xml" : [], "demo_xml" : [], "description": """ A module that adds manufacturers and attributes on the product form. ==================================================================== You can now ...
anufacturer Product Name * Manufacturer Product Code * Product Attributes """, "update_xml" : [ "security/ir.model.access.csv", "product_manufacturer_view.xml" ], "auto_install": False, "installable": True, "certificate" : "00720153953662760781", 'images': ['images/pr...
bgris/ODL_bgris
lib/python3.5/site-packages/odl/tomo/backends/scikit_radon.py
Python
gpl-3.0
4,830
0
# Copyright 2014-2016 The ODL development group # # This file is part of ODL. # # ODL 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. #...
ta(geometry) scikit_range = scikit_sinogram_space(geometry, volu
me.space, range) sinogram = scikit_range.element(radon(volume.asarray(), theta=theta).T) if out is None: out = range.element() out.sampling(clamped_interpolation(scikit_range, sinogram)) scale = volume.space.cell_sides[0] out *= scale return out def scikit_radon_back_projector(si...
Monithon/Monithon-2.0
campaigns/migrations/0003_auto_20141130_0858.py
Python
gpl-2.0
1,412
0.003541
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('campaigns', '0002_auto_20141022_1840'), ] operations = [ migrations.AlterField( model_name='campaignform', ...
aignproject', name='project', field=models.ForeignKey(related_name='campaigns', to='projects.Monitorable'), preserve_default=True, ), migrations.AlterField( model_name='campaignreport', name='campaign', field=models.ForeignKey(relat...
t', name='report', field=models.ForeignKey(related_name='campaigns', to='reports.Report'), preserve_default=True, ), ]
jimmyraywv/cloud-custodian
tests/test_offhours.py
Python
apache-2.0
21,903
0.000274
# Copyright 2015-2017 Capital One Services, 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 agreed ...
) self.assertEqual(f(i), True) i = instance( Tags=[{'Key': 'maid_offhours', 'Value': 'on'}] ) self.assertEqual(f(i), True) i = instance( Tags=[{'Key': 'maid_offhours', 'Value': 'off'}]) self.assertEqual(...
of opt out behavior, verify if its # not configured that we don't touch an instance that # has no downtime tag i = instance(Tags=[]) i2 = instance(Tags=[{'Key': 'maid_offhours', 'Value': ''}]) i3 = instance(Tags=[{'Key': 'maid_offhours', 'Value': 'on'}]) t = datetime.dat...
degiacom/assemble
ForceField.py
Python
gpl-3.0
4,345
0.023245
# Copyright (c) 2014-2018 Matteo Degiacomi and Valentina Erastova # # Assemble is free software ; # you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; # either version 2 of the License, or (at your option) any later version. # Assemb...
know where the minimum is. Return default value else: return self.default_bond def get_angle(self,name): if self.fftype[1]>=1 and self.fftype[1]<=2: return self.bonded[name][0] #no analytical minimum exists, return default else: return self.d...
[2]<=2: return self.bonded[name][0] #no analytical minimum exists, return default else: return self.default_dihedral if __name__=="__main__": FF=ForceField() FF.load("./database/forcefield/trappe.ff.txt") #FF.load("C:\Users\Matteo\workspace\polymer...
techinc/imagepusher
munch.py
Python
mit
651
0.058372
import imagepusher, random if __name__ == '__main__': host, port = '', 18002 pusher = imagepusher.ImagePusher( (host, port) ) width, height
= 12, 10 munch = [ [ [0,0,0] for x in xrange(width) ] for y in xrange(height) ] while True: for i in xrange(16): for j in xrange(i+1): for y in xrange(height): for x in xrange(width): if y == (x ^ j): munch[y][x]
[0] += 1 munch[y][x][0] %= 256 munch[y][x][1] += 5 munch[y][x][1] %= 256 munch[y][x][2] += 9 munch[y][x][2] %= 256 frame = [ [ [n/255., m/255., o/255.] for n,m,o in row ] for row in munch ] pusher.push_frame( frame )
jvictor0/TweetTracker
src/TwitterRank/CheckGraph.py
Python
mit
1,247
0.00401
import sys, os, re, time, resource, gc import ujson, boto import boto.s3.connection from collections import defaultdict access_key = os.environ["AWS_ACCESS_KEY"] secret_key = os.environ["AWS_SECRET_KEY"] def key_iterator(key): """ Iterator for line by line, for going through the whole contents of a key ""...
aws_access_key_id=access_key, aws_secret_access_key=secret_key) bucket = conn.get_bucket("tweettrack") count = 0 keys = bucket.list("Twitterrank_Full_Output/graph") for f in keys: print f f_iter = key_iterator(f) for line in f_iter: count += 1 ...
fuck this shit, we fucked up" print line sys.exit(0) if count % 50000 == 0: print "count is: %d" % (count,) conn.close() if __name__ == "__main__": main(sys.argv)
SimpleGeometry/bisv-ml
tensorflow-2/tf_linreg.py
Python
mit
2,049
0.028306
#import libraries import tensorflow as tf import numpy as np def get_data(): #data is from the computer hardware dataset found on the UCI ML repository with open('data.txt', 'r') as fin: text_in = fin.read() split = text_in.splitlines() data = [] for line in split: data.append(line.split(',')) np_data = np....
n_examples = np.shape(x_data)[0] n_features =
np.shape(x_data)[1] x_data = np.transpose(x_data) y_data = np.reshape(y_data, [1, n_examples]) ############################## YOUR CODE HERE ##################################### ''' Replace all the quotes/variables in quotes with the correct code ''' #declare graph #1: declare placeholders x and y (to hold dat...
jupyterhub/oauthenticator
oauthenticator/mediawiki.py
Python
bsd-3-clause
4,178
0.000957
""" Custom Authenticator to use MediaWiki OAuth with JupyterHub Requires `mwoauth` package. """ import json import os from asyncio import wrap_future from concurrent.futures import ThreadPoolExecutor from jupyterhub.handlers import BaseHandler from jupyterhub.utils import url_path_join from mwoauth import ConsumerTok...
bytestrings, json.dumps balks def jsonify(request_token): return json.dumps( [ request_token.key, request_to
ken.secret, ] ) def dejsonify(js): key, secret = json.loads(js) return RequestToken(key, secret) class MWLoginHandler(BaseHandler): async def get(self): consumer_token = ConsumerToken( self.authenticator.client_id, self.authenticator.client_secret, ) ...
cmorgan/toyplot
toyplot/png.py
Python
bsd-3-clause
2,849
0.002457
# Copyright 2014, Sandia Corporation. Under the terms of Contract # DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain # rights in this software. from __future__ import absolute_import from __future__ import division import toyplot.cairo.png def render(canvas, fobj=None, width=None, hei...
ne of `width`, `height`, or `scale` to override this behavior. Parameters ---------- canvas: :class:`toyplot.canvas.Canvas` Canvas to be rendered. fobj: file-like obje
ct or string, optional The file to write. Use a string filepath to write data directly to disk. If `None` (the default), the PNG data will be returned to the caller instead. width: number, optional Specify the width of the output image in pixels. height: number, optional Specify t...
endlessm/chromium-browser
third_party/llvm/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/list/loop/TestDataFormatterLibcxxListLoop.py
Python
bsd-3-clause
2,446
0.002044
""" Test that the debugger handles loops in std::list (which can appear as a result of e.g. memory corruption). """ import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class LibcxxListDataFormat
terTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) NO_DEBUG_INFO_TESTCASE = True @add_test_categories(["libc++"]) @expectedFailureAndroid(bugnumber="llvm.org/pr32592") def test_with_run_command(self): self.build() exe = self.getBuildArtifact("
a.out") target = self.dbg.CreateTarget(exe) self.assertTrue(target and target.IsValid(), "Target is valid") file_spec = lldb.SBFileSpec("main.cpp", False) breakpoint1 = target.BreakpointCreateBySourceRegex( '// Set break point at this line.', file_spec) self.assertTr...
vivekanand1101/python-fedora
fedora/client/wiki.py
Python
gpl-2.0
9,280
0.000862
#!/usr/bin/python -tt # -*- coding: utf-8 -*- # # Copyright 2008-2009 Red Hat, Inc. # This file is part of python-fedora # # python-fedora 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 # versi...
'api.php', req_params={ 'list': 'recentchanges', 'action': 'query', 'format': 'json', 'rcprop': 'user|title', 'rcend': then.isoformat().split('.')[0] + 'Z',
'rclimit': limit, }) if 'error' in data: raise Exception(data['error']['info']) return data['query']['recentchanges'] def login(self, username, password): data = self.send_request('api.php', req_params={ 'action': 'login', 'format': 'json', ...
Csega/pyTsai
windows_binary_2.4/windows_compiling/msvccompiler.py
Python
lgpl-2.1
22,127
0.004384
"""distutils.msvccompiler Contains MSVCCompiler, an implementation of the abstract CCompiler class for the Microsoft Visual Studio. """ # Written by Perry Stoll # hacked by Robin Becker and Thomas Heller to do a better job of # finding DevStudio (through the registry) # This module should be kept compatible with P...
build Python. For Python 2.3 and up, the version number is included in sys.version. For earlier versions, assume the compiler is MSVC 6. """ prefix = "MSC v." i = string.fin
d(sys.version, prefix) if i == -1: return 6 i = i + len(prefix) s, rest = sys.version[i:].split(" ", 1) majorVersion = int(s[:-2]) - 6 minorVersion = int(s[2:3]) / 10.0 # I don't think paths are affected by minor version in version 6 if majorVersion == 6: minorVersion = 0 ...
yahman72/robotframework
atest/testdata/standard_libraries/remote/specialerrors.py
Python
apache-2.0
689
0.001451
import sys from remoteserver import Direct
ResultRemoteServer class SpecialErrors(object): def
continuable(self, message, traceback): return self._special_error(message, traceback, continuable=True) def fatal(self, message, traceback): return self._special_error(message, traceback, fatal='this wins', continuable=42) def _special_error(self, message, tr...
rereidy/SPSE
module 5 - Exploitation Techniques/5-1.py
Python
gpl-3.0
3,540
0.004237
#!/usr/bin/env python import threading import Queue import ftplib import getopt import os import sys import time DEF_THREAD_CNT = 5 DEF_NAP_TIME = 10 class FTPExcept(Exception): def __init__(self, v): self.value = v def __str__(self): return repr(self.value) class FTPWT(threading.Thread): ...
st of sites" def process_args(argv): sites = [] thread_count = -1 nap_time = -1 locking = False try: opts,
args = getopt.getopt(argv, 'hs:t:l') except getopt.GetoptError: usage() sys.exit(1) for opt, arg in opts: if opt == '-h': usage() sys.exit(2) elif opt == '-s': for s in (arg.split(',')): sites.append(s) elif opt == '-t...
spektom/incubator-airflow
airflow/contrib/sensors/gcs_sensor.py
Python
apache-2.0
3,286
0.003652
# # 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...
KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """This module is deprecated. Please use `airflow.providers.google.cloud.sensors.gcs`.""" import warnings from airflow.providers.google.cloud.sensors.gcs import ( GCSObjectExist...
s deprecated. Please use `airflow.providers.google.cloud.sensors.gcs`.", DeprecationWarning, stacklevel=2 ) class GoogleCloudStorageObjectSensor(GCSObjectExistenceSensor): """ This class is deprecated. Please use `airflow.providers.google.cloud.sensors.gcs.GCSObjectExistenceSensor`. """ def _...
uranusjr/django
django/db/backends/base/introspection.py
Python
bsd-3-clause
7,497
0.001601
from collections import namedtuple # Structure returned by DatabaseIntrospection.get_table_list() TableInfo = namedtuple('TableInfo', ['name', 'type']) # Structure returned by the DB-API cursor.description interface (PEP 249) FieldInfo = namedtuple('FieldInfo', 'name type_code display_size internal_size precision sca...
nfig, self.connection.alias): if not model._meta.managed: continue tables.add(model._meta.db_table) tables.update( f.m2m_db_table() for f in model._meta.local_many_to_
many if f.remote_field.through._meta.managed ) tables = list(tables) if only_existing: existing_tables = self.table_names(include_views=include_views) tables = [ t for t in tables if self.table_na...
sa2ajj/DistroTracker
pts/vendor/skeleton/rules.py
Python
gpl-2.0
11,857
0.000675
# Copyright 2013 The Distro Tracker Developers # See the COPYRIGHT file at the top-level directory of this distribution and # at http://deb.li/DTAuthors # # This file is part of Distro Tracker. It is subject to the license terms # in the LICENSE file found in the top-level directory of this # distribution and at http:/...
: The original received package message :type msg: :py:class:`Message <email.message.Message>` """ pass def add_new_headers(received_message, package_name, keyword): """ The function should return a list of two-tuples (header_name, header_value) which are extra headers that should be added to ...
ers. If no extra headers are wanted return an empty list or ``None`` :param received_message: The original received package message :type received_message: :py:class:`email.message.Message` :param package_name: The name of the package for which the message was intended :type package_name:...
sysuccc/QiuDaBao
manage.py
Python
gpl-2.0
251
0
#!/usr/bin/env python
import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "QiuDaBao.settin
gs") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
ArcherSys/ArcherSys
skulpt/test/run/t242.py
Python
mit
262
0.072519
class O(obje
ct): pass class A(O): pass class B(O): pass clas
s C(O): pass class D(O): pass class E(O): pass class K1(A,B,C): pass class K2(D,B,E): pass class K3(D,A): pass class Z(K1,K2,K3): pass print K1.__mro__ print K2.__mro__ print K3.__mro__ print Z.__mro__
RyanSkraba/beam
sdks/python/apache_beam/examples/streaming_wordcount_it_test.py
Python
apache-2.0
4,580
0.001965
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
# # 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. #...
e.core.allof import all_of from nose.plugins.attrib import attr from apache_beam.examples import streaming_wordcount from apache_beam.io.gcp.tests.pubsub_matcher import PubSubMessageMatcher from apache_beam.runners.runner import PipelineState from apache_beam.testing import test_utils from apache_beam.testing.pipeline...
pat1/autoradio
autoradio/mpris2/decorator/__init__.py
Python
gpl-2.0
323
0.003096
''' This is
not part of specification Helper class to make it work as python lib ''' from .attribute import DbusAttr from .interface import DbusInterface from .method import DbusMethod from .signal import DbusSignal from .utils import get_mainloop, get_uri, implements, \ list_all_interface, list
_interfaces, list_paths
mayfield/plexcli
plexcli/commands/activity.py
Python
mit
1,539
0
""" Activity logs. """ import asyncio import datetime import json import websockets from . import base from shellish.layout import Table class Log(base.PlexCommand): """ Show activity log """ name = 'log' type_map = { 'StatusNotification': 'Status', 'ProgressNotification': 'Progress' ...
self.type_map[obj['_elementType']] def get_msg(self, obj): if 'message' in obj: return obj['message'] return '%s: %s' % (obj['title'], obj['description']) def run(self, args): headers = ['Date', 'Type', 'Message'] accessors = [self.get_ts, self.get_type, self.get_m...
op() with evloop.run_until_complete(self.notifications(table)): pass activity = base.PlexCommand(name='activity', doc=__doc__) activity.add_subcommand(Log, default=True) __commands__ = [activity]
kenshay/ImageScript
ProgramData/SystemFiles/Python/Lib/site-packages/elan/Pools/AddRemove/1_Count_Security_Panels.py
Python
gpl-3.0
2,762
0.005069
from ImageScripter import * from elan.functions import Get_Device_List_Simple,Diff from elan import * #Past_List = ['2GIG GC3', '2GIG GC3', '2GIG GC3 (3.2 firmware)', 'Ademco VISTA-128BP,250BP,FA1660C', 'Ademco VISTA-128BPT,250BPT', 'Ademco VISTA-128FBP,250FBP', 'Bosch/Radionics D7412G,D9412G', 'DSC MAXSYS', 'DSC Powe...
ISTA-128FBP,250FBP', 'Bosch/Radionics D7412G,D94
12G', 'DSC MAXSYS', 'DSC Power Series / 5401', 'DSC Power Series / IT-100', 'ELK-M1', 'GE Concord', 'GE NetworX NX-4,6,8,8E', 'HAI Omni Series', 'Napco Gemini GEM-X255, P9600', 'Paradox Digiplex', 'Texecom Premier Elite', 'Vario (IP)', 'Vario (RS-232)', 'Virtual Security Controller'] Past_List = ['2GIG GC3', '2GIG GC3 ...
volpino/Yeps-EURAC
tools/regVariation/substitutions.py
Python
mit
2,849
0.015444
#! /usr/bin/python #Guruprasad ANanda """ Fetches substitutions from pairwise alignments. """ from galaxy import eggs from galaxy.tools.util import maf_utilities import bx.align.maf import sys import os, fileinput def stop_err(msg): sys.stderr.write(msg) sys.exit() if len(sys.argv) < 3: stop_err("In...
nt('-')) print >>fout, "%s\t%s\t%s" %(src2,start2+sub_be
gin-sequence2[0:sub_begin].count('-'),start2+sub_end-sequence2[0:sub_end].count('-')) begin = False else: if begin: print >>fout, "%s\t%s\t%s" %(src1,start1+sub_begin-sequence1[0:sub_begin].count('-'),end1+sub_end-sequence1[0:sub_end].count('-...
dashee87/cluster-flag
clusterflag/__init__.py
Python
mit
23
0
__v
ersion__ = '0.1.
2'
Adventure-Inc/chachas-adventures
services/views.py
Python
apache-2.0
167
0
from django.shortcuts import render from django.
http import HttpRespo
nse import json def services(request): return render(request, 'services/services.html', {})
bendudson/BOUT
examples/test-staggered/generate.py
Python
gpl-3.0
522
0.005747
#!/usr
/bin/env python # # Generate an input mesh # from boututils import DataFile # Wrapper around NetCDF4 libraries nx = 5 # Minimum is 5: 2 boundary, one evolved ny = 32 # Minimum 5. Should be divisible by number of processors (so powers of 2 nice) d
y = 1. # distance between points in y, in m/g22/lengthunit ixseps1 = -1 ixseps2 = -1 f = DataFile() f.open("test-staggered.nc", create=True) f.write("nx", nx) f.write("ny", ny) f.write("dy", dy) f.write("ixseps1", ixseps1) f.write("ixseps2", ixseps2) f.close()
reminisce/mxnet
tests/python/unittest/test_random.py
Python
apache-2.0
50,683
0.009569
# 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...
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. import os import math import itertools import mxnet as mx from...
ort verify_generator, gen_buckets_probs_with_ppf, retry import numpy as np import random as rnd from common import setup_module, with_seed, random_seed, teardown import scipy.stats as ss import unittest from mxnet.test_utils import * def same(a, b): return np.sum(a != b) == 0 def check_with_device(device, dtype):...
punalpatel/st2
st2common/st2common/exceptions/db.py
Python
apache-2.0
1,337
0
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use th...
StackStormBaseException class StackStormDBObjectNotFoundError(StackStormBaseException): pass class StackStormDBObjectMalformedError(StackStormBaseException): pass class StackStormDBObjectConflict
Error(StackStormBaseException): """ Exception that captures a DB object conflict error. """ def __init__(self, message, conflict_id, model_object): super(StackStormDBObjectConflictError, self).__init__(message) self.conflict_id = conflict_id self.model_object = model_object
tanglei528/ceilometer
ceilometer/compute/notifications/__init__.py
Python
apache-2.0
1,338
0
# -*- encoding: utf-8 -*- # # Copyright © 2013 Intel # # Author: Shuangtai Tian <[email protected]> # # 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/licen...
d 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. from oslo.config import cfg import oslo.messagi...
default='nova', help="Exchange name for Nova notifications."), ] cfg.CONF.register_opts(OPTS) class ComputeNotificationBase(plugin.NotificationBase): @staticmethod def get_targets(conf): """Return a sequence of oslo.messaging.Target defining the exchange and topics to b...
iphoting/healthchecks
hc/api/tests/test_notify_email.py
Python
bsd-3-clause
5,005
0
# coding: utf-8 from datetime import timedelta as td import json from django.core import mail from django.utils.timezone import now from hc.api.models import Channel, Check, Notification, Ping from hc.test import BaseTestCase class NotifyEmailTestCase(BaseTestCase): def setUp(self): super().setUp() ...
ck.schedule = "0 18-23,0-8 * * *" self.check.save() self.channel.notify(self.check) email = mail.outbox[0] html = email.alternatives[0][0] self.assertIn("<code>0 18-23,0-8 * * *</code>", html) def test_it_truncates_long_body(self): self.ping.body = "X" * 10000 + "...
atives[0][0] self.assertIn("[truncated]", html) self.assertNotIn("the rest gets cut off", html) def test_it_handles_missing_ping_object(self): self.ping.delete() self.channel.notify(self.check) email = mail.outbox[0] html = email.alternatives[0][0] self.a...
california-civic-data-coalition/django-calaccess-downloads-website
toolbox/apps.py
Python
mit
130
0
fro
m __future__ import unicode_literals from django.apps import AppConfig class ToolboxConfig(AppConfig):
name = 'toolbox'
fmarani/spam
spam/spamhaus.py
Python
lgpl-3.0
1,760
0.001705
#!/usr/bin/env python from urlparse import urlparse from socket import gethostbyname from spam import DomainInexistentException class SpamHausChecker(object): """spam checker using spamhaus""" IS_SPAM = 1 IS_NOT_SPAM = 2 def _query_spamhaus(self, spamhaus_zone): try: return getho...
.IS_NOT_SPAM def check_url(self, url): """check an url""" domain = urlparse(url).netloc return self.check_domain(domain) def check_domain(self, domain): """check a domain""" domain = domain[domain.find('@')+1:] # remove user info if domain.count(":") > 0: ...
nInexistentException spamhaus_zone = self._build_spamhaus_zone(ip) spamhaus_result = self._query_spamhaus(spamhaus_zone) return self._decode_spamhaus(spamhaus_result) def is_spam(self, url): """shortcut for check_url == IS_SPAM""" return self.check_url(url) == self.IS_SPAM ...
jehomez/pymeadmin
actualizacion_de_precios.py
Python
gpl-2.0
1,494
0.003347
import gtk import treetohtml from mensajes import info, yesno from datetime import date, datetime from articulos import DlgArticulo from articulos_produccion import ArticulosEnProduccion from modelo import Model from comunes import punto_coma, coma_punto, caracter_a_logico, logico_a_caracter, calcular_iva_venta, calcul...
self.dialogo = builder.get_object('dialogo') self.scroll = builder.get_object('scroll_window') self.tree = builder.get_object('vista') self.lista = builder.get_object('lista') self.opcion_algunos = builder.get_object('algunos') s
elf.opcion_todos = builder.get_object('todos') self.dialogo.show() def on_todos_group_changed(self, *args): pass def on_algunos_group_changed(self, *args): if self.opcion_algunos.get_active() == 1: self.scroll.set_visible(True) self.tree.set_visible(Tru...
walteryang47/ovirt-engine
packaging/pythonlib/ovirt_engine/ticket.py
Python
apache-2.0
3,464
0
import base64 import datetime import json from M2Crypto import EVP, X509, Rand class TicketEncoder(): @staticmethod def _formatDate(d): return d.strftime("%Y%m%d%H%M%S") def __init__(self, cert, key, lifetime=5): self._lifetime = lifetime self._x509 = X509.load_cert(cert) ...
) != 1: raise ValueError('Invalid ticket signature') if not ( self._parseDate(decoded['validFrom']) <= datetime.datetime.utcnow() <=
self._parseDate(decoded['validTo']) ): raise ValueError('Ticket life time expired') return decoded['data'] # vim: expandtab tabstop=4 shiftwidth=4
tobspr/LUI
Builtin/LUIInputField.py
Python
mit
8,056
0.002234
import re from LUIObject import LUIObject from LUISprite import LUISprite from LUILabel import LUILabel from LUIInitialState import LUIInitialState from L
UILayouts import LUIHorizontalStretchedLayout __all__ = ["LUIInputField"] class LUIInputField(LUIObject): """ Simple input field, accepting text input. This input field supports entering text and navigating. Selecting text is (currently) not supported. The input field also supports various keyboard sho...
[arrow_left] Move one character to the left [arrow_right] Move one character to the right [ctrl] + [arrow_left] Move to the left, skipping over words [ctrl] + [arrow_right] Move to the right, skipping over words [escape] Un-focus input element ...
anupamaloke/Dell-EMC-Ansible-Modules-for-iDRAC
library/dellemc_idrac_nic.py
Python
gpl-3.0
16,156
0.001795
#! /usr/bin/python # _*_ coding: utf-8 _*_ # # Dell EMC OpenManage Ansible Modules # # Copyright © 2017 Dell Inc. or its subsidiaries. All rights reserved. # Dell, EMC, and other trademarks are trademarks of Dell Inc. or its # subsidiaries. Other trademarks may be trademarks of their respective owners. # # This progra...
Network share user in the format user@domain if user is part of a domain else 'user' type: 'str' share_pwd: required: True description: - Network share user password type: 'str' share_mnt: required: True description: - Local mount path of the network file share with read-write p...
e user type: 'path' nic_selection: required: False description: - NIC Selection mode choices: ['Dedicated','LOM1','LOM2','LOM3','LOM4'] default: "Dedicated" nic_failover: required: False description: - Failover network if NIC selection fails choices: ["None", "LOM1", "LOM...
pat-odoo/TwoRC522_RPi2-3
module/gpio.py
Python
gpl-3.0
391
0.01023
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Class in Python 2.7 for incorporation o
f the RPi.GPIO module to control the GPIO channels of Raspberry Pi. """ import RPi.GPIO as GPIO __author__ = "" __copyright__ = "" __email__ = "" __status__ = "Prototype" class PinsGPIO(object): gpio = None def __init__(self):
self.gpio = GPIO
SINTEFMedtek/CTK
Applications/ctkSimplePythonShell/Testing/Python/wrappedVTKQInvokableTest.py
Python
apache-2.0
531
0.001883
from __future__ import print_function import qt # Importing vtk initializes vtkPythonMap owned by vtkPythonUtil and prevent # call to vtkPythonUtil::GetObjectFromPointer() from segfaulting. # PythonQt internally uses vtkPythonUtil to properly wrap/unwrap VTK objects
from vtk import * t = _testWrappedVTKQInvokableInstance.getTable() print(t.GetClassName()) t2 = vtkTable() _testWrappedVTKQInvokableInstance.setTable(t2) if _testWrappedVTKQInvokableInstance.getTable()
!= t2: qt.QApplication.exit(1) qt.QApplication.exit(0)
amandolo/ansible-modules-core
system/setup.py
Python
gpl-3.0
5,256
0.005327
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2012, Michael DeHaan <[email protected]> # # 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...
playbooks. It can also be executed directly by C(/usr/bin/ansible) to check what variables are available to a host. Ansible provides many I(facts) about the system, automatically. notes: - More ansible facts will be added with successive releases. If I(facter) or I(ohai) are installed, v...
pshotted into the JSON file for usage in templating. These variables are prefixed with C(facter_) and C(ohai_) so it's easy to tell their source. All variables are bubbled up to the caller. Using the ansible facts and choosing to not install I(facter) and I(ohai) means you can avoid Ruby-depende...
cangermueller/deepcpg
tests/deepcpg/data/test_annos.py
Python
mit
2,793
0
from __future__ import division from __future__ import print_function import numpy as np import numpy.testing as npt import pandas as pd from deepcpg.data import annotations as annos def test_join_overlapping(): f = annos.join_overlapping s, e = f([], []) assert len(s) == 0 assert len(e) == 0 ...
s, e) assert result == expect x = np.array([[1, 2], [3, 4], [4, 5], [6, 8], [8, 8], [8, 9], [10, 15], [10, 11], [11, 14], [14, 16]] ) expect = [[1, 2], [3, 5], [6, 9], [10, 16]] result = np.array(f(x[:, 0], x[:, 1])).T npt.asser...
] result = f(x, ys, ye) npt.assert_array_equal(result, expect) x = [-1, 3, 9, 19] expect = [-1, -1, -1, -1] result = f(x, ys, ye) npt.assert_array_equal(result, expect) x = [-1, 2, 2, 3, 4, 8, 15, 16] expect = [-1, 0, 0, -1, 1, 1, 2, -1] result = f(x, ys, ye) npt.assert_array_e...
jpotterm/django-fluent-contents
fluent_contents/tests/testapp/admin.py
Python
apache-2.0
360
0
from django.contrib import admin from fluent_contents.admin import PlaceholderFieldAdmin from .models import PlaceholderFieldTestPage class PlaceholderFieldTestPageAdmin(PlaceholderFieldAdmin):
""" Admin interface for the PlaceholderFieldTestPage model. """ pass admin.site.register(Plac
eholderFieldTestPage, PlaceholderFieldTestPageAdmin)
xclxxl414/rqalpha
rqalpha/utils/package_helper.py
Python
apache-2.0
953
0
# -*- coding: utf-8 -*- # # Copyright 2017 Ricequant, Inc # # Licensed under
the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.a
pache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # li...
edisonlz/fruit
web_project/base/site-packages/django/contrib/syndication/views.py
Python
apache-2.0
8,515
0.007634
from __future__ import unicode_literals from calendar import timegm from django.conf import settings from django.contrib.sites.models import get_current_site from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist from django.http import HttpResponse, Http404 from django.template import loader, Te...
def get_context_data(self, **kwargs): """ Returns a dictionary to use as extra context if either ``self.description_template`` or ``self.item_template`` are used. Default implementation preserves the old behavior of using {'obj': item, 'site'
: current_site} as the context. """ return {'obj': kwargs.get('item'), 'site': kwargs.get('site')} def get_feed(self, obj, request): """ Returns a feedgenerator.DefaultFeed object, fully populated, for this feed. Raises FeedDoesNotExist for invalid parameters. """ ...
jamesaud/se1-group4
address/models.py
Python
mit
9,864
0.004562
from django.db import models from django.core.exceptions import ValidationError from django.db.models.fields.related import ForeignObject try: from django.db.models.fields.related_descriptors import ForwardManyToOneDescriptor except ImportError: from django.db.models.fields.related import ReverseSingleRelatedOb...
country_obj = None # Handle the state. try: state_obj = State.objects.get(name=state, country=country_obj) except State.DoesNotExist: if state: i
f len(state_code) > State._meta.get_field('code').max_length: if state_code != state: raise ValueError('Invalid state code (too long): %s'%state_code) state_code = '' state_obj = State.objects.create(name=state, code=state_code, country=country_obj) ...
stephane-martin/salt-debian-packaging
salt-2016.3.3/salt/modules/boto_sqs.py
Python
apache-2.0
5,122
0.000976
# -*- coding: utf-8 -*- ''' Connection module for Amazon SQS .. versionadded:: 2014.7.0 :configuration: This module accepts explicit sqs credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no furthe...
tributes) for attr, val in six.iteritems(attributes): attr_set = queue_obj.set_attribute(attr, val) if not attr_set: msg = 'Failed to set attribute {0} = {1} on queue {2}' log.error(msg.format(attr, val, name))
ret = False else: msg = 'Set attribute {0} = {1} on queue {2}' log.info(msg.format(attr, val, name)) return ret
kasbah/slim_looper
src/protocol/nanopb/tests/site_scons/site_init.py
Python
gpl-3.0
3,700
0.015135
import subprocess import sys import re try: # Make terminal colors work on windows import colorama colorama.init() except ImportError: pass def add_nanopb_builders(env): '''Add the necessary builder commands for nanopb tests.''' # Build command that runs a test program and saves the output ...
_test, suffix = '.output')
env.Append(BUILDERS = {'RunTest': run_test_builder}) # Build command that decodes a message using protoc def decode_actions(source, target, env, for_signature): esc = env['ESCAPE'] dirs = ' '.join(['-I' + esc(env.GetBuildPath(d)) for d in env['PROTOCPATH']]) return '$PROTOC $PROTOCFLA...
51reboot/actual_09_homework
09/tanshuai/cmdb_v6/user/views.py
Python
mit
8,533
0.006442
#!/usr/bin/env python # -*- coding: utf-8 -*- from flask import render_template, request, redirect, session, flash, url_for from functools import wraps from user import app import services2db import log2db import users import json import time import sys import asset reload(sys) sys.setdefaultencoding('gb18030') # 登录验...
# 显示域名管理信息 @app.route('/services/', methods=['POST', 'GET']) @login_required def service_manage(): params
= request.args if request.method == 'GET' else request.form _url = params.get('url', 'Null') _username = params.get('username', 'Null') _password = params.get('password', 'Null') _func = params.get('func', 'Null') # 添加域名管理信息 if _url != 'Null': if services2db.add_service(_url, _username, ...
ioram7/keystone-federado-pgid2013
build/eventlet/eventlet/support/greenlets.py
Python
apache-2.0
1,085
0.003687
import distutils.version try: import greenlet getcurrent = greenlet.greenlet.getcurrent GreenletExit = greenlet.greenlet.GreenletExit preserves_excinfo = (distutils.version.LooseVersion(greenlet.__version__) >= distutils.version.LooseVersion('0.3.2')) greenlet = greenlet.greenlet except...
etcurrent = greenlet.getcurrent GreenletExit = greenlet.GreenletExit preserves_excinfo = False except ImportError: try: from stackless import greenlet getcurrent = greenlet.getcurrent GreenletExit = greenlet.GreenletExit preserves_excinfo = Fal...
except ImportError: try: from support.stacklesss import greenlet, getcurrent, GreenletExit preserves_excinfo = False (greenlet, getcurrent, GreenletExit) # silence pyflakes except ImportError, e: raise ImportError("Unable to...
Ishydo/miot
miot/forms.py
Python
mit
791
0.005057
from mapwidgets.widgets import GooglePointFieldWidget from miot.models import PointOfInterest, Page, Profile from django import forms class PointOfInterestForm(forms.ModelForm): '''The form for a point of interest.''' class Meta: model = PointOfInterest fields = ("name", "featured_i
mage", "position", "tags", "active", "category") widgets = { 'position': GooglePointFiel
dWidget, } class PageForm(forms.ModelForm): '''The form for a page.''' class Meta: model = Page fields = ("title", "content", "template") class EstimoteAppForm(forms.ModelForm): '''The form for a profile update (estimote credentials).''' class Meta: model = Profile ...
maximilianofaccone/puppy-siberian
root/.conky/gmail.py
Python
gpl-3.0
480
0.03125
import os import string #Enter your username and password below within double quotes # eg. username="username" and password="password" username="username" password="password" com="wget -O - https://"+username+":"+password+"@mail.google.com/
mail/feed/atom --no-check-certificate" temp=os.popen(com) msg=temp.read() index=string.find(msg,"<fullcount>") index2=string.find(msg,"</fullcount>") fc=int(
msg[index+11:index2]) if fc==0: print "0 new" else: print str(fc)+" new"
seerjk/reboot06
06/flask_web.py
Python
mit
1,609
0.003108
from flask import Flask, request, render_template app = Flask(__name__) @app.route('/') def index(): # return 'hello flask' # return '<input type="button" value="click me!!">' # return '<input type="text">' # return '<input type="password">' # return '<input type="date">' # return '<input type=...
ame = request.args.get('name') age = request.args.ge
t('age') # print type(request.args) # print request.args # http://10.1.1.8:9092/reboot?name=abcb&age=15 return 'hello reboot, name: %s, age: %s' % (name, age) @app.route('/login') def login(): user = request.args.get('user') pwd = request.args.get('pwd') res = '' lines = [] user_dic...
dc3-plaso/dfvfs
dfvfs/resolver/lvm_resolver_helper.py
Python
apache-2.0
1,206
0.003317
# -*- coding: utf-8 -*- """The LVM path specification resolver helper implementation.""" # This is necessary to prevent a circular import. import dfvfs.file_io.lvm_file_io import dfvfs.vfs.lvm_file_system from dfvfs.lib import definitions from dfvfs.resolver import resolver from dfvfs.resolver import resolver_helper ...
r.ResolverHelper): """Class that implements the Logical Volume Manager (LVM
) resolver helper.""" TYPE_INDICATOR = definitions.TYPE_INDICATOR_LVM def NewFileObject(self, resolver_context): """Creates a new file-like object. Args: resolver_context: the resolver context (instance of resolver.Context). Returns: The file-like object (instance of file_io.FileIO). ...
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-2.3/Lib/gopherlib.py
Python
mit
5,564
0.010065
"""Gopher protocol client interface.""" __all__ = ["send_selector","send_query"] # Default selector, host and port DEF_SELECTOR = '1/' DEF_HOST = 'gopher.micro.umn.edu' DEF_PORT = 70 # Recognized file types A_TEXT = '0' A_MENU = '1' A_CSO = '2' A_ERROR = '3' A_MACBINHEX = '4' A_PCBIN...
xtfile(f, func): """Get a text file and pass each line to a function, with trailing CRLF stripped.""" while 1: line = f.rea
dline() if not line: print '(Unexpected EOF from server)' break if line[-2:] == CRLF: line = line[:-2] elif line[-1:] in CRLF: line = line[:-1] if line == '.': break if line[:2] == '..': line = line[1:] ...
suselrd/django-wflow
workflows/decorators.py
Python
bsd-3-clause
6,481
0.003857
# coding=utf-8 from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db import models from django.utils.translation import ugettext_lazy as _ from models import WorkflowBase, State from utils import get_wf_dict_value def create_transition_method(transition_name, transit...
Custo
mManagerMixin, manager.__class__): pass setattr(ExtendedManager, 'get_queryset', create_manager_get_queryset_method(manager, CustomQuerySetMixin)) cls.add_to_class(mgr_name, ExtendedManager()) return cls
bjodah/pycompilation
pycompilation/_release.py
Python
bsd-2-clause
31
0
__version__ = '0.5.0.dev0+
git
'
jacobajit/ion
intranet/middleware/environment.py
Python
gpl-2.0
1,848
0.002165
# -*- coding: utf-8 -*- import logging import os logger = logging.getLogger(__name__) class KerberosCacheMiddleware(object): """Reloads the KRB5CCNAME environmental variable from the session for potential use in future LDAP requests. For a login request, the KRB5CCNAME environmental variable has al...
ser who most recently logged in through that worker. The environmental variable must be set by middleware so it is available for requests to any view and so each view does not have to load the environmental variable. The LDAP wrapper (intranet.db.ldap_db) cannot set the environmental variable becau...
variable to the environmental variable.""" if "KRB5CCNAME" in request.session: # It is important to check that the environmental variable # matches the session variable because environmentals stay # on the worker after requests. if "KRB5CCNAME" in os.environ: ...
shanzi/thesiscode
topiccrawler.py
Python
bsd-2-clause
4,289
0.001632
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import time import json import random import urllib import logging import argparse import coloredlogs from pyquery import PyQuery BASEDIR = os.path.dirname(os.path.abspath(__name__)) OUTPUTDIR = os.path.join(BASEDIR, 'data/output') coloredlogs.install() clas...
' % self) logging.debug('writing path: %s' % self.filepath) with open(self.filepath, 'w') as f: json.dump(obj, f) def readtopics(path): topics = [] with open(path) as f: for l in f.readlines(): l = l.decode('utf8').strip() if not l: continue ...
cpair = l.split() topics.append((topicpair[0], int(topicpair[1]))) return topics if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("filename", help="The file which contains the topics to be processed") args = parser.parse_args() if args.filename.strip()...
rdireen/spherepy
documentation/source/conf.py
Python
gpl-3.0
9,496
0.008951
# -*- coding: utf-8 -*- # # spherepy documentation build configuration file, created by # sphinx-quickstart on Sat Feb 7 21:35:42 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # ...
his directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' tim
estamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html...
arborh/tensorflow
tensorflow/lite/testing/op_tests/relu.py
Python
apache-2.0
2,072
0.002896
# 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...
========================
======= """Test configs for relu.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from tensorflow.lite.testing.zip_test_utils import create_tensor_data from tensorflow.lite.testing.zip_test_utils import make_zip_...
bitforks/vanilla
Demos/TinyTextEditor/TinyTextEditor.py
Python
mit
1,067
0.005623
from AppKit import NSDocument from PyObjCTools import AppHelper from tinyTextEditorDocumentWindow import TinyTextEditorDocumentWindow class TinyTextEditorDocument(NSDocument): def init(self): self = super(TinyTextEditorDocument, self).init() se
lf.vanillaWindowController = TinyTextEditorDocumentWindow() self.vanillaWindowController.assignToDocument(self) return self def readFromFile_ofType_(self, path, tp): # refer to the NSDocument reference for information about this method f = open(path, 'rb') text =...
ype, operation): # refer to the NSDocument reference for information about this method text = self.vanillaWindowController.getText() f = open(fileName, 'wb') f.write(text) f.close() return True if __name__ == "__main__": AppHelper.runEventLoop()
arielvega/uremix-app-developer-helper
src/uadh/gui/tkinter/__init__.py
Python
gpl-3.0
936
0.003205
# # # Copyright 2011,2013 Luis Ariel Vega Soliz, Uremix (http://www.uremix.org) and contributors. # # # This file is part of UADH (Uremix App Developer Helper). # # UADH is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public L
icense as published by # the Free Software Foun
dation, either version 3 of the License, or # (at your option) any later version. # # UADH 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 m...
Ledoux/ShareYourSystem
Pythonlogy/build/lib/ShareYourSystem/Standards/Itemizers/Setter/11_ExampleDoc.py
Python
mit
1,233
0.042985
#ImportModules import ShareYourSystem as SYS #Define and set with #key dict for the KeyVariable MySetter=SYS.SetterClass( ).set( 'MyStr', 'HelloStr' ).set( {'#key':"MyStr"}, "hello" ) #Define and set with a #get in the value MySetter.set( "FirstCloneMyStr", '#get:MyStr' ) #Define and set with a recu...
t:FooStr']} ) #Define and set with a #value:#map@get dict for the ValueVariable MySetter.set( MySetter.MyList.append, {'#value':'MyStr'} ) #Define
and set with a #value:#map@get dict for the ValueVariable MySetter.set( MySetter.MyList.append, {'#value:#map@get':['MyInt']} ) #print print('MySetter is ') SYS._print(MySetter)