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 |
|---|---|---|---|---|---|---|---|---|
KyleKing/recipes | tests/configuration.py | Python | mit | 758 | 0 | """Global variables for testing."""
from pathlib import Path
from calcipy.file_helpers import delete_dir, ensure_dir
from calcipy.log_helpers import activate_debug_logging
from recipes import __pkg_name__
activate_debug_logging(pkg_names=[__pkg_name__], clear_log=True)
TEST_DIR = Path(__file__).resolve().parent
""... | he Test Directory."""
TEST_TMP_CACHE = TEST_DIR / '_tmp_cache'
"""Path to the temporary cache folder in the Test directory."""
def clear_test_cache() -> None:
"""Remove the test cache directory if present."""
delete_dir(TEST_ | TMP_CACHE)
ensure_dir(TEST_TMP_CACHE)
|
rootAir/rootAir | finance/type_launch.py | Python | gpl-2.0 | 1,196 | 0.002508 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from datetime import datetime
from django.contrib.contenttypes.models import *
from .exceptions import IncorrectCellLabel
from utils.util import *
from django.db.models import Sum, Max
from django.contrib import messages
from d... | s
import os
class TypeLaunch(models.Model):
# id = models.IntegerField(primary_key=True) # AutoField?
type_name = models.CharField(max_length=100, unique=True)
cost_fixo = models.BooleanField(default=False, db_index=True)
investment = models.BooleanField(default=False, db_index=True)
value_fixed ... | .DecimalField(max_digits=8, decimal_places=2)
synchronized = models.CharField(max_length=1, choices=STATUS_CHOICES)
def __str__(self):
return self.type_name
class Meta:
managed = False
db_table = 'finance_typelaunch'
def save(self, *args, **kwargs):
if settings.DATABAS... |
hsanjuan/dccpi | setup.py | Python | gpl-3.0 | 2,524 | 0 | """
Copyright (C) 2016 Hector Sanjuan
This file is part of "dccpi".
"dccpi" 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... | implementation for Raspberry Pi
==================================================================
This module implements the DCC pr | otocol for controlling model trains using a
Raspberry Pi.
It is able to output direction and speed DCC-encoded packets on one of the
RPi GPIO pins. It needs WiringPi libraries to work.
Please visit the github page for more information:
https://github.com/hsanjuan/dccpi.
"""
)
|
SimenB/thefuck | thefuck/output_readers/shell_logger.py | Python | mit | 1,616 | 0 | import json
import os
import socket
try:
from shutil import get_terminal_size
except ImportError:
from backports.shutil_get_terminal_size import get_terminal_size
import pyte
from .. import const, logs
def _get_socket_path():
return os.environ.get(const.SHELL_LOGGER_SOCKET_ENV)
def is_available():
"... | return json.loads(response)['commands']
def _get_output_lines(output):
lines = output.split('\n')
screen = pyte.Screen(get_terminal_size().columns, len(lines))
stream = pyte.Stream(screen)
stream.feed('\n'.join(lines))
return screen.display
def get_output(script):
"""Gets command output f... | ger'):
commands = _get_last_n(const.SHELL_LOGGER_LIMIT)
for command in commands:
if command['command'] == script:
lines = _get_output_lines(command['output'])
output = '\n'.join(lines).strip()
return output
else:
log... |
Outernet-Project/librarian-ondd | librarian_ondd/routes.py | Python | gpl-3.0 | 2,899 | 0 | import logging
from bottle import request
from bottle_utils.ajax import roca_view
from bottle_utils.i18n import lazy_gettext as _, i18n_url
from librarian_core.contrib.templates.renderer import template, view
from .forms import ONDDForm
from .consts import get_form_data_for_preset
@view('ondd/_status')
def get_sig... | _max = request.app.c | onfig['ondd.cache_quota']
default = {'total': cache_max,
'free': cache_max,
'used': 0,
'alert': False}
cache_status = request.app.supervisor.exts.cache.get('ondd.cache')
return dict(cache_status=cache_status or default)
def routes(config):
skip_plugins = co... |
Jelloeater/mineOSplayerStats | report_generator.py | Python | gpl-2.0 | 9,875 | 0.002025 | #!/usr/bin/env python2.7
"""A python project for managing Minecraft servers hosted on MineOS (http://minecraft.codeemo.com)
"""
from datetime import datetime
import getpass
import json
import smtplib
import sys
import os
import logging
import argparse
from time import sleep
import db_controller
import keyring
from keyr... | ort()
if args.report_scheduler:
db | _controller.db_helper().test_db_setup()
gmail().test_login()
mode.report_scheduler()
class modes(object): # Uses new style classes
def __init__(self, sleep_delay):
self.sleep_delay = sleep_delay
def sleep(self):
try:
sleep(self.sleep_delay)
except Keyboard... |
ocozalp/Algorithms | search/uninformed_search.py | Python | apache-2.0 | 1,797 | 0.002226 | def bfs(node, target, comparator=lambda x, y: x == y):
queue = [node]
visited_nodes = []
while len(queue) != 0:
current_node = queue.pop(0)
if current_node not in visited_nodes:
if comparator(current_node.value, target):
return current_node
queue.exte... | urrent_node_level + 1) for child in current_node])
visited_nodes.append(current_node)
return None, max_level
def iterative_deepening_search(node, target, comparator=lambda x, y: x == y):
level = 0
found_level = 0
while level == found_level:
level += 1
result, found_l... | target, level, comparator)
if result is not None:
return result
return None |
Ultimaker/Cura | plugins/FirmwareUpdateChecker/FirmwareUpdateChecker.py | Python | lgpl-3.0 | 3,835 | 0.007562 | # Copyright (c) 2018 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QDesktopServices
from typing import Set
from UM.Extension import Extension
from UM.Applicatio | n import Application
from UM.Logger import Logger
from UM.i18n import i18nCatalog
from UM.Settings.ContainerRegistry import ContainerRegistry
from .FirmwareUpdateCheckerJob import FirmwareUpdateCheckerJob
from .FirmwareUpdateCheckerMessage import FirmwareUpdateCheckerMessage
i18n_catalog = i18nCatalog("cura")
class... | on number.
The plugin is currently only usable for applications maintained by Ultimaker. But it should be relatively easy
to change it to work for other applications.
"""
def __init__(self) -> None:
super().__init__()
# Listen to a Signal that indicates a change in the list of printer... |
iAmMrinal0/django_moviealert | moviealert/settings/base.py | Python | mit | 4,071 | 0 | """
Django settings for moviealert project.
Generated by 'django-admin startproject' using Django 1.8.6.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build p... | = 'Asia/Kolkata'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS | , JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
STATIC_ROOT = '/static/'
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.Authenticati... |
ryfx/modrana | modules/pyrender/OsmTileData.py | Python | gpl-3.0 | 3,691 | 0.003522 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#----------------------------------------------------------------------------
# Download OSM data covering the area of a slippy-map tile
#
# Features:
# * Recursive (downloads are all at z15, and merged if necessary to get
# a larger area)
# * Cached (all downloads stored... | ames import *
from urllib import *
from OsmMerge import OsmMerge
import os
def GetOsmTileData(z, x, y, AllowSplit=False):
"""Download OSM data for the region covering a slippy-map tile"""
if x < 0 or y < 0 or z < 0 or z > 25:
| print("Disallowed %d,%d at %d" % (x, y, z))
return
DownloadLevel = 15 # All primary downloads are done at a particular zoom level
MergeLevels = 2 # How many layers 'below' the download level to go
directory = 'cache/%d/%d' % (z, x)
filename = '%s/%d.osm' % (directory, y)
if not os.path... |
Prakhash/security-tools | external/django-DefectDojo-1.2.1/dojo/templatetags/event_tags.py | Python | apache-2.0 | 2,640 | 0.001136 | import re
from django import template
from django import forms
register = template.Library()
def _process_field_attributes(field, attr, process):
# split attribute name and value from 'attr:value' string
params = attr.split(':', 1)
attribute = params[0]
value = params[1] if len(params) == 2 else ''... | d.widget, forms.CheckboxSelectMultiple)
@register.filter
def is_radio(field):
return isinstance(field.field.widget, forms.RadioSelect)
@r | egister.filter
def is_file(field):
return isinstance(field.field.widget, forms.FileInput) or \
isinstance(field, forms.ClearableFileInput)
@register.filter
def sum_dict(d):
total = 0
for key, value in d.items():
total += value
return total
@register.filter
def nice_title(title):
... |
dmccloskey/SBaaS_isotopomer | SBaaS_isotopomer/stage01_isotopomer_peakData_io.py | Python | mit | 1,934 | 0.021717 | # System
import json
from .stage01_isotopomer_peakData_query import stage01_isotopomer_peakData_query
from SBaaS_base.sbaas_template_io import sbaas_template_io
# Resources
from io_utilities.base_importData | import base_importData
from io_utilities.base_exportData import base_exportData
class stage01_isotopomer_peakData_io(stage01_isotopomer_peakData_query,sbaas_template_io):
def import_peakData_add(self, filename, experiment_id, samplename, precursor_formula, met_id,
mass_units_I='Da',in... | ds'''
data = base_importData();
try:
data.read_tab_fieldnames(filename,['Mass/Charge','Intensity'],header_I);
#data.read_tab_fieldnames(filename,['mass','intensity','intensity_percent'],header_I);
data.format_data();
if add_data_I:
self.add... |
daweim0/Just-some-image-features | lib/networks/net_labeled_concat_features_shallower.py | Python | mit | 12,807 | 0.004607 | import tensorflow as tf
from networks.network import Network
from fcn.config import cfg
zero_out_module = tf.load_op_library('lib/triplet_flow_loss/triplet_flow_loss.so')
class custom_network(Network):
def __init__(self):
self.inputs = cfg.INPUT
# self.input_format = input_format
self.num... | 1, name='conv2_1', c_i=64, trainable=trainable)
.conv(3, 3, 128, 1, 1, name='conv2_2', c_i=128, trainable=trainable)
.add_immediate(tf.constant(0.0, tf.float32), name='conv2_l')
.max_pool(2, 2, 2, 2, name='pool2')
.conv(3, 3, 256, 1, 1, name='conv3_1', | c_i=128, trainable=trainable)
.conv(3, 3, 256, 1, 1, name='conv3_2', c_i=256, trainable=trainable)
.conv(3, 3, 256, 1, 1, name='conv3_3', c_i=256, trainable=trainable)
.add_immediate(tf.constant(0.0, tf.float32), name='conv3_l')
.max_pool(2, 2, 2, 2, name='pool3')
.conv(3, ... |
johnaparker/MiePy | miepy/__init__.py | Python | mit | 343 | 0.005831 | """
MiePy
=======
Python module to calcuate scattering coefficien | ts of a plane wave incident on a sphere or core-shell structure using Mie theory
"""
#main submodules
from . import scattering
from . import materials
from . import mie_sphere
from . import array_io
from .mie_sphere import sph | ere
from .materials import material, load_material
|
gnboorse/videowatcher | setup.py | Python | gpl-3.0 | 356 | 0.042135 | #!/usr/bin/en | v python3
from setuptools import setup
#setup the package as the default application
setup(
name = 'vid | eowatcher',
packages = ['videowatcher'],
version = '0.1.5',
author = 'Gabriel Boorse',
description = 'Shared video playback package',
include_package_data = True,
install_requires = [
'flask',
],
)
|
jamesliu/mxnet | tests/python/unittest/test_gluon_trainer.py | Python | apache-2.0 | 7,882 | 0.002664 | # 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... | rainer is None)
x._set_trainer(trainer0)
# multiple trainers for a sparse Parameter is not allowe | d
trainer1 = gluon.Trainer([x], 'sgd')
@with_seed()
def test_trainer():
def dict_equ(a, b):
assert set(a) == set(b)
for k in a:
assert (a[k].asnumpy() == b[k].asnumpy()).all()
x = gluon.Parameter('x', shape=(10,))
x.initialize(ctx=[mx.cpu(0), mx.cpu(1)], init='zeros')
tr... |
0compute/makeenv | doc/conf.py | Python | mit | 8,696 | 0.0069 | # -*- coding: utf-8 -*-
#
# makeenv documentation build configuration file, created by
# sphinx-quickstart on Tue Nov 27 21:24:26 2012.
#
# 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.
#
# All... | ee the documentation for
# a list of | builtin themes.
html_theme = 'sphinxdoc'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_... |
repotvsupertuga/tvsupertuga.repository | script.module.streamtvsupertuga/lib/resources/lib/modules/views.py | Python | gpl-2.0 | 1,864 | 0.008584 | # -*- coding: UTF-8 -*-
try: from sqlite3 import dbapi2 as database
except: from pysqlite2 import dbapi2 as database
from resources.lib.modules import control
def addView(content):
try:
skin = control.skin
record = (skin, content, str(control.getCurrentViewId()))
control.makeFile(contro... | try: | return control.execute('Container.SetViewMode(%s)' % str(viewDict[skin]))
except: return
control.sleep(100)
|
kevinseelbach/generic_utils | src/generic_utils/config/__init__.py | Python | bsd-3-clause | 10,446 | 0.003159 | """
Generic configuration interface and module which allows for exposing environment/application configuration through a
generic uniformly available interface
"""
# future/compat
from builtins import str
from past.builtins import basestring
# stdlib
import ast
import importlib
import inspect
import os
from generic_ut... | e: The data type to cast the value to. This can be a single value or an iterable of types to attempt
to cast the value to in the order they are provided. If this is not provi | ded and a value is
provided for `default` then the type of that value will be used.
:return: The value of the configuration property `property_name`.
"""
# pylint: disable=too-many-branches
if property_name in os.environ:
val = os.environ[property_name]
location =... |
thomasWajs/cartridge-external-payment | cartridge_external_payment/providers/be2bill.py | Python | bsd-2-clause | 1,363 | 0.002201 | # -*- coding: utf-8 -*-
from decimal import Decimal
from be2bill_sdk import Be2BillForm
from cartridge_external_payment.providers.base import PaymentProvider
class Be2BillProvider(PaymentProvider):
def get_start_payment_form(self, request, order):
total = Decimal(order.total * 100).quantize(Decima... |
#Save cart id for notification
extra_data=request.cart.id)
def get_order_id(self, notification_reques | t):
return notification_request.GET.get('ORDERID', None)
def get_transaction_id(self, notification_request):
return notification_request.GET.get('TRANSACTIONID', None)
def get_cart_id(self, notification_request):
raise notification_request.GET.get('EXTRADATA', None)
|
abhinavsingh/proxy.py | proxy/dashboard/dashboard.py | Python | bsd-3-clause | 1,872 | 0.000536 | # -*- coding: utf-8 -*-
"""
proxy.py
~~~~~~~~
⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on
Network monitoring, controls & Application development, testing, debugging.
:copyright: (c) 2013-pr | esent by Abhinav Singh and contributors.
:license: BSD, see LICENSE for more detai | ls.
"""
import os
import logging
from typing import List, Tuple
from ..http.parser import HttpParser
from ..http.server import HttpWebServerBasePlugin, httpProtocolTypes
from ..http.responses import permanentRedirectResponse
logger = logging.getLogger(__name__)
class ProxyDashboard(HttpWebServerBasePlugin):
""... |
adamcik/mopidy-echonest | tests/test_extension.py | Python | apache-2.0 | 542 | 0 | from __future__ import unicode_literals
import unittest
from mopidy_echonest import Extension, frontend as frontend_lib
class ExtensionTest(unittest.TestCase):
def test_get_default_config(self):
ext = Extension()
config = ext.get_default_config()
self.assertIn('[echonest]', config)
... | enabled = true', config)
def test_get_config_schema(self):
ext = Extension()
schema = ext.get_config_schema()
self.assertIn('a | pikey', schema)
# TODO Write more tests
|
culturagovbr/sistema-nacional-cultura | adesao/managers.py | Python | agpl-3.0 | 768 | 0.001309 | from django.db import models
from django.core.exceptions import EmptyResultSet
class SistemaManager(models.Manager):
""" Mana | ger utilizado para interações com os Sistemas de Cultura """
def get_queryset(self):
queryset = super().get_queryset()
queryset = queryset.distinct('ente_federado__nome', 'ente_federado')
return queryset.filter(id__in=queryset).select_related()
class HistoricoManager(mod | els.Manager):
"""
Manager responsavel pelo gerenciamento de histórico de um determinado ente federado.
"""
def ente(self, cod_ibge=None):
""" Retorna o histórico de um ente federado """
if not cod_ibge:
raise EmptyResultSet
return self.filter(ente_federado__cod_ibge... |
Sabayon/anaconda | pyanaconda/installclasses/corecd.py | Python | gpl-2.0 | 1,357 | 0.000737 | #
# corecd.py
#
# Copyright (C) 2014 Fabio Erculiani
#
# This program is free software; you can redistr | ibute 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 WITHOUT ANY WARRANTY; without even the implied... | the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from pyanaconda.installclass import BaseInstallClass
from pyanaconda.i18n import N_
from pyanaconda.sabayon import Entropy
... |
TheAlgorithms/Python | data_structures/linked_list/print_reverse.py | Python | mit | 1,768 | 0.000566 | from __future__ import annotations
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
def __repr__(self):
"""Returns a visual representation of the node and all its following nodes."""
string_rep = []
temp = self
while temp:
... | le) | and returns the head of the Linked List.
>>> make_linked_list([])
Traceback (most recent call last):
...
Exception: The Elements List is empty
>>> make_linked_list([7])
7
>>> make_linked_list(['abc'])
abc
>>> make_linked_list([7, 25])
7->25
"""
if not elements_list:
... |
mbr/flatland0 | tests/schema/test_constrained.py | Python | mit | 2,931 | 0.000341 | import six
from flatland import (
Constrained,
Enum,
Integer,
)
def test_constrained_no_default_validity():
el = Constrained(u'anything')
assert el.value is None
assert el.u == u'anything'
def test_constrained_instance_override():
def make_checker(*ok_values):
def is_valid(ele... | assert el.value is None
assert el.u == u''
def test_default_enum():
good_values = (u'a', u'b', u'c')
for good_val in good_values:
for schema in (Enum.using(valid_values=good_values),
Enum.valued(*good_ | values)):
el = schema()
assert el.set(good_val)
assert el.value == good_val
assert el.u == good_val
assert el.validate()
assert not el.errors
schema = Enum.valued(*good_values)
el = schema()
assert not el.set(u'd')
assert el.value ... |
repology/repology | repology-update.py | Python | gpl-3.0 | 16,579 | 0.004102 | #!/usr/bin/env python3
#
# Copyright (C) 2016-2019 Dmitry Marakasov <[email protected]>
#
# This file is part of repology
#
# repology 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 Lic... | : argparse.Namespace
def __ | init__(self, options: argparse.Namespace) -> None:
self.options = options
@cached_method
def get_query_manager(self) -> QueryManager:
return QueryManager(self.options.sql_dir)
@cached_method
def get_main_database_connection(self) -> Database:
return Database(self.options.dsn, s... |
schleichdi2/OPENNFR-6.3-CORE | bitbake/lib/toaster/toastergui/tables.py | Python | gpl-2.0 | 63,230 | 0.001661 | #
# BitBake Toaster Implementation
#
# Copyright (C) 2015 Intel Corporation
#
# SPDX-License-Identifier: GPL-2.0-only
#
from toastergui.widgets import ToasterTable
from orm.models import Recipe, ProjectLayer, Layer_Version, Machine, Project
from orm.models import CustomImageRecipe, Package, Target, Build, LogMe... | s_dirpath_link_url }}">
<span class="glyphicon glyphicon-new-window"></span>
</a>
{% endif %}'''
self.add_column(title="Subdirectory",
help_text="The layer directory within the Git repository",
hidd | en=True,
static_data_name="git_subdir",
static_data_template=git_dir_template)
revision_template = '''
{% if data.layer.local_source_dir %}
<span class="text-muted">Not applicable</span>
<span class="glyphicon glyphicon-question-sign get-... |
slinderman/pyhsmm_spiketrains | experiments/make_figure7.py | Python | mit | 3,751 | 0.003999 | import os
import cPickle
import gzip
from collections import namedtuple
import numpy as np
import matplotlib
matplotlib.rcParams.update({'axes.labelsize': 9,
'xtick.labelsize' : 9,
'ytick.labelsize' : 9,
'axes.titlesize' : 11})
import... | )
ax = create_axis_at_location(fig, 0.6, 0.5, 1.7, .8, transparent=True)
plt.figtext(0.05/5, 1.25/1.5, "A")
ax.box | plot(Ks_alpha_a_0, positions=np.arange(1,1+len(alpha_a_0s)),
boxprops=dict(color=allcolors[1]),
whiskerprops=dict(color=allcolors[0]),
flierprops=dict(color=allcolors[1]))
ax.set_xticklabels(alpha_a_0s)
plt.xlim(0.5,4.5)
plt.ylim(40,90)
# plt.yticks(np.arange... |
SylvainDe/DidYouMean-Python | didyoumean/__init__.py | Python | mit | 66 | 0 | """Empt | y file. Might grow in the future."""
import didyoumean_ap | i
|
crainiarc/poker-ai-planner | agents/adaptive_play_bot.py | Python | mit | 99 | 0.020202 | from human_bot import HumanBo | t
class AdaptivePlayBot(HumanBot):
| def __init(self):
pass |
tomviner/unlimited-weeks-in-google-calendar | tests/test_ext.py | Python | mit | 2,010 | 0.000995 | import time
CALENDAR_URL = 'https://calendar.google.com/calendar'
BUTTONS_CLASS = 'gcal-unlim-weeks-adjust-weeks'
ADD_BUTTON_CLASS = 'gcal-unlim-weeks-add-week'
REMOVE_BUTTON_CLASS = 'gcal-unlim-weeks-remove-week'
def get_num_weeks(selenium):
weeks = selenium.find_elements_by_class_name('month-row')
return l... | else:
button = add_button
for _ in range(abs(delta)):
button.click() |
num_weeks = get_num_weeks(selenium)
assert num_weeks == old_num_weeks + delta
old_num_weeks = num_weeks
|
croxis/SpaceDrive | spacedrive/renderpipeline/rpcore/stages/gbuffer_stage.py | Python | mit | 2,402 | 0.000833 | """
RenderPipeline
Copyright (c) 2014-2016 tobspr <[email protected]>
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 right... |
def make_gbuffer_ubo(self):
ubo = SimpleInputBlock("GBuffer")
ubo.add_input("Depth", self.target.depth_tex)
ubo.add_input("Data0", self.target.color_tex)
ubo.add_input("Data1", self.target.aux_tex[0])
ubo.add_input("Data2", self.target.aux_tex[1])
return ubo... | add_depth_attachment(bits=32)
self.target.add_aux_attachments(bits=16, count=2)
self.target.prepare_render(Globals.base.cam)
def set_shader_input(self, *args):
Globals.render.set_shader_input(*args)
|
TileDB-Inc/TileDB | doc/source/conf.py | Python | mit | 6,868 | 0.002621 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# TileDB documentation build configuration file, created by
# sphinx-quickstart on Mon Feb 5 10:08:37 2018.
#
# -- Imports configuration -------------------------------------------------
import os
import subprocess
import sys
from os.path import abspath, join, dirname... | sion in ['stable', 'latest'] else 'stable'
# On RTD, build the Doxygen XML files.
if readthedocs:
# Build docs
subprocess.check_call(''' |
mkdir ../../build;
cd ../../build;
../bootstrap;
make doc;
''', shell=True)
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension modu... |
kmee/l10n-brazil | l10n_br_fiscal/models/nbm.py | Python | agpl-3.0 | 1,671 | 0 | # Copyright (C) 2020 Renato Lima - Akretion <[email protected]>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from odoo import api, fields, models
from ..tools import misc
class Nbm(models.Model):
_name = 'l10n_br_fiscal.nbm'
_inherit = 'l10n_br_fiscal.data.product.abstract'
... | te_super
@api.multi
def write(self, values):
write_super = super(Nbm, self).write(values)
do_not_write = self.env.context.get('do_not_write')
| if 'ncms' in values.keys() and not do_not_write:
self.with_context(do_not_write=True).action_search_ncms()
return write_super
@api.multi
def action_search_ncms(self):
ncm = self.env['l10n_br_fiscal.ncm']
for r in self:
if r.ncms:
domain = misc... |
wangshunzi/Python_code | 02-Python面向对象代码/面向对象-基础/classDesc.py | Python | mit | 728 | 0.005597 |
class Person:
"""
关于这个类的描述, 类的作用, 类的构造函数等等 | ; 类属性的描述
Attributes:
count: int 代表是人的个数
"""
# 这个表示, 是人的个数
count = 1
def run(self, distance, step):
"""
这个方法的作用效果
:param distance: 参数的含义, 参数的类型int, 是否有默认值
:param step:
:return: 返回的结果的含义(时间), 返回数据的类型int
"""
print("人在跑")
return di... | 这是一个xxx函数, 有xxx作用
:return:
"""
print("xxx")
|
cloudera/hue | desktop/core/ext-py/openpyxl-2.6.4/openpyxl/worksheet/errors.py | Python | apache-2.0 | 2,435 | 0.002464 | #Autogenerated schema
from openpyxl.descriptors.serialisable import Serialisable
from openpyxl.descriptors import (
Typed,
String,
Bool,
Sequence,
)
from openpyxl.descriptors.excel import CellRange
class Extension(Serialisable):
tagname = "extension"
uri = String(allow_none=True)
def __... | umberStoredAsText
self.formula = formula
self.formulaRange = formulaRange
self.unlockedFormula = unlockedFormula
self.emptyCellReference = emptyCellReference
self.listDataValidation = listDataVal | idation
self.calculatedColumn = calculatedColumn
class IgnoredErrors(Serialisable):
tagname = "ignoredErrors"
ignoredError = Sequence(expected_type=IgnoredError)
extLst = Typed(expected_type=ExtensionList, allow_none=True)
__elements__ = ('ignoredError', 'extLst')
def __init__(self,
... |
owlabs/incubator-airflow | airflow/example_dags/example_bash_operator.py | Python | apache-2.0 | 2,045 | 0 | # -*- coding: utf-8 -*-
#
# 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
#... | ator(
task_id='run_after_loop',
bash_command='echo 1',
dag=dag,
)
# [END howto_operator_bash]
run_this >> run_this_last
for i in range(3):
task = BashOperator(
task_id='runme_' + str(i),
bash_command='echo "{{ task_instance_key_str }}" && sleep 1',
dag=dag,
)
task >> ru... | plate]
also_run_this = BashOperator(
task_id='also_run_this',
bash_command='echo "run_id={{ run_id }} | dag_run={{ dag_run }}"',
dag=dag,
)
# [END howto_operator_bash_template]
also_run_this >> run_this_last
if __name__ == "__main__":
dag.cli()
|
kristinriebe/django-prov_vo | tests/travis.local.py | Python | apache-2.0 | 43 | 0 | import | sys
sys.path.append('dja | ngo-vosi/')
|
kanarelo/dairy | dairy/core/migrations/0009_auto_20151128_1236.py | Python | apache-2.0 | 992 | 0.002016 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0008_auto_20151124_1135'),
]
operations = [
migrations.AddField(
mode | l_name='service',
name='short_ | name',
field=models.CharField(max_length=20, null=True),
),
migrations.AlterField(
model_name='product',
name='unit',
field=models.IntegerField(choices=[(1, b'kg'), (2, b'L')]),
),
migrations.AlterField(
model_name='supplierserv... |
unreal666/outwiker | src/outwiker/utilites/collections.py | Python | gpl-3.0 | 322 | 0 | # -*- coding | : utf-8 -*-
def update_recent(items, new_item, max_count):
'''
Move or insert a new_item to begin of items.
Return new list
'''
result = items[:]
if new_item in result:
result.remove(new_item)
result.insert(0, new_item)
result = resu | lt[:max_count]
return result
|
speksi/python-mingus | mingus/containers/composition.py | Python | gpl-3.0 | 3,367 | 0.000891 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# mingus - Music theory Python package, composition module.
# Copyright (C) 2008-2009, Bart Spaans
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software... | btitle = subtitle
def set_author(self, author='', email=''):
"""Set the title and author of the piece."""
self.author = author
self.email = email
def __add__(self, | value):
"""Enable the '+' operator for Compositions.
Notes, note strings, NoteContainers, Bars and Tracks are accepted.
"""
if hasattr(value, 'bars'):
return self.add_track(value)
else:
return self.add_note(value)
def __getitem__(self, index):
... |
NetApp/manila | manila/share/drivers/helpers.py | Python | apache-2.0 | 21,481 | 0.000047 | # Copyright 2015 Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | def configure_access(self, server, share_name):
"""Configure server before allowing access."""
pass
def update_access(self, server, share_name, access_rul | es, add_rules,
delete_rules):
"""Update access rules for given share.
This driver has two different behaviors according to parameters:
1. Recovery after error - 'access_rules' contains all access_rules,
'add_rules' and 'delete_rules' shall be empty. Previously exis... |
hjanime/VisTrails | vistrails/db/versions/v1_0_4/domain/auto_gen.py | Python | bsd-3-clause | 767,323 | 0.005515 | ###############################################################################
##
## Copyright (C) 2014-2015, New York University.
## Copyright (C) 2011-2014, NYU-Poly.
## Copyright (C) 2006-2011, University of Utah.
## All rights reserved.
## Contact: [email protected]
##
## This file is part of VisTrails.
##
## ... | new_obj.db_deleted_cause.append(n_obj)
if 'accounts' in class_dict:
res = class_dict['accounts'](old_obj, | trans_dict)
for obj in res:
new_obj.db_add_account(obj)
elif hasattr(old_obj, 'db_accounts') and old_obj.db_accounts is not None:
for obj in old_obj.db_accounts:
new_obj.db_add_account(DBOpmAccountId.update_version(obj, trans_dict))
if hasattr(old... |
eballetbo/igep_qa | igep_qa/helpers/omap.py | Python | mit | 4,552 | 0.004613 | #!/usr/bin/env python
"""
This provides various OMAP/IGEP related helper functions.
"""
from igep_qa.helpers.common import QMmap, QCpuinfo, QDeviceTree
import commands
import time
def cpu_is_omap5():
""" Returns True if machine is OMAP5, otherwise returns False
"""
return QDeviceTree().compatible("ti,... | utput("amixer sset -c %s MUX_UL00,0 AMic0" % headset)
commands.getoutput("amixer sset -c %s MUX_UL01,0 AMic1" % headset)
commands.getoutput("amixer sset -c %s 'AMIC UL',0 120" % headset)
def igep0050_power_up_bluetooth():
""" Power Up bluetooth device.
Send a pulse to the BT_EN pin.
"""
comma... | etoutput("echo 0 > /sys/class/gpio/gpio142/value")
time.sleep(1)
commands.getoutput("echo 1 > /sys/class/gpio/gpio142/value")
|
vinegret/youtube-dl | youtube_dl/extractor/usatoday.py | Python | unlicense | 2,703 | 0.00259 | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor |
from ..utils import (
ExtractorError,
get_element_by_attribute,
parse_duration,
try_get,
update_url_query,
)
from ..compat import compat_str
class USATodayIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?usatoday\.com/(?:[^/]+/)*(?P<id>[^?/#]+)'
_TESTS = [{
# Brightcove Partne... | lks/',
'md5': '033587d2529dc3411a1ab3644c3b8827',
'info_dict': {
'id': '4799374959001',
'ext': 'mp4',
'title': 'US, France warn Syrian regime ahead of new peace talks',
'timestamp': 1457891045,
'description': 'md5:7e50464fdf2126b0f533748d3c78d5... |
tuskar/tuskar-ui | openstack_dashboard/dashboards/admin/hypervisors/views.py | Python | apache-2.0 | 1,366 | 0.001464 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 B1 Systems GmbH
#
# 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
#... | under the License.
import logging
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import tables
from openstack_dashboard import api
from openstack_dashboard.dashboa | rds.admin.hypervisors.tables import \
AdminHypervisorsTable
LOG = logging.getLogger(__name__)
class AdminIndexView(tables.DataTableView):
table_class = AdminHypervisorsTable
template_name = 'admin/hypervisors/index.html'
def get_data(self):
hypervisors = []
try:
hyper... |
weolar/miniblink49 | third_party/WebKit/Source/bindings/scripts/code_generator_v8.py | Python | apache-2.0 | 21,053 | 0.0019 | # Copyright (C) 2013 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the ... | _typed_object(self, typed_object):
self._resolve_typedefs(typed_object)
class CodeGeneratorBase(object):
"""Base class for v8 bindings generator and IDL dictionary impl generator"""
def __init__(self, info_provider, cache_dir, output_dir):
self.info_pro | vider = info_provider
self.jinja_env = initialize_jinja_env(cache_dir)
self.output_dir = output_dir
self.typedef_resolver = TypedefResolver(info_provider)
set_global_type_info(info_provider)
def generate_code(self, definitions, definition_name):
"""Returns .h/.cpp code as ((... |
benh/twesos | src/webui/master/webui.py | Python | bsd-3-clause | 1,208 | 0.022351 | import sys
import bottle
import commands
import datetime
from bottle import route, send_file, template
start_time = datetime.datetime.now()
@route('/')
def index():
bottle.TEMPLATES.clear() # For rapid developme | nt
return template("index", start_time = start_time)
@route('/framework/:id#[0-9-]*#')
def framework(id):
bottle.TEMPLATES.clear() # For rapid development
return template("framework", framework_id = id)
@route('/static/:filename#.*#')
def static(filename):
send_file(filename, root = './webui/static')
@rou... | #[A-Z]*#/:lines#[0-9]*#')
def log_tail(level, lines):
bottle.response.content_type = 'text/plain'
return commands.getoutput('tail -%s %s/mesos-master.%s' % (lines, log_dir, level))
bottle.TEMPLATE_PATH.append('./webui/master/')
# TODO(*): Add an assert to confirm that all the arguments we are
# expecting have be... |
wxgeo/geophar | wxgeometrie/sympy/utilities/timeutils.py | Python | gpl-2.0 | 2,063 | 0.001454 | """Simple tools for timing functions' execution, when IPython is not available. """
from __future__ import print_function, division
import timeit
import math
from sympy.core.compatibility import range
_sca | les = [1e0, 1e3, 1e6, 1e9]
_units = [u's', u'ms', u'\N{GREEK SMALL LETTER MU}s', u'ns']
def timed(func, setup="pass", limit=None):
"""Adaptively measure execution time of a function. """
timer = timeit.Timer(func, setu | p=setup)
repeat, number = 3, 1
for i in range(1, 10):
if timer.timeit(number) >= 0.2:
break
elif limit is not None and number >= limit:
break
else:
number *= 10
time = min(timer.repeat(repeat, number)) / number
if time > 0.0:
order =... |
pferreir/indico | indico/modules/news/controllers.py | Python | mit | 3,954 | 0.001517 | # This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from datetime import timedelta
from flask import flash, redirect, request, session
from indico.core.db i... | def _is_new(item):
days = news_settings.get('new_days')
if not days:
return False
return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date()
def _process(self):
news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all()
return WPNews.rende... | s_new)
class RHNewsItem(RH):
normalize_url_spec = {
'locators': {
lambda self: self.item.locator.slugged
}
}
def _process_args(self):
self.item = NewsItem.get_or_404(request.view_args['news_id'])
def _process(self):
return WPNews.render_template('news_item... |
evangeline97/localwiki-backend-server | localwiki/links/migrations/0002_populate_page_links.py | Python | gpl-2.0 | 3,623 | 0.00552 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
from django.utils.encoding import smart_str
class Migration(DataMigration):
def forwards(self, orm):
from pages.models import slugify
from links import extract_internal_... | if orm.Link.objects.filter(source=page, destination_name__iexact=pagename).exists():
if destination:
link = orm.Link.objects.filter(source=page, destination_name__iexact=pagename)[0]
link.destination = desti | nation
link.save()
else:
link = orm.Link(
source=page,
region=region,
destination=destination,
destination_name=pagename,
count=count,
... |
Carvuh/TerminalQuest | PlayerInputManager.py | Python | mit | 2,393 | 0.005433 | from DungeonMaster import bcolors
from random import randint
class InputManager:
correctCommand = False
def ParsePlayerInput(playerInput):
commandTokens = ["/yell", "/roll", "/say", "/grab", "/pickup", "/setRac | e"]
## by character
playerInputTokens = list(playerInput)
## by string
splitPlayerInput = playerInput.split()
if splitPlayerInput[0] in commandTokens:
InputManager.correctCommand = True
## LETS ROLL S | OME DICE!
if '/roll' in splitPlayerInput:
if 'd20' in splitPlayerInput[1]:
analyzeRollParse = list(splitPlayerInput[1])
if analyzeRollParse[0] != 'd':
for rollTime in range(0, int(analyzeRollParse[0])):
... |
elastic/elasticsearch-py | elasticsearch/_async/client/graph.py | Python | apache-2.0 | 3,806 | 0.000788 | # Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use ... | cation/json"
return await self.perform_request( # type: ignore[return-value]
"POST", __path, params=__query, headers= | __headers, body=__body
)
|
egnyte/python-egnyte | egnyte/tests/test_folders.py | Python | mit | 2,749 | 0.00146 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from egnyte import exc
from egnyte.tests.config import EgnyteTestCase
FOLDER_NAME = 'Iñtërnâtiônàlizætiøν☃ test'
DESTINATION_FOLDER_NAME = 'destination'
S | UB_FOLDER_NAME = 'subfolder'
FILE_IN_FOLDER_NAME = 'test.txt'
FILE_CONTENT = b'TEST FILE CONTENT'
class TestFolders(EgnyteTestCase):
def setUp(self):
super(TestFolders, self).setUp()
self.folder = self.root_folder.folder(FOLDER_NAME)
self.destination = self.root_folder.folder(DESTINATION_F... | e()
self.assertIsNone(self.folder.check())
with self.assertRaises(exc.InsufficientPermissions):
self.folder.create(False)
def test_folder_recreate(self):
self.folder.create()
self.assertIsNone(self.folder.check())
self.folder.create()
self.assertIsNone(s... |
mcsalgado/ansible | lib/ansible/playbook/play_context.py | Python | gpl-3.0 | 16,111 | 0.009252 | # -*- coding: utf-8 -*-
# (c) 2012-2014, 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 the License,... | ne:
passwords = {}
self.password = passwords.get('conn_pass','') |
self.become_pass = passwords.get('become_pass','')
# a file descriptor to be used during locking operations
self.connection_lockfd = connection_lockfd
# set options before play to allow play to override them
if options:
self.set_options(options)
if play:
... |
JorgeDeLosSantos/pyqus | pyqus/examples/dat/Lug/post_u_data.py | Python | mit | 420 | 0.009524 | # -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('ggplot')
data = np.loadtx | t("u.txt", delimiter=",")
nodes = data[:,0]
ux = data[:,1]
uy = data[:,2]
usum = data[:,3]
plt. | plot(nodes, ux, "r--", label="ux")
plt.plot(nodes, uy, "g--", label="uy")
plt.plot(nodes, usum, "b", label="usum")
plt.xlabel("Nodes")
plt.ylabel("Displacement (m)")
plt.xticks(nodes)
plt.legend()
plt.show()
|
wxgeo/geophar | wxgeometrie/sympy/tensor/tests/test_indexed.py | Python | gpl-2.0 | 14,359 | 0.002159 | from sympy.core import symbols, Symbol, Tuple, oo, Dummy
from sympy.core.compatibility import iterable, range
from sympy.tensor.indexed import IndexException
from sympy.utilities.pytest import raises, XFAIL
# import test:
from sympy import IndexedBase, Idx, Indexed, S, sin, cos, Sum, Piecewise, And, Order, LessThan, S... | (i14 <= i35, LessThan)
assert isinstance(i14 >= i35, GreaterTh | an)
iNone1 = Idx("iNone1")
iNone2 = Idx("iNone2")
assert isinstance(iNone1 < iNone2, StrictLessThan)
assert isinstance(iNone1 > iNone2, StrictGreaterThan)
assert isinstance(iNone1 <= iNone2, LessThan)
assert isinstance(iNone1 >= iNone2, GreaterThan)
@XFAIL
def test_Idx_inequalities_current_f... |
mozman/ezdxf | examples/text_layout_engine_usage.py | Python | mit | 12,087 | 0.001324 | # Copyright (c) 2021, Manfred Moitzi
# License: MIT License
import sys
from typing import Iterable
import pathlib
import random
import ezdxf
from ezdxf import zoom, print_config
from ezdxf.math import Matrix44
from ezdxf.tools import fonts
from ezdxf.tools import text_layout as tl
"""
This example shows the usage o... |
absolute locations are not supported - tabulators are not supported.
The layout engine knows nothing about the content itself, it just manages
content boxes of a fixed given width and height and "glue" spaces in between.
The engine does not alter the size of the content boxes, but resizes the glue
if necessary. T... | xt styling manged by the layout engine is underline, overline and
strike through multiple content boxes.
Features:
- layout alignment like MText: top-middle-bottom combined with left-center-right
- paragraph alignments: left, right, center, justified
- paragraph indentation: left, right, special first line
- cell al... |
CloverHealth/airflow | airflow/migrations/versions/86770d1215c0_add_kubernetes_scheduler_uniqueness.py | Python | apache-2.0 | 1,564 | 0.001918 | # flake8: noqa
#
# 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... | mn("one_row_id", sa.Boolean, server_default=sa.true(), primary_key | =True),
sa.Column("worker_uuid", sa.String(255)),
sa.CheckConstraint("one_row_id", name="kube_worker_one_row_id")
)
op.bulk_insert(table, [
{"worker_uuid": ""}
])
def downgrade():
op.drop_table(RESOURCE_TABLE)
|
eriwoon/2048 | main.py | Python | mit | 9,629 | 0.028595 | #! /usr/bin/python
#encoding=UTF-8
'''
Created on 2014-5-15
@author: XIAO Zhen
'''
'''哈哈'''
import Tkinter as tk
import time
import random
class Application(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.winfo_toplevel().rowconfigure(0,minsize = 1)
self.w... | if self.buttons[i*4 + j]['text'] != str(re[k]):
flag = 1
self.buttons[i*4 + j]['text'] = str(re[k])
k += 1
elif direction == 'to_left':
#rows
for i in range(0, 4):
#columns:
... | elf.buttons[i*4 + j]['text']))
re = self.sum(list)
k = 0
for j in range(0, 4):
if self.buttons[i*4 + j]['text'] != str(re[k]):
flag = 1
self.buttons[i*4 + j]['text'] = str(re[k])
k += ... |
googlemaps/openapi-specification | dist/snippets/maps_http_geocode_place_id/maps_http_geocode_place_id.py | Python | apache-2.0 | 320 | 0.009375 | # [STA | RT maps_http_geocode_place_id]
import requests
url = "https://maps.googleapis.com/maps/api/geocode/json?place_id=ChIJd8BlQ2BZwokRAFUEcm_qrcA&key=YOUR_API_KEY"
payload={}
headers = {}
response = requests.request("GET", url, headers=headers, data=payload)
print(response.text)
# [END maps_http_geocode | _place_id] |
kawamon/hue | desktop/core/ext-py/celery-4.2.1/celery/worker/__init__.py | Python | apache-2.0 | 152 | 0 | """Worker implementation."""
from __future__ import absolute_import, unicode_lite | rals
from .worker import WorkController
__all__ = (' | WorkController',)
|
weiqiangdragonite/blog_tmp | python/学习文档/python_process/p2.py | Python | gpl-2.0 | 987 | 0.016211 | #!/usr/bin/env python
# -*- coding: utf-8 | -*-
import multiprocessing
import time
def worker_1(interval):
print "worker_1: %s" % (time.ctime())
time.sleep(interval)
print "end worker_1"
def worker_2(interval):
print "worker_2: %s" % (time.ctime())
time.sleep(interval)
print "end worker_2"
def worker_3(interval):
| print "worker_3: %s" % (time.ctime())
time.sleep(interval)
print "end worker_3"
if __name__ == "__main__":
p1 = multiprocessing.Process(target = worker_1, args = (2,))
p2 = multiprocessing.Process(target = worker_2, args = (3,))
p3 = multiprocessing.Process(target = worker_3, args = (4,))
... |
michaelpb/omnithumb | omnithumb/types/__init__.py | Python | gpl-3.0 | 35 | 0 | from .type | stri | ng import TypeString
|
jamesmarlowe/Python-Data-Writers | datawriters/sqlitewriter.py | Python | bsd-2-clause | 1,215 | 0.004938 | import sqlite3
class SqliteWriter:
def __init__(self, *args, **kwargs):
if 'database' in kwargs:
self.db_sqlite3 = kwargs['database']
else:
print 'missing database argument, using data.sqlite'
self.db_sqlite3 = 'data.sqlite'
if 'table' in kwargs:
... | ist(set().union(*(d.keys() for d in list_of_dicts)))
db = sqlite3.connect(self.db_sqlite3)
cursor = db.cursor()
CREATE_TABLE = '''CREATE TABLE IF NOT EXISTS '''+self.db_table+'''(
'''+' TEXT,'.join([k for k in all_keys])+' TEXT'+'''
)... | ery = 'INSERT INTO '+self.db_table+' (%s) VALUES (%s)' % (columns, placeholders)
cursor.executemany(query, ({k: d.get(k, None) for k in all_keys} for d in list_of_dicts))
db.commit()
cursor.close()
|
benfinke/ns_python | nssrc/com/citrix/netscaler/nitro/resource/config/appfw/appfwlearningsettings.py | Python | apache-2.0 | 24,257 | 0.029847 | #
# Copyright (c) 2008-2015 Citrix Systems, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | or the specific language governing permissions and
# limitations under the License.
#
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.ni | tro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception
from nssrc.com.citrix.netscaler.nitro.util.nitro_util import nitro_util
class appfwlearningsettings(base_resource) :
""" Configuration for learning settings resource. """
def __init__(self) :
... |
SANDEISON/Python | 04 - Funções e Arquivos À Solta/03 -Agrupando códigos em Módulos/02 - embaralha_nome.py | Python | gpl-2.0 | 176 | 0.028409 | def embaralha (x):
import random
lista = list(x)
| random.shuffle(lista)
return ''.joi | n(lista)
nome = input ("Digite algum nome : ")
print (embaralha(nome))
|
michaelBenin/django-jinja | example_project/example_project/web/templatetags/testags.py | Python | bsd-3-clause | 301 | 0.006645 | # -*- coding: ut | f-8 -*-
from django_jinja.base import Library
import jinja2
register = Library()
@register.filter
@jinja2.contextfilter
def datetimeformat(ctx, value, format='%H:%M / %d-%m-%Y'):
return value.strftime(format)
@register.global_context |
def hello(name):
return "Hello" + name
|
GunioRobot/pywapi-dbus | setup.py | Python | lgpl-3.0 | 1,419 | 0.027484 | from distutils.core import setup
setup(name = "pywapi-dbus",
version = "0.1-git",
description = "D-Bus Python Weather API Service is a D-Bus service providing weather information",
author = "Sasu Karttunen",
author_email = "[email protected]",
url = "https://github.com/skfin/pywapi-dbus",
... | r API provides as Python libr | ary. D-Bus Python Weather API Service can be used in all programming languages that has working D-Bus libraries available.""",
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: GNU Lib... |
slava-sh/NewsBlur | apps/search/management/commands/index_stories.py | Python | mit | 993 | 0.006042 | import re
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from apps.rss_feeds.models import Feed
from apps.reader.models import UserSubscription
from optparse import make_option
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option... | "Specify user id or username"),
)
def handle(self, *args, **options):
if re.match(r"([0-9]+)", options['user']):
user = Use | r.objects.get(pk=int(options['user']))
else:
user = User.objects.get(username=options['user'])
subscriptions = UserSubscription.objects.filter(user=user)
print " ---> Indexing %s feeds..." % subscriptions.count()
for sub in subscriptions:
try:
... |
emlid/ReachView | ReachLED.py | Python | gpl-3.0 | 5,937 | 0.004716 | #!/usr/bin/python
# ReachView code is placed under the GPL license.
# Written by Egor Fedorov ([email protected])
# Copyright (c) 2015, Emlid Limited
# All rights reserved.
# If you are interested in using ReachView code as a part of a
# closed source project, please contact Emlid Limited ([email protected]).
# Th... | # then, export the 3 pwn channels if needed
for ch in self.pwm_channels:
i | f not os.path.exists(self.pwm_prefix + "/pwm" + str(ch)):
with open(self.pwm_prefix + "export", "w") as f:
f.write(str(ch))
# enable all of the channels
for ch in self.pwm_channels:
with open(self.pwm_prefix + "pwm" + str(ch) + "/enable", "w") as f:
... |
cohadar/learn-python-the-hard-way | cohadar/game.py | Python | mit | 663 | 0.033183 | """Classes for a Game."""
class Room(object):
"""Room is something you can walk in and out of.
It has a name and a descript | ion.
It also has a dictionary of "paths" to other rooms.
"""
def __init__(self, name, description):
"""create a room with a name and description and no paths"""
self.name = name
self.description = description
self.paths = {}
def add_paths(self, paths):
"""Blah blah blah."""
self.paths.update(paths)
... | __repr__(self):
"""Ha, this is very useful in test debugging."""
return "Room(name=%s)" % self.name
|
Eigenlabs/EigenD | pisession/oldfixture.py | Python | gpl-3.0 | 1,459 | 0.007539 |
#
# Copyright 2009 Eigenlabs Ltd. http://www.eigenlabs.com
#
# This file is part of EigenD.
#
# EigenD 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) a... | ils.notify(Non | e),utils.stringify(self.logger),'test')
piw.setenv(self.context.getenv())
if self.logger is not None:
self.oldstd = sys.stdout,sys.stderr
sys.stdout,sys.stderr = self.logger.Logger(),sys.stdout
def tearDown(self):
self.context.kill()
self.context = None
... |
uxlsl/uxlsl.github.io | demo/code/2021-11-15/f.py | Python | mit | 135 | 0.007407 | #!/usr/bin/env python
# -*- | coding: ut | f-8 -*-
def f(k, n):
pass
assert f(1, 2) == 2
assert f(2, 6) == 3
assert f(3, 14) == 14
|
axaxaxas/daniel-powell-portfolio | narsil/nutils.py | Python | lgpl-3.0 | 6,200 | 0.029839 | # This software is distributed under the GNU Lesser General Public License.
# See the root of this repository for details.
# Copyright 2012 Daniel Powell
import threading
import math
import os
from struct import pack, unpack
### some default global parameters ###
FRAGMENT_SIZE = 4096
NARSIL_PORT = 28657... | s at least as long as the header.
result = {}
result['filename'] = header.partition("**")[0]
result['size'] = unpack('!Q', header.partition("**")[2].partition("**")[0])[0]
result['data'] = header.partition("**")[2].partition("**")[2]
return result
def parse_supply_header(header):
# Parses a file supply h... | ' is for payload bytes that got scooped up along with the header; parse_supply_header can
# safely accept any substring of the transfer data beginning at byte 0 provided that
# it is at least as long as the header.
result = {}
result['size'] = unpack('!Q', header.partition("**")[0])[0]
result['data'] = header... |
jalanb/kd | cde/timings.py | Python | mit | 1,061 | 0 | """Methods to handle times"""
import time
def now():
"""Current time
This method exists only to save other modules an extra import
"""
return time.time()
def time_since(number_of_seconds):
"""Convert number of seconds to English
Retain only the two most significant numbers
>>> expect... | + 5))
>>> assert actual == expected
"""
interval = int(abs(float(number_of_seconds)) - time.time())
interval = int(time.time() - float(number_of_seconds))
minutes, seconds = divmod(interval, 60)
if not minutes:
return "%s seconds" % seconds
hours, minutes = divmod(minutes, 60)
| if not hours:
return "%s minutes, %s seconds" % (minutes, seconds)
days, hours = divmod(hours, 24)
if not days:
return "%s hours, %s minutes" % (hours, minutes)
years, days = divmod(days, 365)
if not years:
return "%s days, %s hours" % (days, hours)
return "%s years, %s d... |
gfelbing/cppstyle | cppstyle/model/function.py | Python | gpl-3.0 | 229 | 0.004367 | from .node import Node
class Function(Node):
def _ | _init__(self, file, position, access, comments, name, children):
super(Function, self).__init__(file, position, access, c | omments, children)
self.name = name
|
samuelclay/NewsBlur | apps/oauth/views.py | Python | mit | 31,341 | 0.006413 | import urllib.request, urllib.parse, urllib.error
import datetime
import lxml.html
import tweepy
from django.contrib.auth.decorators import login_required
from django.urls import reverse
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.http import HttpResponseForbidde... | graph = facebook.GraphAPI(access_token)
profile = graph.get_object("me")
uid = profile["id"]
# Be sure that two people aren't using the same Facebook account.
existing_user = MSocialServices.objects.filter(facebook_uid=uid)
if existing_user and existing_u | ser[0].user_id != request.user.pk:
try:
user = User.objects.get(pk=existing_user[0].user_id)
logging.user(request, "~BB~FRFailed FB connect, another user: %s" % user.username)
return dict(error=("Another user (%s, %s) has "
"... |
mind1master/aiohttp | aiohttp/worker.py | Python | apache-2.0 | 5,538 | 0 | """Async gunicorn worker for aiohttp.web"""
import asyncio
import os
import signal
import ssl
import sys
import gunicorn.workers.base as base
from aiohttp.helpers import ensure_future
__all__ = ('GunicornWebWorker', 'GunicornUVLoopWebWorker')
class GunicornWebWorker(base.Worker):
def __init__(self, *args, **... | signal.SIGINT, None)
self.loop.add_signal_handler(signal.SIGWINCH, se | lf.handle_winch,
signal.SIGWINCH, None)
self.loop.add_signal_handler(signal.SIGUSR1, self.handle_usr1,
signal.SIGUSR1, None)
self.loop.add_signal_handler(signal.SIGABRT, self.handle_abort,
si... |
kichkasch/rtmom | rtmom.py | Python | gpl-3.0 | 6,976 | 0.007024 | #!/usr/bin/env python
"""
Main module for rtmom
Elementary based client for "Remember the Milk" (http://www.rememberthemilk.com/) written in Python.
Copyright (C) 2010 Michael Pilgermann <[email protected]>
http://github.com/kichkasch/rtmom
rtmom is free software: you can redistribute it and/or modify
it under the ... | @ivar _tasks: Holds information about all tasks in memory
"""
def __init__(self):
"""
Constructor - empy initialize categories and tasks
"""
self._categories = None
self._tasks = None
def getCategories(self):
"""
Return categories in memory
| """
return sorted(self._categories.keys())
def getFullTasks(self, category):
"""
Return tasks in memory
"""
return self._tasks[category]
def getFullTaskFromName(self, taskName):
"""
Searches for the full task using the task name
... |
evereux/flask_template | tests.py | Python | mit | 1,928 | 0.006743 | #! python 3
# -*- coding: utf8 -*-
from coverage import coverage
cov = coverage(branch=True, omit=['venv/*', 'tests.py'])
cov.start()
import os
import unittest
from datetime import datetime, timedelta
import bcrypt
from config import basedir, SQLALCHEMY_DATABASE_URI
from application import app, db
from application.... | password)
db.session.add(u)
assert u.is_authenticated is True
assert u.is_active is True
assert u.is_anonymous is False
# assert u.id == u.get_id() # not possible unless db session i
def test_groups(self):
password = 'testicles'
password = password.encode('u... | # add user
u1 = u = User(name='John Doe', email='[email protected]', username='jdoe', password=password)
db.session.add(u1)
# add group
g = Group(group_name='group_test')
db.session.add(g)
# add user to group
g.users.append(u1)
assert u1.groups.count()... |
Azure/azure-sdk-for-python | sdk/servicefabric/azure-mgmt-servicefabric/setup.py | Python | mit | 2,683 | 0.001491 | #!/usr/bin/env python
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#----------------------------------------------------------------... | 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3 | .10',
'License :: OSI Approved :: MIT License',
],
zip_safe=False,
packages=find_packages(exclude=[
'tests',
# Exclude packages that will be covered by PEP420 or nspkg
'azure',
'azure.mgmt',
]),
install_requires=[
'msrest>=0.6.21',
'azure-commo... |
hgl888/flatbuffers | tests/MyGame/Example/AnyUniqueAliases.py | Python | apache-2.0 | 169 | 0.005917 | # automatically generated by the Fla | tBuffers compiler, do not modify
# namespace: Example
class AnyUniqu | eAliases(object):
NONE = 0
M = 1
T = 2
M2 = 3
|
be-cloud-be/horizon-addons | partner-contact/partner_financial_risk/wizard/__init__.py | Python | agpl-3.0 | 60 | 0 | # -*- cod | ing: ut | f-8 -*-
from . import parner_risk_exceeded
|
ellak-monades-aristeias/naturebank | naturebank/management/commands/migrate_legacy_data.py | Python | agpl-3.0 | 42,355 | 0.001063 | import os
from django.conf impor | t settings
from django.core.management.base import BaseCommand
from django.db import IntegrityError
from django.utils.encoding import DjangoUnicodeDecodeError
from naturebank.models import (
AbandonmentOption,
Biotope,
BiotopeCategoryOption,
ClimateOption | ,
ConditionOption,
ConservationOption,
CulturalValueOption,
DesignationOption,
EcologicalValueOption,
GeoCodeOption,
HabitationOption,
HumanActivityOption,
KnowledgeOption,
OwnerOption,
SiteTypeOption,
SitetypeOption,
SocialReactionOption,
SocialValueOption,
S... |
DasIch/argvard | argvard/signature.py | Python | apache-2.0 | 7,016 | 0.000143 | # coding: utf-8
# Copyright 2013 Daniel Neuhäuser
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | try:
state = parser(state, transaction)
patterns.extend(tr | ansaction)
return state
except InvalidSignature:
pass
raise
class Signature(object):
"""
Represents a signature using patterns.
"""
@classmethod
def from_string(cls, string, option=True):
"""
Returns a :class:`Signature` object based on the given... |
gosom/back-to-basics | search/build-demo-data.py | Python | unlicense | 1,168 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import forgery_py
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-i', dest='init_size', type=int, default=1000,
help='The initial number of entries.DEFAULT | 1000')
parser.add_argument('-s', dest='num', type=int, default=10,
help='How many catalogs to build. Each one has'
' double number of elements than the previous.'
'DEFAULT 10')
parser.add_argument('-f', dest='fname', default='data/%d_catalo... | ries = args.init_size
for i in xrange(1, args.num+1):
catalog = args.fname % i
with open(catalog, 'w') as f:
for _ in xrange(num_entries):
name = forgery_py.forgery.name.full_name()
phone = forgery_py.forgery.address.phone()
print >> f, na... |
USCSoftwareEngineeringClub/pyceratOpsRecs | src/interface/hello.py | Python | mit | 1,646 | 0.044957 | import requests, urllib, httplib, base64
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
@app.route("/")
def hello():
return render_template("index.html")
@app.route("/search", methods=['POST', 'GET'])
def callAPI():
error = None
_url = 'https://api.projectoxford.ai/vision/v1.0/... | key it is a header
_maxNumRetries = 10
bodyURL = request.args.get('uri','')
print(bodyURL)
headersIn = {
"Content-Type": "application/json",
"Host": "api.projectoxford.ai",
"Ocp-Apim-Subscription-Key": _key
}
paramsIn = urllib.urlencode({
"language": "en",
"detectOrientation": "false"
}... | params=paramsIn, headers=headersIn)
print r.json()
returnVal = {"data": r.json()}
return returnVal
#
# conn = httplib.HTTPSConnection('api.projectoxford.ai')
# conn.request("POST", "/vision/v1.0/ocr?%s" % paramsIn, "{body}", headersIn)
# response = conn.getresponse()
# data = response.read()
# p... |
ESS-LLP/frappe | frappe/integrations/doctype/ldap_settings/ldap_settings.py | Python | mit | 4,156 | 0.029355 | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import cstr
from frappe.model.document import Document
class LDAPSettings(Document):
def va... | Guidelines to install ldap dependancies and python package")}},
<a href="https://discuss.erpnext.com/t/frappe-v-7-1-beta-ldap-dependancies/15841" target="_blank">{{_("Click here")}}</a>,
</div>
"""
frappe.throw(msg, title=_("LDAP Not Installed"))
except ldap.LDAPError:
conn.unbind_s()
frappe.thr... | rd"))
def get_ldap_settings():
try:
settings = frappe.get_doc("LDAP Settings")
settings.update({
"method": "frappe.integrations.doctype.ldap_settings.ldap_settings.login"
})
return settings
except Exception:
# this will return blank settings
return frappe._dict()
@frappe.whitelist(allow_guest=True)
... |
theoneandonly-vector/LaZagne | Windows/src/LaZagne/config/header.py | Python | lgpl-3.0 | 1,270 | 0.030709 | import logging
from colorama import init, Fore, Back, Style
class Header():
def __init__(self):
init() # for colorama
def first_title(self):
init()
print Style.BRIGHT + Fore.WHITE
print '|====================================================================|'
print '| ... | + title + ' passwords -----------------\n' + Style.RESET_ALL
# Subtitle
def title1(self, title1):
print S | tyle.BRIGHT + Fore.WHITE + '[*] ' + title1 + '\n' + Style.RESET_ALL
# debug option for the logging
def title_info(self, title):
logging.info(Style.BRIGHT + Fore.WHITE + '------------------- ' + title + ' passwords -----------------\n' + Style.RESET_ALL)
|
dmeulen/home-assistant | homeassistant/config.py | Python | mit | 11,390 | 0.000176 | """Module to help with parsing and generating configuration files."""
import asyncio
import logging
import os
import shutil
from types import MappingProxyType
# pylint: disable=unused-import
from typing import Any, Tuple # NOQA
import voluptuous as vol
from homeassistant.const import (
CONF_LATITUDE, CONF_LONGI... | e(conf_dict, dict):
msg = 'The configuration file {} does not contain a dictionary'.format(
os.path.basename(config_path))
_LOGGER.error(msg)
raise HomeAssistantError(msg)
return conf_dict
def process_ha_config_upgrade(hass):
"""Upgrade config if necessary.
This metho... | _version = inp.readline().strip()
except FileNotFoundError:
# Last version to not have this file
conf_version = '0.7.7'
if conf_version == __version__:
return
_LOGGER.info('Upgrading config directory from %s to %s', conf_version,
__version__)
lib_path = hass.c... |
tylerlaberge/PyPattyrn | tests/behavioral_tests/test_iterator.py | Python | mit | 2,826 | 0 | from unittest import TestCase
from pypattyrn.behavioral.iterator import Iterable, Iterator
class IterableTestCase(TestCase):
"""
Unit testing class for the Iterable class.
"""
def setUp(self):
"""
Initialize testing data.
"""
class Counter(Iterable):
def __... | self.assertEquals(i, next(counter_iterator))
def test_s | top_iteration(self):
"""
Test that stop iteration is raised.
@raise AssertionError: If the test fails.
"""
counter_iterator = self.counter_iterator_class()
with self.assertRaises(StopIteration):
for i in range(12):
next(counter_iterator)
... |
jli05/cs224n-project | optimisers.py | Python | mit | 5,490 | 0.000911 | from __future__ import (division, absolute_import,
print_function, unicode_literals)
import numpy
import theano
import theano.tensor as tensor
profile=False
def itemlist(tparams):
return [v for k, v in tparams.items()]
# name(hyperp, tparams, grads, inputs (list), cost) = f_grad_shared, ... | for ru | 2, ud in zip(running_up2, updir)]
param_up = [(p, p + ud) for p, ud in zip(itemlist(tparams), updir)]
f_update = theano.function([lr], [], updates=ru2up+param_up,
on_unused_input='ignore', profile=profile,
allow_input_downcast=True)
return f_gr... |
HigorSilvaRosa/ForumGeolocalizado | core/models.py | Python | mit | 2,327 | 0.006917 | # coding=utf-8
from django.contrib.auth.models import User
from django.db import models
# Create your models here.
from django.db.models.base import Model
from django.db.models.fields import CharField, TextField, DateTimeField, BooleanField, FloatField
from django.db.models.fields.related import ForeignKey
class Bas... | Longitude", default=0)
class Meta:
verbose_name = u"Tópico"
verbose_name_plural = u"Tópicos"
def __unicode__(self):
return self.name
class Post(BaseModel):
topic = ForeignKey(Topic, relate | d_name="posts", verbose_name=u"Tópico")
user = ForeignKey(User, verbose_name=u"Criador")
content = TextField(verbose_name=u"Texto")
class Meta:
verbose_name = u"Postagem"
verbose_name_plural = u"Postagens"
ordering = ["-id"]
class TopicReport(BaseModel):
post=ForeignKey(Topic,... |
magus424/powerline | powerline/lib/inotify.py | Python | mit | 6,081 | 0.024009 | # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
import sys
import os
import errno
import ctypes
import struct
from ctypes.util import find_library
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
... | ne
def load_inotify():
''' Initialize the inotify library '''
global _inotify
if _inotify is None:
if hasattr(sys, 'getwindowsversion'):
# On windows abort before loading the C library. Windows has
# multiple, incompatible C runtimes, and we have no way of knowing
# if the one chosen by ctypes is compat... | ys.platform == 'darwin':
raise INotifyError('INotify not available on OS X')
if not hasattr(ctypes, 'c_ssize_t'):
raise INotifyError('You need python >= 2.7 to use inotify')
name = find_library('c')
if not name:
raise INotifyError('Cannot find C library')
libc = ctypes.CDLL(name, use_errno=True)
for ... |
roberzguerra/scout_mez | institutional/admin.py | Python | gpl-2.0 | 3,528 | 0.003975 | # -*- coding:utf-8 -*-
from copy import deepcopy
from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from django import forms
from django.template.defaultfilters import slugify
from filebrowser_safe.fields import FileBrowseFormField, FileBrowseWidget, FileBrowseField
from mezzanin... | self.fields['featured_image'].help_text = _(u"Imagem destaque da notícia, resolução mínima 460x260px ou proporcional.")
self.fields['image_top'].directory = upload_to("blog.BlogPost.featured_image", "blog")
blogpost_fieldsets[0][1]["fields"].insert(4, "image_top")
BlogPostAdmin.form = BlogPostAdminForm
admin... | gPost, BlogPostAdmin)
class PageAdminInstitutionalForm(PageAdminForm):
"""
Form customizado para Paginas do Site
Seta o atributo "Exibir no sitemap" como False e não obrigatorio
"""
in_sitemap = forms.BooleanField(label=_(u"Show in sitemap"), required=False, initial=False)
PageAdmin.form = Page... |
IT-PM-OpenAdaptronik/Webapp | apps/register/urls.py | Python | mit | 1,410 | 0.000709 | """ License
MIT License
Copyright (c) 2017 OpenAdaptronik
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge,... | ense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARR... |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from django.urls import path
from .views import IndexView, register_success, ... |
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/fs/commands/fstree.py | Python | agpl-3.0 | 2,201 | 0.009995 | #!/usr/bin/env python
import sys
from fs.opener import opener
from fs.commands.runner import Command
from fs.utils import print_fs
class FSTree(Command):
usage = """fstree [OPTION]... [PATH]
Recursively display the contents of PATH in an ascii tree"""
def get_optparse(self):
optparse = supe... | if options.gui:
from fs.browsewin import browse
if path:
| fs = fs.opendir(path)
browse(fs, hide_dotfiles=not options.all)
else:
if options.depth < 0:
max_levels = None
else:
max_levels = options.depth
print_fs(fs, path or '',
f... |
bslatkin/pycon2014 | lib/asyncio-0.4.1/tests/test_futures.py | Python | apache-2.0 | 11,378 | 0 | """Tests for futures.py."""
import concurrent.futures
import threading
import unittest
import unittest.mock
import asyncio
from asyncio import test_utils
def _fakefunc(f):
return f
class FutureTests(unittest.TestCase):
def setUp(self):
self.loop = test_utils.TestLoop()
asyncio.set_event_l... |
@unittest.mock.patch('asyncio.base_events.logger')
def test_tb_logger_result_retrieved(self, m_log):
fut = asyncio.Future(loop=self.loop)
fut.set_result(42)
fut.result()
del fut
self.assertFalse(m_log.error.called)
@unittest.mock.patch('asyncio.base_events.logger')
... | RuntimeError('boom'))
del fut
test_utils.run_briefly(self.loop)
self.assertTrue(m_log.error.called)
@unittest.mock.patch('asyncio.base_events.logger')
def test_tb_logger_exception_retrieved(self, m_log):
fut = asyncio.Future(loop=self.loop)
fut.set_exception(RuntimeError... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.