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 |
|---|---|---|---|---|---|---|---|---|
vinoth3v/In | In/vakai/page/load_more.py | Python | apache-2.0 | 2,553 | 0.061888 |
def action_vakai_load_more(context, action, parent_entity_bundle, last_id, parent_entity_id, **args):
try:
parent_entity_type = 'Vakai'
parent_entity_id = int(parent_entity_id)
last_id = int(last_id)
output = Object()
db = IN.db
connection = db.connection
# TODO: paging
# get total
... | 0 and la | st_id > 0:
output.add('TextDiv', {
'id' : more_id,
'value' : str(remaining) + ' more...',
'css' : ['ajax i-text-center pointer i-panel-box i-panel-box-primary'],
'attributes' : {
'data-href' : ''.join(('/vakai/more/!', str(parent_entity_bundle), '/', str(last_id), '/', str(parent_entity_id... |
KevinOConnor/klipper | klippy/webhooks.py | Python | gpl-3.0 | 20,782 | 0.001203 | # Klippy WebHooks registration and server connection
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
import logging, socket, os, sys, errno, json, collections
import gcode
REQUEST_LOG_SIZE = 20
# Json decodes strings as unicode ty... | me, request in self.request_log:
out.append("Received %f: %s" % (eventtime, request))
logging.info("\n".join(out))
def set_client_info(self, client_info, state_msg=None):
if state_msg is None:
state_msg = "Client info %s" % (repr(client_info),)
logging.info("webhooks... | log=False)
return
rollover_msg = "webhooks client %s: %s" % (self.uid, repr(client_info))
self.printer.set_rollover_info(log_id, rollover_msg, log=False)
def close(self):
if self.fd_handle is None:
return
self.set_client_info(None, "Disconnected")
sel... |
vipul-sharma20/fossevents.in | tests/frontend/test_page_contents.py | Python | mit | 869 | 0.002301 | # -*- coding: utf-8 -*-
import pytest
from django.core.urlresolvers import reverse
pytestmark = pytest.mark.django_db
global_footer_links = [
'About',
'Developers',
'Privacy',
'Report an issue',
]
def assert_title_and_links_on_page(browser, url, title, links_text):
browser.visit(url)
assert... | test_homepage(browser):
url = reverse('pages:home')
assert_title_and_links_on_page | (browser, url, "FossEvents", global_footer_links)
def test_about_page(browser):
url = reverse('pages:about')
assert_title_and_links_on_page(browser, url, "About", global_footer_links)
def test_privacy_page(browser):
url = reverse('pages:privacy')
assert_title_and_links_on_page(browser, url, "Privacy... |
3dfxsoftware/cbss-addons | mass_mailing/controllers/main.py | Python | gpl-2.0 | 2,342 | 0.005978 |
import werkzeug
from openerp import http, SUPERUSER_ID
from openerp.http import request
class MassMailController(http.Controller):
@http.route('/mail/track/<int:mail_id>/blank.gif', type='http', auth='none')
def track_mail_open(self, mail_id, **post):
""" Email tracking. """
mail_mail_stats... | id), (email_fname, 'ilike', email)], context=context)
if 'opt_out' in request.registry[mailing.mailing_model]._all_columns:
request.registry[mailing.mailing_model].write( | cr, SUPERUSER_ID, record_ids, {'opt_out': True}, context=context)
return 'OK'
|
neuroo/equip | examples/sample-test-program/test_module/mistune.py | Python | apache-2.0 | 31,391 | 0 | # coding: utf-8
"""
mistune
~~~~~~~
The fastest markdown parser in pure Python with renderer feature.
:copyright: (c) 2014 by Hsiaoming Yang.
"""
import re
import inspect
__version__ = '0.4.1'
__author__ = 'Hsiaoming Yang <me@lepture.com>'
__all__ = [
'BlockGrammar', 'BlockLexer',
'InlineGra... | ins|del|img)\b)\w+(?!:/|[^\w\s@]*@)\b'
)
def_links = re.compile(
r'^ *\[([^^\]]+)\]: *' # [key]:
r'<?([^\s>]+)>?' # <link> or link
r'(?: +["(]([^\n]+)[")])? *(?:\n+|$)'
)
def_footnotes = re.compile(
r'^\[\^([^\]]+)\]: *('
r'[^\n]*(?:\n+|$)' # [^key]:
r'... | re.compile(r'^\n+')
block_code = re.compile(r'^( {4}[^\n]+\n*)+')
fences = re.compile(
r'^ *(`{3,}|~{3,}) *(\S+)? *\n' # ```lang
r'([\s\S]+?)\s*'
r'\1 *(?:\n+|$)' # ```
)
hrule = re.compile(r'^(?: *[-*_]){3,} *(?:\n+|$)')
heading = re.compile(r'^ *(#{1,6}) *([^\n]+?) *#* *(... |
unicef-zambia/zambia-ureport | docs/conf.py | Python | bsd-3-clause | 7,753 | 0.007739 | # -*- coding: utf-8 -*-
#
# zambiaureport documentation build configuration file, created by
# sphinx-quickstart.
#
# 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 configuration values ... | False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = Tr | ue
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'zambiaureport', u'zambiaureport Documentation',
[u'Andre Lesa'], 1)
]
# If true, show U... |
dskoda1/hpds | hpds/trees/__init__.py | Python | bsd-2-clause | 49 | 0 | from .binary_search_tree | import | BinarySearchTree
|
evolvIQ/railgun | setup.py | Python | apache-2.0 | 990 | 0.017189 | # -*- coding: utf-8 -*
from distutils.core import setup
import os
PACKAGE_NAME = "railgun"
def recurse(d):
ret = []
for f in os.listdir(d):
if f.startswith("."): continue
df = os.path.join(d, f)
if os.path.isfile(df):
ret.append(df)
elif f != "build":
re... | inue
d = PACKAGE_NAME + d[4:]
v = s.get(d, [])
s[d] = v
v.append(f)
return s.items()
setup(name='docker-railgun',
version='0.1',
description='Self-organizing Docker-based container building and provisioning',
author='Rickard Petzäll',
author_email='rickard@evolvi... | com',
url='https://github.com/evolvIQ/railgun',
packages=[PACKAGE_NAME, "%s.host_providers" % PACKAGE_NAME],
scripts=['bin/railgun'],
data_files=structure(recurse("meta"))
)
|
freedesktop-unofficial-mirror/gstreamer__cerbero | cerbero/utils/__init__.py | Python | lgpl-2.1 | 10,438 | 0.000958 | # 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... | rt messages as m
_ = gettext.gettext
N_ = lambda x: x
class ArgparseArgument(object):
def __init__(self, *name, **kwargs):
self.name = name
| self.args = kwargs
def add_to_parser(self, parser):
parser.add_argument(*self.name, **self.args)
def user_is_root():
''' Check if the user running the process is root '''
return hasattr(os, 'getuid') and os.getuid() == 0
def determine_num_of_cpus():
''' Number of virtual or physica... |
masschallenge/django-accelerator | accelerator/tests/test_program_partner_type.py | Python | mit | 423 | 0 | from __future_ | _ import unicode_literals
from django.test import TestCase
from accelerator.tests.factories import ProgramPartnerTypeFactory
class TestProgramPartnerType(TestCase):
def test_str(self):
program_partner_type = ProgramPartnerTypeFactory()
assert program_partner_type.partner_type in str(program_par... | type)
|
omnitrogen/enigma | gui/enigma-gui-resizable-window.py | Python | mit | 11,660 | 0.038346 | #!/usr/bin/python3
from tkinter import *
from tkinter.messagebox import *
fenetre = Tk()
fenetre.title("The Enigma Machine")
fenetre.configure(background='white')
fenetre.geometry("550x800")
class AutoScrollbar(Scrollbar):
#create a 'responsive' scrollbar
def set(self, lo, hi):
if float(lo) <= 0.0 and ... | , weight=1)
fenetre.grid_columnconfigure(0, weight=1)
#
# create canvas contents
frame = Frame(canvas, background="white", borderwidth=0)
#enigma_image
image = PhotoImage(file="enigma.gif")
Label(frame, image=image, background="white", borderwidth=0).pack(padx=10, pady=10, side=TO | P)
#help_button
def help():
showinfo("The Enigma Machine Quick Start", "Hello World!\nThis is a quick tutorial on how to use this app!\nFirst, you need to choose the order of the rotors.\nThen you need to set the rotors' position\nYou can finally write your message and encrypt it by pressing the Return key!\nThat'... |
yast/yast-python-bindings | examples/Frame1.py | Python | gpl-2.0 | 340 | 0.017647 | # encoding: utf-8
from yast import import_module
import_module('UI')
from | yast import *
class Frame1Client:
def main(self):
UI. | OpenDialog(
VBox(
Frame("Hey! I&mportant!", Label("Hello, World!")),
PushButton("&OK")
)
)
UI.UserInput()
UI.CloseDialog()
Frame1Client().main()
|
davrv93/creed-en-sus-profetas-backend | django_rv_apps/apps/believe_his_prophets_api/views/book/filters.py | Python | apache-2.0 | 550 | 0.001818 | import django_filters
from django_filters | import rest_framework as filters
from django_rv_apps.apps.believe_his_prophets.models.book import Book
from django_rv_apps.apps.believe_his_prophets.models.bible_read import BibleRead
from django_rv_apps.apps.believe_his_prophets.models.testament import Testament
class BookFilter(django_filters.FilterSet):
t... |
queryset=Testament.objects.all())
class Meta:
model = Book
fields = ('id', 'testament',
'book_order')
|
ewindisch/nova | nova/tests/api/openstack/compute/contrib/test_aggregates.py | Python | apache-2.0 | 20,787 | 0.000625 | # Copyright (c) 2012 Citrix 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
#
# Unless ... | lf):
self.assertRaises(exc.HTTPBadRequest, self.controller.create,
self.req, {"foo":
{"name": "test",
"availability_zone": "nova1"}})
def test_create_with_no_name(self):
self.assertRaises(exc.HTTPBa... | "availability_zone": "nova1"}})
def test_create_with_no_availability_zone(self):
def stub_create_aggregate(context, name, availability_zone):
self.assertEqual(context, self.context, "context")
self.assertEqual("test", name, "name")
self.assertIsNo... |
omelkonian/cds | cds/modules/deposit/receivers.py | Python | gpl-2.0 | 2,693 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016 CERN.
#
# Invenio is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later... | munities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Deposit API."""
from __future__ import absolute_import, print_function
from flask import current_app
from invenio_pidstore.models import PersistentIdentifier
from invenio_indexer.api import ... | er_publish as original_index_deposit_after_publish
from invenio_jsonschemas import current_jsonschemas
from .api import Project
from .tasks import datacite_register
def index_deposit_after_publish(sender, action=None, pid=None, deposit=None):
"""Index the record after publishing."""
project_schema = current_... |
bmi-forum/bmi-pyre | pythia-0.8/packages/pyre/pyre/inventory/Configurable.py | Python | gpl-2.0 | 9,858 | 0.006898 | #!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Michael A.G. Aivazis
# California Institute of Technology
# (C) 1998-2005 All Rights Reserved
#
# {LicenseText}
#
# ~~~~~~~~~~~~~~~~~~~~~~~~... | ibuteError("object '%s' of type '%s' has no attribute '%s'" % (
self.name, self.__class__.__name__, name))
# support for the help facility
def showProperties(self):
"""print a report describing my properties"""
| facilityNames = self.inventory.facilityNames()
propertyNames = self.inventory.propertyNames()
propertyNames.sort()
print "properties of %r:" % self.name
for name in propertyNames:
if name in facilityNames:
continue
# get th... |
vertexproject/synapse | synapse/tests/test_model_gov_us.py | Python | apache-2.0 | 1,328 | 0.000753 | import synapse.tests.utils as s_t_utils
class UsGovTest(s_t_utils.SynTest):
async def test_models_usgov_cage(self):
async with self.getTestCore() as core:
input_props = {
'street': '123 Main St',
'city': 'Smallville',
'state': 'Kansas',
... | : '17035551213',
'name0': 'kent labs',
}
formname = 'gov:us:cage'
valu = '7qe71'
expected_ndef = (formname, valu)
async with await core.snap() as snap:
n0 = await snap.addNode(formname, valu.upper(), input_props)
se... | f)
for prop, valu in expected_props.items():
self.eq(n0.get(prop), valu)
|
AAAI-DISIM-UnivAQ/ASP_DALI | LindaProxy/proxyLinda.py | Python | apache-2.0 | 10,523 | 0.002946 | '''
PyDALI proxyLinda module to encapsulate DALI agent communication
in the ASP solver case study
Licensed with Apache Public License
by AAAI Research Group
Department of Information Engineering and Computer Science and Mathematics
University of L'Aquila, ITALY
http://www.disim.univaq.it
'''
__autho... | print 'DLV ended.'
try:
self.planner.readresult()
global temporaryresult
temporaryresult = self.planner.getresult()
if self.currentproblem == 1:
system_connection[self.identifier].sendConsoleMessage(
... | on[self.identifier].sendConsoleMessage('Weak Constraint Problem has found a solution')
elif self.currentproblem == 3:
system_connection[self.identifier].sendConsoleMessage('With Blank Problem has found a solution')
message = 'new_moves_for_evaluate(%s)' % len(tem... |
folkrav/rts-b51 | src/projectX/bgui/text_input.py | Python | gpl-3.0 | 15,841 | 0.031816 | """
This module defines the following constants:
*InputText options*
* BGUI_INPUT_NONE = 0
* BGUI_INPUT_SELECT_ALL = 1
* BGUI_INPUT_DEFAULT = BGUI_INPUT_NONE
"""
from .widget import Widget, WeakMethod, BGUI_DEFAULT, BGUI_CENTERY, \
BGUI_NO_FOCUS, BGUI_MOUSE_ACTIVE, BGUI_MOUSE_CLICK, BGUI_MOUSE_RELEASE, \
BGUI_... | nnot be edited by | user (this can be changed later via the prefix property)
:param font: the font to use
:param pt_size: the point size of the text to draw
:param color: color of the font for this widget
:param aspect: constrain the widget size to a specified aspect ratio
:param size: a tuple containing the width and height
... |
airbnb/streamalert | streamalert_cli/athena/helpers.py | Python | apache-2.0 | 9,745 | 0.00236 | """
Copyright 2017-present Airbnb, 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 law or agreed to in writing, sof... | )
PARTITION_PARTS = re.compile(
r'dt=(?P<year>\d{4})\-(?P<month>\d{2})\-(?P<day>\d{2})\-(?P<hour>\d{2})')
# The returned partition from the SHOW PARTITIONS command is dt=YYYY-MM-DD-HH,
# But when re-creating new partitions this value must be quoted
PARTITION_STMT = ("PARTITION (dt = '{year}-{month}-{day}-{hour}')... | PING = {
'string': 'string',
'integer': 'bigint',
'boolean': 'boolean',
'float': 'decimal(10,3)',
dict: 'map<string,string>',
list: 'array<string>'
}
# Athena query statement length limit
MAX_QUERY_LENGTH = 262144
def add_partition_statements(partitions, bucket, table_name):
"""Generate A... |
helldorado/ansible | lib/ansible/modules/network/f5/bigip_dns_cache_resolver.py | Python | gpl-3.0 | 16,802 | 0.000595 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2018, F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | f):
if self._values['route_domain'] is None:
return None
return fq_name(self.partition, self._values['route_domain'])
@property
def answer_default_zones(self):
| return flatten_boolean(self._values['answer_default_zones'])
class ApiParameters(Parameters):
@property
def forward_zones(self):
if self._values['forward_zones'] is None:
return None
result = []
for x in self._values['forward_zones']:
tmp = dict(
... |
Hiyorimi/scikit-image | skimage/data/_binary_blobs.py | Python | bsd-3-clause | 1,995 | 0 | import numpy as np
from ..filters import gaussian
def binary_blobs(length=512, blob_size_fraction=0.1, n_dim=2,
volume_fraction=0.5, seed=None):
"""
Generate synthetic binary image with several rounded blob-like objects.
Parameters
----------
length : int, optional
Linear... | blob, as a fraction of ``length``, should be
smaller than 1.
n_dim : int, optional
Number of dimensions of output image.
volume_fraction : float, default 0.5
Fraction of image pixels covered by the blobs (where the output is 1).
Should be in [0, 1].
seed : int, optional
... | erator.
Returns
-------
blobs : ndarray of bools
Output binary image
Examples
--------
>>> from skimage import data
>>> data.binary_blobs(length=5, blob_size_fraction=0.2, seed=1)
array([[ True, False, True, True, True],
[ True, True, True, False, True],
... |
npotts/dotfiles | ipython/profile_default/ipython_config.py | Python | unlicense | 38,662 | 0.005276 | c = get_config()
# NEVER NAG ME
c.TerminalInteractiveShell.confirm_exit = False
# Configuration file for ipython.
# ------------------------------------------------------------------------------
# InteractiveShellApp(Configurable) configuration
# -----------------------------------------------------------------------... | ', 'osx', 'pyglet', 'qt', 'qt4', 'qt5', 'tk', 'wx', 'gtk2', 'qt4'] (case-insensitive) or None
# Default: None
# c.InteractiveShellApp.gui = N | one
## Should variables loaded at startup (by startup files, exec_lines, etc.) be
# hidden from tools like %who?
# Default: True
# c.InteractiveShellApp.hide_initial_ns = True
## If True, IPython will not add the current working directory to sys.path. When
# False, the current working directory is added to sys.pat... |
Distrotech/scons | build/scons/engine/SCons/Tool/zip.py | Python | mit | 3,328 | 0.005709 | """SCons.Tool.zip
Tool-specific initialization for zip.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 The SCon... | py 2014/01/04 01:12:18 root"
import os.path
import SCons.Builder
import SCons.Defaults
import SCons.Node.FS
import SCons.Util
try:
import zipfile
internal_zip = 1
except ImportError:
internal_zip = 0
if intern | al_zip:
zipcompression = zipfile.ZIP_DEFLATED
def zip(target, source, env):
compression = env.get('ZIPCOMPRESSION', 0)
zf = zipfile.ZipFile(str(target[0]), 'w', compression)
for s in source:
if s.isdir():
for dirpath, dirnames, filenames in os.walk(str(s)):
... |
XXN/pwb-custom | wd-videogame.descriptions.py | Python | mit | 7,056 | 0.004789 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# (C) XXN, 2017
#
from __future__ import absolute_import, unicode_literals
import os, re, sys, time
import pywikibot
def main():
site = pywikibot.Site('wikidata', 'wikidata')
repo = site.data_repository()
mylist = \
[
u"Q3001778",
... | wideo z ~YEAR~ roku',
'pt': 'vídeojogo de ~YEAR~',
'pt-br': 'jogo eletrônico de ~YEAR~',
| 'ro': 'joc video din ~YEAR~',
'ru': 'видеоигра ~YEAR~ года',
'sco': 'video gemme',
'sh': 'videoigra',
'sk': 'počítačová hra z ~YEAR~',
'sl': 'videoigra iz leta ~YEA... |
GirlsCodePy/girlscode-coursebuilder | modules/math/math.py | Python | gpl-3.0 | 4,047 | 0.000494 | # Copyright 2014 Google 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 ... | ommon import tags
from controllers import sites
from models import custom_modules
from models import services
from modules.math import messages
MATH_MODULE_URI = '/modules/math'
RESOURCES_URI = MATH_MODULE_URI + '/resources'
MATHJAX_URI = MATH_MODULE_URI + '/MathJax'
class MathTag(tags.ContextAwareTag):
"""Custo... | dor(cls):
return 'gcb'
def render(self, node, context):
math_script = cElementTree.XML('<script/>')
# The formula is "text" type in the schema and so is presented in the
# tag's body.
math_script.text = node.text
input_type = node.attrib.get('input_type')
i... |
henrysher/opslib | opslib/__init__.py | Python | apache-2.0 | 1,905 | 0.000525 | """
ICS Ops Common Library
"""
import os
from os.path import dirname
from os.path import realpath
from os.path import join as pathjoin
import boto
__version__ = "0.0.3.3"
__release__ = "alpha"
CONFIG = "opslib.ini"
LOG_NAME = "opslib"
AWS_ACCESS_KEY_NAME = "aws_access_key_id"
AWS_SECRET_KEY_NAME = "aws_secret_acces... | join(pwdpath, CONFIG)
if enable_boto:
# Initialize credentials for boto
from boto.pyami.config import Config
boto.config = Config(filepath)
ac | cess_key = boto.config.get('Credentials', AWS_ACCESS_KEY_NAME, None)
secret_key = boto.config.get('Credentials', AWS_SECRET_KEY_NAME, None)
# FIXME: a trick when the value is empty
if not access_key or not secret_key:
boto.config.remove_section('Credentials')
if enable_botocore... |
mpharrigan/msmbuilder | MSMBuilder/clustering.py | Python | gpl-2.0 | 49,464 | 0.002628 | from __future__ import print_function, division, absolute_import
from mdtraj.utils.six import PY2
from mdtraj.utils.six.moves import xrange
import sys
import types
import random
import numpy as np
try:
import fastcluster
except ImportError:
pass
import scipy.cluster.hierarchy
import mdtraj as md
from msmbuild... | s, len(longlist)=%s' % (sum(lengths), len(longlist)))
def func(x):
length, cumlength = x
return longlist[cumlength - length: cumlength]
output = [func(elem) for elem in zip(lengths, np.cumsum(lengths))]
return output
def stochastic_subsa | mple(trajectories, shrink_multiple):
"""Randomly subsample from a trajectory
Given a list of trajectories, return a single trajectory
shrink_multiple times smaller than the total number of frames in
trajectories taken by random sampling of frames from trajectories
Parameters
----------
tra... |
theanalyst/cinder | cinder/volume/drivers/windows/constants.py | Python | apache-2.0 | 742 | 0 | # Copyright 2014 Cloudbase Solutions Srl
#
# Licensed under the Apache License, Version 2.0 (the "Li | cense"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BA... | he License.
WMI_JOB_STATUS_STARTED = 4096
WMI_JOB_STATE_RUNNING = 4
WMI_JOB_STATE_COMPLETED = 7
VHD_TYPE_FIXED = 2
VHD_TYPE_DYNAMIC = 3
|
TeXitoi/navitia | source/sql/alembic/versions/224621d9edde_timezone_at_metavj_level.py | Python | agpl-3.0 | 1,446 | 0.01314 | """timezone at metavj level
Revision ID: 224621d9edde
Revises: 14346346596e
Create Date: 2015-12-21 16:52:30.275508
"""
# revision identifiers, used by Alembic.
revision = '224621d9edde'
down_revision = '5a590ae95255'
from alembic import op
import sqlalchemy as sa
import geoalchemy2 as ga
def upgrade():
op.cr... | me=u'associated_tz_dst_fkey'),
sa.PrimaryKeyConstraint('id'),
schema='navitia'
)
op.add_column(u'meta_vj', sa.Column('timezone', sa.BIGINT(), nullable=True), schema=u'navitia')
op.drop_column(u'vehicle_journey', 'utc_to_local_offset', schema=u'navitia')
def downgrade():
op.drop_column(u'meta_v... | 'navitia')
op.add_column(u'vehicle_journey', sa.Column('utc_to_local_offset', sa.BIGINT(), nullable=True), schema=u'navitia')
|
bombehub/SEconsistent | diagrams/overhead_savePDF.py | Python | gpl-3.0 | 699 | 0.020029 | __ | author__ = 'mk'
import matplotlib.pyplot as plt
import sys
import math
import numpy as np
dataDir = sys.argv[1]
resDir | = sys.argv[2]
plt.figure(figsize=(8,4))
algLabel=['naive','cou','zigzag','pingpong','MK','LL']
for i in range(0,6,1):
filePath = dataDir + str(i) + '_overhead.dat'
file = open(filePath)
x = []
y = []
for eachLine in file.readlines():
xStr,yStr = eachLine.split()
x.append(int(xSt... |
mcldev/DjangoCMS_Charts | djangocms_charts/base/consts.py | Python | mit | 824 | 0.002427 | from django.utils.translation import ugettext_lazy as _
# Legend Position
def get_legend_class(position):
return 'legend-' + str(position)
class LEGEND_POSITIONS:
BOTTOM = _('bottom')
TOP = _('top')
LEFT = _('left')
RIGHT = _('right')
get_choices = ((get_legend_class(BOTTOM), BOTTOM),
... | (get_legend_class(LEFT), LEFT),
(get_legend_class(RIGHT), RIGHT) | ,)
def get_chart_position_class(position):
return 'chart-' + str(position)
class CHART_POSITIONS:
CENTER = _('center')
LEFT = _('left')
RIGHT = _('right')
get_choices = ((get_chart_position_class(CENTER), CENTER),
(get_chart_position_class(LEFT), LEFT),
(ge... |
kgilmo/penning_artiq | artiq/gui/datasets.py | Python | gpl-3.0 | 5,603 | 0.000714 | import asyncio
from collections import OrderedDict
from functools import partial
import logging
from quamash import QtGui, QtCore
from pyqtgraph import dockarea
from pyqtgraph import LayoutWidget
from artiq.protocols.sync_struct import Subscriber
from artiq.tools import short_format
from artiq.gui.tools import DictSy... | it)
def sort_key(self, k, v):
return k
def convert(self, k, v, column):
if column == 0:
return k
elif column == 1:
return "Y" if v[0] else "N"
elif column = | = 2:
return short_format(v[1])
else:
raise ValueError
def _get_display_type_name(display_cls):
for name, (_, cls) in display_types.items():
if cls is display_cls:
return name
class DatasetsDock(dockarea.Dock):
def __init__(self, dialog_parent, dock_area):
... |
jay-johnson/sci-pype | bins/ml/extractors/extract_and_upload_iris_classifier.py | Python | apache-2.0 | 2,955 | 0.01286 | #!/usr/bin/env python
# Load common imports and system envs to build the core object
import sys, os
# Load the Environment:
os.environ["ENV_DEPLOYMENT_TYPE"] = "JustRedis"
from src.common.inits_for_python import *
#####################################################################
#
# Start Arg Processing:
#
act... | ', help='S3 Key (Optional)', dest='s_key')
parser.add_argument("-d", "--debug", help="Debug Flag", dest='debug', action='store_true')
args = parser.parse_args()
if args.debug:
debug = True
core.enable_debug()
data_dir = str(os.getenv(" | ENV_DATA_DST_DIR", "/opt/work/data/dst"))
if not os.path.exists(data_dir):
os.mkdir(data_dir, 0777)
ds_name = "iris_classifier"
cur_date_str = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
s3_bucket = "unique-bucket-name-for-datasets"
s3_key = "dataset_" + core.to_... |
dreibh/planetlab-lxc-plcapi | PLC/Methods/AddNetworkMethod.py | Python | bsd-3-clause | 651 | 0.006144 | from PLC.Faults import *
from PLC.Method import Method
from PLC.Parameter import Parameter, Mixed
from PLC.NetworkMethods import NetworkMethod, NetworkMethods
from PLC.Auth import Auth
class AddNetworkMethod(Method):
"""
Adds a new network method.
Returns 1 if successful, faults otherwise.
"""
ro... | hod.field | s['method']
]
returns = Parameter(int, '1 if successful')
def call(self, auth, name):
network_method = NetworkMethod(self.api)
network_method['method'] = name
network_method.sync(insert = True)
return 1
|
lovexiaov/python-in-practice | texteditor2/Display.py | Python | gpl-3.0 | 4,435 | 0.005187 | #!/usr/bin/env python3
# Copyright © 2012-13 Qtrac Ltd. All rights reserved.
# This program or module 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 ... |
@property
def line_spacing(self) | :
return int(self.__lineSpacing.get())
@line_spacing.setter
def line_spacing(self, value):
self.__lineSpacing.set(value)
if __name__ == "__main__":
if sys.stdout.isatty():
application = tk.Tk()
application.title("Display")
dock = Dock(application, None)
do... |
openstack/tempest | tempest/api/compute/admin/test_migrations.py | Python | apache-2.0 | 7,577 | 0 | # Copyright 2014 NEC Corporation. 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 ... | ost)
@decorators.idempotent_id('4bf0be52-3b6f-4746-9a27-3143636fe30d')
@testtools.skipUnless(CONF.compute_feature_enabled.cold_migration,
'Cold migration not available.')
def test_cold_migration(self):
"""Test cold migrating server and then confirm the migration"""
... | old_migration,
'Cold migration not available.')
def test_revert_cold_migration(self):
"""Test cold migrating server and then revert the migration"""
self._test_cold_migrate_server(revert=True)
|
trezor/micropython | extmod/webrepl/webrepl.py | Python | mit | 2,184 | 0.001374 | # This module should be imported from REPL | , not run from command line.
import socket
import uos
import network
import uwebsocket
import websocket_helper
import _webrepl
listen_s = None
client_s = None
def setup_conn(port, accept_handler):
global listen_s
listen_s | = socket.socket()
listen_s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
ai = socket.getaddrinfo("0.0.0.0", port)
addr = ai[0][4]
listen_s.bind(addr)
listen_s.listen(1)
if accept_handler:
listen_s.setsockopt(socket.SOL_SOCKET, 20, accept_handler)
for i in (network.AP_IF, n... |
jorgebg/tictactoe | time.py | Python | mit | 74 | 0 | from .game import Boa | rd
for i in range(10):
Board.all()
pr | int(i)
|
AlManja/logs.py | logsgui3.py | Python | mit | 9,203 | 0.004781 | #!/usr/bin/env python
import os
import sys # provides interaction with the Python interpreter
from functools import partial
from PyQt4 import QtGui # provides the graphic elements
from PyQt4.QtCore import Qt # provides Qt identifiers
from PyQt4.QtGui import QPushButton
t... | self.checks[6]:
print('free disk space')
# os.system('df')
f.write(HEADER.format("Free Disk Space", "Free space per pertition"))
try:
f.write(str(df()))
except:
print('free disk space error')
f.write('free disk ... | for: failed, error & (WW) keywords"))
try:
f.write(look_in_file('/var/log/Xorg.0.log', ['failed', 'error', '(WW)']))
except FileNotFoundError:
print("/var/log/Xorg.0.log not found!")
f.write("Xorg.0.log not found!")
f.write('\n')
... |
threeaims/browserstep | tests/test_browserstep.py | Python | mit | 432 | 0.00463 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_browserstep
----------------------------------
Tests for `browserstep` module.
"""
import sys
import unittest
from browserstep import browserstep
class TestBrowsers | tep(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_000_something(self):
pass
if __name__ == '__main__':
sys.exit(unittest.mai | n())
|
sahilshekhawat/sympy | sympy/core/tests/test_assumptions.py | Python | bsd-3-clause | 27,164 | 0.00011 | from sympy import I, sqrt, log, exp, sin, asin, factorial
from sympy.core import Symbol, S, Rational, Integer, Dummy, Wild, Pow
from sympy.core.facts import InconsistentAssumptions
from sympy import simplify
from sympy.core.compatibility import range
from sympy.utilities.pytest import raises, XFAIL
def test_symbol_u... | ranscendental is None
assert nan.is_real is None
assert nan.is_complex is None
assert nan.is_noninteger is None
assert nan.is_irrational is None
assert nan.is_imaginary is None
assert nan.is_positive is None
assert nan.is_negative is None
| assert nan.is_nonpositive is None
assert nan.is_nonnegative is None
assert nan.is_even is None
assert nan.is_odd is None
assert nan.is_finite is None
assert nan.is_infinite is None
assert nan.is_comparable is False
assert nan.is_prime is None
assert nan.is_composite is None
assert ... |
Korred/advent_of_code_2016 | day_6_part_2.py | Python | mit | 5,783 | 0.001383 | recording = '''jtfxgqec
zxoeuddn
anlfufma
dxuuyxkg
ttnewhlw
sjoyeiry
rgfwwdhw
qymxsllk
forftdvy
rzmnmewh
hogawihi
mtsyexba
mrjzqqfk
ypmkexpg
pjuyopgv
rtqquvaj
evubmlrq
bqlrtuce
ndidnbps
vqukosam
mzdyfkcd
rrbwdimb
uhnvxgly
aaimxpcv
acxvinqj
muaeikzy
lhzbosjd
fflqqiit
unfhzfrs
gmwoyvob
cculubmy
zqbugcwa
ijouicwt
bildjjww... | ubjok
afshwptc
sjgpuoch
bnfylydl
rsyxsbzi
psyuvyzx
npngqypd
xejayhdk
aqfmvjfi
tpffksph
uekwkjnj
ljsjimwm
hbgzjlig
ngssshxx
icitlosb
unxryqyt
nzpujfti
lupxnzhe
kxglfnic
ecewosbs
htlqxpiq
clqgnyfd
yyiozvar
mbvjgmyc
srhwhlin
casmlryr
ebuzskkp
iewhdqtr
oyidcobe
avptvltf
mfheqaxl
shqnezrq
xrpkzuvb
soxdjwba
aitmzlds
rpmpozpd... |
tbaxnjdu
xwbsiquk
hsftntsn
ajraaorz
mwmycrff
ymnbrbpj
uyfscatq
kzkgmbeh
libgpgnr
kxlgthxc
vzjbobyx
isqessab
ehursvof
guwrjnbi
xivkphwn
rurrmdmi
nqijeuzq
jambocej
qrtidktb
sbzvehmq
aikgzrsq
lgydnujf
twafyzry
nxhtklba
xhyaqyqe
xgvdfcrf
wdieppsd
iabrfmdm
doijaavc
oxydttkg
qsqiofwv
titrvjym
mwojqcku
tewiyhjx
jlqbksqd
knyc... |
google/jax | jax/interpreters/sharded_jit.py | Python | apache-2.0 | 22,527 | 0.006659 | # 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | om jax._src.lib import xla_bridge as xb
from jax._src.lib import xla_client as xc
from jax._src.lib.mlir import ir
from jax._src.lib.mlir.dialects import func as func_dialect
from jax._src.api_util import (argnums_partial, flatten_axes, flatten_fun,
_ensure_index_tuple)
import jax._sr | c.util as util
from jax.tree_util import tree_flatten, tree_unflatten
from jax._src.util import (new_name_stack, wrap_name, wraps, safe_map,
safe_zip, HashableFunction)
from jax._src.config import config
xops = xc._xla.ops
def _map(f, *xs):
return tuple(map(f, *xs))
class ResultToPopul... |
arkanister/django-contact-form-site | django_contact/apps.py | Python | bsd-3-clause | 255 | 0.003922 | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class ContactFormConfig(AppConfig):
"""The default AppConfig for admin which does autodiscover | y."""
name = 'dja | ngo_contact'
verbose_name = _("Contact") |
soltanmm-google/grpc | src/python/grpcio/grpc/beta/_client_adaptations.py | Python | bsd-3-clause | 26,840 | 0.000261 | # Copyright 2016, 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 f... | outError:
raise future.TimeoutError()
except grpc.FutureCancelledError:
raise future.CancelledError()
def add_done_callback(self, fn):
self._future.add_done_callback(lambda ignored_callback: fn(self))
def __iter__(self):
return self
def _next(self):
... | raise _abortion_error(rpc_error_call)
def __next__(self):
return self._next()
def next(self):
return self._next()
def is_active(self):
return self._call.is_active()
def time_remaining(self):
return self._call.time_remaining()
def add_abortion_callback... |
dariosena/LearningPython | PY-14/conta.py | Python | gpl-3.0 | 1,698 | 0.00708 | import datetime
class Historico:
def __init__(self):
self.data_abertura = datetime.datetime.today()
self.transacoes = []
def imprime(self):
print('data abertura: {}'.format(self.data_abertura))
print('transações: ')
for t in self.transacoes:
print('... | ._historico.transacoes.append('tirou | extrato - saldo de {}'.format(self._saldo))
|
vvladych/forecastmgmt | src/forecastmgmt/ui/masterdata/organisation_add_mask.py | Python | unlicense | 1,939 | 0.017535 | '''
Created on 03.05.2015
@author: vvladych
'''
from gi.repository import Gtk
from forecastmgmt.model.organisation import Organisation
from masterdata_abstract_window import AbstractAddMask
class OrganisationAddMask(AbstractAddMask):
def __init__(self, main_window, reset_callback):
super(OrganisationAd... | self.uuid_text_entry.set_text(self.current_object.uuid)
self.common_name_text_entry.set_text(self.current_object.common_name)
else:
self.uuid_text_entry.set_text("")
self.common_name_text_entry.set_text("")
def create_object_from... | xt()
if common_name is None:
self.show_error_dialog("common name cannot be null")
return
organisation=Organisation(None,common_name)
return organisation
|
nycholas/ask-undrgz | src/ask-undrgz/django/contrib/sessions/models.py | Python | bsd-3-clause | 2,675 | 0.001495 | import base64
import cPickle as pickle
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from django.utils.hashcompat import md5_constructor
class SessionManager(models.Manager):
def encode(self, session_dict):
"""
Returns the gi... | essions framework is entirely cookie-based. It does
not fall back to putting session IDs in URLs. This is an intentional
design decision. Not only does that behavior make URLs ugly, it makes
your site vulnerable to session-ID theft via the "Referer" hea | der.
For complete documentation on using Sessions in your code, consult
the sessions documentation that is shipped with Django (also available
on the Django website).
"""
session_key = models.CharField(_('session key'), max_length=40,
primary_key=True)
session... |
abbot/android-restore-tools | extract.py | Python | mit | 9,201 | 0.003261 | #!/usr/bin/env python
import optparse
import os
import sys
import tempfile
import datetime
from xml.etree import ElementTree as etree
from convert import read_messages, read_calls
import yaffs
def read_chunk(fd, size):
s = fd.read(size)
if len(s) > 0 and len(s) != size:
raise IOError("Broken image fi... | = raw_input("Save as: ")
else:
new_filename = raw_input("Save as (empty=%s): " % filename)
if new_filename == "" and filename == "":
continue
if new_filename != "":
filename = new_filename
try:
os.stat(filename)
ans = raw_input... | except OSError:
break
return filename
def save(filename, content):
open(get_save_filename(filename), "wb").write(content)
def extract_sms(content):
fd_n, name = tempfile.mkstemp()
fd = os.fdopen(fd_n, "wb")
try:
fd.write(content)
fd.close()
messages = read_me... |
daodaoliang/bokeh | bokeh/server/websocket/manager.py | Python | bsd-3-clause | 3,294 | 0.00425 | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2015, Continuum Analytics, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# | The full license is in the file LICENSE.txt, distributed with this software.
#-----------------------------------------------------------------------------
fr | om __future__ import absolute_import
import logging
log = logging.getLogger(__name__)
import atexit
import uuid
from ..utils.multi_dict import MultiDict
class WebSocketManager(object):
def __init__(self):
self.sockets = {}
self.topic_clientid_map = MultiDict()
self.clientid_topic_map = ... |
mlperf/training_results_v0.6 | Fujitsu/benchmarks/resnet/implementations/mxnet/sockeye/sockeye/train.py | Python | apache-2.0 | 46,961 | 0.004152 | # Copyright 2017 Amazon.com, Inc. or its affiliates. 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. A copy of the License
# is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file acc... | argparse.Namespace, exit_stack: ExitStack) -> List[mx.Context]:
"""
Determine the context we should run on (CPU or GPU).
:param args: Arguments as returned by argparse.
:param exit_stack: An ExitStack | from contextlib.
:return: A list with the context(s) to run on.
"""
if args.use_cpu:
logger.info("Training Device: CPU")
context = [mx.cpu()]
else:
num_gpus = utils.get_num_gpus()
check_condition(num_gpus >= 1,
"No GPUs found, consider running on t... |
YannickJadoul/Parselmouth | pybind11/tests/test_pickling.py | Python | gpl-3.0 | 1,191 | 0.00084 | # -*- coding: utf-8 -*-
import pytest
import env # noqa: F401
from pybind11_tests import pickling as m
try:
import cPickle as pickle # Use cPickle on Pyth | on 2.7
except ImportError:
import pickle
@pytest.mark.parametrize("cls_name", ["Pickleable", "PickleableNew"])
def test_roundtrip(cls_name):
cls = getattr(m, cls_name)
p = cls("test_value")
p.setExtra1(15)
p.setExtra2(48)
data = pickle.dumps(p, 2) # Must use pickle protocol >= 2
| p2 = pickle.loads(data)
assert p2.value() == p.value()
assert p2.extra1() == p.extra1()
assert p2.extra2() == p.extra2()
@pytest.mark.xfail("env.PYPY")
@pytest.mark.parametrize("cls_name", ["PickleableWithDict", "PickleableWithDictNew"])
def test_roundtrip_with_dict(cls_name):
cls = getattr(m, cls_na... |
ruibarreira/linuxtrail | usr/lib/python3/dist-packages/softwareproperties/gtk/dialogs.py | Python | gpl-3.0 | 1,305 | 0.009962 | # dialogs - provide common dialogs
#
# Copyright (c) 2006 FSF Europe
#
# Authors:
# Sebastian Heinlein <glatzor@ubuntu.com>
# | Michael Vogt <mvo@canonical.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is dist... | LITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA
from gi... |
openstack/cinder | cinder/cmd/volume_usage_audit.py | Python | apache-2.0 | 10,093 | 0.000694 | #!/usr/bin/env python
# Copyright (c) 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/LICE... | nerates usages for
July 3rd. |
- `year` - previous year. If run on Jan 1, it generates usages for
Jan 1 through Dec 31 of the previous year.
"""
import datetime
import sys
import iso8601
from oslo_config import cfg
from oslo_log import log as logging
from cinder import i18n # noqa
i18n.enable_lazy()
from cinder import context
from cinder.i18... |
maferelo/saleor | saleor/graphql/discount/bulk_mutations.py | Python | bsd-3-clause | 839 | 0.002384 | import graphene
from ...core.permis | sions import DiscountPermissions
from ...discount import models
from ..core.mutations import ModelBulkDeleteMutation
cl | ass SaleBulkDelete(ModelBulkDeleteMutation):
class Arguments:
ids = graphene.List(
graphene.ID, required=True, description="List of sale IDs to delete."
)
class Meta:
description = "Deletes sales."
model = models.Sale
permissions = (DiscountPermissions.MANAGE... |
oppia/oppia | core/domain/event_services.py | Python | apache-2.0 | 12,316 | 0.000081 | # coding: utf-8
#
# Copyright 2014 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | he type of the event. Should be specified by
# subclasses and considered immutable.
EVENT_TYPE = None
@classmethod
def _handle_event(cls, *args, **kwargs):
"""Perform in-request processing of an incoming event."""
| raise NotImplementedError(
'Subclasses of BaseEventHandler should implement the '
'_handle_event() method, using explicit arguments '
'(no *args or **kwargs).')
@classmethod
def record(cls, *args, **kwargs):
"""Process incoming events.
Callers of eve... |
htygithub/bokeh | bokeh/server/protocol/messages/__init__.py | Python | bsd-3-clause | 643 | 0.021773 | '''
'''
from __future__ i | mport absolute_import
from ...exceptions import ProtocolError
index = {}
def register(cls):
''' Decorator to add a Message (and its revision) to the Protocol index.
'''
key = (cls.msgtype, cls.revision)
if key | in index:
raise ProtocolError("Duplicate message specification encountered: %r" % key)
index[key] = cls
return cls
from .ack import *
from .ok import *
from .patch_doc import *
from .pull_doc_req import *
from .pull_doc_reply import *
from .push_doc import *
from .error import *
from .server_info_reply... |
endlessm/chromium-browser | third_party/catapult/dashboard/dashboard/create_health_report.py | Python | bsd-3-clause | 4,168 | 0.007917 | # Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Provides the web interface for adding and editing sheriff rotations."""
from __future__ import print_function
from __future__ import division
from __futur... | json.dumps({
'error': 'Invalid config name.'
}))
def _CreateTableConfig(self):
"""Creates a table config. Wr | ites a valid name or an error message."""
self._ValidateToken()
name = self.request.get('tableName')
master_bot = self.request.get('tableBots').splitlines()
tests = self.request.get('tableTests').splitlines()
table_layout = self.request.get('tableLayout')
override = int(self.request.get('overrid... |
lsst-sqre/sqre-codekit | codekit/progressbar.py | Python | mit | 2,070 | 0 | """ progressbar2 related utils"""
from codekit.codetools import warn
from public import public
from time import sleep
import progressbar
import functools
@public
def setup_logging(verbosity=0):
"""Configure progressbar sys.stderr wrapper which is required to play nice
with logging and not have strange format... | nctools.lru_cache()
def wait_for_user_panic_once(**kwargs):
"""Same functionality as wait_for_user_panic() but will only display a
countdown once, reguardless of how many times it is called.
| Parameters
----------
kwargs
Passed verbatim to wait_for_user_panic()
"""
wait_for_user_panic(**kwargs)
@public
def eta_bar(msg, max_value):
"""Display an adaptive ETA / countdown bar with a message.
Parameters
----------
msg: str
Message to prefix countdown bar lin... |
pantsbuild/pants | src/python/pants/backend/scala/goals/tailor_test.py | Python | apache-2.0 | 802 | 0 | # Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants. | backend.scala.goals.tailor import classify_source_files
from pants.backend.scala.target_types import (
ScalaJunitTestsGeneratorTarget,
ScalaSourcesGeneratorTarget,
ScalatestTestsGeneratorTarget,
)
def test_classify_source_files() -> None:
scalatest_files = {
"foo/bar/BazSpec.scala",
}
... | ar/BazTest.scala",
}
lib_files = {"foo/bar/Baz.scala"}
assert {
ScalatestTestsGeneratorTarget: scalatest_files,
ScalaJunitTestsGeneratorTarget: junit_files,
ScalaSourcesGeneratorTarget: lib_files,
} == classify_source_files(junit_files | lib_files | scalatest_files)
|
lento/cortex | test/IECoreHoudini/procedurals/subdRender/subdRender-1.py | Python | bsd-3-clause | 2,590 | 0.011583 | #=====
#
# Copyright 2010 Dr D Studios Pty Limited (ACN 127 184 954) (Dr. D Studios),
# its affiliates and/or its licensors.
#
# 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 following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of condi... | ls provided with the distribution.
#
# * Neither the name of Image Engine Design nor the names of any
# other contributors to this software may be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COP... |
analyst-collective/dbt | test/unit/test_yaml_renderer.py | Python | apache-2.0 | 2,904 | 0.000344 | import unittest
import dbt.exceptions
import dbt.utils
from dbt.parser.schema_renderer import SchemaYamlRenderer
class TestYamlRendering(unittest.TestCase):
def test__models(self):
context = {
"test_var": "1234",
"alt_var": "replaced",
}
renderer = SchemaYamlRend... | }
renderer = SchemaYamlRenderer(context, 'macros')
# Look for description in arguments
dct = {
"name": "my_macro",
"arguments": [
{"name": "my_arg", "attr": "{{ alt_var }}"},
{"name" | : "an_arg", "description": "{{ alt_var}}"}
]
}
expected = {
"name": "my_macro",
"arguments": [
{"name": "my_arg", "attr": "replaced"},
{"name": "an_arg", "description": "{{ alt_var}}"}
]
}
dct = renderer.rend... |
Honzin/ccs | dev/bitnz/public/__init__.py | Python | agpl-3.0 | 1,090 | 0.006422 | import urllib.parse
import sys
from ccs import core
from ccs import constants
from . import response
def ticker():
s = __name__.split(".")[1]
r = sys._getframe().f_code.co_name
# complete request
cr = core.request(s, r)
return core.get(core.hostname(s), cr, core.header(s), core.compression(s), ... | er(s), core.compression(s), core.timeout(s))
# nejaky problem s kodovanim
# def trades_chart():
# s = __name__.split(".")[1]
# r = sys._getframe().f_code.co_name
#
# # complete request
# cr = core.request(s, r)
#
# return core.get(core.hostname(s), cr, core.header(s), core.compression(s), core.time... | complete request
cr = core.request(s, r)
return core.get(core.hostname(s), cr, core.header(s), core.compression(s), core.timeout(s)) |
glennrub/micropython | tools/pydfu.py | Python | mit | 20,108 | 0.001392 | #!/usr/bin/env python
# This file is part of the OpenMV project.
# Copyright (c) 2013/2014 Ibrahim Abdelkader <i.abdalkader@gmail.com>
# This work is licensed under the MIT license, see the file LICENSE for
# details.
"""This module implements enough functionality to program the STM32F4xx over
DFU, without requiring d... | argspec)
if "length" in getargspec(usb.util.get_string).args:
# PyUSB 1.0.0.b1 has the length argument
def get_string(dev, index):
return usb.util.get_string(dev, 255, index)
else:
| # PyUSB 1.0.0.b2 dropped the length argument
def get_string(dev, index):
return usb.util.get_string(dev, index)
def find_dfu_cfg_descr(descr):
if len(descr) == 9 and descr[0] == 9 and descr[1] == _DFU_DESCRIPTOR_TYPE:
nt = collections.namedtuple(
"CfgDescr",
[
... |
redshodan/codepunks | tests/testconfig.py | Python | apache-2.0 | 1,388 | 0 | import argparse
import configparser
from codepunks.config import (Config, INISource, XMLSource, JSONSource,
| YAMLSource, ArgParserSource)
ARGS1 = argparse.Namespace()
ARGS1.apkey1 = "apval1"
ARGS1.apkey2 = "apval2"
ARGS1.apkey3 = "apval3"
def testEmptyCfg():
Config()
def testINISource():
c = Co | nfig(INISource("tests/config/config.ini"))
c.load()
def testINISourcePreBuilt():
fname = "tests/config/config.ini"
parser = configparser.ConfigParser()
parser.read(fname)
c = Config(INISource(fname, cfgparser=parser))
c.load()
def testINISource2():
c = Config([INISource("tests/config/con... |
ccc-ffm/christian | modules/dudle.py | Python | gpl-3.0 | 250 | 0 |
class Dudle(ob | ject):
def __init__(self):
self.baseurl = 'https://dudle.inf.tu-dresden.de/?create_poll='
def getDudle(self, name, ty | pe='time', url=''):
return(self.baseurl + name + '&poll_type=' + type + '&poll_url=' + url)
|
dhavalmanjaria/dma-student-information-system | university_credits/apps.py | Python | gpl-2.0 | 110 | 0 | from django.apps import AppConf | ig
class UniversityCreditsConfig(AppConfig):
name = 'university | _credits'
|
vrbagalkote/avocado-misc-tests-1 | perf/libunwind.py | Python | gpl-2.0 | 3,140 | 0.000318 | #!/usr/bin/env python
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that ... | in %s' % dist.name)
for package in deps:
if not smm.check_installed(package) and not smm.install(package):
self.cancel("Failed to install %s, which is needed for"
"t | he test to be run" % package)
tarball = self.fetch_asset('vanilla_pathscale.zip', locations=[
'https://github.com/pathscale/libunwind/archive/'
'vanilla_pathscale.zip'], expire='7d')
archive.extract(tarball, self.srcdir)
self.sourcedir = os.path.join(self.srcdir, 'libunw... |
IgnitedAndExploded/pyfire | pyfire/contact.py | Python | bsd-3-clause | 3,814 | 0.001049 | """
pyfire.contact
~~~~~~~~~~
Handles Contact ("roster item") interpretation as per RFC-6121
:copyright: 2011 by the pyfire Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import xml.etree.ElementTree as ET
from sqlalchemy import Table, Column, Boolean, Integ... | n = "none"
self.groups = []
for k, v in kwds.iteritems():
setattr(self, k, v)
def to_element(self):
"""Formats contact as `class`:ET.Element object"""
element = ET.Element("item")
if self.approved is no | t None:
element.set("approved", 'true' if self.approved else 'false')
if self.ask is not None:
element.set("ask", self.ask)
element.set("jid", str(self.jid))
if self.name is not None:
element.set("name", self.name)
if self.subscription is not None:
... |
tgbugs/pyontutils | nifstd/nifstd_tools/parcellation/paxinos.py | Python | mit | 40,653 | 0.007306 | import re
from collections import defaultdict, Counter
from ttlser import natsort
from pyontutils.core import LabelsBase, Collector, Source, resSource, ParcOnt
from pyontutils.core import makePrefixes
from pyontutils.config import auth
from pyontutils.namespaces import nsExact
from pyontutils.namespaces import NIFRID, ... | axinos/uris/rat/versions/7'], # ilxtr.paxr7,
label='The Rat Brain in Stereotaxic Coordinates 7th Edition',
synonyms=('Paxinos Rat 7th',
'Paxinos and Watson\'s The Rat Brain | in Stereotaxic Coordinates 7th Edition', # branding >_<
),
abbrevs=tuple(),
shortname='PAXRAT7', # TODO upper for atlas lower for label?
copyrighted='2014',
version='7th Edition',)
class PaxSr... |
Karlon/pychess | lib/pychess/Savers/epd.py | Python | gpl-3.0 | 5,385 | 0.011513 | from __future__ import absolute_import
from __future__ import print_function
from .ChessFile import ChessFile, LoadingError
from pychess.Utils.GameModel import GameModel
from pychess.Utils.const import WHITE, BLACK, WON_RESIGN, WAITING_TO_START, BLACKWON, WHITEWON, DRAW
from pychess.Utils.logic import getStatus
from py... | file in fen f | ormat"""
color = model.boards[-1].color
fen = model.boards[-1].asFen().split(" ")
# First four parts of fen are the same in epd
file.write(u" ".join(fen[:4]))
############################################################################
# Repetition count ... |
Lekensteyn/Solaar | lib/logitech_receiver/hidpp20.py | Python | gpl-2.0 | 14,409 | 0.028732 | # -*- python-mode -*-
# -*- coding: UTF-8 -*-
## Copyright (C) 2012-2013 Daniel Pavel
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your opti... | pack('!H', ivalue))
if reply:
index = ord(reply[0:1])
self.features[index] = FEATURE[ivalue]
return index
raise ValueError("%r not in list" % featureId)
def __iter__(self):
if self._check():
yield FEATURE.ROOT
index = 1
last_index = len(self. | features)
while index < last_index:
yield self.__getitem__(index)
index += 1
def __len__(self):
return len(self.features) if self._check() else 0
#
#
#
class KeysArray(object):
"""A sequence of key mappings supported by a HID++ 2.0 device."""
__slots__ = ('device', 'keys', 'keyversion')
def __init_... |
Diti24/python-ivi | ivi/lecroy/lecroyWR44MXIA.py | Python | mit | 1,652 | 0.001816 | """
Python Interchangeable Virtual Instrument Library
Copyright (c) 2012-2016 Alex Forencich
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... | D NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TOR | T OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
from .lecroyWRXIA import *
class lecroyWR44MXIA(lecroyWRXIA):
"Lecroy WaveRunner 44MXi-A IVI oscilloscope driver"
def __init__(self, *args, **kwargs):
self.__dict__.setdefault('_... |
PyQwt/PyQwt3D | Doc/sourceforge.py | Python | gpl-2.0 | 924 | 0.002165 | #!/usr/bin/env python
import os
import re
import sys
def stamp(html):
"""Stamp a Python HTML documentation page with the S | ourceForge logo"""
def replace(m):
return ('<span class="release-info">%s '
'Hosted on <a href="http://sourceforge.net">'
'<img src="http://sourceforge.net/'
'sflogo.php?group_id=82987&type=1" width="88" height="31"'
'border="0" alt="SourceFor... | nfo">(.*)</span>')
return re.sub(mailRe, replace, html)
# stamp()
if __name__ == '__main__':
for name in sys.argv[1:]:
html = open(name, 'r').read()
text = stamp(html)
if text != html:
os.remove(name)
file = open(name, 'w')
file.write(text)
... |
streed/simpleGossip | run.py | Python | mit | 211 | 0.009479 | from simpleGossip.gossiping.gossip import RemoteGossipService
if __name__ == "__main__":
| from rpyc.utils.server impor | t ThreadedServer
t = ThreadedServer( RemoteGossipService, port=18861 )
t.start()
|
rebolinho/liveit.repository | script.video.F4mProxy/lib/f4mUtils/pycrypto_aes.py | Python | gpl-2.0 | 869 | 0 | # Author: Trevor Perrin
# See the LICENSE file for legal information regarding use of this file.
"""PyCrypto AES implementation."""
from .cryptomath import *
from .aes import *
if pycryptoLoaded:
import Crypto.Cipher.AES
def new(key, mode, IV):
return PyCrypto_AES(key, mode, IV)
c... | key = bytes(key)
IV = bytes(IV)
self.context = Crypto.Cipher.AES.new(key, mode, IV)
def encrypt(self, p | laintext):
plaintext = bytes(plaintext)
return bytearray(self.context.encrypt(plaintext))
def decrypt(self, ciphertext):
ciphertext = bytes(ciphertext)
return bytearray(self.context.decrypt(ciphertext))
|
Trust-Code/trust-addons | trust_crm/models/crm_lead.py | Python | agpl-3.0 | 2,232 | 0 | # -*- encoding: utf-8 -*-
###############################################################################
# #
# Copyright (C) 2016 Trustcode - www.trustcode.com.br #
# Danimar Ribeiro <danimaribeiro@gmail.co... |
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU Affero General Public License as published by #
# the Free Software Foundation, either | version 3 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without eve... |
battlemidget/conjure-up | conjureup/controllers/spellpicker/tui.py | Python | mit | 108 | 0.009259 | cl | ass SpellPickerC | ontroller:
def render(self):
pass
_controller_class = SpellPickerController
|
moskytw/mosql | tests/test_query.py | Python | mit | 2,404 | 0.000416 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import OrderedDict
from nose.tools import eq_, assert_raises
from mosql.query import select, insert, replace
from mosql.util import param, ___, raw, DirectionError, OperatorError, autoparam
def test_select_customize():
gen = select('person', Order... | stom_param', param('my_param')), ('auto_param', autoparam),
('using_alias', ___),
]))
exp = (
'SELECT * FROM "table" WHERE "custom_param" = %(my_param)s '
'AND "auto_param" = %(auto_param)s AND "using_alias" = %(using_alias)s'
)
eq_(gen, exp)
def test_insert_dict():
gen = i... | SERT INTO "person" ("person_id", "name") '
'VALUES (\'mosky\', \'Mosky Liu\')')
eq_(gen, exp)
def test_insert_returing():
gen = insert('person', OrderedDict([
('person_id', 'mosky'), ('name', 'Mosky Liu'),
]), returning=raw('*'))
exp = ('INSERT INTO "person" ("person_id", "name") '
... |
jaeilepp/mne-python | tutorials/plot_stats_cluster_spatio_temporal_repeated_measures_anova.py | Python | bsd-3-clause | 12,088 | 0.000083 | """
.. _tut_stats_cluster_source_rANOVA:
======================================================================
Repeated measures ANOVA on source data with spatio-temporal clustering
======================================================================
This example illustrates how to make use of the clustering funct... | X[:, :, :, ii] += condition.lh_data[:, :, np.newaxis]
###############################################################################
# It's a good idea to spatially smooth the data, and for visualization
# purposes, let's morph these to fsaverage, which is a grade 5 source space
# with vertices 0:10242 for each hemis... | one
# morph matrix for all the heavy lifting.
fsave_vertices = [np.arange(10242), np.array([], int)] # right hemi is empty
morph_mat = compute_morph_matrix('sample', 'fsaverage', sample_vertices,
fsave_vertices, 20, subjects_dir)
n_vertices_fsave = morph_mat.shape[0]
# We have to c... |
ToureNPlaner/tourenplaner-web | js/lang/po2js.py | Python | apache-2.0 | 1,277 | 0.022709 | #!/usr/bin/python
#
# convert .po to .js
#
import json
import optparse
import os
import polib
import re
import string
import sys
parser = optparse.OptionParser(usage="us | age: %prog [options] pofile...")
parser.add_option("--callback", default="_.setTranslation", dest="callback", help="callback function to call with data")
parser.add_option("--quiet", action="store_false", default=True, dest="verbose", help="don't | print status messages to stdout")
(options, args) = parser.parse_args()
if args == None or len(args) == 0:
print("ERROR: you must specify at least one po file to translate");
sys.exit(1)
paramFix = re.compile("(\\(([0-9])\\))")
for srcfile in args:
destfile = os.path.splitext(srcfile)[0] + ".js"
if options.ver... |
eSiUX/siux-python | tests/sourceinfo_test.py | Python | mit | 4,760 | 0.070168 | #!/usr/bin/python
import unittest, pprint, sys
sys.path.append( '../siux' )
import siuxlib
class TestSourceInfo(unittest.TestCase):
# config
auth = '<YOUR_API_KEY>'
def checkSourceInfo( self,retList ):
"""
Method tests sourceInfo structure
:param retList: - structure reported by API
"""
self.assert... | n retList )
self.assertTrue( 'clientPay' in retList )
self.assertTrue( isinstance( retList['clientPay'] ,int ))
self.assertTrue( | 'domainId' in retList )
self.assertTrue( isinstance( retList['domainId'] ,int ))
self.assertTrue( 'googleGaProfileId' in retList )
self.assertTrue( isinstance( retList['googleGaProfileId'] ,int ))
self.assertTrue( 'googleGaTsCreate' in retList )
self.assertTrue( isinstance( retList['googleGaTsCreate'] ,... |
jda/unifi-tools | gen-minrssi.py | Python | mit | 828 | 0.018116 | #!/usr/bin/env python
from pymongo import MongoClient
import json
import sys
# print message and die
def msgDie(msg):
print msg
sys.exit(2)
if len(sys.argv) != 4:
msgDie("usage: unifi-minder.py config.json site-name minSNR")
# load config
cfgFile = sys.argv[1]
siteName = sys.argv[2]
minSNR = sys.argv[3]
with ope... | cfg = json.load(data_file)
# get database
dbCfg = cfg['database']
client = MongoClient(dbCfg['host'], dbCfg['port'])
db = client[dbCfg['db']]
sites = db['site']
site = sites.find_one({"name": siteName})
sid = | str(site["_id"])
devices = db['device']
for device in devices.find({"site_id": sid}):
mac = device["mac"]
mac = mac.replace(":", "")
for radio in device['radio_table']:
radtype = radio['radio']
print "config.minrssi.%s.%s=%s" % (mac, radtype, minSNR)
|
squilter/ardupilot | Tools/scripts/decode-ICSR.py | Python | gpl-3.0 | 2,047 | 0 | #!/usr/bin/env python
'''
decode an stm32 ICSR register value
'''
import sys
import optparse
def num(s):
try:
return int(s)
except ValueError:
return int(s, 16)
parser = optparse.OptionParser(__file__)
opts, args = parser.parse_args()
if len(args) == 0:
| print(parser.usage)
sys.exit(0)
ICSR = num(args[0])
# https: | //www.st.com/content/ccc/resource/technical/document/programming_manual/6c/3a/cb/e7/e4/ea/44/9b/DM00046982.pdf/files/DM00046982.pdf/jcr:content/translations/en.DM00046982.pdf
# page 225
def decoder_m4_vectactive(value):
exceptions = {
0: "Thread mode",
1: "Reserved",
2: "NMI",
3: "... |
bsmr-eve/Pyfa | gui/utils/numberFormatter.py | Python | gpl-3.0 | 5,541 | 0.002166 | import math
def formatAmount(val, prec=3, lowest=0, highest=0, currency=False, forceSign=False):
"""
Add suffix to value, transform value to match new suffix and round it.
Keyword arguments:
val -- value to process
prec -- precision of final number (number of significant positions to show)
lo... | # Divide mantissa and use suffix of greater order
# Use special handling of zero key as it's not on the map
mantissa, suffix = mantissa / orderDiff, posSuffixMap[nextKey] if nextKey != 0 else ""
# Otherwise consider current results as acceptable
| break
# Round mantissa according to our prec variable
mantissa = roundToPrec(mantissa, prec)
sign = "+" if forceSign is True and mantissa > 0 else ""
# Round mantissa and add suffix
result = "{0}{1}{2}".format(sign, mantissa, suffix)
return result
def roundToPrec(val, prec):
# We're... |
ruibarreira/linuxtrail | usr/lib/python2.7/dist-packages/reportlab/lib/utils.py | Python | gpl-3.0 | 45,338 | 0.017491 | #Copyright ReportLab Europe Ltd. 2000-2012
#see license.txt for license details
# $URI:$
__version__=''' $Id$ '''
__doc__='''Gazillions of miscellaneous internal utility functions'''
import os, sys, imp, time, types
from base64 import decodestring as base64_decodestring, encodestring as base64_encodestring
try:
fr... | bytesT = bytes
unicodeT = str
strTypes = (str,bytes)
def _digeste | r(s):
return md5(s if isBytes(s) else s.encode('utf8')).hexdigest()
def asBytes(v,enc='utf8'):
return v if isinstance(v,bytes) else v.encode(enc)
def asUnicode(v,enc='utf8'):
return v if isinstance(v,str) else v.decode(enc)
def asUnicodeEx(v,enc='utf8'):
return v if isinst... |
tarballs-are-good/sympy | sympy/printing/repr.py | Python | bsd-3-clause | 4,037 | 0.004706 | """
A Printer for generating executable code.
The most important function here is srepr that returns a string so that the
relation eval(srepr(expr))=expr holds in an appropriate environment.
"""
from printer import Printer
from sympy.core import Basic
import sympy.mpmath.libmp as mlib
from sympy.mpmath.libmp import p... | name__"):
return "<'%s.%s'>"%(expr.__module__, expr.__name_ | _)
else:
return str(expr)
def _print_Add(self, expr):
args = list(expr.args)
args.sort(Basic._compare_pretty)
args = map(self._print, args)
return "Add(%s)"%", ".join(args)
def _print_Function(self, expr):
r = '%s(%r)' % (expr.func.__base__.__name__,... |
zacharyvoase/zenqueue | zenqueue/client/http/async.py | Python | mit | 507 | 0.00789 | # -*- coding: utf-8 -*-
from eventlet import httpc
from zenqueue.client.http.common import HTTPQueueClient
class QueueClient(HTTPQueueClient):
def send(self, url, data=''):
# Catch non-successful HTTP requests and treat them as if they were.
try:
result = httpc.post(url, data=da... | t=utf-8')
except httpc.ConnectionError, exc:
result | = exc.params.response_body
return result |
ANKRAJG/movieStats | movieGraphs/admin.py | Python | bsd-3-clause | 570 | 0.007018 | from djan | go.contrib import admin
from . import models
from .models import Hollywood, Profession, Artist, Xaxis, Y | axis, MovieImage, ArtistImage
class ArtistInline(admin.StackedInline):
model = Artist
extra = 4
class ProfessionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['prof_name']}),
]
inlines = [ArtistInline]
admin.site.register(Profession, ProfessionAdmin)
admin.site.re... |
huchoi/edx-platform | cms/djangoapps/contentstore/views/public.py | Python | agpl-3.0 | 2,264 | 0.001325 | """
Public views
"""
from django_future.csrf import ensure_csrf_cookie
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from django.conf import settings
from edxmako.shortcuts import render_to_response
from external_auth.views import (s... | ssl_get_cert_from_request(request)):
# SSL login doesn't require a login view, so redirect
# to course now that the user is authenticated via
# the decorator.
next_url = request.GET.get('next')
if next_url:
return redirect(next_url)
else:
re... | CAS is enabled, redirect auth handling to there
return redirect(reverse('cas-login'))
return render_to_response(
'login.html',
{
'csrf': csrf_token,
'forgot_password_link': "//{base}/login#forgot-password-modal".format(base=settings.LMS_BASE),
'platform_... |
rocky/python2-trepan | test/unit/test-info-files.py | Python | gpl-3.0 | 1,573 | 0.001271 | #!/usr/bin/env python
'Unit test for debugger info file'
import inspect, unittest
from trepan import debugger as Mdebugger
from trepan.processor.command import info as Minfo
from trepan.processor.command.info_subcmd import files as MinfoFile
from cmdhelper import dbg_setup
class TestInfoFile(unittest.TestCase):
... | r
return
def clear_output(self):
self.msgs = [ | ]
self.errmsgs = []
self.last_was_newline = True
return
def msg_nocr(self, msg):
if len(self.msgs) > 0:
self.msgs[-1] += msg
else:
self.msgs += msg
pass
return
def msg(self, msg):
self.msgs += [msg]
return
... |
econandrew/bandicoot | bandicoot/tests/test_group.py | Python | mit | 7,063 | 0.004247 | """
Test for the bandicoot.helper.group module.
"""
import bandicoot as bc
from bandicoot.core import Record, Position
import unittest
import datetime
from bandicoot.tests.generate_user import random_burst
from bandicoot.helper.group import group_records
from bandicoot.helper.tools | import std, mean
from datetime import timedelta
import numpy as np
import os
class TestGroup(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls._dir_changed = False
def setUp(self):
if not TestGroup._dir_changed:
abspath = os.path.abspath(__file__)
name = ab... | elf.maxDiff = None
self.user = bc.io.read_orange("u_test", "samples", describe=False)
self.random_int_list = np.random.randint(1, 1000, size=9001)
self.sum_stats_list = [bc.helper.tools.SummaryStats(np.random.rand(), np.random.rand(),
np.random.rand(), np.random.... |
marcosbontempo/inatelos | poky-daisy/scripts/lib/mic/utils/oe/misc.py | Python | mit | 4,324 | 0.004625 | # ex:ts=4:sw=4:sts=4:et
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
#
# Copyright (c) 2013, Intel Corporation.
# All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free ... | real errors based on return
# code.
msger.warning("WARNING: %s returned '%s' instead of 0" % (cmd_and_args, rc))
return (rc, out)
def exec_cmd_quiet(cmd_and_args, as_shell = False):
"""
Execute command, catching nothing in the output
Need to execute as_shell if the command uses wild... | """
return exec_cmd(cmd_and_args, as_shell, 0)
def exec_native_cmd(cmd_and_args, native_sysroot, catch = 3):
"""
Execute native command, catching stderr, stdout
Need to execute as_shell if the command uses wildcards
Always need to execute native commands as_shell
"""
native_paths = \
... |
ATIX-AG/foreman-ansible-modules | plugins/modules/realm.py | Python | gpl-3.0 | 2,670 | 0.001498 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Lester R Claudio <claudiol@redhat.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your opti... | .theforeman.foreman.plugins.module_utils.foreman_helper imp | ort ForemanTaxonomicEntityAnsibleModule
class ForemanRealmModule(ForemanTaxonomicEntityAnsibleModule):
pass
def main():
module = ForemanRealmModule(
foreman_spec=dict(
name=dict(required=True),
realm_proxy=dict(type='entity', required=True, resource_type='smart_proxies'),
... |
SportySpice/Collections | src/gui/EnumButton.py | Python | gpl-2.0 | 4,537 | 0.020719 | from src.tools.enum import enum
import pyxbmct.addonwindow as pyxbmct
from src.tools.dialog import dialog
EnumMode = enum(SELECT=0, ROTATE=1)
class EnumButton(object):
def __init__(self, label, values, current, default, changeCallback=None, saveCallback=None, customLabels=None, mode=EnumMode.SELECT, returnValue... |
def _findDefaultIndex(self):
for i in range(0, le | n(self.values)):
value = self.values[i]
if value == self.defaultValue:
self.defaultIndex = i
if self.defaultIndex is None:
raise ValueError ('Default value not found in value list')
def _findCurrentIndex(self... |
chatelak/RMG-Py | rmgpy/qm/mopacTest.py | Python | mit | 7,951 | 0.043013 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
import os
import numpy as np
from rmgpy import getPath
from rmgpy.qm.main import QMCalculator
from rmgpy.molecule import Molecule
from rmgpy.qm.mopac import MopacMolPM3, MopacMolPM6, MopacMolPM7
mopacEnv = os.getenv('MOPAC_DIR', default="/opt/mopac")
if os.... | (getPath(),'..'))
qm = QMCalculator(software = 'mopac',
method = 'pm6',
fileStore = os.path.join(RMGpy_path, 'testing', 'qm', 'QMfiles'),
scratchDirectory = os.path.join(RMGpy_path, 'testing', 'qm', 'QMscratch'),
)
if not os.path.exists(qm.settings.fileStore):
os.makedirs(qm.s... | ngs.fileStore)
self.qmmol1 = MopacMolPM6(mol1, qm.settings)
def testGenerateThermoData(self):
"""
Test that generateThermoData() works correctly.
"""
try:
fileList = os.listdir(self.qmmol1.settings.fileStore)
for fileName in fileList:
os.remove(os.path.join(self.qmmol1.settings.fileStore, fileNam... |
ageitgey/face_recognition | docs/conf.py | Python | mit | 8,789 | 0.005461 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# face_recognition documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in t... | uilt
# documents.
#keep_warnings = False
# -- Options for HTML output -------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation | for
# a list of builtin themes.
html_theme = 'default'
# 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... |
rogerscristo/BotFWD | env/lib/python3.6/site-packages/telegram/files/venue.py | Python | mit | 2,201 | 0.000909 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as publish... | (:class:`telegram.Location`): Venue location.
title (:obj:`str`): Name of the venue.
address (:obj:`str`): Address of the venue.
foursquare_id (:obj:`str`, optional): Foursquare identifier of the venue.
**kwargs (:obj:`dict`): Arbitrary keyword argum | ents.
"""
def __init__(self, location, title, address, foursquare_id=None, **kwargs):
# Required
self.location = location
self.title = title
self.address = address
# Optionals
self.foursquare_id = foursquare_id
self._id_attrs = (self.locatio... |
hellhovnd/dentexchange | dentexchange/apps/search/strings.py | Python | bsd-3-clause | 551 | 0 | # -*- coding:utf-8 -*-
from django.utils.translation import ugettext_lazy as _
# SearchForm's strings
SEA | RCH_FORM_KEYWORDS = _(u'Key Words / Profession')
SEARCH_FORM_LOCATION = _(u'City, State or Zip Code')
# SearchFiltersForm's strings
SEARCH_FILTERS_FORM_JOB_POSITION = _(u'Job Position')
SEARCH_FILTERS_FORM_EXPERIENCE_YEARS = _(u'Experience')
SEARCH_FIL | TERS_FORM_DISTANCE = _(u'Distance')
SEARCH_FILTERS_FORM_FULL_TIME = _(u'Full Time')
SEARCH_FILTERS_FORM_PART_TIME = _(u'Part Time')
SEARCH_FILTERS_FORM_VISA = _(u'Has a Visa / Visa required')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.