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 |
|---|---|---|---|---|---|---|---|---|
mlperf/training_results_v0.6 | Fujitsu/benchmarks/resnet/implementations/mxnet/3rdparty/tvm/python/tvm/contrib/debugger/debug_result.py | Python | apache-2.0 | 6,677 | 0.002396 | """Graph debug results dumping class."""
import os
import json
import tvm
GRAPH_DUMP_FILE_NAME = '_tvmdbg_graph_dump.json'
class DebugResult(object):
"""Graph debug data module.
Data dump module manage all the debug data formatting.
Output data and input graphs are formatted and dumped to file.
Front... | ----", "-------", "----------", \
"--------", "-----", "------", "-------"]
eid = 0
data = []
total_time = sum(time[0] for time in self._time_list)
for node, time in zip(se | lf._nodes_list, self._time_list):
num_outputs = self.get_graph_node_output_num(node)
for j in range(num_outputs):
op = node['op']
if node['op'] == 'param':
continue
name = node['name']
shape = str(self._output_te... |
richrr/scripts | python/merging-python-script.py | Python | gpl-3.0 | 5,595 | 0.0084 | import sys
import os
import pandas as pd
import multiprocessing as mp
import csv
# this code is written for the merged file with combined pval & fdr. although it could have been written for the file without comb fisher and fdr,
# it is easier to have the output with the comb pval and fdr and use what we need rather t... | d fdr
# or run the next (create network) command to calc the combined pva | l and fdr.
# cd /nfs3/PHARM/Morgun_Lab/richrr/Cervical_Cancer/analysis/merged/corr/gexpress/stage-ltest_corr/p1
"""
SGE_Batch -c "python ~/Morgun_Lab/richrr/scripts/python/merging-python-script.py merged_gexp_sp_corr_p1_FolChMedian_merged-parallel-output.csv-comb-pval-output.csv 1 2" -m 150G -F 100G -r log_merge-py_... |
ckamm/mirall | shell_integration/nautilus/ownCloud.py | Python | gpl-2.0 | 5,047 | 0.038439 | #!/usr/bin/python3
import os
import urllib
import socket
from gi.repository import GObject, Nautilus
class ownCloudExtension(GObject.GObject, Nautilus.ColumnProvider, Nautilus.InfoProvider):
nautilusVFSFile_table = {}
registered_paths = {}
remainder = ''
connected = False
watch_id = 0
d... | eturn path.replace("file://", "")
def update_file_info(self, item):
if item.get_uri_scheme() != 'file':
return
filename = urllib.unquote(item.get_uri()[7:])
if item.is_directory():
filename += '/'
for reg_path in self.registered_paths:
if filename.startswith(reg_pat... | m.add_string_attribute('share_state', "share state")
self.askForOverlay(filename)
break
else:
print "Not in scope:"+filename
|
pyroscope/pyroscope | pyroscope/pyroscope/controllers/torrent.py | Python | gpl-2.0 | 1,556 | 0.003213 | """ PyroScope - Controller "torrent".
Copyright (c) 2009 The PyroScope Project <pyroscope.project@gmail.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 L... | opy of the GNU General Public License along
with th | is program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""
import logging
from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect_to
from pyroscope.lib.base import render, PageContro... |
olivierverdier/sfepy | examples/navier_stokes/stokes.py | Python | bsd-3-clause | 4,109 | 0.024093 | # 24.05.2007, c
# last revision: 25.02.2008
from sfepy import data_dir
from sfepy.fem.periodic import *
filename_mesh = data_dir + '/meshes/2d/special/channels_symm944t.mesh'
if filename_mesh.find( 'symm' ):
region_1 = {
'name' : 'Y1',
'select' : """elements of group 3""",
}
region_2 = {
... | n
(elements of group 2 *n elements of group 6)
+n
(elements of group 9 *n elements of group 8)
+n
(elements of group 2 *n elements of group 8 | )
""",
}
w2 = 0.499
# Sides.
region_20 = {
'name' : 'Left',
'select' : 'nodes in (x < %.3f)' % -w2,
}
region_21 = {
'name' : 'Right',
'select' : 'nodes in (x > %.3f)' % w2,
}
region_22 = {
'name' : 'Bottom',
'select' : 'nodes in (y < %.3f)' % -w2,
}
region_23 = {
... |
lockerfish/assertj-android | generate-assertions-java.py | Python | apache-2.0 | 4,345 | 0.014499 | #!/usr/bin/env python
from datetime import date
import os
import re
SRC_DIR = 'src/main/java/'
ABSTRACT = re.compile(r'public abstract class Abstract')
TYPE = re.compile(r'class [A-Za-z0-9]+(<[^>]+?(?: extends ([A-Za-z0-9_]+))?>)?')
TARGET = re.compile(r'\s[A-Z][A-Za-z0-9_]+<[A-Z][A-Za-z0-9_]+(?:<.+?>)?, (([A-Z][A-... | match.group(2)
if generics:
print('bou | nds type: %s' % bounds_type)
print('bounds ext : %s' % bounds_ext)
if bounds_ext:
for match in IMPORT.finditer(java):
if match.group(1).endswith(bounds_ext):
bounds_type = bounds_type.replace(bounds_ext, match.group(1))
break
else:
raise Excepti... |
openego/oeplatform | modelview/migrations/0010_auto_20160301_1032.py | Python | agpl-3.0 | 728 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-03-01 09:32
from __future__ import unicode_lit | erals
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("modelview", "0009_auto_20160301_1030")]
operations = [
migrations.AlterField(
model_name="energyscenario",
name="tools_models",
... | tools have been used?",
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="modelview.Energymodel",
verbose_name="Tools",
),
)
]
|
ntt-sic/heat | heat/engine/update.py | Python | apache-2.0 | 7,456 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | _
logger = logging.getLogger(__name__)
class StackUpdate(object):
"""
A Task to perform the update of an existing stack to a new template.
"""
def __init__(self, existing_stack, new_stack, previous_stack,
rollback=False):
"""Initialise with the existing stack and the new st... | ing_stack = existing_stack
self.new_stack = new_stack
self.previous_stack = previous_stack
self.rollback = rollback
self.existing_snippets = dict((n, r.parsed_template())
for n, r in self.existing_stack.items())
def __repr__(self):
if ... |
Shrews/PyGerrit | webapp/django/contrib/localflavor/us/forms.py | Python | apache-2.0 | 4,166 | 0.00312 | """
USA-specific Form helpers
"""
from django.forms import ValidationError
from django.forms.fields import Field, RegexField, Select, EMPTY_VALUES
from django.utils.encoding import smart_unicode
from django.utils.translation import ugettext_lazy as _
import re
phone_digits_re = re.compile(r'^(?:1-?)?(\d{3})[-\.]?(\d{... | .clean(value)
if value in EMPTY_VALUES:
return u''
try:
value = value.strip().lower()
except AttributeError:
pass
else:
try:
return STATES_NORMALIZED[value.strip().lower()].decode('asci | i')
except KeyError:
pass
raise ValidationError(self.error_messages['invalid'])
class USStateSelect(Select):
"""
A Select widget that uses a list of U.S. states/territories as its choices.
"""
def __init__(self, attrs=None):
from us_states import STATE_CHOICE... |
monouno/site | judge/migrations/0019_og_images.py | Python | agpl-3.0 | 716 | 0.002793 | # -*- coding: utf-8 | -*-
# Generated by Django 1.9 on 2015-12-19 18:47
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('judge', '0018_django_1_9'),
]
operations = [
migrations.A | ddField(
model_name='blogpost',
name='og_image',
field=models.CharField(default=b'', help_text='', max_length=150, verbose_name=b'OpenGraph image'),
),
migrations.AddField(
model_name='contest',
name='og_image',
field=models.CharFie... |
mwcraig/ccdproc | docs/conf.py | Python | bsd-3-clause | 6,953 | 0.001726 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
#
# Astropy documentation build configuration file.
#
# 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 file.
#
# All configurati... | docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = ''
from os.path import join
html_favicon = join('_static', 'ccd_proc.ico')
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt ... | '{0} v{1}'.format(project, release)
# Output file base name for HTML help builder.
htmlhelp_basename = project + 'doc'
# Static files to copy after template files
html_static_path = ['_static']
html_style = 'ccdproc.css'
# -- Options for LaTeX output -------------------------------------------------
# Grouping the... |
ztane/jaspyx | jaspyx/visitor/binop.py | Python | mit | 1,067 | 0 | from __future__ import absolute_import, divi | sion, print_function
import ast
from jaspyx.ast_util import ast_load, ast_call
from jaspyx.visitor import BaseVisitor
class BinOp(BaseVisitor):
def visit_BinOp(self, node):
attr = getattr(self, 'BinOp_%s' % node.op.__class__.__name__, None)
attr(node.left, node.right)
for key, value in {
... | : '|',
'BitXor': '^',
'LShift': '<<',
'RShift': '>>',
}.items():
def gen_op(op):
def f_op(self, left, right):
self.group([left, op, right])
return f_op
exec('BinOp_%s = gen_op("%s")' % (key, value))
def BinOp_Pow(self, left, right)... |
arenadata/ambari | ambari-server/src/main/resources/common-services/ZEPPELIN/0.7.0/package/scripts/interpreter_json_template.py | Python | apache-2.0 | 15,680 | 0.000255 | #!/usr/bin/env python
"""
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");... | "users": [],
"isUserImpersonate": false
}
},
"2CKX6DGQZ": {
"id": "2CKX6DGQZ",
"name": "livy",
"group": "livy",
"properties": {
"zeppelin.li | vy.pull_status.interval.millis": "1000",
"livy.spark.executor.memory": "",
"zeppelin.livy.session.create_timeout": "120",
"zeppelin.livy.principal": "",
"zeppelin.livy.spark.sql.maxResult": "1000",
"zeppelin.livy.keytab": "",
"zeppelin.livy.concurrentSQL": "false",
... |
zhang0137/chromite | lib/cros_test_lib.py | Python | bsd-3-clause | 29,541 | 0.008158 | #!/usr/bin/python
# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Cros unit test library, with utility functions."""
from __future__ import print_function
import collections
import contextlib
i... |
# We cannot just import chromite since this module is still accessed
# from non chromite.lib.cros_test_lib pathways (which will be resolved
# implicitly via 37517).
sys.path.insert(0, os.path.join(
os.path.dirname(os.path.abspath(__file__)), '../third_party'))
import mock
Directory = collections.named... | uct):
"""Converts a directory structure to a list of paths."""
flattened = []
for obj in dir_struct:
if isinstance(obj, Directory):
new_base = os.path.join(base_path, obj.name).rstrip(os.sep)
flattened.append(new_base + os.sep)
flattened.extend(_FlattenStructure(new_base, obj.contents))
... |
weissj3/MWTools | Scripts/MakeNormalizedHistogram.py | Python | mit | 1,516 | 0.030343 | import sys
import math as ma
import numpy as np
params = ["$\\varepsilon_{sph}$ & ", "$q$ & ", "$\\varepsilon$ & ", "$\mu$ & ", "R & ", "$\\theta$ & ", "$\phi$ &", " $\sigma$ & ", "$\\varepsilon$ & ", "$\mu$ & ", "R & ", "$\\theta$ & ", "$\phi$ & ", "$\sigma$ & ", "$\\varepsilon$ & ", "$\mu$ & ", "R & ", "$\\theta$ & ... |
a = [( ("%.2g" % k) if (abs(k) < 1000 and abs(k) > .01) else ("%.1e" % k)) for k in [j/(84046.0) for j in map(float, sys.argv[i].split())] ]
a[i-1] = "\textbf{" + a[i-1] + "}"
placeholder = [ "& ---" for j in range(i+1, len(sys.argv)) ]
if count == 0:
placeholder[2-i] = "& \multicolumn{1}{|c}... | unt == 2:
a[8] = "\multicolumn{1}{|c}{" + a[8] + "}"
placeholder[14-i] = "& \multicolumn{1}{|c}{---}"
if count == 3:
a[14] = "\multicolumn{1}{|c}{" + a[14] + "}"
#print str(a[:i]).replace('[', '').replace(',', ' &').replace("'",'').replace(']', ' ')
print params[i-1] + str(a[:i]).r... |
k340/SULI | setup.py | Python | bsd-3-clause | 378 | 0.005291 | from setuptools import setup
setup(
name="SULI",
packages=['SULI'],
version='0.0.1',
description="SULI project",
author='Kelin Kurzer-Ogul',
au | thor_email='kelin.kurzerogul@gmail.com',
url='https://github.com/k340/SULI',
keywords=['SULI', 'Fermi', 'LAT', 'transients'],
classifiers=[],
install_requires=['numpy','a | stropy'],
)
|
machacek/information-retrieval-project | lucene-experiment/collection.py | Python | unlicense | 618 | 0.011327 | import os
from itertools import imap
from multiprocessing import | Pool
from config import config
from document_topic import Document, Topic
class Collection(object):
def __init__(self, list_file, prefix=''):
self.names_list = [os.path. | join(prefix, file_name.strip()) for file_name in list_file]
def __iter__(self):
pool = Pool(min(config.workers,len(self.names_list)))
return pool.imap(self.type, self.names_list)
#return imap(self.type, self.names_list)
class TopicCollection(Collection):
type = Topic
class Do... |
nett55/caniusepypy | caniusepypy/command.py | Python | apache-2.0 | 1,565 | 0 | # 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 agre... | ols
import caniusepypy as ciu
import caniusepypy.__main__ as ciu_main
from caniusepypy import pypi
class Command(setuptools.Command):
description = """Run caniusepypy over a setup.py file."""
user_option | s = []
def _dependencies(self):
projects = []
for attr in ('install_requires', 'tests_require'):
requirements = getattr(self.distribution, attr, None) or []
for project in requirements:
if not project:
continue
projects.app... |
axbaretto/beam | sdks/python/.tox/lint/lib/python2.7/site-packages/pylint/test/functional/class_members_py27.py | Python | apache-2.0 | 1,691 | 0.011236 | """ Various tests for class members access. """
# pylint: disable=R0903,print-statement,no-absolute-import, metaclass-assignment,import-error,no-init,missing-docstring, wrong-import-order,wrong-import-position
from missing import Missing
class MyClass(object):
"""class docstring"""
def __init__(self):
... | Test attribute access for metaclasses. """
__metaclass__ = ABCMeta
class Metaclass(type):
""" metaclass """
@classmethod
def test(mcs):
""" classmethod """
class UsingMetaclass(object):
""" empty """
__metaclass__ = Metaclass
#TestMetaclass.register(int)
#UsingMetaclass.test()
TestMe... | ember if we don't know the bases of a class."""
NoKnownBases().lalala()
# Should be enabled on astroid > 1.4.0
#class MetaClass(object):
# """Look some methods in the implicit metaclass."""
#
# @classmethod
# def whatever(cls):
# return cls.mro() + cls.missing()
|
madrisan/pyoocs | oocs/services.py | Python | gpl-3.0 | 6,244 | 0.004164 | # This python module is part of the oocs scanner for Linux.
# Copyright (C) 2015 Davide Madrisan <davide.madrisan.gmail.com>
import glob
from os import sep
from os.path import join
from pwd import getpwuid
from oocs.filesystem import Filesystems, UnixCommand, UnixFile
from oocs.io import Config, message_add, quote, u... | alse):
services = Services(verbose=verbose)
localscan = {}
curr_runlevel = services.sysv_runlevel()
if services.runlevel and curr_runlevel != services.r | unlevel:
message_add(localscan, 'warning',
'the current runlevel is ' + quote(curr_runlevel) +
' but should be ' + quote(services.runlevel))
if not services.enabled:
if verbose:
message_add(localscan, 'info',
'Skipping ' + quote(module_name) +
... |
ZeitOnline/zeit.newsletter | src/zeit/newsletter/browser/tests/test_form.py | Python | bsd-3-clause | 668 | 0 | import zeit.newsletter.testing
class MetadataTest(zeit.newsletter.testing.SeleniumTestCase):
def test_form_should_save_entered_data_on_blur(self):
| s = self.selenium
self.open('/repository/newsletter/@@checkout')
s.waitForElementPresent('id=metadata.subject')
s.assertValue('id=metadata.subject', '')
s.type('id=metadata.subject', 'flubber\t')
s.waitForElementNotPresent('css=.field.dirty')
# Re-open the page and... | is still there
s.clickAndWait('link=Edit contents')
s.waitForElementPresent('id=metadata.subject')
s.assertValue('id=metadata.subject', 'flubber')
|
mayblue9/scikit-learn | examples/classification/plot_lda_qda.py | Python | bsd-3-clause | 5,046 | 0.001585 | """
====================================================================
Linear and Quadratic Discriminant Analysis with confidence ellipsoid
====================================================================
Plot the confidence ellipsoids of each class and decision boundary
"""
print(__doc__)
from scipy import lin... | 'red')
plot_ellipse(splot, lda.means_[1], lda.covariance_, 'blue')
def plot_qda_cov(qda, splot):
plot_ellipse(splot, qda.means_[0], qda.covariances_[0], 'red')
plot_ellipse(splot, qda.means_[1], qda.covariances_[1], 'blue')
############################################################################### |
for i, (X, y) in enumerate([dataset_fixed_cov(), dataset_cov()]):
# Linear Discriminant Analysis
lda = LinearDiscriminantAnalysis(solver="svd", store_covariance=True)
y_pred = lda.fit(X, y).predict(X)
splot = plot_data(lda, X, y, y_pred, fig_index=2 * i + 1)
plot_lda_cov(lda, splot)
plt.axis('t... |
ooovector/qtlab_replacement | tunable_coupling_transmons/Misis_two_qubit_August_2019_setup.py | Python | gpl-3.0 | 9,950 | 0.003973 | from qsweepy.instruments import *
from qsweepy import *
from qsweepy import awg_iq_multi
import numpy as np
device_settings = {'vna_address': 'TCPIP0::10.20.61.48::inst0::INSTR',
'lo1_address': 'TCPIP0::10.20.61.59::inst0::INSTR',
'lo1_timeout': 5000, 'rf_switch_address': '10.20... | _points = 20000
self.hdawg.set_nop(global_num_points)
self.hdawg.clear()
| # а вот длину сэмплов, которая очевидно то же самое, нужно задавать на всех авгшках.
# хорошо, что сейчас она только одна.
# this is zashkvar WUT THE FUCK MAN
self.hdawg.set_trigger_impedance_1e3()
self.hdawg.set_dig_trig1_source([0, 0, 0, 0])
self.hdawg.set_dig_trig1_slo... |
bjolivot/ansible | lib/ansible/modules/cloud/openstack/os_nova_flavor.py | Python | gpl-3.0 | 8,477 | 0.004719 | #!/usr/bin/python
# Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
#
# This 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 late... | ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: os_nova_flavor
short_description: M | anage OpenStack compute flavors
extends_documentation_fragment: openstack
version_added: "2.0"
author: "David Shrewsbury (@Shrews)"
description:
- Add or remove flavors from OpenStack.
options:
state:
description:
- Indicate desired state of the resource. When I(state) is 'present',
then I(... |
glasnt/voc | tests/builtins/test_input.py | Python | bsd-3-clause | 687 | 0 | from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class InputTests(TranspileTestCase):
pass
# FIXME: This test can't run without a redirection for stdin.
# class BuiltinInputFunctionTests(BuiltinFunctionTestCase, Trans | pileTestCase):
# functions = ["input"]
# not_implemented = [
# 'test_bool',
# 'test_bytearray',
# 'test_bytes',
# 'test_class',
# 'test_complex',
# 'test_dict',
# 'test_float',
# 'test_frozenset',
# 'test_int',
# 'test_list',
# ... | ,
# 'test_set',
# 'test_str',
# 'test_tuple',
# ]
|
SavinaRoja/npyscreen2 | npyscreen2/logs.py | Python | gpl-3.0 | 1,956 | 0.001022 | # -*- coding: utf-8 -*-
"""
"""
import logging
import logging.handlers
import sys
STANDARD_FORMAT = '%(name)s [%(levelname)s] %(message)s'
MESSAGE_ONLY_FORMAT = '%(message)s'
def get_level(level_string):
"""
Returns an appropriate logging level integer from a string name
"""
levels = {'debug': loggi... | e=mode)
if level is None:
handler.setLevel(logging.WARNING)
else:
ha | ndler.setLevel(get_level(level))
if filtr is not None:
handler.addFilter(logging.Filter(filtr))
if frmt is None:
handler.setFormatter(logging.Formatter(STANDARD_FORMAT))
else:
handler.setFormatter(logging.Formatter(frmt))
log.addHandler(handler)
#def deactivate_logging():
... |
Warbo/bugseverywhere | libbe/command/merge.py | Python | gpl-2.0 | 6,074 | 0.001976 | # Copyright (C) 2008-2012 Chris Ball <cjb@laptop.org>
# Gianluca Montecchi <gian@grys.it>
# W. Trevor King <wking@tremily.us>
#
# This file is part of Bugs Everywhere.
#
# Bugs Everywhere is free software: you can redistribute it and/or modify it
# under the terms of the ... | libbe.command.Argument(
name='bug-id', metavar='BUG-ID', default=None,
completion_callback=libbe.command.util.complete_bug_id),
libbe.command.Argument(
name='bug-id-to-merge', metavar='BUG-ID', default=None,
compl... | ])
def _run(self, **params):
storage = self._get_storage()
bugdirs = self._get_bugdirs()
bugdirA,bugA,comment = (
libbe.command.util.bugdir_bug_comment_from_user_id(
bugdirs, params['bug-id']))
bugA.load_comments()
bugdirB,bugB,dummy_comme... |
zibawa/zibawa | front/views.py | Python | gpl-3.0 | 12,712 | 0.014553 | from __future__ import absolute_import
#from urllib.parse import urlparse, urlunparse
from builtins import str
from builtins import range
from django.conf import settings
# Avoid shadowing the login() and logout() views below.
from django.contrib.auth import (
REDIRECT_FIELD_NAME, get_user_model, login as auth_lo... | sponseRedirect, QueryDict
from django.shortcuts import resolve_url
from django.shortcuts import render
from django.template.response import TemplateResponse
from django.urls import reverse, reverse_lazy
from django.utils.decorators import method_decorator
#from django.utils.deprecation import RemovedInDjango21Warning
... | y as _
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.debug import sensitive_post_parameters
from django.views.generic.base import TemplateView
from django.views.generic.edit import FormView
UserModel = get_user_model()
from djan... |
safehammad/mancify | mancify/dialects/manc.py | Python | mit | 7,080 | 0.053107 | from __future__ import (
unicode_literals,
absolute_import,
division,
print_function,
)
# Make Py2's str type like Py3's
str = type('')
# Rules that take into account part of speech to alter text
structure_rules = [
((["JJ*","NN*"],),
(["chuffing",0,1],),
0.1),
((["."],),... | n","pad",
"residency","place",),
("gaff",)),
(("was",),
("were",)),
(("were",),
("was",)),
(("yes","ok",),
("aye",)),
(("are",),
("iz",)),
(("no",),
("nah",)),
(("haven't",),
("a | in't",)),
(("right",),
("reet",)),
(("the",),
("t'",)),
(("?",),
("eh?","or wot?","yeah?")),
]
# Alterations to the sound of a word based on its consonant and vowel sounds
phoneme_rules = [
((["START","HH"],),
["START","'"]),
((["ER","END"],),
["AA","'","END"]... |
goddardl/gaffer | python/GafferTest/ApplicationTest.py | Python | bsd-3-clause | 2,198 | 0.010919 | ##########################################################################
#
# Copyright (c) 2015, Image Engine Design 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:
#
# * Redistrib... | tware may be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF ... | L THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIAB... |
rajeshgupta14/pathend | consultantform/apps.py | Python | apache-2.0 | 168 | 0 | # -*- coding: | utf-8 -*-
from __future__ import unicode_literals
from django.apps import AppConfig
class ConsultantformConfig(AppConfig):
| name = 'consultantform'
|
lubokkanev/cloud-system | core/main/runtimes/runtime_validation_error.py | Python | gpl-2.0 | 50 | 0 | class RuntimeValidationE | rror(Excepti | on):
pass
|
jawilson/home-assistant | homeassistant/components/alarm_control_panel/const.py | Python | apache-2.0 | 642 | 0 | """Provides the constants needed for component."""
from typing import Fin | al
SUPPORT_ALARM_ARM_HOME: Final = 1
SUPPORT_ALARM_ARM_AWAY: Final = 2
SUPPORT_ALARM_ARM_NIGHT: Final = 4
SUPPORT_ALARM_TRIGGER: Final = 8
SUPPORT_ALARM_ARM_CUSTOM_BYPASS: Final = 16
SUPPORT_ALARM_ARM_VACATION: Final = 32
CONDITION_TRIGGERED: Final = "is_triggered"
CONDITION_DISARMED: Final = "is_disarmed"
CONDITION_... | rmed_vacation"
CONDITION_ARMED_CUSTOM_BYPASS: Final = "is_armed_custom_bypass"
|
crdoconnor/cookiecutter-django | {{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/users/views.py | Python | bsd-3-clause | 1,459 | 0 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.core.urlresolvers import reverse
from django.views.generic import DetailView, ListView, RedirectView, UpdateView
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import User
class UserDetailView(Login... | view | to index lookups by username
slug_field = "username"
slug_url_kwarg = "username"
class UserRedirectView(LoginRequiredMixin, RedirectView):
permanent = False
def get_redirect_url(self):
return reverse("users:detail",
kwargs={"username": self.request.user.username})
cla... |
vivekanand1101/fedmsg | fedmsg/tests/__init__.py | Python | lgpl-2.1 | 822 | 0 | # This file is part of fedmsg.
# Copyright (C) 2012 Red Hat, Inc.
#
# fedmsg is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#... | PARTICULAR PURPOSE. See the GNU
# Lesser General Pu | blic License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with fedmsg; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# Authors: Ralph Bean <rbean@redhat.com>
#
|
mikequentel/sarrus_cramer | sclinear.py | Python | mit | 4,841 | 0.026854 | #!/usr/bin/python
# System of three linear equations
# ax + by + cz = j
# dx + ey + fz = k
# gx + hy + iz = l
# System of three linear equations in matrix notation
# - - - - - -
# | a b c | | x | | j |
# | | | | | |
# | d e f | | y | = | k |
# | | | | |... | :inputs_di | ct['g'], 'h':inputs_dict['h'], 'i':inputs_dict['i']}
x_numerator_matrix = {'j':inputs_dict['j'], 'b':inputs_dict['b'], 'c':inputs_dict['c'],
'k':inputs_dict['k'], 'e':inputs_dict['e'], 'f':inputs_dict['f'],
'l':inputs_dict['l'], 'h':inputs_dict['h'], 'i':inputs_dict['i']}
y_numerator_matrix = {'a':inputs_dict['... |
morissette/devopsdays-hackathon-2016 | venv/lib/python2.7/site-packages/aniso8601/resolution.py | Python | gpl-3.0 | 359 | 0.005571 | # -*- coding: utf- | 8 -*-
# This software may be modified and distributed under the term | s
# of the BSD license. See the LICENSE file for details.
from aniso8601 import compat
class DateResolution(object):
Year, Month, Week, Weekday, Day, Ordinal = list(compat.range(6))
class TimeResolution(object):
Seconds, Minutes, Hours = list(compat.range(3))
|
alexandonian/ptutils | ptutils/datastore/query.py | Python | mit | 17,240 | 0.001624 | from key import Key
def _object_getattr(obj, field):
"""Attribute getter for the objects to operate on.
This function can be overridden in classes or instances of Query, Filter, and
Order. Thus, a custom function to extract values to attributes can be
specified, and the system can remain agnostic to ... | self.field == other.field and self.op == other.op
def __ne__(self, other):
return not self.__eq__(other)
def __hash__(self):
return hash(repr(self))
def isAscending(self):
return self.op == '+'
def isDescending(self):
return not self.isAscending()
def keyfn(self,... | """A key function to be used in pythonic sort operations."""
return self.object_getattr(obj, self.field)
@classmethod
def multipleOrderComparison(cls, orders):
"""Returns a function that will compare two items according to `orders`"""
comparers = [(o.keyfn, 1 if o.isAscending() else... |
EternityForest/KaithemAutomation | kaithem/src/thirdparty/iot_devices/devices/NVRPlugin/__init__.py | Python | gpl-3.0 | 46,929 | 0.006393 | from multiprocessing import RLock
from sys import path
from mako.lookup import TemplateLookup
from scullery import iceflow,workers
import os
import time
import threading
import logging
import weakref
import traceback
import | shutil
import re
import io
import random
logger = logging.Logger("plugins.nvr")
templateGetter = TemplateLookup(os.path.dirname(__file__))
from datetime import date, datetime
| from datetime import timezone
defaultSubclassCode = """
class CustomDeviceType(DeviceType):
def onIncomingCall(self,number):
# Uncomment to accept all incoming calls
# self.accept()
pass
"""
path = os.path.abspath(__file__)
path = os.path.dirname(path)
objectDetector = [None,None]
# Onl... |
xlcteam/pynxc | pynxc/tests/in/_issue_5.py | Python | bsd-3-clause | 54 | 0.018519 | def | main():
a1="X"
| TextOut(10, LCD_LINE1, a1)
|
NervanaSystems/coach | rl_coach/agents/n_step_q_agent.py | Python | apache-2.0 | 6,933 | 0.00375 | #
# Copyright (c) 2017 Intel Corporation
#
# 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 t... | s_every_x_episodes: (int)
The number of episodes between applying the accumulated gradients to the network. After every
num_steps_between_gradient_updates steps, the agent will calculate the gradients for the collected data,
it will then accumulate it in internal accumulators, and will only appl... | the network once in every
apply_gradients_every_x_episodes episodes.
:param num_steps_between_gradient_updates: (int)
The number of steps between calculating gradients for the collected data. In the A3C paper, this parameter is
called t_max. Since this algorithm is on-policy, only the steps... |
SINGROUP/pycp2k | pycp2k/classes/_each438.py | Python | lgpl-3.0 | 1,114 | 0.001795 | from pycp2k.inputsection import InputSection
class _each438(InputSection):
def __init__(self):
InputSection.__init__(self)
self.Just_energy = None
self.Powell_opt = None
self.Qs_scf = None
self.Xas_scf = None
self | .Md = None
self.Pint = None
self.Metadynamics = None
self.Geo_opt = None
self.Rot_opt = None
self.Cell_opt = None
| self.Band = None
self.Ep_lin_solver = None
self.Spline_find_coeffs = None
self.Replica_eval = None
self.Bsse = None
self.Shell_opt = None
self.Tddft_scf = None
self._name = "EACH"
self._keywords = {'Bsse': 'BSSE', 'Cell_opt': 'CELL_OPT', 'Just_energy... |
jstar88/wotmods | files/uncompyled/tests/overriding/b.py | Python | gpl-2.0 | 341 | 0.01173 | # 2015.09.05 18:13:46 ora legale Europa occidentale
# Embedded file name: b.py
from a import x
def x():
print 'b'
x()
from a import x
x()
# okay decompy | ling C:\Users\nicola user\wotmods\files\originals\tests\overriding\b.pyc
# decompiled 1 files: 1 okay, 0 failed, 0 verify failed
# 2015.09.05 1 | 8:13:46 ora legale Europa occidentale
|
tchellomello/home-assistant | homeassistant/components/knx/schema.py | Python | apache-2.0 | 14,928 | 0.000335 | """Voluptuous schemas for the KNX integration."""
import voluptuous as vol
from xknx.devices.climate import SetpointShiftMode
from homeassistant.const import (
CONF_ADDRESS,
CONF_DEVICE_CLASS,
CONF_ENTITY_ID,
CONF_HOST,
CONF_NAME,
CONF_PORT,
CONF_TYPE,
)
import homeassistant.helpers.config_... | ddress"
CONF_HEAT_COOL_STATE_ADDRESS = "heat_cool_state_address"
CONF_OPERAT | ION_MODE_FROST_PROTECTION_ADDRESS = (
"operation_mode_frost_protection_address"
)
CONF_OPERATION_MODE_NIGHT_ADDRESS = "operation_mode_night_address"
CONF_OPERATION_MODE_COMFORT_ADDRESS = "operation_mode_comfort_address"
CONF_OPERATION_MODE_STANDBY_ADDRESS = "operation_mode_standby_address"
C... |
azlanismail/prismgames | examples/games/car/networkx/algorithms/flow/__init__.py | Python | gpl-2.0 | 98 | 0.010204 | from networkx.algorithms.flow.maxflow i | mport *
from networkx.algorithms.flow.mincost i | mport *
|
clawpack/clawpack-4.x | doc/sphinx/conf.py | Python | bsd-3-clause | 6,603 | 0.005755 | # -*- coding: utf-8 -*-
#
# Clawpack documentation build configuration file, created by
# sphinx-quickstart on Wed Mar 25 12:07:14 2009.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# The contents of this file are pickled, so don't put values in the namespace
# that aren't pickle... | enSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The valu | e of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = ''
# Output file base name for HTML help builder.
htmlhelp_basename = 'Clawpackdoc'
# Options for LaTeX output
# -... |
edmorley/django | tests/forms_tests/widget_tests/test_hiddeninput.py | Python | bsd-3-clause | 603 | 0.001658 | from django.forms import HiddenInput
from .base import WidgetTest
class HiddenInputTest( | WidgetTest):
widget = HiddenInput()
def test_render(self):
self.check_html(self.widget, 'email', '', html='<input type="hidden" name="email" />')
def test_use_required_attribute(self):
# Always False to avoid browser validation on inputs hidden from the
# user.
self.assertI... | quired_attribute('foo'), False)
|
FoldingAtHome/fah-control | fah/db/Database.py | Python | gpl-3.0 | 5,550 | 0.013694 | ################################################################################
# #
# Folding@Home Client Control (FAHControl) #
# Copyright (C) 2016-2020 foldingathome.org ... | (at your option) any later version. #
# #
# This program is di | stributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# ... |
danaukes/popupcad | api_examples/switch_subdesign.py | Python | mit | 1,814 | 0.011577 | # -*- coding: utf-8 -*-
"""
Written by Daniel M. Aukes and CONTRIBUTORS
Email: danaukes<at>asu.edu.
Please see LICENSE for full license.
"""
import sys
import popupcad
import qt.QtCore as qc
import qt.QtGui as qg
if __name__=='__main__':
app = qg.QApplication(sys.argv[0])
filename_from = 'C:/Users/d... | addWidget(list2)
layout2.addWidget(button_ok)
layout2.addWidget(button_cancel)
layout.addLayout(layout1)
layout.addLayout(layout2)
widget.setLayout(layout)
button_ok.pressed.connect(widget.accept)
button_cancel.pressed.connect(widget.reject)
if widget.exec_():
i | f len(list1.selectedIndexes())==1 and len(list2.selectedIndexes())==1:
ii_from = list1.selectedIndexes()[0].row()
ii_to = list2.selectedIndexes()[0].row()
print(ii_from,ii_to)
d.replace_subdesign_refs(subdesign_list[ii_from].id,subdesign_list[ii_to].i... |
terryjbates/test-driven-development-with-python | myflaskapp/autoapp.py | Python | mit | 278 | 0 | # -*- coding: utf-8 -*-
"""Create an app | lication instance."""
from flask.helpers import get_debug_flag
from myflaskapp.app import create_app
from myflaskapp.settings import DevConfig, ProdConfig
CONFIG = DevConfig if get_debug_flag() else ProdConfig
app = create_app(CO | NFIG)
|
jorisvandenbossche/DS-python-data-analysis | notebooks/_solutions/case1_bike_count21.py | Python | bsd-3-clause | 53 | 0.018868 | df | _monthly = df.resample('M').sum()
df_monthly.plot( | ) |
Tumetsu/FMI-weather-downloader | tests/fmiapi/test_fmiparser.py | Python | gpl-2.0 | 2,344 | 0.00128 | import copy
from fmiapi.fmixmlparser import FMIxmlParser
from tests.testUtils import *
from tests.fmiapi.testdata.expected_data import *
def describe_fmi_xml_parser():
parser = FMIxmlParser()
def describe_daily_data():
test_data1 = load_xml('./tests/fmiapi/testdata/daily_12_days.xml')
test_da... | ree different dicts to one df
expected_df = copy.deepcopy(EXPECTED_DAILY_12_DAYS)
for key in EXPEC | TED_DAILY_4_DAYS:
expected_df[key] = expected_df[key] + EXPECTED_DAILY_4_DAYS[key]
for key in EXPECTED_DAILY_14_DAYS:
expected_df[key] = expected_df[key] + EXPECTED_DAILY_14_DAYS[key]
verify_dataframe(result, expected_df)
def describe_realtime_data():
... |
tommyip/zulip | zerver/migrations/0207_multiuseinvite_invited_as.py | Python | apache-2.0 | 482 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-02-06 21:49
from __future__ import unicode_literals
fro | m django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0206_stream_rendered_descript | ion'),
]
operations = [
migrations.AddField(
model_name='multiuseinvite',
name='invited_as',
field=models.PositiveSmallIntegerField(default=1),
),
]
|
gavyur/vkbuddy | config.py | Python | gpl-3.0 | 2,070 | 0.000966 | # -*- coding: utf-8 -*-
# Config file handling module
# Copyright | (C) 2014 Yury Gavrilov <yuriy@igavrilov.ru>
# This file is part of VKBuddy.
# VKBuddy is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.... | ITY 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 VKBuddy. If not, see <http://www.gnu.org/licenses/>.
import yaml
class IncorrectConfig(Exception): pass
class BareConfig:
def __in... |
brianmhunt/SIWorldMap | werkzeug/__init__.py | Python | mit | 7,097 | 0.001832 | # -*- coding: utf-8 -*-
"""
werkzeug
~~~~~~~~
Werkzeug is the Swiss Army knife of Python web development.
It provides useful classes and functions for any WSGI application to make
the life of a python web developer much easier. All of the provided
classes are independent from each other so yo... | , 'ResponseStreamMixin',
'CommonResponseDescriptorsMixin',
'UserAgentMixin', 'AuthorizationMixin',
'WWWAuthenticateMixin',
'CommonRequestDescriptorsMixin'],
'werkzeug.security': ['generate_password... | hould be imported when accessed as attributes of werkzeug
attribute_modules = frozenset(['exceptions', 'routing', 'script'])
object_origins = {}
for module, items in all_by_module.iteritems():
for item in items:
object_origins[item] = module
class module(ModuleType):
"""Automatically import objects ... |
romana/networking-romana | networking_romana/driver/ipam_romana.py | Python | apache-2.0 | 15,559 | 0.001928 | # Copyright (c) 2016 Pani Networks 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 req... | teway_ip=None, tenant_id=None,
subnet_id=None):
"""Initialize RomanaDbSubnet."""
LOG.debug("RomanaDbSubnet.__init__()")
self._cidr = cidr
self._pools = []
self._gateway_ip = gateway_ip
self._tenant_id = tenant_id
self._s | ubnet_id = subnet_id
self._context = ctx
self._neutron_id = internal_id
config = cfg.CONF.romana
LOG.debug("RomanaDbSubnet.__init__()")
if not config:
raise ipam_exc.exceptions.InvalidConfigurationOption(
{'opt_name': 'romana', 'opt_value': 'missing'})... |
mishbahr/staticgen-demo | staticgen_demo/blog/conf.py | Python | bsd-3-clause | 347 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings # noqa
from django.utils.translation import ugettext_lazy as _ # noqa
from appconf | import AppConf
class BlogConf(AppConf):
DISQUS_SHORTNAME = 'django-staticgen'
POST_IDENTIFIER = 'cu | rrent_post'
class Meta:
prefix = 'blog'
|
welchbj/tt | tt/satisfiability/__init__.py | Python | mit | 59 | 0 | """Functionality | for determining logic satisfiasbility."" | "
|
szha/mxnet | python/mxnet/api.py | Python | apache-2.0 | 938 | 0 | # 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... | ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Functions defined in MXNet.
Acknowledgement: This file originates from incubator-tvm"""
from ._ffi.function im | port _init_api
_init_api("mxnet.api")
|
kacper1095/asl-translator | api/src/scripts/train_simple_network.py | Python | gpl-3.0 | 3,211 | 0.005294 | import os
import argparse
import datetime
import yaml
import api.src.common.initial_environment_config
from ..models.dense import create_model
from ..data_processing.data_generator import DataGenerator
from ..common.config import TrainingConfig, DataConfig, Config
from ..common.utils import print_info, ensure_dir
from... | epochs')
argparser.add_argument('--num_workers', type=int, default=TrainingConfig.NUM_WORKERS, help='Number of workers during training')
argparser.add_argument('--batch_size', type=int, default=TrainingConfig.BATCH_SIZE, help='Batch size')
argparser.add_argument('--input_size', type=int, default=Config.IMA... | e size to input')
arguments = argparser.parse_args()
main(arguments)
|
town-hall-pinball/project-omega | pin/lib/score.py | Python | mit | 4,429 | 0.001129 | # Copyright (c) 2014 - 2016 townhallpinball.org
#
# 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, p... | OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACT | ION 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 pin.lib import p, ui, util
class Classic(object):
initial = True
def __init__(self, handler):
self.handler = handler
self.display = ui.Panel()
... |
Saethlin/astrotools | fit_transit.py | Python | mit | 3,396 | 0.001767 | import numpy as np
import scipy.optimize
from scipy.signal import lombscargle
import batman
import ctools
import matplotlib.pyplot as plt
def periodogram(time, data, periods):
freq = 1/periods
nfactor = 2/(data.size * np.var(data))
power = nfactor * lombscargle(time, data-np.mean(data), freq*2*np.pi)
... | plt.show()
p, cov = sc | ipy.optimize.curve_fit(transit_model_partial, time, flux, p0=p0)
p0 = [period, t0] + list(p)
p, cov = scipy.optimize.curve_fit(transit_model, time, flux, p0=p0)
#plt.plot(time, flux, 'k.')
#plt.plot(time, transit_model(time, *p0))
#plt.plot(time, transit_model(time, *p))
#plt.show()
retur... |
cloudera/ibis | ibis/backends/tests/test_column.py | Python | apache-2.0 | 1,384 | 0 | import numpy as np
import pandas as pd
import pytest
ROWID_ZERO_INDEXED_BACKENDS = ('omniscidb',)
@pytest.mark.parametrize(
'column',
[
'string_col',
'double_col',
'date_string_col',
pytest.param('timestamp_col', marks=pytest.mark.skip(reason='hangs')),
],
)
@pytest.mark.x... | )
pd.testing.assert_series_equal(result.iloc[:, 0], expected)
@pytest.mark.xfail_unsupported
def test_named_rowid(con, backend):
t = con.table('functional_alltypes')
result = t[t.rowid().name('number')].execute()
first_value = 0 if backend.name() in ROWID_ZERO_IN | DEXED_BACKENDS else 1
expected = pd.Series(
range(first_value, first_value + len(result)),
dtype=np.int64,
name='number',
)
pd.testing.assert_series_equal(result.iloc[:, 0], expected)
|
Nodraak/Prologin2015 | 4_Expert-itinerant.py | Python | gpl-2.0 | 3,054 | 0.005239 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
# @Author: Adrien Chardon
# @Date: 2014-11-16 14:29:10
# @Last Modified by: Adrien Chardon
# @Last Modified time: 2014-11-16 16:31:32
import time as t
################################################################################
# Usefull functions
###################... | == -1) or (cur['distanceFromStart'] + getDist(data, cur_id, child_id) < child['distanceFromStart']):
child['distanceFromStart'] = cur['distanceFromStart'] + getDist(data, cur_id, child_id)
chi | ld['origin'] = cur_id
if child_id not in notVisited:
notVisited.append(child_id)
return getObjectInList(nodes, end)['distanceFromStart']
def expert_itinerant(nb_node, nb_link, nb_request, data, request):
for dic in request:
print expert_itinerant_one(nb_nod... |
realityone/flaskbb | flaskbb/management/views.py | Python | bsd-3-clause | 24,085 | 0.000166 | # -*- coding: utf-8 -*-
"""
flaskbb.management.views
~~~~~~~~~~~~~~~~~~~~~~~~
This module handles the management views.
:copyright: (c) 2014 by the FlaskBB Team.
:license: BSD, see LICENSE for more details.
"""
import sys
from flask import (Blueprint, current_app, request, redirect, url_for, flas... | new_settings[key] = form[key].data
except KeyError:
pass
Setting.update(settings=new_settings, app=current_app)
flash(_("Settings saved."), "success")
else:
for key, values in iteritems(old_settings):
try:
form[key].dat... | turn render_template("management/settings.html", form=form,
all_groups=all_groups, active_group=active_group)
# Users
@management.route("/users", methods=['GET', 'POST'])
@allows.requires(IsAtleastModerator)
def users():
page = request.args.get("page", 1, type=int)
search_form = Use... |
glynjackson/django-oscar-sagepay | sagepay/templatetags/checkout_mode_tag.py | Python | mit | 613 | 0.001631 | from classytags.helpers import InclusionTag
from django import template
from django.conf import settings
from django.template.loader import render_to_string
register = template.Library()
class Banner(InclusionTag):
"""
Displays a checkout mode banner.
"""
template = 'sa | gepay/checkout_mode_banner.html'
def render_tag(self, context, **kwargs):
template = self.get_template(context, **kwargs)
if settings.SAGEPAY_MODE == "Live":
return | ''
data = self.get_context(context, **kwargs)
return render_to_string(template, data)
register.tag(Banner) |
kernow/ansible-modules-core | cloud/amazon/route53.py | Python | gpl-3.0 | 22,225 | 0.009719 | #!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed... | e": "foo.com"
"record": "_example-service._tcp.foo.com"
"type": "SRV"
"value": ["0 0 22222 host1.foo.com", "0 0 22222 host2.foo.com"]
# Add a TXT record. Note that TXT and SPF records must be surrounded
# by quotes when sent to Route 53:
- route53:
command: "create"
zone: "foo.com"
... | 0"
value: '"bar"'
# Add an alias record that points to an Amazon ELB:
- route53:
command=create
zone=foo.com
record=elb.foo.com
type=A
value="{{ elb_dns_name }}"
alias=True
alias_hosted_zone_id="{{ elb_zone_id }}"
# Retrieve the details for elb.foo.com
- route53:
... |
CoderBotOrg/coderbotsrv | server/lib/engineauth/utils.py | Python | gpl-3.0 | 948 | 0.003165 |
def load_config(default_values, user_values):
if us | er_values is None:
return default_va | lues
config = {}
for k, v in user_values.items():
if k in default_values:
if isinstance(v, dict):
cloned = user_values[k].copy()
for key, value in default_values[k].items():
if key is not None and key not in user_values[k] \
... |
philgyford/django-ditto | devproject/devproject/urls.py | Python | mit | 795 | 0.001258 | from django.conf import settings
from django.conf.urls import static
from django.urls import include, path, re_path
from django.contrib import admin
urlpatterns = [
path(r"admin/", admin.site.urls),
path(r"flickr/", include("ditto.flickr.urls")),
path(r"lastfm/", include("ditto.lastfm.urls")),
| path(r"pinboard/", include("ditto.pinboard.urls")),
path(r"twitter/", include("ditto.twitter.urls")),
path(r"", include("ditto.core.urls")),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns += [
re_path(r"^__debug__/", include(debug_toolbar.urls)),
]
urlpatterns += static.s... | ngs.STATIC_URL, document_root=settings.STATIC_ROOT
)
|
nephila/cmsplugin-filer | cmsplugin_filer_file/south_migrations/0005_auto__chg_field_filerfile_file.py | Python | bsd-3-clause | 10,023 | 0.007982 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'FilerFile.file'
db.alter_column(u'cmsplugin_filer_file... | : 'True'}),
'is_public': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'modified_at': ('django.db.models.fields.DateTimeField', [], {'aut | o_now': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '255', 'blank': 'True'}),
'original_filename': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'owner': ('django.db... |
awsdocs/aws-doc-sdk-examples | python/test_tools/pinpoint_stubber.py | Python | apache-2.0 | 7,368 | 0.001629 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Stub functions that are used by the Amazon Pinpoint unit tests.
When tests are run against an actual AWS account, the stubber class does not
set up stubs and passes all calls through to the Boto 3 client.
""... | sageResponse': {
'ApplicationId': app_id,
'Result': {
to_address: {
'MessageId': message_id,
'DeliveryStatus': 'SUCCESSFU | L',
'StatusCode': 200
}
for to_address, message_id in zip(to_addresses, message_ids)
}
}
}
self._stub_bifurcator(
'send_messages', expected_params, response, error_code=error_code)
def stub_send_... |
stalker314314/nasa_mala_kladionica | tests/unit/tests_view_results.py | Python | gpl-3.0 | 772 | 0.001295 | # -*- coding: utf-8 -*-
from django.test import Client
from django.urls import reverse
from nmkapp import views
from .nmk_unit_test_case import NmkUnitTestCase
class ResultsTests(NmkUnitTestCase): |
def test_anon_user(self):
"""
Test result view with anonymous user
"""
self.client = Client()
response = self.client.get(reverse(views.results))
self.assertEqual(response.status_code, 302)
def test_regular_user(self):
"""
Test result view with lo... | ient.login(username='kokan@mail.com', password='12345'))
response = self.client.get(reverse(views.results))
self.assertEqual(response.status_code, 200)
|
sysadminmatmoz/account-invoicing | account_invoice_check_total/__manifest__.py | Python | agpl-3.0 | 607 | 0 | # -*- coding: utf-8 -*-
# Copyright 2 | 016 Acsone SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': 'Account Invoice Check Total',
'summary': """
Check if the verification total is equal to the bill's total""",
'version': '10.0.1.0.0',
'license': 'AGPL-3',
'author': 'Acsone SA/NV,Odoo Community Asso... | : [
'account',
],
'data': [
'views/account_config_settings.xml',
'security/account_invoice_security.xml',
'views/account_invoice.xml',
],
}
|
ljean/coop_cms | coop_cms/forms/fields.py | Python | bsd-3-clause | 371 | 0.002695 | # -*- coding: utf-8 -*-
"""forms"""
import floppyforms.__future__ as floppyforms
class HidableMultipleChoiceField(floppyforms.MultipleChoiceF | ield):
"""
The MultipleChoiceField doesn't return an <input type="hidden"> when hidden but an empty string
Overload this field to restore an <input type="hidden">
| """
hidden_widget = floppyforms.HiddenInput
|
sniemi/SamPy | sandbox/src1/examples/subplot_toolbar.py | Python | bsd-2-clause | 222 | 0.018018 | #!/usr/bin/env python
from pylab import *
fig = figure()
subplot(221)
imshow(rand(100,100))
subplot(222)
imshow(rand(100,100))
subplot(223)
imshow(rand(100,100))
subp | lot | (224)
imshow(rand(100,100))
subplot_tool()
show()
|
vi/enki | tests/test_core/test_uisavefiles.py | Python | gpl-2.0 | 2,949 | 0.001695 | #!/usr/bin/env python
import unittest
import os.path
import sys
import time
sys.path.insert(0, os.path.join(os.path.abspath(os.path.dirname(__file__)), ".."))
import base
from PyQt4.QtTest import QTest
from enki.core.core import core
class Test(base.TestCase):
def _verifyText(self, fileName, text):
w... | lambda dialog: self.keyClick('s'))
self.assertIsNone(core.workspace().currentDocument())
self._verifyText('file2.rb', 'new text+fdsa\n')
@base.inMainLoop
def test_5(self):
# Close all, reject save dialog
self.createFile('file1.rb', 'asdf\nfdsa')
s... | +N') # file without name
self.keyClicks('new text') # but modified
def inUiSaveFilesDialog(dialog):
# open and reject save dialog for file without name
def inSaveFileDialog(saveDialog):
QTest.qWait(4000)
self.keyClick('Esc')
self.op... |
gpodder/mygpo | mygpo/podcasts/migrations/0006_auto_20140614_0836.py | Python | agpl-3.0 | 701 | 0 | # encoding: utf8
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [("podcasts", "0005_auto_20140610_1854")]
operations = [
mig | rations.AlterField(
model_name="episode",
name="outdated",
field=models.BooleanField(default=False, db_index=Tr | ue),
),
migrations.AlterField(
model_name="podcast",
name="outdated",
field=models.BooleanField(default=False, db_index=True),
),
migrations.AlterField(
model_name="episode",
name="guid",
field=models.CharField(max_l... |
GroestlCoin/p2pool-grs | p2pool/util/p2protocol.py | Python | gpl-3.0 | 4,140 | 0.006039 | '''
Generic message-based protocol used by Bitcoin and P2Pool for P2P communication
'''
import hashlib
import struct
from twisted.internet import protocol
from twisted.python import log
import p2pool
from p2pool.bitcoin import data as bitcoin_data
from p2pool.util import datachunker, variable
class TooLong(Exceptio... | .transport.abortConnection()
else:
# This doesn't always close timed out connections! warned about in main
self.transport.loseConnection()
def badPeerHappene | d(self):
self.disconnect()
def sendPacket(self, command, payload2):
if len(command) >= 12:
raise ValueError('command too long')
type_ = getattr(self, 'message_' + command, None)
if type_ is None:
raise ValueError('invalid command')
#print 'SEND', ... |
alonisser/Open-Knesset | laws/admin.py | Python | bsd-3-clause | 5,183 | 0.001929 | from django.db.models import Q
from import_export.admin import ImportExportModelAdmin
from models import Vote, Law, PrivateProposal, KnessetProposal, GovProposal, Bill, GovLegislationCommitteeDecision
from laws.management.commands.scrape_votes import Command as ScrapeVotesCommand
from django.utils.translation import u... | ccessfully recreated {0} votes: {1}".format(len(recreated_votes),
| recreated_vote_ids_string))
recreate_vote.short_description = "recreate vote by deleting and then getting fresh data from knesset api"
actions = ['update_vote', 'recreate_vote']
admin.site.register(Vote, VoteAdmin)
class LawAdmin(ImportExportModelAdmin):
search_fields = ('title',)
li... |
kambysese/mne-python | mne/__init__.py | Python | bsd-3-clause | 5,932 | 0.000337 | """MNE software for MEG and EEG data analysis."""
# PEP0440 compatible formatted version, see:
# https://www.python.org/dev/peps/pep-0440/
#
# Generic release markers:
# X.Y
# X.Y.Z # For bugfix releases
#
# Admissible pre-release markers:
# X.YaN # Alpha release
# X.YbN # Beta release
# X.YrcN # Rele... | er is: 'X.Y.devN' where N is an integer.
#
from ._version import __version__
# have to import verbose first since it's needed by | many things
from .utils import (set_log_level, set_log_file, verbose, set_config,
get_config, get_config_path, set_cache_dir,
set_memmap_min_size, grand_average, sys_info, open_docs)
from .io.pick import (pick_types, pick_channels,
pick_channels_regexp, pic... |
bsmr-eve/Pyfa | eos/effects/subsystembonusgallentepropulsion2agility.py | Python | gpl-3.0 | 331 | 0.003021 | # subsystemBonusGallentePropulsion2Agility
#
# Used by | :
# Subsystem: Proteus Propulsion - Hyperspatial Optimization
type = "passive"
def handler(fit, src, context):
fit.ship.boostItemAttr("agility", src.getModifiedItemAttr( | "subsystemBonusGallentePropulsion2"),
skill="Gallente Propulsion Systems")
|
crhaithcock/RushHour | RushHourPy/numpy_utilities.py | Python | cc0-1.0 | 413 | 0.031477 | import numpy a | s np
vec_bitstring_3 = np. | vectorize(lambda x: np.binary_repr(x,width=3) )
def board_to_int(v):
t = vec_bitstring_3(v)
return int(''.join(np.apply_along_axis(lambda x: ''.join(x), 1,t)),2)
def int_to_board(i):
#i = '154444257952488798331863040'
s = bin(int(i))[2:].zfill(108)
v = np.array([int(s[i:i+3],2) for i in range(0,l... |
ElitosGon/medgoproject | medgointranet/migrations/0013_atencion_formulario.py | Python | apache-2.0 | 507 | 0.001976 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2017-03-07 02:03
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('medgointranet', '0012_motivoanulacion'),
]
operations = [
migra | tions.AddField(
model_name='atencion',
name='formulario',
field=models.BooleanField(default=False, verbose_name='¿Docto | r completo formulario?'),
),
]
|
yeti-platform/yeti | plugins/feeds/public/alienvault_ip_reputation.py | Python | apache-2.0 | 1,699 | 0 | import logging
from datetime import timedelta
from core import Feed
from core.errors import ObservableVal | idationError
from core.observables import Ip
class AlienVaultIPReputation(Feed):
default_values = {
"frequency": timedelta(hours=4),
"name": "AlienVaultIPReputation",
"source": "http://reputation.alienvault.com/reputation.data",
"description": "Reputation IP generated by Alienvault... | comment=None,
header=None,
names=[
"IP",
"number_1",
"number_2",
"Tag",
"Country",
"City",
"Coord",
"number_3",
],
):
self.ana... |
airelil/pywinauto-64 | pywinauto/unittests/test_common_controls.py | Python | lgpl-2.1 | 33,312 | 0.005734 | # GUI Application automation and testing library
# Copyright (C) 2006 Mark Mc Mahon
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either version 2.1
# of the License, or (at your opti... | to.controls import common_controls
from pywinauto.controls.common_controls import *
from pywinauto.win32structures import RECT
from pywinauto.controls import WrapHandle
#from pywinauto.controls.HwndWrapper import HwndWrapper
from pywinauto import findbestma | tch
from pywinauto.SendKeysCtypes import is_x64
from pywinauto.RemoteMemoryBlock import AccessDenied
from pywinauto.RemoteMemoryBlock import RemoteMemoryBlock
controlspy_folder = os.path.join(
os.path.dirname(__file__), "..\..\controlspy0998")
if is_x64():
controlspy_folder = os.path.join(controlspy_folder, 'x... |
knowmetools/km-api | km_api/functional_tests/know_me/profile/profile_topics/test_profile_topic_list.py | Python | apache-2.0 | 2,774 | 0 | from rest_framework import status
from test_utils import serialized_time
def test_get_profile_topics(
api_client, enable_premium_requirement, profile_topic_factory, user_factory
):
"""
Premium users should be able to list their own profile topics.
"""
password = "password"
user = user_factory... | .primary_email.email, password)
topic = profile_topic_factory(profile__km_user__user=user)
url = f"/know-me/profile/profiles/{topic.profile.pk}/topics/"
response = api_client.get(url)
assert response.status_code == status.HTTP_200_OK
assert response.json() == [
{
"id": topic.p... | ld_full_url(
f"/know-me/profile/profile-topics/{topic.pk}/"
),
"created_at": serialized_time(topic.created_at),
"updated_at": serialized_time(topic.updated_at),
"is_detailed": topic.is_detailed,
"items_url": api_client.build_full_url(
... |
facebook/fbthrift | thrift/test/py/TestSerializationSorted.py | Python | apache-2.0 | 3,066 | 0.000326 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# 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 ... | t)
self.assertNotEqual(blob, unsort | ed_blob)
self.assertEqual(blob, sorted_blob)
self.assertEqual(static_struct, sorted_struct)
def testSetSorted(self):
unsorted_set = set(["5", "4", "3", "2", "1", "0"])
static_struct = SortedSetStruct(aSet=unsorted_set)
unsorted_blob = (
textwrap.dedent(
... |
jjas0nn/solvem | tensorflow/lib/python2.7/site-packages/tensorflow/python/debug/lib/stepper_test.py | Python | mit | 32,092 | 0.002586 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | /read:0", "b:0", "a:0"},
set(stepper.closure_elements()))
with self.assertRaisesRegexp(
ValueError,
"Target \"f:0\" is not in the transi | tive closure for the fetch of the "
"stepper"):
stepper.cont("f:0")
def testContToNodeNameShouldReturnTensorvalue(self):
stepper = NodeStepper(self.sess, "e:0")
cont_result = stepper.cont("c")
self.assertAllClose(6.0, cont_result)
def testUsingNamesNotUsingIntermediateTensors(self):
... |
jellis18/enterprise | enterprise/signals/utils.py | Python | mit | 29,066 | 0.001239 | # utils.py
"""
Utilities module containing various useful
functions for use in other modules.
"""
import logging
import numpy as np
import scipy.linalg as sl
import scipy.sparse as sps
import scipy.special as ss
from pkg_resources import Requirement, resource_filename
from scipy.integrate import odeint
from scipy.int... | gnmatrix(designmat, fastDesign=True):
"""
Stabilize the timing-model design matrix.
:param designmat: Pulsar timing model design matrix
:param fastDesign: Stabilize the design matrix the fast way [True]
:return: Mm: Stabilized timing model design matrix
"""
Mm = designmat.copy()
if f... | linalg.svd(Mm)
Mm = u[:, : len(s)]
return Mm
###################################
# Deterministic GW signal functions
###################################
def make_ecc_interpolant():
"""
Make interpolation function from eccentricity file to
determine number of harmonics to use for a given
... |
kirberich/djangae | djangae/db/constraints.py | Python | bsd-3-clause | 11,037 | 0.003534 | import datetime
import logging
from django.conf import settings
from django.core.exceptions import NON_FIELD_ERRORS
from google.appengine.api.datastore import Key, Delete, MAX_ALLOWABLE_QUERIES
from google.appengine.datastore.datastore_rpc import TransactionOptions
from google.appengine.ext import db
from .unique_uti... |
instance=entity_key,
created=now
))
elif existing_marker.instance != entity_key and key_exists(existing_marker.instance):
fields_and_values = identifier_key.name().split("|")
table_name = fields_and_values[0]
fields_and_values = fi... | in fields_and_values]
raise IntegrityError("Unique constraint violation for kind {} on fields: {}".format(table_name, ", ".join(fields)))
elif existing_marker.instance != entity_key:
markers_to_create.append(UniqueMarker(
key=identifier_key,
instance=entit... |
samueldotj/TeeRISC-Simulator | tests/configs/simple-atomic-dummychecker.py | Python | bsd-3-clause | 2,321 | 0 | # Copyright (c) 2013 ARM Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality ... | LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF S | UCH DAMAGE.
#
# Authors: Andreas Hansson
from m5.objects import *
from base_config import *
root = BaseSESystemUniprocessor(mem_mode='atomic',
cpu_class=AtomicSimpleCPU,
checker=True).create_root()
|
obrienadam/boTAB | boTAB.py | Python | gpl-2.0 | 2,667 | 0.003 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
boTAB
=====
This solver uses the popular TAB model to simulate the atomization of droplets
Author: Adam O'Brien
"""
from input import *
from math import exp, cos, sin, sqrt
from fluid import *
from evaporation import *
from TAB import *
from output import *
impor... | the input file
setObjectParametersFromInput(userInput, freestream, initialDroplet, dropletInlet)
# Set-up the simulation parameters in accordance with the input
maxTime = userInput["maxTime"]
nTimeSteps = userInput["nTim | eSteps"]
# Initialize a droplet list, with one copy of the initial droplet
droplets = [cp.deepcopy(initialDroplet)]
# Initialize misc parameters
dt = maxTime/nTimeSteps
t = [0.]
nChildDroplets = 0
# Begin the simulation
print "\nBeginning time-stepping..."
####################... |
CSL-Consulting/asterisk-installation-script | asterisk-installation-script.py | Python | gpl-2.0 | 2,662 | 0.009016 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###################### | ###############################################
# Author: Cristian Segura L. #
# Email: cristian+dot+segura+dot+lepe+arroba+dot+gmail+dot+com | #
# Creation Date: Sat nov 8 20:11:38 CLST 2014 #
# Version: 0.1 #
# License: GPL v2.0 (check LICENSE file) #
# Usage: Installation of Asterisk IP PBX #
# Dependencies: ... |
eJRF/ejrf | questionnaire/tests/factories/theme_factory.py | Python | bsd-3-clause | 196 | 0.005102 | import factory
from questionnaire.models import Theme
class ThemeFac | tory(factory.DjangoModelFactory):
class Meta:
model = Theme
| name = "A title"
description = 'Description' |
csridhar/58A78C12-3B74-48F6-B265-887C33ED5F98-odat-5DD613ED-1FE0-4D6A-8A20-4C26C3F2C95B | src/main.py | Python | mit | 528 | 0.007576 | #!/usr/bin/env python
from server import Serve
from utils import get_authenticated_user
import os
import sys
authenticated_user = None
try:
authent | icated_user = get_authenticated_user('server.cfg')
except IOError:
print ("File 'server.cfg' doesn't exist on disk. Please ensure that it"
" does and try again.")
sys.exit(1)
except ValueError:
print ("'server.cfg' is empty. P | lease run 'python get_oauth_token.py' prior.")
sys.exit(1)
# Start appserver
app = Serve(__name__, authenticated_user)
|
yuweijun/learning-programming | language-python/getitem.py | Python | mit | 281 | 0.064057 | #! /usr/bin/python
class Indexer:
def __geti | tem__(self, index):
return index ** 2
x = Indexer()
for i in range(5):
print x[i],
class Stepper:
def __getitem__ | (self, index):
return self.data[index]
s = Stepper()
s.data = "spam"
for x in s:
print x,
print s.data[0] |
dragonfly-science/django-custom-user | test_settings/settings_subclass.py | Python | bsd-3-clause | 339 | 0 | DEBUG = True
USE_ | TZ = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
| }
}
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'custom_user',
'test_custom_user_subclass',
]
SECRET_KEY = 'not_random'
AUTH_USER_MODEL = 'test_custom_user_subclass.MyCustomEmailUser'
|
rdegraw/numbers-py | prime_requests.py | Python | unlicense | 748 | 0.05615 | #-----------------------------------------------------
#
# Find the next prime number as the user keeps asking
#
#-----------------------------------------------------
import sys
#------------------------
# is the number a prime?
#------------------------
def is_prime( num ):
for i in range( 2, num ):
if num % i ==... | ue:
response | = raw_input( "Print the next prime? [Y]es " )
if response.upper().startswith('Y'):
while True:
curr_prime += 1
if is_prime(curr_prime):
print curr_prime
break
else:
break
|
bitmazk/django-monitoring | monitoring/views.py | Python | mit | 2,525 | 0 | """Views for the monitoring app."""
from django.contrib.auth.decorators import login_required
from django.db.models import Count
from django.http import Http404
from django.utils.decorators import method_decorator
from django.views.generic import ListView, TemplateView
from .register import monitor
class MonitoringV... | ).get_queryset()
qs = qs.values('date_created').annotate(
count=Count('date_created')).distinct()
return qs
class MonitoringView(TemplateView):
template_name = 'monitoring/index.html'
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
if no... | atch(
request, *args, **kwargs)
def get_context_data(self, **kwargs):
ctx = super(MonitoringView, self).get_context_data(**kwargs)
ctx.update({
'monitor': monitor,
})
return ctx
|
olexiim/edx-platform | common/test/acceptance/pages/studio/users.py | Python | agpl-3.0 | 6,650 | 0.001955 | """
Page classes to test either the Course Team page or the Library Team page.
"""
from bok_choy.promise import EmptyPromise
from bok_choy.page_object import PageObject
from ...tests.helpers import disable_animations
from . import BASE_URL
def wait_for_ajax_or_reload(browser):
"""
Wait for all ajax requests t... | .q(css='.form-create.create-user .user-email-input').fill(email)
def click_submit_new_user_form(self):
""" Submit the "New User" form """
self.q(css='.form-create.create-user .action-primary').click()
wait_for_ajax_or_reload(self.browser)
class LibraryUsersPage(UsersPage):
"""
Lib... |
@property
def url(self):
"""
URL to the "User Access" page for the given library.
"""
return "{}/library/{}/team/".format(BASE_URL, unicode(self.locator))
class UserWrapper(PageObject):
"""
A PageObject representing a wrapper around a user listed on the course/library... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.