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
xmnlab/minilab
ia/ocr/alpr.py
Python
gpl-3.0
10,141
0.008776
#! /usr/bin/env python # -*- coding: utf-8 -*- import cv2 import numpy as np import pymeanshift as pms from blobs.BlobResult import CBlobResult from blobs.Blob import CBlob # Note: This must be imported in order to destroy blobs and use other methods ################################################################...
cv2.cv.CV_RGB(255, 255, 255), 0, 0) # we can now save the image #annotated_image = np.asarray(license_plate_ipl[:,:]) blob_image = np.asarray(license_plate_grayscale_ipl[:,:]) cv2.imwrite("%s_blobs.png" % fname_prefix, blob_image) blob_white_image = np.asarray(license_plate_...
fname_prefix, blob_white_image) # Looking for a rectangle - Plates are rectangular # Thresholding image, the find contours then approxPolyDP (threshold_value, blob_threshold_image) = cv2.threshold( blob_white_image, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_O...
Caoimhinmg/PmagPy
programs/gofish.py
Python
bsd-3-clause
1,976
0.0167
#!/usr/bin/env python from __future__ import print_function from builtins import input import sys import pmagpy.pmag as pmag def main(): """ NAME gofish.py DESCRIPTION calculates fisher parameters from dec inc data INPUT FORMAT takes dec/inc as first two columns in space delimite...
om standard input if '\t' in line: rec=line.split('\t') # split each line on space to get records
else: rec=line.split() # split each line on space to get records DIs.append((float(rec[0]),float(rec[1]))) # fpars=pmag.fisher_mean(DIs) outstring='%7.1f %7.1f %i %10.4f %8.1f %7.1f %7.1f'%(fpars['dec'],fpars['inc'],fpars['n'],fpars['r'],fpars['k'],fpars['alpha95'], fpars['csd']) if...
cschwede/django-userattributes
userattributes/runtests.py
Python
mit
846
0.002364
""" This file mainly exists to allow python setup.py test to work. """ import os import sys from django.conf import settings settings.configure( DEBUG=True, DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'testdb', } }, INSTALLED_APPS=( ...
(os.path.abspath(__file__)))) from django.test.utils import get_runner def runtests(): """ Runs test.py """ Test
Runner = get_runner(settings) test_runner = TestRunner(verbosity=1, interactive=True) failures = test_runner.run_tests(['userattributes']) sys.exit(bool(failures)) if __name__ == '__main__': runtests()
20centaurifux/meat-a
controller.py
Python
agpl-3.0
29,635
0.02902
# -*- coding: utf-8 -*- """ project............: meat-a description........: web application for sharing meta information date...............: 04/2013 copyright..........: Sebastian Fedrau Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation f...
gger(request_id) if method == "OPTIONS": return self.__options__() m = {"post": self.__post__, "get": self.__get__, "put": self.__put__, "delete": self.__delete__} self.__start_process__(env, **kwargs) self.__check_rate_limit__(env) f = m[method.lower()] # get function argument names: spec...
_values(kwargs, argnames) # set default values: defaults = spec[3] if not defaults is None: diff = len(values) - len(defaults) for i in range(len(values)): if values[i] is None and i >= diff: values[i] = defaults[diff - i] # test required parameters: if hasattr(f, "__required__"): ...
oposs/check_mk_mirror
web/htdocs/guitester.py
Python
gpl-2.0
10,454
0.005452
#!/usr/bin/python # -*- encoding: utf-8; py-indent-offset: 4 -*- # +------------------------------------------------------------------+ # | ____ _ _ __ __ _ __ | # | / ___| |__ ___ ___| | __ | \/ | |/ / | # | | | | '_ \ / _ \/ __| |/ /...
th), e)) def replay_guitest(self): test_name = self.var("test") if not test_name: raise MKGuitestFailed([_("Missing the name of the GUI test to run (URL variable 'test')")]) guitest = self.load_guitest(test_name) step_nr_text = self.var("step")
try: step_nr = int(step_nr_text) except: raise MKGuitestFailed([_("Invalid or missing test step number (URL variable 'step')")]) if step_nr >= len(guitest) or step_nr < 0: raise MKGuitestFailed([_("Invalid test step number %d (only 0...%d)") % (step_nr, len(guitest)-1...
elli0ttB/problems
sorting/test_are_anagrams.py
Python
mit
556
0.008993
from strings_anagrams import are_anagrams def test_funny_anagrams(): assert are_anagrams("the eyes", "they see") assert are_anag
rams("Allahu Akbar, Obama", "Aha bub, koala alarm") assert are_anagrams("Donald Trump", "Damp Old Runt") def test_same_is_anagram(): ass
ert are_anagrams("foo", "Foo") assert are_anagrams(" ", " ") def test_wrong(): assert not are_anagrams("mary", "cow") assert not are_anagrams("123", "12345") def test_explosion(): assert not are_anagrams(None, "") assert not are_anagrams(321, 123)
ProfessorX/Config
.PyCharm30/system/python_stubs/-1247971765/PyQt4/QtGui/QGraphicsLayout.py
Python
gpl-2.0
2,337
0.009414
# encoding: utf-8 # module PyQt4.QtGui # from /usr/lib/python3/dist-packages/PyQt4/QtGui.cpython-34m-x86_64-linux-gnu.so # by generator 1.135 # no doc # imports import PyQt4.QtCore as __PyQt4_QtCore from .QGraphicsLayoutItem import QGraphicsLayoutItem class QGraphicsLayout(QGraphicsLayoutItem): """ QGraphicsLay...
(self, p_int): # real signature unknown; restored from __doc__ """ QGraphicsLayout.itemAt(int) -> QGraphicsLayoutItem """ return QGraphicsLayoutItem def removeAt(self, p_int): # real signature unknown; restored from __doc__ """ QGraphicsLayout.removeAt(int) """ pass d
ef setContentsMargins(self, p_float, p_float_1, p_float_2, p_float_3): # real signature unknown; restored from __doc__ """ QGraphicsLayout.setContentsMargins(float, float, float, float) """ pass def updateGeometry(self): # real signature unknown; restored from __doc__ """ QGraphicsLayout.up...
flying-sheep/aiohttp
tests/test_client_session.py
Python
apache-2.0
13,926
0
# -*- coding: utf-8 -*- """Tests for aiohttp/client.py""" import asyncio import gc import unittest from unittest import mock import aiohttp from aiohttp.client import ClientSession from aiohttp.multidict import MultiDict, CIMultiDict from aiohttp.connector import BaseConnector, TCPConnector class TestClientSession(...
lti_dict(self): session = ClientSession( headers={ "h1": "header1", "h2": "header2" },
loop=self.loop) headers = session._prepare_headers(MultiDict([("h1", "h1")])) self.assertIsInstance(headers, CIMultiDict) self.assertEqual(headers, CIMultiDict([ ("h2", "header2"), ("h1", "h1") ])) session.close() def test_merge_headers_with_list_of_t...
ArcheProject/arche_pas
arche_pas/tests/test_models.py
Python
gpl-2.0
17,498
0.000343
import unittest from BTrees.OOBTree import OOBTree from arche.interfaces import IObjectUpdatedEvent from arche.interfaces import IWillLoginEvent from arche.interfaces import IUser from arche.testing import barebone_fixture from pyramid import testing from zope.interface.verify import verifyObject from zope.interface.v...
ef test_store(self): self.config.include('arche.testing') self.config.include('arche.testing.catalog') self.config.include('arche_pas.catalog') self.config.include('arche_pas.models') root = barebone_fixture(self.config) request = testing.DummyRequest() apply_requ...
ta(user) provider_data['dummy'] = {'dummy_key': 'very_secret'} provider = self._dummy_provider() self.config.registry.registerAdapter(provider, name=provider.name) root['users']['jane'] = user obj = provider(request) L = [] def subsc(obj, event): L.ap...
puddl3glum/gen_scraper
build/lib/gen_scraper/gen_master.py
Python
mit
5,572
0.006999
import os import pickle import socket import sys import threading import struct import time import yaml # from gen_scraper import scraper def handle_slave(slaveconn_info, config_info, work_info): # print(v_chunk) """ handles a slave connection, sending config, work, or receiving more results. param...
ething with the clientsocket # in this case, we'll pretend this is a threaded server # co
nstruct v_chunk slaveconn_info = {'conn':slaveconn, 'address':address} config_info = {'config':config, 'config_dump': config_dump} work_info = {'v_list':v_list, 'work_loc': work_loc, 'r_lock':r_lock} print(v_list) ct = threading.Thread(target=handle_slave, args=[slavec...
magul/volontulo
backend/apps/volontulo/utils.py
Python
mit
1,857
0
# -*- coding: utf-8 -*- """ .. module:: utils """ from django.contrib.auth.models import User from django.shortcuts import get_object_or_404 from django.shortcuts import redirect from django.utils.text import slugify from apps.volontulo.models import UserProfile # Offers statuses dictionary with meaningful names. ...
that is reposponsible for redirect to url with correct slug. It is used by url for offers, organizations and users. """ def decorator(wrapped_func): """Decorator function for correcting slugs.""" def wrappi
ng_func(request, slug, id_): """Wrapping function for correcting slugs.""" obj = get_object_or_404(model_class, id=id_) if slug != slugify(getattr(obj, slug_field)): return redirect( view_name, slug=slugify(getattr(obj, slug_fie...
natural/django-objectcounters
objectcounters/templatetags/counter_tags.py
Python
bsd-3-clause
398
0
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.template import Library from ..models import Coun
ter register = Library() @register.assignment_tag def counter_for_object(name, obj, default=0): """Returns the counter value for the given name and instance.""" try: r
eturn Counter.objects.get_for_object(name, obj).value except (Exception, ): return default
pengli09/Paddle
python/paddle/v2/framework/optimizer.py
Python
apache-2.0
21,289
0.000141
from collections import defaultdict import paddle.v2.framework.framework as framework from paddle.v2.framework.backward import append_backward_ops from paddle.v2.framework.regularizer import append_regularization_ops __all__ = [ 'SGDOptimizer', 'MomentumOptimizer', 'AdagradOptimizer', 'AdamOptimizer', 'Adamax...
asses to manage their internal state. """ # This is a default implementation of create_optimization_pass that # can be shared by most optimizers. This implementation assumes that # the subclass will implement the _append_optimize_op method and the # _initialize_tensors...
# Create any accumulators self._create_accumulators(loss.block, [p[0] for p in parameters_and_grads]) # Create any necessary tensors self._initialize_tensors(loss.block) optimize_ops = [] for param_and_grad in parameters_and_grads: ...
suninsky/ReceiptOCR
Python/server/lib/python2.7/site-packages/pyvirtualdisplay/__init__.py
Python
mit
216
0
import logging from pyvirtualdisplay.display import Display from pyvirtualdisplay.about import __version__ log = logging.getLo
gger(__name_
_) log = logging.getLogger(__name__) log.debug('version=%s', __version__)
lisael/pg-django
tests/regressiontests/admin_changelist/tests.py
Python
bsd-3-clause
24,196
0.003017
from __future__ import with_statement, absolute_import from django.contrib import admin from django.contrib.admin.options import IncorrectLookupParameters from django.contrib.admin.views.main import ChangeList, SEARCH_VAR, ALL_VAR from django.contrib.auth.models import User from django.template import Context, Templat...
""" new_parent = Parent.objects.create(name='parent') new_child = Child.objects.create(name='name', parent=new_parent) request = self.factory.get('/child/') m = ChildAdmin(Child, admin.site) list_display = m.get_list_display(request) list_display_links = m.get_list_displa...
, Child, list_display, list_display_links, m.list_filter, m.date_hierarchy, m.search_fields, m.list_select_related, m.list_per_page, m.list_max_show_all, m.list_editable, m) cl.formset = None template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% ...
florianpaquet/sublime-sync
upload.py
Python
mit
3,373
0.001779
# -*- coding:utf-8 -*- import os import sys import sublime import sublime_plugin from .archiver import Archiver from .settings import API_UPLOAD_URL from .command import CommandWithStatus sys.path.append(os.path.dirname(__file__)) import requests class SublimeSyncUploadCommand(sublime_plugin.ApplicationCommand, Comm...
sponse = requests.post(url=API_UPLOAD_URL, files=files) status_code = response.status_code f.close() os.unlink(self.archive_filename) if status_code == 200: self.set_message("Successfuly sent archive") elif status_code == 403: self.set_message("Error wh...
self.set_message("Error while sending archive: filesize too large (>10MB)") else: self.set_message("Unexpected error (HTTP STATUS: %s)" % response.status_code) self.post_send() def run(self, *args): """ Create an archive of all packages and settings """ ...
singingwolfboy/flask-dance
flask_dance/consumer/storage/session.py
Python
mit
1,085
0.001843
from flask_dance.consumer.storage import BaseStorage import flask class SessionSto
rage(BaseStorage): """ The default storage backend. Stores and retrieves OAuth tokens u
sing the :ref:`Flask session <flask:sessions>`. """ def __init__(self, key="{bp.name}_oauth_token"): """ Args: key (str): The name to use as a key for storing the OAuth token in the Flask session. This string will have ``.format(bp=self.blueprint)`` ...
NeCTAR-RC/designate
designate/utils.py
Python
apache-2.0
8,767
0.000114
# Copyright 2012 Managed I.T. # # Author: Kiall Mac Innes <kiall@managedit.ie> # # 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 r...
s not None and part[-1:] == '"' and part[-2:] != '\\"': # Handle End of Quoted Sentance tmp += " " + part.strip('"') outparts.append(tmp) tmp = None elif tmp is not
None: # Handle Middle of Quoted Sentance tmp += " " + part else: # Handle Standalone words outparts.append(part) if tmp is not None: # Handle unclosed quoted strings outparts.append(tmp) # This looks odd, but both calls are necessary to ...
airween/hamlib
bindings/pytest.py
Python
gpl-2.0
4,198
0.00143
#!/usr/bin/env python2 # -*- coding: utf-8 -*- import sys ## Uncomment to run this script from an in-tree build (or adjust to the ## build directory) without installing the bindings. #sys.path.append ('.') #sys.path.append ('.libs') import Hamlib def StartUp(): """Simple script to test the Hamlib.py module with...
my_rig.set_conf("retry", "5") my_rig.open() # 1073741944 is token value for "itu_region" # but using get_conf is much more convenient region = my_rig.get_conf(1073741944)
rpath = my_rig.get_conf("rig_pathname") retry = my_rig.get_conf("retry") print "status(str):\t\t", Hamlib.rigerror(my_rig.error_status) print "get_conf:\t\tpath = %s, retry = %s, ITU region = %s" \ % (rpath, retry, region) my_rig.set_freq(Hamlib.RIG_VFO_B, 5700000000) my_rig.set_vfo(Haml...
mtagle/airflow
airflow/configuration.py
Python
apache-2.0
29,594
0.002298
# 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 ...
for name, info in replacement.items(): old, new, version = info if self.get(section, name, fallback=None) == old:
# Make sure the env var option is removed, otherwise it # would be read and used instead of the value we set env_var = self._env_var_name(section, name) os.environ.pop(env_var, None) self.set(section, name
CRLab/curvox
src/curvox/pc_vox_utils.py
Python
mit
14,287
0.00378
import numpy as np import binvox_rw import numba import mcubes @numba.jit(forceobj=True) def get_voxel_resolution(pc, patch_size): """ This function takes in a pointcloud and returns the resolution of a voxel given that there will be a fixed number of voxels. For example if patch_size is 40, then we...
o contain the grid, shape, offset in the world, and grid resolution voxel_grid = binvox
_rw.Voxels(vox_np, vox_np.shape, tuple(offset), voxel_resolution * patch_size, "xyz") # Where am I putting my point cloud relative to the center of my voxel grid # ex. (20, 20, 20) or (20, 20, 18) center_point_in_voxel_grid = (patch_size * percent_x, patch_size * percent_y, patch_size * percent_z) ret...
nikolas/splinter
tests/cookies.py
Python
bsd-3-clause
3,162
0
# -*- coding: utf-8 -*- # Copyright 2012 splinter authors. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. class CookiesTest(object): def test_create_and_access_a_cookie(self): "should be able to create and access a cookie"
self.browser.cookies.add({'sha': 'zam'}) self.assertEqual(self.browser.cookies['sha'], 'zam') def test_create_many_cookies_at_once_as_dict(self): "should be able to create many cookies at once as dict" cookies = {'sha': 'zam', 'foo': 'bar'} self.browser.cookies.add(cookies) ...
any_cookies_at_once_as_list(self): "should be able to create many cookies at once as list" cookies = [{'sha': 'zam'}, {'foo': 'bar'}] self.browser.cookies.add(cookies) self.assertEqual(self.browser.cookies['sha'], 'zam') self.assertEqual(self.browser.cookies['foo'], 'bar') d...
sorgerlab/belpy
indra/literature/pubmed_client.py
Python
mit
22,934
0.000392
""" Search and get metadata for articles in Pubmed. """ import logging import requests from time import sleep from typing import List from functools import lru_cache import xml.etree.ElementTree as ET from indra.util import UnicodeXMLTreeBuilder as UTB logger = logging.getLogger(__name__) pubmed_search = 'https://eu...
6. PubMed, by default, limits returned PMIDs to a small number, and this number can be controlled by the "retmax" parameter. This function uses a retmax value of 100,000 by default that can be changed via the corresponding keyword argument. Parameters ---------- search_term : str A...
: Optional[bool] If True, the "[tw]" string is appended to the search term to constrain the search to "text words", that is words that appear as whole in relevant parts of the PubMed entry (excl. for instance the journal name or publication date) like the title and abstract. Using this ...
victorianorton/SimpleRPGGame
src/game/Decorators.py
Python
mit
1,582
0.007585
__author__ = 'Victoria' #Decorator Pattern in Characters class BarDecorators(Barbarian): pass class ImageBarDecorator(BarDecorators): def __init__(self, decorated, picFile): self.decorated = decorated self.picFile = picFile super(ImageBarDecorator, self).__init__(self.decorated.canvas, ...
ionX, self.decorated.positionY, self.decorated.name, self.decorated.picFile) class FastBarMoveDecorator(BarDecorators): def __init__(self, decorated): self.decorated = decorated() super(FastBarMoveDecorator, self).__init__(self.decorated.can
vas, self.decorated.positionX, self.decorated.positionY, self.decorated.name, self.decorated.picFile) #Decorator Pattern in Monsters class DragDecorators(Dragon): pass class ImageDragDecorator(DragDecorators): def __init__(self, decorated, picFile): se...
level12/blazeweb
tests/apps/nlsupporting/components/news/__init__.py
Python
bsd-3-clause
26
0
def som
efunc(): p
ass
ajaybhatia/archlinux-dotfiles
home/.config/offlineimap/offlineimap-helpers.py
Python
mit
2,790
0.010394
import os import sys import subprocess """ Use gpg to decrypt password. """ def mailpasswd(path): cmd = "gpg --quiet --batch --use-agent --decrypt --output - " + os.path.expanduser(path) try: return subprocess.check_output(cmd, shell=True).strip() except subprocess.CalledProcessError: retur...
: 'spam', } mapping_gmail = { 'INBOX' : 'INBOX', '[Gmail]/Drafts' : 'drafts', '[Gmail]/Sent Mail' : 'sent', '[Gmail]/Bin' : 'trash', '[Gmail]/Spam' : 'spam', } mapping_gmx = { 'INBOX' : 'INBOX', 'Drafts' : 'drafts'...
: 'trash', 'arch' : 'arch', 'aur-general' : 'aur-general', 'arch-general' : 'arch-general', 'arch-wiki' : 'arch-wiki', 'mw' : 'mw', } # values from mapping_* dicts with high priority prio_queue_fjfi = ['INBOX'] prio_queue_gmail =...
epequeno/ThinkPy-Solutions
ch08/8.06.py
Python
gpl-3.0
828
0.002415
# -*- coding: utf-8 -*- """ Created on Su
n Aug 7 18:08:41 2011 @author: steven """ # word = 'banana' # count = 0 # for letter in word: # if letter == 'a': # count = count + 1 # print count # Rewrite this function so that instead of traversing the string, it uses the # three-parameter version of find from the previous section. # Current Status: ...
return index index += 1 return -1 def count(letter, word): counter = 0 index = 0 while index < len(word): result = find(letter, word, index) if result == -1: return counter else: counter += 1 index = result + 1 return count...
FedeRez/webldap
app/webldap/local_settings.docker.py
Python
mit
764
0
# Docker-specific local settings import os DEBUG = True TEMPLATE_DEBUG = DEBUG DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'db', } } # Make this unique, and don't share it with anybody. SECRET_KEY = '' TEMPLATE_DIRS = ( '/srv/webldap/templates', ) EMAIL_F...
viron['LDAP_PORT_389_TCP_ADDR'], os.environ['LDAP_PORT_389_TCP_PORT']) LDAP_STARTTLS = False LDAP_CACERT = '' LDAP_BASE = 'dc=example,dc=net' LDAP_WEBLDAP_USER = 'cn=webldap,ou=service-users,dc=example,dc=net' LDA
P_WEBLDAP_PASSWD = 'secret' LDAP_DEFAULT_GROUPS = [] LDAP_DEFAULT_ROLES = ['member']
jpmfribeiro/PyCharts
pycharts/fields/plot_options/data_labels.py
Python
mit
493
0.004057
class DataLabels(object): def __init__(self, enabled=Tr
ue): self.enabled = enabled def show_labels(self, enable): if not type(enable) is bool: raise TypeError('enable should be a boolean (True or False).') self.enabled = enable def to_javascript(self): jsc = "dataLabels: {" jsc += "enabled: " if self.en...
jsc
tanglei528/glance
glance/tests/functional/v1/test_api.py
Python
apache-2.0
24,300
0
# Copyright 2011 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...
ervers(**self.__dict__.copy()) # 0. GET /images # Verify no publi
c images path = "http://%s:%d/v1/images" % ("127.0.0.1", self.api_port) http = httplib2.Http() response, content = http.request(path, 'GET') self.assertEqual(response.status, 200) self.assertEqual(content, '{"images": []}') # 1. GET /images/detail # Verify no pub...
OCA/bank-payment
account_payment_partner/tests/test_account_payment_partner.py
Python
agpl-3.0
21,944
0.001276
# Copyright 2017 ForgeFlow S.L. # Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import _, fields from odoo.exceptions import UserError, ValidationError from odoo.fields import Date from odoo.tests.common import Form, SavepointCase class Tes...
_id = cls.company_2.id cls.chart.try_loading() cls.env.user.company_id = old_company.id # refs cls.manual_out = cls.env
.ref("account.account_payment_method_manual_out") cls.manual_out.bank_account_required = True cls.manual_in = cls.env.ref("account.account_payment_method_manual_in") cls.journal_sale = cls.env["account.journal"].create( { "name": "Test Sales Journal", ...
fluks/youtube-dl
youtube_dl/extractor/common.py
Python
unlicense
38,144
0.001022
from __future__ import unicode_literals import base64 import datetime import hashlib import json import netrc import os import re import socket import sys import time import xml.etree.ElementTree from ..compat import ( compat_cookiejar, compat_http_client, compat_urllib_error, compat_urllib_parse_urlp...
live stream that goes on instead of a fixed-length video. Unless mentioned otherwise, the fields should be Unicode strings. Unless mentioned otherwise, None is equivalent to absence of information. _type "playlist" indicates multiple videos. There must be a key "entries", which is a list, an ...
ment of which is a valid dictionary by this specification. Additionally, playlists can have "title" and "id" attributes with the same semantics as videos (see above). _type "multi_video" indicates that there are multiple videos that f
sserrot/champion_relationships
venv/Lib/site-packages/win32com/test/testArrays.py
Python
mit
2,505
0.050699
# Originally contributed by Stefan Schukat as part of this arbitrary-sized # arrays patch. from win32com.client import gencache from win32com.test import util import unittest ZeroD = 0 OneDEmpty = [] OneD = [1,2,3] TwoD = [ [1,2,3], [1,2,3], [1,2,3] ] TwoD1 = [ [ ...
[ [1,2,3], [1,2,3], [1,2,3] ], [ [1,2,3], [1,2,3], [1,2,3] ] ] FourD = [ [ [[1,2,3],[1,2,3],[1,2,3]], [[1,2,3],[1,2,3],[1,2,3]], [[1,2,3],[1,2,3],[...
2,3],[1,2,3],[1,2,3]] ] ] LargeD = [ [ [list(range(10))] * 10], ] * 512 def _normalize_array(a): if type(a) != type(()): return a ret = [] for i in a: ret.append(_normalize_array(i)) return ret class ArrayTest(util.TestCase): def setUp(self): self.a...
getconnect/connect-python
tests/test_api.py
Python
mit
9,933
0.010772
# -*- coding: utf-8 -*- import json from mock import patch from colle
ctions import defaultdict from requests import Session from connect.api import ConnectApi from connect.event import Event from connect import responses PROJECT_ID = "MY_PROJECT_ID" API_PUSH_KEY
= "MY_PUSH_API_KEY" BASE_URL = "https://api.getconnect.io" COLLECTION_NAME = 'my_collection' MULTI_EVENT_DATA = [{ 'type': 'cycling', 'distance': 21255, 'caloriesBurned': 455, 'duration': 67, 'user': { 'id': '638396', 'name': 'Bruce' ...
erickpeirson/django-ncbi
ncbi/manage.py
Python
gpl-3.0
247
0
#!/usr/bin/env python import os import sys if __name__ == "__ma
in__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ncbi.settings") from django.core.management import execute_from_command_li
ne execute_from_command_line(sys.argv)
MrYsLab/s2-pi
s2_pi/s2_pi.py
Python
agpl-3.0
5,512
0.000727
#!/usr/bin/env python3 """ s2_pi.py Copyright (c) 2016-2018 Alan Yorinks All right reserved. Python Banyan is free software; you can redistribute it and/or modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 as published by the Free Software Foundation; either or (at your option) any la...
t(payload['pin']) self.pi.set_mode(pin, pigpio.OUTPUT) value = int(payload['value']) self.pi.set_PWM_dutycycle(pin, value) elif client_cmd == 'servo': # HackEduca ---> When a user wishes to set a servo: # Using S
G90 servo: # 180° = 2500 Pulses; 0° = 690 Pulses # Want Servo 0°-->180° instead of 180°-->0°: # Invert pulse_max to pulse_min # pulse_width = int((((pulse_max - pulse_min)/(degree_max - degree_min)) * value) + pulse_min) # Where: # Test the followi...
sunchaoatmo/cplot
plotset.py
Python
gpl-3.0
28,891
0.077291
#!/usr/bin/env python import matplotlib.pyplot as plt from mpl_toolkits.basemap import cm import numpy as np# reshape from cstoolkit import drange from matplotlib.colors import LinearSegmentedColormap """ cmap_cs_precp = [ (242, 242, 242), (191, 239, 255), (178, 223, 238), (154, 192, 205), ( 0, 235, 235)...
0), (73,167,116), (
73,168,113), (73,169,109), (73,170,106), (73,172,102), (73,173,99), (73,174,95), (73,175,91), (73,176,88), (73,177,84), (73,178,81), (73,179,77), (73,181,70), (78,182,71), (83,184,71), (87,185,72), (92,187,72), (97,188,73), (102,189,74), (106,191,74), (111,192,75), (116,193,75), (121,195,76), (126,196,77), (130,198,77)...
dhuppenkothen/UTools
simpower.py
Python
bsd-2-clause
7,317
0.02132
import numpy as np import scipy import math import argparse import lightcurve import powerspectrum #### MULTIPLY LIGHT CURVES TOGETHER ################## # # Little functions that multiplies light curves of different # processes together. # Base_lc can be any LightCurve object, even one of the three options given...
ar = np.log(rms**2.0 + 1.0) #print("Variance of log-normal light curve: " + str(lnvar)) ### make a shape for the power spectrum, depending on ### psshape specified if psshape.lower() in ['flat', 'constant', 'white', 'white noise']: ## assume white noise power spectrum, <P> = N*sigma_ln ...
s = self.n*lnvar*(1.0/self.freq)**pind ### Don't do other shapes for now, until I need them ### CAREFUL: normalization of these is not right yet! elif psshape.lower() in ['qpo', 'lorentzian', 'periodic']: #print('I am here!') alpha = (gamma/math.pi)*dnu*N/2.0 sold = alph...
puffinrocks/puffin
puffin/core/network.py
Python
agpl-3.0
1,606
0.003113
import ipaddress import docker.types def init(): pass def get_next_cidr(client): networks = client.networks.list() last_cidr = ipaddress.ip_network("10.0.0.0/24") for network in networks: if (network.attrs["IPAM"] and network.attrs["IPAM"]["Config"] and len(network.attrs["IPA...
fig(pool_c
onfigs=[ipam_pool]) client.networks.create(name, ipam=ipam_config)
m-weigand/Cole-Cole-fit
tests/2-term/test_cases.py
Python
gpl-3.0
1,602
0.003121
#!/usr/bin/python # -*- coding: utf-8 -*- """ Execute to run double Cole-Cole term characterization """ import sys sys.path.append('..') import test_helper as th import os import itertools import numpy as np import subprocess testdir = 'data' def _generate_cc_sets(): """Generate multiple complex resistivity spec...
os.chdir(directory) cmd = 'cc_fit.py -p -c 2 -m 2' subprocess.call(cmd, shell=True) os.chdir(pwd) if __name__ == '__main__': frequencies = _get_frequencies() for x in _generate_cc_sets(): print x th._generate_spectra(frequencies, testdir, _generate_cc_sets)
_fit_spectra() th._evaluate_fits(testdir)
teriyakichild/photoboard
photoboard/tests/test.py
Python
apache-2.0
133
0.007519
from backend import photos, boards p = photos() #print p.n
ew('asdf',1,1) print p.get(1) b = b
oards() print p.all(1) print b.get(1)
jtrobec/pants
contrib/scrooge/tests/python/pants_test/contrib/scrooge/tasks/test_scrooge_gen.py
Python
apache-2.0
4,867
0.005137
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os from textw...
with self.assertRaises(TaskError): task._validate_compiler
_configs([self.target('test_validate:three')]) def test_scala(self): build_string = ''' java_thrift_library(name='a', sources=['a.thrift'], dependencies=[], compiler='scrooge', language='scala', rpc_style='finagle' ) ''' sources = [os.path.join(self.tas...
looker-open-source/sdk-codegen
examples/python/simple_schedule_plan.py
Python
mit
1,296
0.022377
from looker_sdk import methods, models40 import looker_sdk import exceptions sdk = looker_sdk.init40("../looker.ini") def create_simple_schedule(dashboard_id:int,user_id:int,schedule_title:str, format:str, email:str,type:str, message:str, crontab:str): ### For more information on the Params accepted https://githu...
inline_json", "json", "json_detail", "xlsx", "html", "wysiwyg_pdf", "assembled_pdf", "wysiwyg_png" ### type: Type of the address ('email', 'webhook', 's3', or 'sftp') schedule = sdk.create_scheduled_plan( body=models40.WriteScheduledPlan(name=schedule_title, dashboard_id=dashboard_id, user_id=user_id, run_a...
=True, apply_vis=True, address=email, type=type, message=message)])) create_simple_schedule(1234,453,"This is an automated test", "assembled_pdf", "test@looker.com", "email", "Hi Looker User!", "0 1 * * *")
openstack/tempest
tempest/api/object_storage/test_container_acl_negative.py
Python
apache-2.0
10,958
0
# Copyright (C) 2013 eNovance SAS <licensing@enovance.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
= self.object_client.create_object( self.containe
r_name, object_name, 'data') self.assertHeaders(resp, 'Object', 'PUT') # trying to get object with non authorized user token self.object_client.auth_provider.set_alt_auth_data( request_part='headers', auth_data=self.test_auth_data ) self.assertRaises(lib_e...
pattisdr/osf.io
osf/models/preprint.py
Python
apache-2.0
40,401
0.002401
# -*- coding: utf-8 -*- import functools import urlparse import logging import re import pytz from dirtyfields import DirtyFieldsMixin from include import IncludeManager from django.db import models from django.db.models import Q from django.utils import timezone from django.contrib.contenttypes.fields import GenericR...
tle', 'description', } # Node fields that trigger an update to elastic search on save SEARCH_UPDATE_FIELDS = { 'title', 'description', 'is_published', 'license', 'is_public', 'deleted', 'subjects', 'primary_file', 'contributors...
ey('osf.PreprintProvider', on_delete=models.SET_NULL, related_name='preprints', null=True, blank=True, db_index=True) node = models.ForeignKey('osf.AbstractNode', on_delete=models.SET_NULL, ...
micfan/dinner
src/public/forms.py
Python
mit
2,640
0.001515
# coding=utf-8 __author__ = 'mic' from django import forms from django.utils.translation import ugettext, ugettext_lazy as _ from django.contrib.auth.forms import UserCreationForm from public.models import User class UserSignupForm(forms.ModelForm): """ A form that creates a user, with no privileges, from th...
"@/./+/-/_ only."), error_messages={ 'invalid': _("This value may contain only letters, numbers and " "@/./+/-/_ characters.")}) password1 = forms.CharField(label=_("Password"),
widget=forms.PasswordInput) password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput, help_text=_("Enter the same password as above, for verification.")) invite_code = forms.RegexField(la...
amcat/amcat
amcat/scripts/__init__.py
Python
agpl-3.0
482
0.008299
"""
Main organisation: - L{amcat.scripts.tools} contains helper classes that are
used by the scripts - L{amcat.scripts.searchscripts} contains scripts that search the index or the database - L{amcat.scripts.processors} contains scripts that process the input of a script - L{amcat.scripts.output} contains scripts that output script results in various formats, such as csv and html. - L{amcat.scr...
2gis/Winium.StoreApps
Winium/TestApp.Test/py-functional/tests_silverlight/test_commands.py
Python
mpl-2.0
8,916
0.002916
# coding: utf-8 import base64 import pytest from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By from tests_silverlight import SilverlightTestCase By.XNAME = 'xname' class TestGetCommands(SilverlightTestCase): """ Test GET commands that do not change an...
@pytest.mark.parametrize(("name", "expected_value"), [ (
'May', True), ('June', True), ('November', False), ]) def test_is_displayed(self, name, expected_value): element = self.driver.find_element_by_name(name) assert expected_value == element.is_displayed() def test_file_ops(self): encoding = 'utf-8' with open(__f...
SEC-i/ecoControl
server/urls.py
Python
mit
2,212
0.005425
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() import hooks import manager.hooks import technician.hooks urlpatterns = patterns('', # general hooks (r'^$', hooks.index), (r'^api/$', hooks.api_index), (r'^api/export/$', hooks.export_csv), ...
oks.live_data), (r'^api/manage/thresholds/$', technician.hooks.handle_threshold), (r'^api/settings/tunable/$', technician.hooks.get_tunable_device_configurations), (r'^api/snippets/$', technician.hooks.handle_snippets), (r'^api/code/$', technician.hooks.handle_code), (r'^api/start/$', technician.hoo...
/thresholds/$', technician.hooks.list_thresholds), # manager hooks (r'^api/avgs/(sensor/(?P<sensor_id>[0-9]+)/)?(year/(?P<year>[0-9]+)/)?$', manager.hooks.get_avgs), (r'^api/balance/total/((?P<year>\d+)/)?((?P<month>\d+)/)?$', manager.hooks.get_total_balance), (r'^api/balance/total/latest/$', manager.h...
aboyett/blockdiag
src/blockdiag/plugins/__init__.py
Python
apache-2.0
1,527
0
# -*- coding: utf-8 -*- # Copyright 2011 Takeshi KOMIYA # # 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.apac
he.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, # W
ITHOUT 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 pkg_resources import iter_entry_points node_handlers = [] def load(plugins, diagram, **kwargs): for name in plugins: for e...
jxtech/wechatpy
tests/test_create_reply.py
Python
mit
4,741
0
# -*- coding: utf-8 -*- import unittest from wechatpy.replies import TextReply, create_reply class CreateReplyTestCase(unittest.TestCase): def test_create_reply_with_text_not_render(self): text = "test" reply = create_reply(text, render=False) self.assertEqual("text", reply.type) ...
png", "url": "http://www.qq.com/4", }, { "title": "test 5", "description": "test 5", "image": "http://www.qq.com/5.png", "url": "http://www.qq.com/5", }, { "title": "test 6", ...
ption": "test 6", "image": "http://www.qq.com/6.png", "url": "http://www.qq.com/6", }, { "title": "test 7", "description": "test 7", "image": "http://www.qq.com/7.png", "url": "http://www.qq.com/7", ...
mmilaprat/policycompass-services
apps/feedbackmanager/views.py
Python
agpl-3.0
891
0.001122
from rest_framework import generics from rest_
framework.views import APIView from rest_framework.response import Response from rest_framework.reverse import reverse from .models import Feedback from .serializers import * class FeedbackListView(generics.ListCreateAPIView): # permission_classes = IsAuthenticatedOrReadOnly, queryset = Feedback.objects.all()...
erializer_class = FeedbackSerializer class FeedbackCategoryListView(generics.ListCreateAPIView): queryset = FeedbackCategory.objects.all() serializer_class = FeedbackCategorySerializer class Base(APIView): def get(self, request): result = { "Feedbacks": reverse('feedback-list', reque...
ryfeus/lambda-packs
pytorch/source/caffe2/python/operator_test/adadelta_test.py
Python
mit
7,954
0.002137
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import functools import hypothesis from hypothesis import given, settings, HealthCheck import hypothesis.strategies as st import numpy as np from caffe2.python import c...
decay=st.floats(min_value=0.01, max_value=0.99, allow_nan=False, allow
_infinity=False), data_strategy=st.data(), **hu.gcs) def test_sparse_adadelta_empty(self, inputs, lr, epsilon, decay, data_strategy, gc, dc): param, moment, moment_delta = inputs moment = np.abs(moment) lr = np.array([lr], dtype=np.floa...
BrummbQ/plantcontrol
plant/modelcontrol/views.py
Python
gpl-3.0
1,079
0.000927
# Create your views here. from django.shortcuts import render, get_object_or_404 from django.views import generic from modelcontrol.models import Plant from xmlrpclib import ServerProxy, Error class IndexView(generic.ListView): template_name = 'modelcontrol/index.html' context_object_name = 'plant_list' ...
jects.all() def update(request, plant_id): p = get_object_or_404(Plant, pk=plant_id) try: motor = ServerProxy('http://127.0.0.1:1337', allow_none=True) if 'position' in request.POST: p.servo.position = request.POST['position'] p.servo.save() if 'speed' in reques...
tor.set_rate(0, 7) motor.set_rate(int(p.motor.speed), 25) # set device except (KeyError): # error page pass plant_list = Plant.objects.all() context = {'plant_list': plant_list} return render(request, 'modelcontrol/index.html', context)
tBaxter/tango-happenings
happenings/signals.py
Python
mit
368
0.002717
def update_time(sender, **kwargs): """ When a Comment is added, updates the Update to set "last_updated" time """
comment = kwargs['instance'] if comment.content_type.app_label == "happenings" and comment.content_type.name == "Update": from .models import Update it
em = Update.objects.get(id=comment.object_pk) item.save()
ricomoss/learn-tech
python/track_2/lesson2/apples_to_apples/common/models.py
Python
gpl-3.0
490
0
from django.db import models class Person(models.Model): first_nam
e = models.CharField(max_length=25, default='Rico') last_name = models.CharField(max_length=25, blank=True) hair_color = models.CharField(max_length=10, blank=True) eye_color = models.CharField(max_length=10) age = models.IntegerField() height = models.CharField(max_length=6) favor
ite_animal = models.CharField(max_length=25, blank=True) number_of_animals = models.IntegerField(null=True)
dyf102/Gomoku-online
client/controller/basecontroller.py
Python
apache-2.0
2,390
0.000418
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import logging import os # import json as JSON from network import Client from PyQt4.QtCore import SIGNAL, QObject, QString from PyQt4 import Qt, QtCore, QtGui import threading import socket import Queue import time sys.path.append('../') # from util.util import...
se def get_client(self): return self.c # Object of this class has to be shared between # the two threads (Python and Qt one). # Qt thread calls 'connect', # Python thread calls 'emit'. # The slot corresponding to the emitted signal # will be called in Qt's thread. @singleton class SafeConnector: def ...
.Queue() self._qt_object = QtCore.QObject() self._notifier = QtCore.QSocketNotifier(self._rsock.fileno(), QtCore.QSocketNotifier.Read) self._notifier.activated.connect(self._recv) def connect(self, signal, receiver): QtCore.QObject.con...
frerepoulet/ZeroNet
src/File/FileRequest.py
Python
gpl-2.0
19,416
0.003348
# Included modules import os import time import json import itertools # Third party modules import gevent from Debug import Debug from Config import config from util import RateLimit from util import StreamingMsgpack from util import helper from Plugin import PluginManager FILE_BUFF = 1024 * 512 # Incoming request...
self.log.debug( "Delay %s %s, cpu_time used by connection: %.3fs" % (self.connection.ip, cmd, self.connection.cpu_time) ) time.sleep(self.connection.cpu_time) if self.connection.cpu_time > 5: ...
self.connection.close("Cpu time: %.3fs" % self.connection.cpu_time) if func: func(params) else: self.actionUnknown(cmd, params) if cmd not in ["getFile", "streamFile"]: taken = time.time() - s self.connection....
brain-tec/server-tools
users_ldap_groups/__manifest__.py
Python
agpl-3.0
704
0
# Copyright 2020 initOS GmbH # Copyright 2012-2018 Therp BV <https://therp.nl> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "LDAP groups assignment", "version": "11.0.1.0.0", "depends": ["auth_ldap"], "author": "init
OS GmbH, Ther
p BV, Odoo Community Association (OCA)", "website": "https://github.com/OCA/server-tools", "license": "AGPL-3", "summary": "Adds user accounts to groups based on rules defined " "by the administrator.", "category": "Authentication", "data": [ 'views/base_config_settings.xml', 'se...
jonyroda97/redbot-amigosprovaveis
lib/matplotlib/quiver.py
Python
gpl-3.0
46,115
0.00039
""" Support for plotting vector fields. Presently this contains Quiver and Barb. Quiver plots an arrow in the direction of the vector, with the size of the arrow related to the magnitude of the vector. Barbs are like quiver in that they point along a vector, but the magnitude of the vector is given schematically by t...
*None*. e.g. *scale_units* is 'inches', *scale* is 2.0, and ``(u,v) = (1,0)``, then the vector will be 0.5 inches long. If *scale_units* is 'width'/'height', then t
he vector will be half the width/height of the axes. If *scale_units* is 'x' then the vector will be 0.5 x-axis units. To plot vectors in the x-y plane, with u and v having the same units as x and y, use ``angles='xy', scale_units='xy', scale=1``. width : scalar, optional Shaft width in arrow u...
qma/pants
src/python/pants/backend/jvm/tasks/jvm_compile/jvm_classpath_publisher.py
Python
apache-2.0
2,151
0.010693
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os from pant...
symlink_name = '{}-{}'.format(index, file_name) os.symlink(entry.path, os.path.join(folder_for_symlinks, symlink_name)) with safe_open(os.path.join(folder_for_symlinks, 'classpath.txt'), 'w') as classpath_file: classpath_file.write(os.pathsep.join(classpath)) classpath_file.wr...
e('\n')
50wu/gpdb
src/backend/gporca/scripts/cal_bitmap_test.py
Python
apache-2.0
70,529
0.003474
#!/usr/bin/env python3 # Optimizer calibration test for bitmap and brin indexes, also btree on AO tables # # This program runs a set of queries, varying several parameters: # # - Selectivity of predicates # - Plan type (plan chosen by the optimizer, various forced plans) # - Width of the selected columns # # The progr...
e # can be reported, computing a mean and standard deviation of several # query executions. # # The printed results are useful to copy and paste in
to a Google Sheet # (expand columns after pasting) # # Run this program with the -h or --help option to see argument syntax # # See comment "How to add a test" below in the program for how to # extend this program. import argparse import time import re import math import os import sys try: from gppylib.db import ...
cryptapus/electrum
electrum/gui/qt/console.py
Python
mit
11,672
0.002656
# source: http://stackoverflow.com/questions/2758159/how-to-embed-a-python-interpreter-in-a-pyqt-widget import sys import os import re import traceback import platform from PyQt5 import QtCore from PyQt5 import QtGui from PyQt5 import QtWidgets from electrum import util from electrum.i18n import _ if platform.sys...
t) self.setMinimumHeight(150) self.setGeometry(0, 0, self.width(), self.height()) self.setStyleSheet(self.STYLESHEET) self.setMargin(0) parent.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.setWordWrap(True) def mousePress
Event(self, e): self.hide() def on_resize(self, w): padding = 2 # px, from the stylesheet above self.setFixedWidth(w - padding) class Console(QtWidgets.QPlainTextEdit): def __init__(self, prompt='>> ', startup_message='', parent=None): QtWidgets.QPlainTextEdit.__init__(self, ...
PhonologicalCorpusTools/PolyglotDB
tests/test_io_ilg.py
Python
mit
1,972
0.000507
import pytest import os import sys from polyglotdb.io import ins
pect_ilg from polyglotdb.io.helper import guess_type from polyglotdb.exceptions import DelimiterError, ILGWordMismatchError from polyglotdb import CorpusContext def test_inspect_ilg(ilg_test_dir): basic_path = os.path.join(ilg_test_dir, 'basic.txt') parser = inspect_ilg(basic_path) assert (len(parser.a...
assert (len(parser.annotation_tiers) == 2) @pytest.mark.xfail def test_export_ilg(graph_db, export_test_dir): export_path = os.path.join(export_test_dir, 'export_ilg.txt') with CorpusContext('untimed', **graph_db) as c: export_discourse_ilg(c, 'test', export_path, annota...
MartinThoma/pysec
pysec/utils.py
Python
mit
108
0.009259
#!/usr/bin
/env python # -*- coding: utf-8 -*- """Utility functions that can be used in
multiple scripts."""
anhstudios/swganh
data/scripts/templates/object/tangible/deed/guild_deed/shared_tatooine_guild_style_02_deed.py
Python
mit
473
0.046512
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DO
NE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/deed/guild_deed/shared_tatooine_guild_style_02_deed.iff" resu
lt.attribute_template_id = 2 result.stfName("deed","tatooine_guild_2_deed") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
shaded-enmity/docker-hica
injectors/libs.py
Python
mit
1,615
0.011765
# vim: set fileencoding=utf-8 # Pavel Odvody <podvody@redhat.com> # # HICA - Host integrated container applications # # MIT License (C) 2015 import os, sys from json import loads from base.hica_base import * library_path='/usr/lib64' class LibraryInjector(HicaInjector): def _get_libs(self): return sorted(loads...
: :type from_args: dict """ load_libs = self._get_libs() all_libs = {} found_libs = [] for root, dirs, files in os.walk(library_path): for f in files: if not f.endswith('.so'): continu
e full_path = os.path.join(root, f) if '.' in f: name, ext = f.split('.', 1) else: name = f if name in all_libs: all_libs[name].append(full_path) else: all_libs[name] = [full_path] for lib in load_libs: if 'lib' + lib in all_li...
fstagni/DIRAC
FrameworkSystem/Client/SystemAdministratorClient.py
Python
gpl-3.0
683
0.005857
""" The SystemAdministratorClient is a class representing the client of the DIRAC SystemAdministrator service. It has also methods to update the Configuration Service with the DIRAC components options """ __RCSID__ =
"$Id$" from DIRAC.Core.Base.Client import Client, createClient SYSADMIN_PORT = 9162 @createClient('Framework/SystemAdministrator') class SystemAdministratorClient(Client): def __init__(
self, host, port=None, **kwargs): """ Constructor function. Takes a mandatory host parameter """ Client.__init__(self, **kwargs) if not port: port = SYSADMIN_PORT self.setServer('dips://%s:%s/Framework/SystemAdministrator' % (host, port))
matrix-org/synapse
synapse/rest/client/versions.py
Python
apache-2.0
4,936
0.003241
# Copyright 2016 OpenMarket Ltd # Copyright 2017 Vector Creations Ltd # Copyright 2018-2019 New Vector Ltd # Copyright 2019 The Matrix.org Foundation C.I.C. # # 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 t...
s signing as described in MSC1756 "org.matrix.e2e_cross_signing": True, # Implements additional endpoints as described in MSC2432 "org.matrix.msc2432": True, # Implements additional endpoints as described in MSC2666
"uk.half-shot.msc2666": True, # Whether new rooms will be set to encrypted or not (based on presets). "io.element.e2ee_forced.public": self.e2ee_forced_public, "io.element.e2ee_forced.private": self.e2ee_forced_private, "io.element.e...
gppezzi/easybuild-framework
test/framework/suite.py
Python
gpl-2.0
4,872
0.001437
#!/usr/bin/python # # # Copyright 2012-2019 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Res...
error=True) except EasyBuildError as err: sys.stderr.write("No execution rights on temporary files, specify another location via $TMPDIR: %s\n" % err) sys.exit(1) # initialize logger for all the unit tests fd, log_fn = tempfile.mkstemp(prefix='easybuild-tests-', suffix='.log') os.close(fd) os.remove(log_fn) fa...
make sure the options unit tests run first, to avoid running some of them with a readily initialized config tests = [gen, bl, o, r, ef, ev, ebco, ep, e, mg, m, mt, f, run, a, robot, b, v, g, tcv, tc, t, c, s, lic, f_c, tw, p, i, pkg, d, env, et, y, st, h, ct, lib] SUITE = unittest.TestSuite([x.suite() for x ...
yuuki0xff/nvpy
setup.py
Python
bsd-3-clause
1,989
0.001508
#!/usr/bin/env python3 import os from setuptools import setup import nvpy # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname): ...
f', 'pdoc3'
, 'nose', 'nose-timer', 'mypy'], }, entry_points={'gui_scripts': ['nvpy = nvpy.nvpy:main']}, # use MANIFEST.in file # because package_data is ignored during sdist include_package_data=True, classifiers=[ # See https://pypi.org/classifiers/ "Development Status :: 5 - Production/St...
oVirt/ovirt-hosted-engine-ha
ovirt_hosted_engine_ha/broker/submonitors/mem_free.py
Python
lgpl-2.1
1,774
0
# # ovirt-hosted-engine-ha -- ovirt hosted engine high availability # Copyright (C) 2013 Red Hat, Inc. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; e
ither # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more det...
s library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # import logging from ovirt_hosted_engine_ha.broker import submonitor_base from ovirt_hosted_engine_ha.lib import log_filter from ovirt_hosted_engine_ha.lib import util as util from vdsm.clien...
googleapis/python-aiplatform
samples/generated_samples/aiplatform_generated_aiplatform_v1beta1_metadata_service_query_context_lineage_subgraph_async.py
Python
apache-2.0
1,624
0.001847
# -*- coding: utf-8 -*- # Copyright 2020 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...
ibuted 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. # # Generated code. DO NOT EDIT! # # Snippet for QueryContextLineageSubgraph # NOTE: This snippet has been automat...
the latest published package dependency, execute the following: # python3 -m pip install google-cloud-aiplatform # [START aiplatform_generated_aiplatform_v1beta1_MetadataService_QueryContextLineageSubgraph_async] from google.cloud import aiplatform_v1beta1 async def sample_query_context_lineage_subgraph(): # ...
zeroincombenze/tools
wok_code/scripts/main.py
Python
agpl-3.0
6,236
0.00016
# -*- coding: utf-8 -*- # template 18 """ Various tools at your fingertips. The available tools are: * cvt_csv_2_rst.py: convert csv file into rst file * cvt_csv_2_xml.py: convert csv file into xml file * cvt_script: parse bash script and convert to meet company standard * gen_readme.py: generate documentation files,...
read_setup() if action == '-h': print('%s [-h][-H][--help][-V][--version][-C][--copy-pkg-data]' % setup_args['name']) elif action in ('-V', '--version'): if setup_args['version'] == __version__: print(setup_args['version']) else:
print('Version mismatch %s/%s' % (setup_args['version'], __version__)) elif action in ('-H', '--help'): for text in __doc__.split('\n'): print(text) elif action in ('-C', '--copy-pkg-data'): copy_pkg_data(setup_args, verbose)...
bzamecnik/sms-tools
smst/ui/transformations/sineTransformations_GUI_frame.py
Python
agpl-3.0
9,380
0.004158
# GUI frame for the sineTransformations_function.py import os from Tkinter import * import tkFileDialog import tkMessageBox import numpy as np from smst.utils import audio from . import sineTransformations_function as sT from smst.utils.files import strip_file class SineTransformationsFrame: def __init__(self,...
cky=W + E, padx=5, pady=(0, 2)) self.timeScaling.del
ete(0, END) self.timeScaling.insert(0, "[0, .0, .671, .671, 1.978, 1.978+1.0]") # BUTTON TO DO THE SYNTHESIS self.compute = Button(self.parent, text="Apply Transformation", command=self.transformation_synthesis, bg="dark green", fg="white") self.compute.gri...
knuu/competitive-programming
atcoder/corp/codethanksfes2017_e.py
Python
mit
389
0
N = int(input()) ans = [0] * N for i in range(0, N, 5): q = [0] * N for j in range(i, min(N, i + 5)): q[j] = 10 ** (j - i) print('? {}'.format(' '.join(map(str, q))), flush=
True) S = str
(int(input().strip()) - sum(q) * 7)[::-1] for j in range(i, min(N, i + 5)): ans[j] = (int(S[j - i]) % 2) ^ 1 print('! {}'.format(' '.join(map(str, ans))), flush=True)
krukas/Mage2Gen
mage2gen/utils.py
Python
gpl-3.0
1,144
0.012238
# A Magento 2 module generator library # Copyright (C) 2016 Maikel Martens # # This file is part of Mage2Gen. # # Mage2Gen 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 # ...
# You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import string class DefaultFormatter(string.Formatter): def __init__(self, default=''): self.default = default def get_field(self, field_name, args, kwargs): try: retu...
per() + word[1:] def lowerfirst(word): return word[0].lower() + word[1:]
openstack/cinder
cinder/zonemanager/drivers/cisco/cisco_fc_zone_client_cli.py
Python
apache-2.0
20,088
0
# (c) Copyright 2014 Cisco Systems Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unl...
ired by applicable law or agreed to in writing, software # distributed under the License is di
stributed 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. # """ Script to push the zone configuration to Cisco SAN switches. """ import random import re from...
AlexandreDecan/Lexpage
app/profile/migrations/0002_auto_20171206_0943.py
Python
gpl-3.0
651
0.001541
# Generated by Django 2.0 on 2017-12-06 09:43 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('profile', '0001_squashed_0005_auto_20170408_1400'), ] operations = [ migrations.AlterField( mode
l_name='Profile', name='theme', field=models.CharField(blank=True,
choices=[('style', 'Lexpage'), ('style_nowel', 'Nowel'), ('style_st_patrick', 'Saint-Patrick'), ('style_halloween', 'Halloween')], help_text='Laissez vide pour adopter automatiquement le thème du moment.', max_length=16, null=True, verbose_name='Thème'), ), ]
UTSA-ICS/keystone-kerberos
keystone/exception.py
Python
apache-2.0
15,384
0
# Copyright 2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
message format errors fatal _FATAL_EXCEPTION_FORMAT_ERRORS = False class Error(Exception): """Base error class. Child classes should define an HTTP status code, title, and a message_format. """ c
ode = None title = None message_format = None def __init__(self, message=None, **kwargs): try: message = self._build_message(message, **kwargs) except KeyError: # if you see this warning in your logs, please raise a bug report if _FATAL_EXCEPTION_FORMAT_E...
crmccreary/openerp_server
openerp/addons/event/wizard/event_confirm_registration.py
Python
agpl-3.0
2,865
0.002792
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from osv import fields, osv from tools.translate import _ class event_confirm_registration(osv.osv_...
scription = "Confirmation for Event Registration" _columns = { 'msg': fields.text('Message', readonly=True), } _defaults = { 'msg': 'The event limit is reached. What do you want to do?' } def default_get(self, cr, uid, fields, context=None): """ This function gets...
nir0s/logrotated
setup.py
Python
apache-2.0
879
0
from setuptools import setup, find_packages import os import codecs here = os.path.abspath(os.path.dirname(__file__)) def read(*parts): # intentionally *not* adding an encoding option to open return codecs.open(os.path.join(here, *parts), 'r').read() install_requires = [ "click==6.6", "jinja2==2.8"...
LICENSE', platforms='All', description='A logrotate human friendly interface.', long_description=read('README.rst'), packages=find_packages(exclude=[]), package_data={'logrotated': ['resources/logrotate']},
entry_points={ 'console_scripts': [ 'rotatethis = logrotated.logrotated:main', ] }, install_requires=install_requires )
T2DREAM/t2dream-portal
src/encoded/upgrade/publication.py
Python
mit
1,991
0
from snovault import upgrade_step @upgrade_step('publication', '', '2') def publication(value, system): # http://redmine.encodedcc.org/issues/2591 value['identifiers'] = [] if 'references' in value: for reference in value['references']: value['identifiers'].append(reference) d...
(set(value['datasets'])) if 'categories' in value:
value['categories'] = list(set(value['categories'])) if 'published_by' in value: value['published_by'] = list(set(value['published_by'])) # Upgrade 3 to 4 in item.py. @upgrade_step('publication', '4', '5') def publication_4_5(value, system): # https://encodedcc.atlassian.net/browse/ENCD-3646 ...
coreymcdermott/artbot
artbot_website/views.py
Python
mit
793
0.022699
from django.shortcuts import render from datetime import date, datetime, timedelta from .models import Event, SponsoredContent from pytz import timezone def index(request): now = datetime.now(timezone('Australia/Sydney')).date() if now.isoweekday() in [5, 6, 7]: weekend_s...
imedelta((5 - now.isoweekday()) % 7) events = Event.objects.filter(start__lte = weekend_start, end__gte = weekend_start, status = Event.PUBLISHED_S
TATUS).order_by('-start') sponsoredContent = SponsoredContent.objects.filter(start__lte = now, end__gte = now, status = SponsoredContent.PUBLISHED_STATUS).first() return render(request, 'index.html', {'events': events, 'sponsoredContent': sponsoredContent},)
nickcrafford/python-pygame-tetris
src/Tetromino.py
Python
gpl-3.0
8,712
0.015725
#!/usr/bin/
env python """ Python Tetris is a clunky pygame Tetris clone. Feel free to make it better!! Copyright (C) 2008 Nick Crafford <nickcrafford@earthlink.net> This program i
s 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. This program is distributed in the hope that it will be useful, but WITHO...
tuxfux-hlp-notes/python-batches
archieves/batch-56/logging/second.py
Python
gpl-3.0
1,002
0.005988
#!/usr/bin/python # logging.basicConfig # Messages on screen or file like object - StreamHandlers # logging.Formatter # man date/https://docs.python.org/2/library/time.html#time.strftime import logging logging.basicConfig(filename="disk.log",filemode='a',level=logging.DEBUG,format='%(asct
ime)s - %(name)s - %(levelname)s - %(message)s',datefmt='%c') # modes # r - read mode - reading a file. # w - write mode - write to a file. if file doesnot exist it should create it. # if it exist truncates it to zero. # a - append mode - appends contents to the file. disk_size = input("plese enter the disk size:") ...
"Your disk is getting filled up {}".format(disk_size)) elif disk_size < 90: logging.error("your disk is stomach full. It going to burst out {}".format(disk_size)) elif disk_size < 100: logging.critical("your application is sleeping {}".format(disk_size))
aurzenligl/prophy
prophyc/generators/prophy.py
Python
mit
5,118
0.00254
from collections import namedtuple from prophyc.generators import base, word_wrap INDENT_STR = u" " MAX_LINE_WIDTH = 100 DocStr = namedtuple("DocStr", "block, inline") def _form_doc(model_node, max_inl_docstring_len, indent_level): block_doc, inline_doc = "", "" if model_node.docstring: if len(m...
thod def translate_include(include): doc = _form_doc(include, 50, indent_level=0) return u"{d
.block}#include \"{0.name}\"{d.inline}".format(include, d=doc) @staticmethod def translate_constant(constant): doc = _form_doc(constant, max_inl_docstring_len=50, indent_level=0) return u"{d.block}\n{0.name} = {0.value};{d.inline}".format(constant, d=doc) @staticmethod def translate_en...
justincely/pyspecfit
setup.py
Python
bsd-3-clause
731
0.025992
from distutils.core import setup import os import glob setup( name = 'pyspecfit', url = 'http://justincely.github.io', version = '0.0.1', description = 'interact with IRAF task specfit I/O products',
author = 'Justin Ely', author_email = 'ely@stsci.edu', keywords = ['astronomy'], classifiers = ['Programming Language :: Python', 'Development Status :: 1 - Planning', 'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering :: Astro...
ring :: Physics', 'Topic :: Software Development :: Libraries :: Python Modules'], packages = ['pyspecfit'] )
huangz1990/riacn-code
ch05_listing_source.py
Python
mit
29,256
0.006797
# coding: utf-8 import bisect import contextlib import csv from datetime import datetime import functools import json import logging import random import threading import time import unittest import uuid import redis QUIT = False SAMPLE_COUNT = 100 config_connection = None # 代码清单 5-1 # <start id="recent_log"/> # ...
artition(':')[0]) # 因为清理程序每60秒钟就会循环一次, # 所以这里需要根据计数器的更新频率来判断是否真的有必要对计数器进行清理。 bprec = int(prec // 6
0) or 1 # 如果这个计数器在这次循环里不需要进行清理, # 那么检查下一个计数器。 # (举个例子,如果清理程序只循环了三次,而计数器的更新频率为每5分钟一次, # 那么程序暂时还不需要对这个计数器进行清理。) if passes % bprec: continue hkey = 'count:' + hash # 根据给定的精度以及需要保留的样本数量, # 计算出我们需要保留什么时间之前的样本。 ...
wuqize/FluentPython
chapter16/coro_exc_demo.py
Python
lgpl-3.0
1,499
0.00403
# -*- coding: utf-8 -*- """ Created on Sun May 14 22:13:58 2017 """ #python3 """ >>> exc_coro = demo_exc_handling() >>> next(exc_coro) -> coroutine started >>> exc_coro.send(11) -> coroutine received: 11 >>> exc_coro.send(22) -> coroutine received: 22 >>> exc_coro.close() >>> from inspect import getgeneratorstate >...
neratorstate(exc_coro) 'GEN_CLOSED' """ from inspect import getgeneratorstate class DemoException(Exception): """异常类型。""" def demo_exc_handling(): print('-> coroutine started') while True: try: x = yield except DemoException: print('*** DemoException handled. ...
imeError('This line should never run.') if __name__ == "__main__": exc_coro = demo_exc_handling() next(exc_coro) exc_coro.send(11) exc_coro.send(22) exc_coro.close() print(getgeneratorstate(exc_coro))
0xc0ffeec0de/tapioca-discourse
tapioca_discourse/resource_mapping/admin.py
Python
mit
3,741
0.001604
# -*- coding: utf-8 -*- ADMIN_MAPPING = { 'admin_user_suspend': { 'resource': 'admin/users/{id}/suspend', 'docs': ('http://docs.discourse.org/#tag/' 'Admin%2Fpaths%2F~1admin~1users~1%7Bid%7D~1suspend%2Fput'), 'methods': ['PUT'], }, 'admin_user_unsuspend': { ...
' 'Admin%2Fpaths%2F~1admin~1users~1%7Bid%7D~1generate_api_key%2Fpost'), 'methods': ['POST'], }, 'admin_group_assign': { 'resource': 'admin/users/{id}/groups', 'docs': ('http://docs.discourse.org/#tag/' 'Admin%2Fpaths%2F~1admin~
1users~1%7Bid%7D~1groups%2Fpost'), 'methods': ['POST'], }, 'admin_group_remove': { 'resource': 'admin/users/{id}/groups/{group_id}', 'docs': ('http://docs.discourse.org/#tag/' 'Admin%2Fpaths%2F~1admin~1users~1%7Bid%7D~1groups~1%7Bgroup_id%7D%2Fdelete'), 'methods'...
HarryLoofah/gae-bead-calculator
main.py
Python
mit
8,656
0.000116
#!/usr/bin/env python # # The MIT License (MIT) # # Copyright (c) 2015 Greg Aitkenhead # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the ...
(webapp2.RequestHandler): """ Run all logic and create templates depending on value of beads_entered. Value 'beads_entered/ comes from textarea value of main-form in base.html. """ def get(self): """Gets number of beads entered from base.html form input.""" bead_input = cgi.escape(se...
mber entered (beads), is greater than 12 and that it is divisible by 6 or 9. If 'beads' is less than 12, print error message. """ if int(bead_input) < 12: beads_user_chose = str(bead_input) more_beads_message = "Please re-try using more tha...
jalanb/jab
ipython/profile_jalanb/ipython_config.py
Python
mit
18,065
0.001439
# Configuration file for ipython. # pylint: disable=E0602 c = get_config() # ----------------------------------------------------------------------------- # InteractiveShellApp configuration # ----------------------------------------------------------------------------- # A Mixin for applications that start Interac...
# variable IPYTHONDIR. # Whether to display a banner upon starting IPython. c.TerminalIPythonApp.display_banner = False # Whether to install the default config files into the profile dir. If a new # profile is being c
reated, and IPython contains config files for that profile, # then they will be staged into the new directory. Otherwise, default config # files will be automatically generated. # c.TerminalIPythonApp.copy_config_files = False # List of files to run at IPython startup. # c.TerminalIPythonApp.exec_files = [] # Enable...
atsushieno/cerbero
cerbero/bootstrap/linux.py
Python
lgpl-2.1
10,061
0.00497
# cerbero - a multi-platform build system for Open Source software # Copyright (C) 2012 Andoni Morales Alastruey <ylatuya@gmail.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; eit...
command = ' -S %s --needed' yes_arg = ' --noconfirm' packages = ['intltool', 'cmake', 'doxygen', 'gtk-doc', 'libtool', 'bison', 'flex', 'automake', 'autoconf', 'mak
e', 'curl', 'gettext', 'alsa-lib', 'yasm', 'gperf', 'docbook-xsl', 'transfig', 'libxrender', 'libxv', 'mesa', '
Comunitea/CMNT_004_15
project-addons/prepaid_order_discount/__manifest__.py
Python
agpl-3.0
697
0.002869
{ 'name': 'Discount prepaid order', 'version': '1.0', 'category': 'Custom', 'description': """ Order Discount when it's prepaid and margin is between specific values """, 'author': 'Nadia Ferreyra', 'website': '', 'depends': ['base',
'sale', 'product', 'sale_promotions_extend', 'commercial_rules', 'flask_middleware_connector', 'sale_custom' ], 'data': ['data/product_data.xml', 'data/parameters.xml', 'views/sale_...
modoboa/modoboa-webmail
modoboa_webmail/tests/test_fetch_parser.py
Python
mit
3,016
0
# coding: utf-8 """FETCH parser tests.""" from __future__ import print_function import unittest import six from modoboa_webmail.lib.fetch_parser import FetchResponseParser from . import data def dump_bodystructure(fp, bs, depth=0): """Dump a parsed BODYSTRUCTURE.""" indentation = " " * (depth * 4) f...
ultipart/{}".format(indentation, mp[1]), file=fp) dump_bodystructure(fp, mp, depth + 1) else: dump_bodystructure(fp, mp, depth)
elif isinstance(mp, dict): if isinstance(mp["struct"][0], list): print("{}multipart/{}".format( indentation, mp["struct"][1]), file=fp) dump_bodystructure(fp, mp["struct"][0], depth + 1) else: print("{}{}/{}".format( ...
alirizakeles/tendenci
tendenci/apps/forms_builder/forms/models.py
Python
gpl-3.0
20,327
0.002903
from django.core.urlresolvers import reverse from django.db import models from django.utils.translation import ugettext, ugettext_lazy as _ from django.contrib.auth.models import User from django.contrib.contenttypes.fields import GenericRelation from django.shortcuts import get_object_or_404 from django_countries im...
ate checklist if str(self.pk) == get_setting('site', 'global', 'contact_form'): checklist_update('update-contact') super(Form, self).save(*args, **kwargs) @model
s.permalink def get_absolute_url(self): return ("form_detail", (), {"slug": self.slug}) def get_payment_type(self): if self.recurring_payment and self.custom_payment: return _("Custom Recurring Payment") if self.recurring_payment: return _("Recurring Payment") ...
MilesDuronCIMAT/django_image
upload_image/models.py
Python
mit
145
0.027586
from django.db import models # Cre
ate your models here. class ImageModel(model
s.Model): image = models.ImageField(upload_to = 'pic_folder/')
mpurzynski/MozDef
mq/plugins/nagioshostname.py
Python
mpl-2.0
902
0.002217
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at https://mozilla.org/MPL/2.0/. # Copyright (c) 2014 Mozil
la Corporation import hashlib class message(object): def __init__(self): ''' takes an incoming nagios message and assigns a static ID so we always update the same doc for current status. ''' # this plugin # sets a static document ID # for a particular even...
def onMessage(self, message, metadata): docid = hashlib.md5('nagiosstatus' + message['details']['nagios_hostname']).hexdigest() metadata['id'] = docid return (message, metadata)
alexa-infra/negine
thirdparty/boost-python/libs/python/test/staticmethod.py
Python
mit
826
0.007264
# Copyright David Abrahams 2004. Dis
tributed under the Boost # Software License, Version 1.0. (See accompanying # file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ''' >>> from staticmethod_ext import * >>> class X1(X): ... pass >>> x = X(16) >>> x1 = X1(17) >>> x1.count() 2 >
>> x.count() 2 >>> X1.count() 2 >>> X.count() 2 >>> x1.magic() 7654321 >>> x.magic() 7654321 >>> X1.magic() 7654321 >>> X.magic() 7654321 ''' def run(args = None): import sys import doctest if args is not None: sys.argv = args return doctest.testmod(sys....