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 |
|---|---|---|---|---|---|---|---|---|
kubeflow/pipelines | components/gcp/container/component_sdk/python/tests/google/dataproc/test__submit_pig_job.py | Python | apache-2.0 | 1,768 | 0.007353 | # Copyright 2018 The Kubeflow Authors
#
# 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... | mock_submit_job.assert_called_with('mock-project', 'mock-region', 'mock-cluster',
{
| 'pigJob': {
'queryList': { 'queries': [
'select * from mock_table'
]},
'scriptVariables': {'var-1': 'value1'},
'continueOnFailure': True
},
'labels': {
'key1... |
samsath/skeleton | src/website/calendar/management/commands/import_weather.py | Python | gpl-3.0 | 1,499 | 0.006004 | import json
import requests
from django.conf import settings
from website.calendar.models import WeatherTypes, Calendar
from django.conf import settings
from datetime import datet | ime
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Import the weather information"
def handle(self, **options):
params = {
'key':sett | ings.APIXU_KEY,
'q':settings.APIXU_LOCATION,
'days':settings.APIXU_DAYS
}
r = requests.get('https://{0}'.format(settings.APIXU_URL), params=params)
if r.status_code == 200:
data = r.json()
for day in data['forecast']['forecastday']:
... |
chakki-works/elephant_sense | scripts/features/charactor_extractor.py | Python | apache-2.0 | 3,901 | 0.002072 | import re
from bs4 import BeautifulSoup
from scripts.features.feature_extractor import FeatureExtractor
from scripts.data.cleaning import clean_code
def clean_html_tags(html_text):
soup = BeautifulSoup(html_text, 'html.parser')
if soup.find("h") is not None:
soup.find("h").extract()
cleaned_text... | (html_text):
"""Qiitaのコードを取り除きます
:param html_text:
:return:
"""
soup = BeautifulSoup(html_text, 'html.parser')
[x.extract() for x in soup.findAll(class_="code-frame")]
[x.extract() for x in soup.findAll("code")]
cleaned_text = soup.get_text()
cleaned_text = ''.join(cleaned_text.split... | eaned_text
def cleaning(text):
replaced_text = clean_code(html_text=text) # remove source code
replaced_text = clean_html_tags(html_text=replaced_text) # remove html tag
replaced_text = re.sub(r'\$.*?\$+', '', replaced_text) # remove math equation
replaced_text = re.sub(r'[@@]\w+', '', replaced_tex... |
akatsoulas/mozillians | lib/jinjautils.py | Python | bsd-3-clause | 1,577 | 0 | # TODO: let's see if we can get rid of this, it's garbage
from django.contrib.admin import options, actions, sites
from django.template import loader
import jingo
def django_to_jinja(template_name, context, **kw):
"""
We monkeypatch Django admin's render_to_response to work in our Jinja
environment. We ... | 's functions. An example can be found in the users
app.
"""
if context is None:
context = {}
context_instance = kw.pop('context_instance')
request = context_instance['request']
for d in context_instance.dicts:
context.update(d)
return jingo.render(request, template_name, con... | |
MoebiuZ/OpcodeOne | oldfiles/oldcode/tools/assemblerold/functions.py | Python | apache-2.0 | 5,835 | 0.048517 | import re
import sys
import struct
import codecs
class REMatcher(object):
def __init__(self, matchstring):
self.matchstring = matchstring
def match(self,regexp):
self.rematch = re.match(regexp, self.matchstring, re.IGNORECASE)
return bool(self.rematch)
def group(self,i):
... | 1)] = self.inst_addr
elif m.match("\.code\Z"): # Section.code
self.in_code = True
elif m.match("\.data\Z"): # Section .data
self.in_code = False
elif m.match(self.LABEL + "\.DS\s+(?:\'|\")(.+)(?:\'|\")\Z"): # Data String
self.checkInData()
self.newlabel(m.group(1))
i = 0
for char i... | self.push8( ord(char.encode('latin-1')) )
i += 1
if i % 3 == 0:
self.inst_addr += 1
self.push8(0x00) # String terminator
i += 1
# Fix word alignment
while i % 3 != 0:
self.push8(0x00)
i += 1
self.inst_addr += 1
elif m.match(self.LABEL + "\.DW\s+(" + self.HEX + ")... |
tartley/pyweek11-cube | source/view/modelview.py | Python | bsd-3-clause | 682 | 0.001466 | from _ | _future__ import division
from pyglet.gl import gl, glu
class ModelView(object):
'''
Manage modelview matrix, performing the MVC's 'view' parts of the 'camera'
'''
def __init__(self, camera):
self.camera = camera
def set_identity(self):
gl.glMatrixMode(gl.GL_MODELVIE... | look_at = self.camera.look_at
glu.gluLookAt(
position.x, position.y, position.z,
look_at.x, look_at.y, look_at.z,
0, 1, -1)
|
vinicius-ronconi/WeatherForecast | WeatherForecast/wsgi.py | Python | mit | 408 | 0 | """
WSGI config for WeatherForecast project.
It exposes the WSGI callable as a module-level var | iable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_ws | gi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "WeatherForecast.settings")
application = get_wsgi_application()
|
Parallel-in-Time/pySDC | pySDC/projects/AllenCahn_Bayreuth/run_temp_forcing_benchmark.py | Python | bsd-2-clause | 5,134 | 0.002922 | from argparse import ArgumentParser
import numpy as np
from mpi4py import MPI
from pySDC.helpers.stats_helper import filter_stats, sort_stats
from pySDC.implementations.collocation_classes.gauss_radau_right import CollGaussRadau_Right
from pySDC.implementations.controller_classes.controller_MPI import controller_MPI
f... | ng_setup'), sortby='time')
out = f'Setup time on rank {time_rank}: {timing[0][1]:.4f} sec.'
print(out)
timing = sort_stats(filter_stats(stats, type='timing_run'), sortby='time')
out = f'Time to solution on rank {time_rank}: {timing[0][1]:.4f} sec.'
print(out)
if __name__ == "_... | add_argument("-n", "--nprocs_space", help='Specifies the number of processors in space', type=int)
args = parser.parse_args()
name = 'AC-bench-tempforce'
run_simulation(name=name, nprocs_space=args.nprocs_space)
|
bayespy/bayespy | bayespy/inference/vmp/nodes/gate.py | Python | mit | 7,980 | 0.001504 | ################################################################################
# Copyright (C) 2014 Jaakko Luttinen
#
# This file is licensed under the MIT License.
################################################################################
"""
"""
import numpy as np
from bayespy.utils import misc
from .nod... | ermi | nistic._ensure_moments(
z,
CategoricalMoments,
categories=categories
)
nodes = [node[...,None] for node in nodes]
combined = Concatenate(*nodes)
return Gate(z, combined)
|
kostyll/Cryptully | cryptully/qt/qNickInputWidget.py | Python | gpl-3.0 | 2,500 | 0.0024 | from PyQt4.QtCore import Qt
from PyQt4.QtGui import QHBoxLayout
from PyQt4.QtGui import QLabel
from PyQt4.QtGui import QLineEdit
from PyQt4.QtGui import QMessageBox
from PyQt4.QtGui import QPixmap
from PyQt4.QtGui import QPushButton
from PyQt4.QtGui import QVBoxLayout
from PyQt4.QtGui import QWidget
import qtUtils
fr... | ils.getAbsoluteImagePath(image)).scaledToWidth(imageWidth, Qt.SmoothTransformation))
# Nick field
self.nickLabel = QLabel("Nickname:", self)
self.nickEdit = QLineEdit(nick, self)
self.nickEdit.setMaxLength(constants.NICK_MAX_LEN)
self.nickEdit.returnPressed.connect(self.__connec... | # Connect button
self.connectButton = QPushButton("Connect", self)
self.connectButton.resize(self.connectButton.sizeHint())
self.connectButton.setAutoDefault(False)
self.connectButton.clicked.connect(self.__connectClicked)
hbox = QHBoxLayout()
hbox.addStretch(1)
... |
cloudbase/nova | nova/tests/unit/policy_fixture.py | Python | apache-2.0 | 4,908 | 0.000204 | # Copyright 2012 Hewlett-Packard Development Company, L.P.
#
# 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 applicabl... | implement ``_prepare_policy`` in the subclass, and adjust the
``policy_file`` accordingly.
"""
def _prepare_policy(self):
"""Allow changing of the policy before we get started"""
pass
def setUp(self):
super(RealPolicyFixture, self).setUp()
# policy_file can be overri... | _policy')
nova.policy.reset()
nova.policy.init()
self.addCleanup(nova.policy.reset)
def set_rules(self, rules):
policy = nova.policy._ENFORCER
policy.set_rules(oslo_policy.Rules.from_dict(rules))
def add_missing_default_rules(self, rules):
"""Adds default rules ... |
CognizantOneDevOps/Insights | PlatformAgents/com/cognizant/devops/platformagents/agents/alm/qtest/QtestAgent.py | Python | apache-2.0 | 18,777 | 0.002929 | #-------------------------------------------------------------------------------
# Copyright 2017 Cognizant Technology Solutions
#
# 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:... | ypes = dynamicTemplate.get('testRunsType', {})
if 'test-runs' in almEntities:
for testRunType in testRunTypes:
almEntities[testRunType] = almEntities.get('test-runs', {})
almEntities.pop('test-runs', {})
payloadConfig = dict()
for entityType in almEntities... | payload['fields'] = ['*']
entity = entityType
if entityType in testRunTypes:
testRunType = testRunTypes[entityType]
payload['query'] = testRunType.get('query') + " and " + "'Last Modified Date' >= '%s'"
entity = 'test-runs'
... |
Balandat/cont_no_regret | old_code/NLopt.py | Python | mit | 1,667 | 0.010198 | '''
Nonlinear optimization by use of Affine DualAveraging
@author: Maximilian Balandat
@date: May 13, 2015
'''
import numpy as np
from .Domains import nBox
class NLoptProblem():
""" Basic class describing a Nonlinear Optimization problem. """
def __init__(self, domain, objective):
""" Construct... | bounds = np.array(self.domain.bounds)
while t<T:
A += self.objective.grad(actions[-1])
actions.append(quicksample(bounds, A, etas[t]))
t += 1
| return actions
def quicksample(bounds, A, eta):
""" Function returning actions sampled from the solution of the Dual Averaging
update on an Box with Affine losses, Exponential Potential. """
C1, C2 = np.exp(-eta*A*bounds[:,0]), np.exp(-eta*A*bounds[:,1])
Finv = lam... |
asimshankar/tensorflow | tensorflow/python/ops/rnn_cell_impl.py | Python | apache-2.0 | 61,366 | 0.004856 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | ll.
ASSERT_LIKE_RNNCELL_ERROR_REGEXP = "is not an RNNCell"
def assert_like_rnncell(cell_name, cell):
"""Raises a | TypeError if cell is not like an RNNCell.
NOTE: Do not rely on the error message (in particular in tests) which can be
subject to change to increase readability. Use
ASSERT_LIKE_RNNCELL_ERROR_REGEXP.
Args:
cell_name: A string to give a meaningful error referencing to the name
of the functionargumen... |
simongibbons/numpy | numpy/polynomial/__init__.py | Python | bsd-3-clause | 6,788 | 0.000148 | """
A sub-package for efficiently dealing with polynomials.
Within the documentation for this sub-package, a "finite power series,"
i.e., a polynomial (also referred to simply as a "series") is represented
by a 1-D numpy array of the polynomial's coefficients, ordered from lowest
order term to highest. For example, a... | ", "Chebyshev",
"legendre", "Legendre",
"hermite", "Hermite",
"hermite_e", "HermiteE",
"laguerre", "Laguerre",
]
def set_default_printstyle(style):
""" |
Set the default format for the string representation of polynomials.
Values for ``style`` must be valid inputs to ``__format__``, i.e. 'ascii'
or 'unicode'.
Parameters
----------
style : str
Format string for default printing style. Must be either 'ascii' or
'unicode'.
No... |
berserkerbernhard/Lidskjalv | code/networkmonitor/modules/serviceutilities/rdp.py | Python | gpl-3.0 | 1,463 | 0 | i | mport subprocess
import os
import dialog
class RDP():
def __init__(self):
self.d = dialog.Dialog(dialog="dialog")
self.storage_path = os.path.expanduser("~/LidskjalvData")
def show_rdp_menu(self, site, host):
# """ """
# FIXME
# print("FIXME: rdp_menu")
# sys.... | choices.append(["", " "])
choices.append(["Q", "Quit"])
sz = os.get_terminal_size()
# width = sz.columns
# height = sz.lines
code, tag = self.d.menu(
"Choose an action",
height=sz.lines - 5,
width=sz.columns - ... |
sparkslabs/kamaelia_ | Sketches/JT/Jam/library/trunk/Axon/SchedulingComponent.py | Python | apache-2.0 | 3,988 | 0.003761 | # -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License, Version 2.0 (the "Lic... | vent):
""" Remove | a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue)
def eventReady(self):
""" Returns true if there is an event ready to be processed """
if self.eventQueue:
eventTime = self.eventQueue[0][0]
if time.time() >... |
krzychb/rtd-test-bed | components/efuse/test_efuse_host/efuse_tests.py | Python | apache-2.0 | 16,074 | 0.004977 | #!/usr/bin/env python
from __future__ import print_function, division
import unittest
import sys
try:
import efuse_table_gen
except ImportError:
sys.path.append("..")
import efuse_table_gen
'''
To run the test on local PC:
cd ~/esp/esp-idf/components/efuse/test_efuse_host/
./efuse_tests.py
'''
class P... | le_gen.InputError, | "overlap"):
t.verify()
def test_empty_field_name_fail(self):
csv = """
# field_name, efuse_block(EFUSE_BLK0..EFUSE_BLK3), bit_start(0..255), bit_count, comment
, EFUSE_BLK3, , 5,
name2, EFUSE_BLK2, ... |
ironexmaiden/csd_post_sw | docs/conf.py | Python | mit | 7,270 | 0.005227 | # -*- coding: utf-8 -*-
#
# Bottle documentation build configuration file, created by
# sphinx-quickstart on Thu Feb 18 18:09:50 2010.
#
# 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 ... | ts, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_use_modindex = True
# Example ... | tersphinx: refer to the Python standard library.
intersphinx_mapping = {'python': ('http://docs.python.org/', None),
'werkzeug': ('http://werkzeug.pocoo.org/docs/', None)}
autodoc_member_order = 'bysource'
locale_dirs = ['./locale']
|
artPlusPlus/elemental-backend | elemental_backend/serialization/_immutable_type_resource_io.py | Python | mpl-2.0 | 180 | 0 | from marshmallow import fields
from ._resource_io import ResourceSchema
class ImmutableTypeResourceSchema(ResourceSchema):
| label = fields.String()
| doc = fields.String()
|
fernandalavalle/mlab-ns | server/mapreduce/lib/simplejson/__init__.py | Python | apache-2.0 | 12,383 | 0.001615 | #!/usr/bin/env python
r"""A simple, fast, extensible JSON encoder and decoder
JSON (JavaScript Object Notation) <http://json.org> is a subset of
JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data
interchange format.
simplejson exposes an API familiar to uses of the standard libr | ary
marshal and pickle modules.
Enco | ding basic Python object hierarchies::
>>> import simplejson
>>> simplejson.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> print simplejson.dumps("\"foo\bar")
"\"foo\bar"
>>> print simplejson.dumps(u'\u1234')
"\u1234"
>>> print simplejson.du... |
pattisdr/osf.io | admin/nodes/urls.py | Python | apache-2.0 | 2,100 | 0.003333 | from django.conf.urls import url
from admin.nodes import views
app_name = 'admin'
urlpatterns = [
url(r'^$', views.NodeFormView.as_view(),
name='search'),
url(r'^flagged_spam$', views.NodeFlaggedSpamList.as_view(),
name='flagged-spam'),
url(r'^known_spam$', views.NodeKnownSpamList.as_view(... | +)/$', views.NodeVi | ew.as_view(),
name='node'),
url(r'^(?P<guid>[a-z0-9]+)/logs/$', views.AdminNodeLogView.as_view(),
name='node-logs'),
url(r'^registration_list/$', views.RegistrationListView.as_view(),
name='registrations'),
url(r'^stuck_registration_list/$', views.StuckRegistrationListView.as_view(),... |
wangyum/tensorflow | tensorflow/contrib/seq2seq/python/kernel_tests/decoder_test.py | Python | apache-2.0 | 6,979 | 0.006591 | # 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... | puts = np.random.randn(max_time, batch_size,
input_depth).astype(np.float32)
else:
inputs = np.random.randn(batch_size, max_time,
input_depth).astype(np.float32)
cell = core_rnn_cell.LSTMCell(cell_depth)
helper = helper_py.Train... | itial_state=cell.zero_state(
dtype=dtypes.float32, batch_size=batch_size))
final_outputs, final_state, final_sequence_length = (
decoder.dynamic_decode(my_decoder, output_time_major=time_major,
maximum_iterations=maximum_iterations))
def _t(shape):
... |
fkorotkov/pants | src/python/pants/java/nailgun_client.py | Python | apache-2.0 | 7,704 | 0.010903 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import errno
import ... | as e:
raise self.NailgunError('Problem communicating with nailgun server at {}:{}: {!r}'
.format(self._host, self._port, e))
except NailgunProtocol.ProtocolError as e:
raise self.NailgunError('Problem in nailgun protocol with nailgun server at {}:{}: {!r}'
... |
def __repr__(self):
return 'NailgunClient(host={!r}, port={!r}, workdir={!r})'.format(self._host,
self._port,
self._workdir)
|
b29308188/cs598vqa | src/CBP/reuse_test.py | Python | mit | 98 | 0.040816 | import tensor | flow as tf
def f():
with tf.variable_scope('A') as scope:
print scope.reu | se
f()
|
jdmcbr/Shapely | tests/test_multilinestring.py | Python | bsd-3-clause | 3,200 | 0.000625 | from . import unittest, numpy, test_int_types
from .test_multi import MultiGeometryTestCase
from shapely.geos import lgeos
from shapely.geometry import LineString, MultiLineString, asMultiLineString
from shapely.geometry.base import dump_coords
class MultiLineStringTestCase(MultiGeometryTestCase):
def test_multi... | l = MultiLineString([coords1, coords2])
copy = MultiLineString(ml)
self.assertIsInstance(copy, MultiLineString)
self.assertEqual('MultiLineString',
lgeos.GEOSGeomType(copy._geom).decode('ascii'))
self.assertEqual(len(copy.geoms), 2)
self.assertEqual(dump_... | self):
from numpy import array
from numpy.testing import assert_array_equal
# Construct from a numpy array
geom = MultiLineString([array(((0.0, 0.0), (1.0, 2.0)))])
self.assertIsInstance(geom, MultiLineString)
self.assertEqual(len(geom.geoms), 1)
self.assertEqua... |
jkatzsam/matchtools | matchtools/hamming.py | Python | bsd-3-clause | 1,270 | 0.040157 | # -*- coding: utf-8 -*-
"""hamming.py: Return the Hamming distance between two integers (bitwise)."""
__author__ = "Russell J. Funk"
__date__ = "February 7, 2013"
__copyright__ = "Copyright (C) 2013"
__reference__ = ["http://wiki.python.org/moin/BitManipulation",
"http://en.wikipedia.org/wiki/Hamming... | Value Error: Inputs must have the same bit length.
"""
if len(a) != len(b):
raise ValueError("Inputs must have same bit length.")
else:
distance = 0
for i in range(len(a)):
if a[i] != b[i]:
distance += 1
retu | rn distance
def hamming_ratio(a, b, bits = 384):
"""Calculates the hamming ratio between two integers
represented as a list of bits.
Args:
a and b must be lists of 1s and 0s; the calculation
is relative to the number of bits.
Returns:
The hamming ratio ... |
afrantzis/pixel-format-guide | tests/__init__.py | Python | lgpl-2.1 | 768 | 0 | # Copyright © 2017 Collabora Ltd.
#
# This file is part of pfg.
#
# pfg 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.
#
# pf... | Y or FITNESS
# FOR A PARTICU | LAR PURPOSE. See the GNU Lesser General Public License for
# more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pfg. If not, see <http://www.gnu.org/licenses/>.
#
# Authors:
# Alexandros Frantzis <[email protected]>
|
mir-group/flare | flare/utils/parameter_helper.py | Python | mit | 49,237 | 0.001361 | """
For multi-component systems, the configurational space can be highly complicated.
One may want to use different hyper-parameters and cutoffs for different interactions,
or do constraint optimisation for hyper-parameters.
To use more hyper-parameters, we need special kernel function that can differentiate different... | cutoff_groups (dict): Define different cutoffs f | or different species
parameters (dict): Define signal variance, length scales, and cutoffs
constraints (dict): If listed as False, the cooresponding hyperparmeters
will not be trained
allseparate (bool): If True, define each type pair/triplet into a
separate group.
... |
bureaucratic-labs/yargy | yargy/api.py | Python | mit | 1,590 | 0 |
from .check import assert_type
from .predicates import (
eq,
is_predicate,
Predicate,
AndPredicate,
OrPredicate,
NotPredicate,
)
from .relations import (
is_relation,
Main,
Relation,
AndRelation,
OrRelation,
NotRelation
)
from .rule import (
is_rule,
Production,
... | on = Production([prepare_production_item(_) for _ in items])
return Rule([production])
empty = EmptyRule
forward = ForwardRule
def and_(*items):
if all(is_predicate(_ | ) for _ in items):
return AndPredicate(items)
elif all(is_relation(_) for _ in items):
return AndRelation(items)
else:
types = [type(_) for _ in items]
raise TypeError('mixed types: %r' % types)
def or_(*items):
if all(is_predicate(_) for _ in items):
return OrPredi... |
ghchinoy/tensorflow | tensorflow/contrib/distribute/python/monitor.py | Python | apache-2.0 | 2,460 | 0.005691 | # Copyright 2018 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... | sorflow.python.framework import errors
from tensorflow.python.ops import variables
class Monitor(object):
"""Executes training steps, recovers and checkpoints.
Note that this class is particularly preliminary, experimental, and
expected | to change.
"""
# TODO(isaprykin): Support step functions that need multiple session calls.
# TODO(isaprykin): Support extra arguments to the step function.
# TODO(isaprykin): Support recovery, checkpointing and summaries.
def __init__(self, step_callable, session=None):
"""Initialize the Monitor with com... |
lechuckcaptain/urlwatch | lib/urlwatch/__init__.py | Python | bsd-3-clause | 598 | 0.001672 | """A tool for monitoring webpages for updates
urlwatch is intended to help you watch changes in webpages and get notified
(via email, in your terminal or with a custom-written reporter class) of any
changes. The change notification will include the URL that | has changed and
a unified diff of what has changed.
"""
pkgname = 'urlwatch'
__copyright__ = 'Copyright 2008-2016 Thomas Perl'
__author__ = 'Thomas Perl <[email protected]>'
__license__ = 'BSD'
__url__ = 'http://thp.io/2008/urlwatch/'
__version__ = '2.5'
__user_agent__ = '%s/%s (+http://thp.io/200 | 8/urlwatch/info.html)' % (pkgname, __version__)
|
OpenDaisy/daisy-client | daisyclient/openstack/common/_i18n.py | Python | apache-2.0 | 1,733 | 0 | # 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, software
# d... | oslo.i18n.TranslatorFactory(domain='glanceclient')
# The primary translation function using the well-known name "_"
| _ = _translators.primary
# Translators for log levels.
#
# The abbreviated names are meant to reflect the usual use of a short
# name like '_'. The "L" is for "log" and the other letter comes from
# the level.
_LI = _translators.log_info
_LW = _translators.log_warning
_LE = _translato... |
jaric-thorning/ProjectCapital | GUI.py | Python | mit | 6,637 | 0.02019 | import datetime
from Tkinter import *
import tkMessageBox
import tkFileDialog
import random
import time
import share
class App(object):
'''Controls the running of the app'''
def __init__(self, master = None):
'''A controller class that runs the app
Constructor: Controller(object)'''
#... | ill = X)
self.canvas = Canvas(master, bg | = "black", height = self._canvas_height, width = self._canvas_width)
self.canvas.pack(side = TOP, fill = BOTH, expand = False)
#File Button
# create a toplevel menu
menubar = Menu(master)
menubar.add_command(label="Hello!")
menubar.add_command(label="Quit!")
... |
nikdoof/dropbot | dropbot/bot.py | Python | mit | 28,390 | 0.001937 | from datetime import datetime
from xml.etree import ElementTree
import pkgutil
from json import loads as base_loads
from random import choice
import logging
import re
import urlparse
from sleekxmpp import ClientXMPP
from redis import Redis, ConnectionPool
import requests
from humanize import intcomma, naturaltime, int... | if body:
| msg.reply(body).send()
# Helpers
def _system_picker(self, name):
systems = self.map.get_systems(name)
if len(systems) > 1:
if len(systems) > 10:
return 'More than 10 systems match {}, please provide a more complete name'.format(name)
return 'Did you mea... |
prerit2010/web-frontend | config.py | Python | gpl-3.0 | 49 | 0 | SERV | ER_HOSTNAME = "127.0.0.1"
SE | RVER_PORT = 9671
|
pokermania/pokerengine | tests/test_game.py | Python | gpl-3.0 | 244,876 | 0.009131 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2006 - 2010 Loic Dachary <[email protected]>
# Copyright (C) 2006 Mekensleep
#
# Mekensleep
# 26 rue des rosiers
# 75004 Paris
# [email protected]
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of ... | meNoCase('player1'), 1)
self.failUnlessEqual(self.game.getSerialByNameNoCase('pLaYEr2'), 2)
self.failUnlessEqual(self.game.getSerialByNameNoCa | se('unknown'), 0)
# ---------------------------------------------------------
def testSetPosition(self):
"""Test Poker Game: Set position"""
self.game.setMaxPlayers(3)
# Create players
player1 = self.AddPlayerAndSit(1, 2)
player2 = self.AddP... |
withanage/HEIDIEditor | static/WysiwigEditor/cgi/createJSON.py | Python | gpl-3.0 | 4,094 | 0.006839 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import os
import xmltodict
from bs4 import BeautifulSoup
from bs4 import CData
UPLOAD_DIR = '../html/uploads'
METADATA_NAME = 'metadata.xml'
PUBLISHER_NAME = 'Heidelberg University Press'
PUBLISHER_LOC = 'Heidelberg'
jsondata = [{'selected': True, 'type': 'book'}... |
i.string.replace_with(cdata)
for i in soup.find_all('mixed-citation'):
if i.string is None:
string = ''.join([str(j) for j in i.contents])
cdata = CData(string)
i.string = ''
i.string.replace_with(cdata)
return str(soup)
for root, dirs, fi... | ta)
xmldict = xmltodict.parse(xmldata)
tagset = predictTagset(xmldict)
xmldict['tagset'] = tagset
xmldict['id'] = root.split('/')[-1]
xmldict[tagset] = xmldict['metadata']
del xmldict['metadata']
xmldict = validate(xmldict)
jsondata[0].update(xmldict)
... |
hjuutilainen/autopkg-virustotalanalyzer | VirusTotalAnalyzer/VirusTotalAnalyzer.py | Python | apache-2.0 | 12,577 | 0.001193 | #!/usr/bin/env python
#
# Copyright 2016 Hannes Juutilainen
#
# 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 applicabl... | "VIRUSTOTAL_AUTO_SUBMIT": {
"required": False,
"description": "If item is not found in VirusTotal database, automatically submit it for scanning.",
},
"CURL_PATH": {
"required": False,
"default": "/usr/bin/curl",
"description": "Path to c... | "description": "Description of interesting results."
},
}
description = __doc__
def fetch_content(self, url, headers=None, form_parameters=None, data_parameters=None, curl_options=None):
"""Returns content retrieved by curl, given an url and an optional
dictionaries of header-na... |
kopringo/Scarky2 | Scarky2/builder/migrations/0002_auto_20150505_2035.py | Python | mit | 577 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migr | ations
class Migration(migrations.Migration):
dependencies = [
('builder', '0001_initial'),
| ]
operations = [
migrations.AlterField(
model_name='problem',
name='date_start',
field=models.DateTimeField(null=True, blank=True),
),
migrations.AlterField(
model_name='problem',
name='date_stop',
field=models.DateT... |
credativ/pulp | server/test/unit/server/managers/repo/test_dependency.py | Python | gpl-2.0 | 4,601 | 0.004347 | from .... import base
from pulp.devel import mock_plugins
from pulp.plugins.conduits.dependency import DependencyResolutionConduit
from pulp.plugins.config import PluginCallConfiguration
from pulp.plugins.types import database, model
from pulp.server.db.model.criteria import UnitAssociationCriteria
from pulp.server.db.... | ntent_unit('type-1', None,
{'key-1': 'v1'})
| unit_id_2 = manager_factory.content_manager().add_content_unit('type-1', None,
{'key-1': 'v2'})
association_manager = manager_factory.repo_unit_association_manager()
association_manager.associate_unit_by_id(self.repo_id, 'type-1'... |
mistercrunch/airflow | airflow/operators/bash.py | Python | apache-2.0 | 8,272 | 0.003264 | #
# 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... | r"""
Execute a Bash script, command or set of commands.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:BashOperator`
If BaseOperator.do_xcom_push is True, the last line written to stdout
will also be pushed to an XCom wh... | completes
:param bash_command: The command, set of commands or reference to a
bash script (must be '.sh') to be executed. (templated)
:type bash_command: str
:param env: If env is not None, it must be a dict that defines the
environment variables for the new process; these are used instead
... |
power12317/weblate | weblate/trans/views.py | Python | gpl-3.0 | 68,329 | 0.000688 | # -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2013 Michal Čihař <[email protected]>
#
# This file is part of Weblate <http://weblate.org/>
#
# 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, eithe... | ignore=False
).values_list(
'language', flat=True
).distinct()
for lang in langs:
checks = Check.objects.filter(
check=name,
project=subprj.project,
language=lang,
ignore=False
).values_lis... | ation__language=lang,
translated=True
).values(
'translation__language_ |
keen99/SickRage | sickbeard/dailysearcher.py | Python | gpl-3.0 | 4,533 | 0.002647 | # Author: Nic Wolfe <[email protected]>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickRage.
#
# SickRage 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,... | airdate > 1)",
[common.UNAIRED, curDate])
sql_l = []
show = None
for sqlEp in sqlResults:
try:
if not show or int(sqlEp["showid"]) != show.indexerid:
show = helpers.findCertainShow(sickbeard.showList, int(sqlEp["s... | continue
except exceptions.MultipleShowObjectsException:
logger.log(u"ERROR: expected to find a single show matching " + str(sqlEp['showid']))
continue
try:
end_time = network_timezones.parse_date_time(sqlEp['airdate'], show.airs,
... |
gautam1858/tensorflow | tensorflow/python/keras/backend_test.py | Python | apache-2.0 | 68,908 | 0.005819 | # 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 applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
... | =============================================================
"""Tests for Keras backend."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
import numpy as np
import scipy.sparse
from tensorflow.core.protobuf import c... |
scollis/iris | lib/iris/tests/unit/plot/test_pcolor.py | Python | gpl-3.0 | 1,395 | 0 | # (C) British Crown Copyright 2014, Met Office
#
# This file is part of Iris.
#
# Iris 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 3 of the License, or
# (at your option) any later ve... | ld have received a copy of the GNU Lesser General Public License
# along with Iris. If not, see <http://www.gnu.org/licenses/>.
"""Unit tests for the `iris.plot.pcolor` function."""
# Import iris.tests first so that some things can be initialised before
# importing anything else.
import iris.tests as tests
from iris.... | p_plot
class TestStringCoordPlot(TestGraphicStringCoord):
def test_yaxis_labels(self):
iplt.pcolor(self.cube, coords=('bar', 'str_coord'))
self.assertBoundsTickLabels('yaxis')
def test_xaxis_labels(self):
iplt.pcolor(self.cube, coords=('str_coord', 'bar'))
self.assertBoundsTickL... |
huanchenz/STX-h-store | tests/scripts/xml2/__init__.py | Python | gpl-3.0 | 262 | 0 | """XML parser package.
This package parses the XML | file returned by the Graffiti tracker.
"""
from xmlparser import XMLParser
from xmlgenerator import XMLGenerator
from exceptions import *
__all__ = ["XMLParser", "XMLGenerator", " | XMLException", "InvalidXML"]
|
LLNL/spack | var/spack/repos/builtin/packages/casacore/package.py | Python | lgpl-2.1 | 4,875 | 0.001846 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import os
from spack import *
class Casacore(CMakePackage):
"""A suite of c++ libraries for radio astronomy data pr... | ant('USE_ADIOS2', 'adios2'))
args.append(self.define_from_variant('USE_MPI', 'adios2'))
if spec.satisfies('+adios2'):
args.append(self.define('ENABLE_TABLELOCKING', False))
# fftw3 is required by casacore starting with v3.4.0, but the
# old fftpack is still available. For v3... | al addition
# of FFTPack. In older casacore versions, only one of FFTW3 or
# FFTPack can be selected.
if spec.satisfies('@3.4.0:'):
if spec.satisfies('+fftpack'):
args.append('-DBUILD_FFTPACK_DEPRECATED=YES')
args.append(self.define('USE_FFTW3', True))
... |
timkrentz/SunTracker | IMU/VTK-6.2.0/Common/Core/Testing/Python/TestGhost.py | Python | mit | 1,901 | 0.001578 | """Test ghost object support in VTK-Python
When PyVTKObject is destroyed, the vtkObjectBase that it
contained often continues to exist because references to
it still exist within VTK. When that vtkObjectBase is
returned to python, a new PyVTKObject is created.
If the PyVTKObject has a custom class or a custom... | o = vtk.vtkObject()
o.customattr = 'hello'
a = vtk.vtkVariantArray()
a.InsertNextValue(o)
i = id(o)
del o
o = vtk.vtkObject()
o = a.GetValue(0).ToVTKObject()
# make sure the id has changed, but dict the same
self.assertEqual(o.customattr, ... | o = vtkCustomObject()
a = vtk.vtkVariantArray()
a.InsertNextValue(o)
i = id(o)
del o
o = vtk.vtkObject()
o = a.GetValue(0).ToVTKObject()
# make sure the id has changed, but class the same
self.assertEqual(o.__class__, vtkCustomObject)
sel... |
kailIII/emaresa | rent.resp/partner.py | Python | agpl-3.0 | 1,548 | 0.008398 | # -*- coding: utf-8 -*-
# | #############################################################################
#
# Author: OpenDrive Ltda
# Copyright (c) 2013 Opendrive Ltda
#
# WARNING: This program as such is intended to b | e used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly advised to contract a Free Software
# Service C... |
koalakoker/knote_gcrypt | GCryptNote/PyMyPackage.py | Python | gpl-2.0 | 807 | 0.007435 | '''
Created on 23/mag/2015
@author: koala
'''
import Cript
key = b'dfdfjdnjnjvnfkjn vnfj vjfk d nvkfd j'
plaintext = b'jfghksdjfghksdjfgksdhgljdkghjh fgh fhg jfhgdkjfkjg hkdfjg hkdfj ghkdf | ghfdjk ghfdjkg hkdfjg h'
testoC | riptato, seme, orLen = Cript.criptIt(plaintext, key)
testoDecriptato = Cript.deCriptIt(testoCriptato, key, seme, orLen)
# dec = cipher.decrypt(msg)
# def pr(iStr):
# l = len(iStr)
# print l
# r = range(l)
# print r
# for i in r:
# print i,iStr[i]
# print (Cript.hashIt("pippa"))
print (pla... |
husky-prophet/personal-backup | PRETEND assessment/PRETEND assessment csv.py | Python | mit | 4,661 | 0.039262 | import csv
from subprocess import call#
from datetime import datetime#Importing various libraries
call(["color","F9"], shell=True)#
call(["cls"], shell = True)#Setting colour for shell
import sys, time#
import time#More libraries
prog=True#creating variable prog and assigning it as true
time.sleep(1)#
def typi... | print "=|That will be $"+str(price)+"|="#
prog3=False#
elif tilep=="no":#
prog3=False#
time.sleep(0.5)#
typing("Generating Unique Custom ID")#
customid=name+str(len(name))+str(len(tileq))+str(len(tilep))+ | str(length)+str(width)#The ID is name[lengthofname][lengthofquality][lengthofprice][length][width]
print "Your Customer ID is",str(customid)#print ID
with open ("Tiledetails.csv","ab") as csvfile:
usr=csv.writer (csvfile, delimiter=",",
quotechar=",", quoting=csv.QUOTE... |
Heufneutje/txircd | txircd/modules/core/accountdata.py | Python | bsd-3-clause | 1,023 | 0.021505 | from twisted. | plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implementer
from typing import Callable, List, Optional, Tuple
# Numerics and names are taken from the IRCv3.1 SASL specification at http://ircv3.net/specs/extensions/sas... | GGEDIN = "900"
irc.RPL_LOGGEDOUT = "901"
@implementer(IPlugin, IModuleData)
class AccountMetadata(ModuleData):
name = "AccountData"
core = True
def actions(self) -> List[Tuple[str, int, Callable]]:
return [ ("usermetadataupdate", 10, self.sendLoginNumeric) ]
def sendLoginNumeric(self, user: "IRCUser", key: s... |
aetros/aetros-cli | aetros/commands/GPUCommand.py | Python | mit | 1,123 | 0.005343 | from __future__ import absolute_import, print_function, division
import argparse
import sys
class GPUCommand:
def __init__(self, logger):
self.logger = logger
self.client = None
self.registered = False
self.active = True
def main(self, args):
import aetros.cuda_gpu
... | erly.')
sys.exit(2)
for gpu in aetros.cuda_gpu.get_ordered_devices():
properties = aetros.cuda_gpu.get_device_properties(gpu['device'], all=True)
free, total = aetros.cuda_gpu.get_memory(gpu['device'])
print("%s GPU id=%s %s (memory %.2fGB, free %.2fGB)" %(gpu['f... | 024/1024))
|
LSIR/gsn | gsn-webui/app/urls.py | Python | gpl-3.0 | 712 | 0 | """mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-base... | e='home')
Includin | g another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
urlpatterns = [
url(r'^', include('gsn.urls')),
]
|
sandeva/appspot | settings.py | Python | apache-2.0 | 3,965 | 0.002774 | # Copyright 2008 Google 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, ... | # Or path to database file if using sqlite3.
DATABASE_USER = '' # Not used with sqlite3.
DATABASE_PASSWORD = '' # Not used with sqlite3.
DATA | BASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all ... |
borqsat/TCT-lite | setup.py | Python | gpl-2.0 | 506 | 0.047431 | #!/usr/bin/python
from setuptools import setup, find_packages
setup(
name = "testkit-lite",
description = "Test runner for test execution",
url = "https://github.com/testkit/testkit-lite",
author = "Cathy Shen",
author_email = "cathy.shen@ | intel.com",
version = "2.3.4",
inclu | de_package_data = True,
data_files = [('/opt/testkit/lite/',
('VERSION', 'doc/testkit-lite_user_guide_for_tct.pdf'))],
scripts = ('testkit-lite',),
packages = find_packages(),
)
|
jannewulf/Anki-Translator | TranslatorAddon/GUI/TranslatorDialog.py | Python | gpl-3.0 | 7,181 | 0.004178 | from PyQt4.QtGui import *
from PyQt4.QtCore import Qt
from aqt.utils import tooltip
from TranslatorAddon.Parser.PONSParser import PONSParser
# This class describes the Dialog Window in which a vocable can be translated
class TranslatorDialog(QDialog):
col0Width = 40
def __init__(self, vocable, defaultSourceL... | connect(self.updateTargetLanguages)
self.chkBoxGrammarInfo = QCheckBox()
self.chkBoxGrammarInfo.setChecked(self.defaultGram)
layout = QHBoxLayout()
layout.addWidget(QLabel("Source Language"))
layout.addWidget(self.cmbBoxSourceLang)
| layout.addStretch(1)
layout.addWidget(QLabel("Target Language"))
layout.addWidget(self.cmbBoxTargetLang)
layout.addStretch(1)
layout.addWidget(self.chkBoxGrammarInfo)
layout.addWidget(QLabel("Load Grammar Infos"))
self.settingsBox.setLayout(layout)
# creates all the... |
dims/cinder | cinder/zonemanager/fc_zone_manager.py | Python | apache-2.0 | 11,517 | 0 | # (c) Copyright 2014 Brocade Communications Systems Inc.
# All Rights Reserved.
#
# Copyright 2014 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# ... |
i_t_map, True)
LOG.info(_LI("Final filtered map for fabric: %(i_t_map)s"),
{'i_t_map': valid_i_t_map})
# Call driver to add connection control
| self.driver.add_connection(fabric, valid_i_t_map,
host_name, storage_system)
LOG.info(_LI("Add connection: finished iterating "
"over all target list"))
except Exception as e:
msg = _("Failed adding connection... |
Princu7/open-event-orga-server | migrations/versions/b5abafa45063_.py | Python | gpl-3.0 | 1,145 | 0.013974 | """empty message
Revision ID: b5abafa45063
Revises: 4e5dd0df14b5
Create Date: 2016-08-06 22:29:36.948000
"""
# revision identifiers, used by Alembic.
revision = 'b5abafa45063'
down_revision = '4e5dd0df14b5'
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils
def upgrade():
### commands auto... | sa.Integer(), nullable=False),
sa.Column('stripe_secret_key', sa.String(), nullable=True),
sa.Column('stripe_refresh_token', sa.String(), nullable=True),
sa.C | olumn('stripe_publishable_key', sa.String(), nullable=True),
sa.Column('stripe_user_id', sa.String(), nullable=True),
sa.Column('stripe_email', sa.String(), nullable=True),
sa.Column('event_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['event_id'], ['events.id'], ondelete='CASCADE'),
s... |
scattm/DanceCat | DanceCat/Console/__init__.py | Python | mit | 2,383 | 0 | """This module include console commands for DanceCat."""
from __future__ import print_function
import datetime
import sqlalchemy.exc
from dateutil.relativedelta import relativedelta
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from DanceCat import app, db, Models, Constants
# py... | base initial."""
db.create_all()
@manage | r.command
def schedule_update():
"""Update outdated schedules on offline time."""
schedules = Models.Schedule.query.filter(
Models.Schedule.is_active,
Models.Schedule.schedule_type != Constants.SCHEDULE_ONCE,
Models.Schedule.next_run <= datetime.datetime.now()
).all()
while len(... |
snazy2000/netbox | netbox/dcim/formfields.py | Python | apache-2.0 | 607 | 0 | from __future__ import unicode_literals
from netaddr import | EUI, AddrFormatError
from django import forms
from django.core.exceptions import ValidationError
#
# Form fi | elds
#
class MACAddressFormField(forms.Field):
default_error_messages = {
'invalid': "Enter a valid MAC address.",
}
def to_python(self, value):
if not value:
return None
if isinstance(value, EUI):
return value
try:
return EUI(value, ve... |
FFMG/myoddweb.piger | monitor/api/python/Python-3.7.2/Lib/test/test_winreg.py | Python | gpl-2.0 | 21,678 | 0.000554 | # Test the windows specific win32reg module.
# Only win32reg functions not hit here: FlushKey, LoadKey and SaveKey
import os, sys, errno
import unittest
from test import support
import threading
from platform import machine
# Do this first so test will be skipped if module doesn't exist
support.import_module('winreg'... | o this, some
# tests are only valid up until 6.1
HAS_REFLECTION = True if WIN_VER < (6, 1) else False
# Use a per-process key to prevent concurrent test runs | (buildbot!) from
# stomping on each other.
test_key_base = "Python Test Key [%d] - Delete Me" % (os.getpid(),)
test_key_name = "SOFTWARE\\" + test_key_base
# On OS'es that support reflection we should test with a reflected key
test_reflect_key_name = "SOFTWARE\\Classes\\" + test_key_base
test_data = [
("Int Value"... |
ex0hunt/redrat | func/viewer.py | Python | bsd-2-clause | 2,852 | 0.00495 | from common.connector import redmine
class ViewIssues:
def __init__(self, view_type, assigned_to='me', minimal_priority=0, exclude_projects=(), milestone=None):
self.redmine = redmine()
self.assigned_to = assigned_to
self.minimal_priority = minimal_priority
self.exclude_projects = ... | e != 'all' and str(i.fixed_version) not in self.milestone:
continue
except:
continue
i_count += 1
if i.priority.id < self.minimal_priority:
continue
color_priority = self.colorify_priority(i.p... | ority(i.status)
end_color = '\033[0m'
print('[%s%s%s][%s%s%s]\t%i:\t%s' %(color_priority,
i.priority,
end_color,
color_state,
... |
chrisb87/advent_of_code_2016 | day13/test_day13.py | Python | unlicense | 783 | 0.045977 | import unittest
import pdb
from day13 import *
class TestDay13(unittest.TestCase):
def test_is_wall(self):
tests = (
(0, 0, False),
(1, 0, True),
(2, 0, False),
(-1, 0, True),
(0, -1, Tru | e),
)
for x, y, expected in tests:
self.assertEqual(
is_wall(x, y, 10),
expected,
"(%d,%d) should be %s" % (x,y, expected))
def test_solve_example(self):
solution = solve((1,1), (7,4), 10)
self.assertEqual(len(solution) - 1, 11)
@unittest.skip("slow")
def test_solve_part_1(self):
soluti... | tEqual(len(solution) - 1, 92)
@unittest.skip("slow")
def test_solve_part_2(self):
solution = solve((1,1), (31,39), 1350, 50)
self.assertEqual(solution, 124)
if __name__ == "__main__":
unittest.main()
|
JoeJasinski/WindyTransit | mobiletrans/urls.py | Python | mit | 1,139 | 0.022827 | from django.conf.urls import patterns, include, url
from .views import MapView
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(a | dmin.site.urls)),
url('^$', 'mobi | letrans.views.index', { 'template_name':'index.html'},
name="index"),
url('^about/$', 'mobiletrans.views.about', { 'template_name':'about.html'},
name="about"),
url('^routemap/$', MapView.as_view( template_name='routemap.html'),
name="routemap"),
url('^transitheat/$', MapView.as_v... |
autosportlabs/RaceCapture_App | autosportlabs/uix/color/colorsequence.py | Python | gpl-3.0 | 1,401 | 0.002141 | #
# Race Capture App
#
# Copyright (C) 2014-2017 Autosport Labs
#
# This file is part of the Race Capture App
#
# This 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 ... | r:
index = s | elf.color_index
color = rgb(self.colors[index])
index = index + 1 if index < len(self.colors) - 1 else 0
self.color_index = index
self.color_map[key] = color
return color
|
UMWRG/HydraPlatform | HydraLib/python/HydraLib/config.py | Python | gpl-3.0 | 5,352 | 0.003737 | # (c) Copyright 2013, 2014, University of Manchester
#
# HydraPlatform 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 3 of the License, or
# (at your option) any later version.
#
# Hydra... | t_program_files())
config.set('DEFAULT', 'win_program_files_common', winpaths.get_program_files_common())
config.set('DE | FAULT', 'win_system', winpaths.get_system())
config.set('DEFAULT', 'win_windows', winpaths.get_windows())
config.set('DEFAULT', 'win_startup', winpaths.get_startup())
config.set('DEFAULT', 'win_recent', winpaths.get_recent())
def get(section, option, default=None):
if CONFIG is None:
load_conf... |
wikilinks/neleval | doc/conf.py | Python | apache-2.0 | 8,305 | 0 | # -*- coding: utf-8 -*-
#
# project-template documentation build configuration file, created by
# sphinx-quickstart on Mon Jan 18 14:44:12 2016.
#
# 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 fi... | fault role (used for this markup: `text`) to use for all
# documents.
default_role = 'any'
# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True
# If true, the current module name will be prepended to | all description
# unit titles (such as .. function::).
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of... |
timesong/pycha | chavier/dialogs.py | Python | lgpl-3.0 | 7,040 | 0.00071 | # Copyright(c) 2007-2010 by Lorenzo Gil Sanchez <[email protected]>
#
# This file is part of Chavier.
#
# Chavier 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 3 of the Lice... | flags, buttons)
self.size_group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
self.number = self._create_spin_button('Number of points | to generate',
0, 1, 5, 1, 1000, 10)
self.min = self._create_spin_button('Minimum y value',
2, 0.5, 1, -1000, 1000, 0)
self.max = self._create_spin_button('Maximum y value',
... |
kennethd/moto | moto/ec2/exceptions.py | Python | apache-2.0 | 10,404 | 0.000192 | from __future__ import unicode_literals
from moto.core.exceptions import RESTError
class EC2ClientError(RESTError):
code = 400
class DependencyViolationError(EC2ClientError):
def __init__(self, message):
super(DependencyViolationError, self).__init__(
"DependencyViolation", message)
cl... | The keypair '{0}' does not exist."
.format(key))
clas | s InvalidKeyPairDuplicateError(EC2ClientError):
def __init__(self, key):
super(InvalidKeyPairDuplicateError, self).__init__(
"InvalidKeyPair.Duplicate",
"The keypair '{0}' already exists."
.format(key))
class InvalidVPCIdError(EC2ClientError):
def __init__(self, vpc... |
eharney/nova | nova/tests/virt/vmwareapi/stubs.py | Python | apache-2.0 | 3,393 | 0.000295 | # Copyright (c) 2011 Citrix Systems, Inc.
# Copyright 2011 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0... | return isinstance(module, fake.FakeVim)
def fake_temp_method_exception():
raise error_util.VimFaultException(
[error_util.NOT_AUTHENTICATED],
"Session Empty/Not Authenticated")
def fake_temp_session_excep | tion():
raise error_util.SessionConnectionException("it's a fake!",
"Session Exception")
def fake_session_file_exception():
fault_list = [error_util.FILE_ALREADY_EXISTS]
raise error_util.VimFaultException(fault_list,
Exception('fake'))
def set_stubs(stu... |
vicamo/pcsc-lite-android | UnitaryTests/SCardConnect_DIRECT.py | Python | bsd-3-clause | 3,325 | 0.001203 | #! /usr/bin/env python
# SCardConnect_DIRECT.py : Unitary test for SCardConnect in DIRECT mode
# Copyright (C) 2009 Ludovic Rousseau
#
# T | his 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 option) any later version.
#
# This program is distributed | in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; i... |
DArtagan/charityfund | charityfund/settings.py | Python | mit | 1,699 | 0 | """
Django settings for charityfund project.
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import dj_database_url
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('SECRET_KEY')
... | re.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'charityfund.urls'
WSGI_APPLICATION = 'charityfund.wsgi.application'
# Database
DATABASES = {
'default': dj_database_url.config(default='sqlite://../db.sqlite3'),
}
# Internati | onalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
|
fergalmoran/energenie | socket.py | Python | apache-2.0 | 147 | 0.020408 | from energenie import switch_on, switch_off
from time import sleep
print | ("Turning off")
switch_off()
sleep(5)
print ("Turning on")
switc | h_on()
|
brendangregg/bcc | tools/tcpconnect.py | Python | apache-2.0 | 17,972 | 0.002393 | #!/usr/bin/python
# @lint-avoid-python-3-compatibility-imports
#
# tcpconnect Trace TCP connect()s.
# For Linux, uses BCC, eBPF. Embedded C.
#
# USAGE: tcpconnect [-h] [-c] [-t] [-p PID] [-P PORT [PORT ...]] [-4 | -6]
#
# All connection attempts are traced, even if they ultimately fail.
#
# This uses d... | e_read_kernel(&data6.daddr, sizeof(data6.daddr),
skp->__sk_common.skc_v6_daddr.in6_u.u6_addr32);
data6.l | port = lport;
data6.dport = ntohs(dport);
bpf_get_current_comm(&data6.task, sizeof(data6.task));
ipv6_events.perf_submit(ctx, &data6, sizeof(data6));"""
}
}
# This defines an additional BPF program that instruments udp_recvmsg system
# call to ... |
yinglanma/AI-project | tensorpack/tfutils/summary.py | Python | apache-2.0 | 3,816 | 0.002621 | # -*- coding: UTF-8 -*-
# File: summary.py
# Author: Yuxin Wu <[email protected]>
import six
import tensorflow as tf
import re
from ..utils import *
from . import get_global_step_var
from .symbolic_functions import rms
__all__ = ['create_summary', 'add_param_summary', 'add_activation_summary',
'add_movin... | m? Maybe use scalar instead. FIXME!"
if name is None:
name = x.name
with tf.name_scope('act_summary'):
tf.histogram_summary(name + '/activation', x)
| tf.scalar_summary(name + '/activation_sparsity', tf.nn.zero_fraction(x))
tf.scalar_summary(
name + '/activation_rms', rms(x))
def add_param_summary(summary_lists):
"""
Add summary for all trainable variables matching the regex
:param summary_lists: list of (regex, [list of summar... |
MattNolanLab/ei-attractor | grid_cell_model/simulations/007_noise/figures/paper/ee_connections_ei_flat/figure_drifts.py | Python | gpl-3.0 | 501 | 0.001996 | #!/usr/bin/env python
from __future__ import absolute_import, print_function
from grid | _cell_model.submitting import flagparse
import noisefigs
from noisefigs.env import NoiseEnvironment
import config_standard_gEE_3060 as config
parser = flagparse.FlagParser()
parser.add_flag('--bumpDriftSweep')
args = parser.parse_args()
env = NoiseEnvironment(user_config=config.get_config())
if args.bumpDriftSweep | or args.all:
env.register_plotter(noisefigs.plotters.BumpDriftAtTimePlotter)
env.plot()
|
noironetworks/neutron | neutron/tests/unit/extensions/test_network_ip_availability.py | Python | apache-2.0 | 21,269 | 0 | # Copyright 2016 GoDaddy.
#
# 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, ... | e.NetworkIPAvailabilityPlugin()
ext_mgr = api_ext.PluginAwareExtensionManager(
EXTENSIONS_PATH, {"network-ip-availability": self.plugin}
)
app = config.load_paste_app('extensions_test_app')
self.ext_api = api_ext.ExtensionMiddleware(app, ext_mgr=ext_mgr)
def _validate_av... | '], availability['network_name'])
self.assertEqual(network['id'], availability['network_id'])
self.assertEqual(expected_used_ips, availability['used_ips'])
self.assertEqual(expected_total_ips, availability['total_ips'])
def _validate_from_availabilities(self, availabilities, wrapped_network... |
immerrr/numpy | numpy/lib/twodim_base.py | Python | bsd-3-clause | 26,858 | 0.000037 | """ Basic functions for manipulating 2d arrays
"""
from __future__ import division, absolute_import, print_function
__all__ = ['diag', 'diagflat', 'eye', 'fliplr', 'flipud', 'rot90', 'tri',
'triu', 'tril', 'vander', 'histogram2d', 'mask_indices',
'tril_indices', 'tril_indices_from', 'triu_indice... | tive (negative) `k` giving the number of the diagonal above
(below) the main.
Returns
-------
out : ndarray
The 2-D output array.
See Also
--------
diag : MATLAB work-alike for 1-D and 2-D arrays.
diagonal : Return specified diagonals.
trace : Sum alon | g diagonals.
Examples
--------
>>> np.diagflat([[1,2], [3,4]])
array([[1, |
simphony/simphony-lammps-md | edmsetup.py | Python | bsd-2-clause | 1,237 | 0 | import sys
import click
import os
import subprocess
from packageinfo import BUILD, VERSION, NAME
# The version of the buildcommon to checkout.
BUILDCOMMONS_VERSION = "v0.2"
def bootstrap_devenv():
try:
os.makedirs(".devenv")
except | OSError:
pass
if not os.path.exists(".devenv/buildrecipes-common"):
subprocess.check_call([
"git", "clone", "-b", BUILDCOMMONS_VERSION,
"http://github.com/simphony/buildrecipes-common.git",
".devenv/buildrecipes-common"
])
sys.path.insert(0, ".dev... | orkspace = common.workspace()
common.edmenv_setup()
@click.group()
def cli():
pass
@cli.command()
def egg():
common.local_repo_to_edm_egg(".", name=NAME, version=VERSION, build=BUILD)
@cli.command()
def upload_egg():
egg_path = "endist/{NAME}-{VERSION}-{BUILD}.egg".format(
NAME=NAME,
V... |
jayclassless/tidypy | src/tidypy/tools/pyroma.py | Python | mit | 4,228 | 0.000237 |
import logging
import os
import warnings
from ..util import SysOutCapture
from .base import Tool, Issue, ToolIssue
# Hacks to prevent pyroma from screwing up the logging system for everyone else
old_config = logging.basicConfig
try:
logging.basicConfig = lambda **k: None
from pyroma import projectdata, rati... | ('PythonVersion', '_major_version_specified', False),
('ValidREST', '_message', ''),
| ('ClassifierVerification', '_incorrect', []),
('Licensing', '_message', ''),
)
for clazz, attr, value in HACKS:
if hasattr(ratings, clazz):
setattr(getattr(ratings, clazz), attr, value)
TIDYPY_ISSUES = {
'NOT_CALLED': (
'SetupNotCalled',
'setup() was not invoked.',
),
'SC... |
Jaden-J/shape2ge | src/shapeobjects.py | Python | gpl-2.0 | 10,069 | 0.049558 | ###############################################################################
# Copyright (C) 2008 Johann Haarhoff <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of Version 2 of the GNU General Public License as
# published by the Free Softwar... |
kmlwriter.endDocument()
class SHPArcObject(SHPArcZObject):
def __init__(self,SHPId | = -1,Verts = [[]],Label="",Desc=""):
SHPObject.__init__(self,shapelibc.SHPT_ARC,SHPId,Verts,Label,Desc)
def createFromFile(self,filestream,shapenum):
SHPObject.createFromFile(self,filestream,shapenum)
if self._SHPType != shapelibc.SHPT_ARC:
raise WrongShapeObjectError()
def createFromObject(self,shpo... |
scottcunningham/ansible | lib/ansible/executor/process/worker.py | Python | gpl-3.0 | 6,192 | 0.004037 | # (c) 2012-2014, Michael DeHaan <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) an... | atfork()
while True:
task = None
try:
if not self._main_q.empty():
debug("there's work to be done!")
| (host, task, basedir, job_vars, play_context, shared_loader_obj) = self._main_q.get(block=False)
debug("got a task/handler to work on: %s" % task)
# because the task queue manager starts workers (forks) before the
# playbook is loaded, set the basedir of ... |
ktan2020/legacy-automation | samples/misc/sel_google_search_phantomjs.py | Python | mit | 1,101 | 0.00545 | from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0
# Create a new instance of the IE driver
driver = webdri... | r the page to refresh, the last thing that seems to be updated is the title
WebDriverWait(driver, 10).until(EC.title_conta | ins("cheese!"))
# You should see "cheese! - Google Search"
print driver.title
finally:
driver.quit() |
MDAnalysis/mdanalysis | package/MDAnalysis/converters/OpenMM.py | Python | gpl-2.0 | 7,397 | 0.001622 | # -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
# MDAnalysis --- https://www.mdanalysis.org
# Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors
# (see the file AUTHORS for the full list of names)
#
# Released under t... | ts_of(u.kilojoule/u.mole)
)
ts.data["kinetic_energy"] = (
state.getKineticEnergy().in_units_of(u.kilojoule/u.mole)
)
ts.triclinic_dimensions = state.getPeriodicBoxVectors(
asNumpy=True)._value
ts.dimensions[3:] = _sanitize_box_angles(ts.dimensions[3:])... | te.getForces(asNumpy=True)._value
return ts
class OpenMMAppReader(base.SingleFrameReaderBase):
"""Reader for OpenMM Application layer objects
See also `the object definition in the OpenMM Application layer <http://docs.openmm.org/latest/api-python/generated/openmm.app.simulation.Simulation.html#open... |
vipmunot/HackerRank | Data Structures/Arrays/Sparse Arrays.py | Python | mit | 249 | 0.02008 | n = int(input())
arr = []
for i in range(n):
arr.append(input())
q = int(input())
fo | r i in range(q):
query = input()
count = 0
for j in range(len(arr)):
if arr[j] == query:
count +=1
print(count)
| |
terhorst/psmcpp | smcpp/analysis/base.py | Python | gpl-3.0 | 6,269 | 0.001276 | import numpy as np
import json
import sys
from .. import _smcpp, util, logging, data_filter
| import smcpp.defaults
from smcpp.optimize.optimizers import SMCPPOptimizer, TwoPopulationOptimizer
from smcpp.optimize.plugins import analysis_saver, parameter_optimizer
logger = logging.get | Logger(__name__)
from ..model import SMCModel, SMCTwoPopulationModel
_model_cls_d = {cls.__name__: cls for cls in (SMCModel, SMCTwoPopulationModel)}
class BaseAnalysis:
"Base class for analysis of population genetic data."
def __init__(self, files, args):
# Misc. parameter initialiations
se... |
praekeltfoundation/ndoh-hub | registrations/management/commands/upload_clinic_codes.py | Python | bsd-3-clause | 2,626 | 0.001142 | from csv import DictReader
from django.core.management.base import BaseCommand
from registrations.models import ClinicCode
class Command(BaseCommand):
help = (
"This command takes in a CSV with the columns: uid, code, facility, province,"
"and location, and creates/updates the cliniccodes in the... | return None
def handle(self, *args, **kwargs):
updated = 0
| created = 0
with open(kwargs["data_csv"]) as f:
reader = DictReader(f)
for row in reader:
_, new = ClinicCode.objects.update_or_create(
uid=row["uid"].strip(),
defaults={
"code": row["code"].strip(),
... |
sjug/perf-tests | verify/boilerplate/boilerplate.py | Python | apache-2.0 | 4,896 | 0.003881 | #!/usr/bin/env python
# Copyright 2015 The Kubernetes Authors.
#
# Licensed under the Apache L | icense, 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, software
# distributed under the License is distributed on a... | CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import argparse
import datetime
import glob
import json
import mmap
import os
import re
import sys
parser = argparse.Argumen... |
akscram/lollipop-jsonschema | lollipop_jsonschema/jsonschema.py | Python | mit | 5,661 | 0.00159 | __all__ = [
'json_schema',
]
import lollipop.types as lt
import lollipop.validators as lv
from lollipop.utils import identity
from collections import OrderedDict
from .compat import iteritems
def find_validators(schema, validator_type):
return [validator
for validator in schema.validators
... | ors[0].choices)
for validator in any_of_validators[1:]:
choices = choices.intersection(set(validator.choices))
if not choices:
raise ValueError('AnyOf constraints choices does not allow any values')
js['enum'] = lis | t(schema.dump(choice) for choice in choices)
return js
none_of_validators = find_validators(schema, lv.NoneOf)
if none_of_validators:
choices = set(none_of_validators[0].values)
for validator in none_of_validators[1:]:
choices = choices.union(set(validator.values))
... |
tensorflow/moonlight | moonlight/staves/staffline_distance.py | Python | apache-2.0 | 10,559 | 0.00483 | # Copyright 2018 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, ... | ffline distances in the
image. One of the distances may be chosen arbitrarily.
Returns:
A scalar tensor with the staffline thickness for the en | tire page, or -1 if
it could not be estimated (staffline_distance is empty, or there are not
enough runs to estimate the staffline thickness).
"""
with tf.name_scope('estimate_staffline_thickness'):
def do_estimate():
"""Compute the thickness if distance detection was successful."""
ru... |
mastizada/kuma | kuma/core/tests/__init__.py | Python | mpl-2.0 | 6,376 | 0.000471 | from django.conf import settings, UserSettingsHolder
from django.contrib.auth.models import User
from django.contrib.messages.storage.fallback import FallbackStorage
from django.test.client import Client
from django.utils.functional import wraps
from django.utils.importlib import import_module
import constance.config
... | (constance.config, k))
for k in dir(constance.config))
for k, v in self.options.items():
constance.config._backend.set(k, v)
def disable(self):
for k, v in self.old_settings.items():
constance.co | nfig._backend.set(k, v)
constance_database.db_cache = self.old_cache
class override_settings(overrider):
"""Decorator / context manager to override Django settings"""
def enable(self):
self.old_settings = settings._wrapped
override = UserSettingsHolder(settings._wrapped)
for k... |
angelapper/edx-platform | openedx/core/djangoapps/user_api/api.py | Python | agpl-3.0 | 35,762 | 0.002489 | import copy
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from django_countries import countries
import accounts
import third_party_auth
from edxmako.shortcuts import marketing_li... | ord.
password_label = _(u"Password")
form_desc.add_field(
"password",
label=password_label,
field_type="password",
restrictions={
"max_length": accounts.PASSWORD_MAX_LENGTH,
}
)
form_desc.add_field(
"remember",
field_type="checkbox",
... | user. """
DEFAULT_FIELDS = ["email", "name", "username", "password"]
EXTRA_FIELDS = [
"confirm_email",
"first_name",
"last_name",
"city",
"state",
"country",
"gender",
"year_of_birth",
"level_of_education",
"company",
"ti... |
skyostil/tracy | src/generator/Cheetah/Tests/unittest_local_copy.py | Python | mit | 34,313 | 0.003934 | #!/usr/bin/env python
""" This is a hacked version of PyUnit that extends its reporting capabilities
with optional meta data on the test cases. It also makes it possible to
separate the standard and error output streams in TextTestRunner.
It's a hack rather than a set of subclasses because a) Steve had used doub... | "
__author__ = "Steve Purcell"
__email__ = "stephen_purcell at yahoo dot com"
__revision__ = "$Revision: 1.1 $"[11:-2]
##################################################
## DEPENDENCIES ##
import os
import re
import string
import sys
import time
import traceback
import types
import pprint
######... | e = (1==1),(1==0)
##############################################################################
# Test framework core
##############################################################################
class TestResult:
"""Holder for test result information.
Test results are automatically managed by t... |
bzero/bitex | apps/api_receive/api_receive_application.py | Python | gpl-3.0 | 4,247 | 0.014834 | import ssl
import logging
import tornado.ioloop
import tornado.web
import sys
from tornado import httpclient
from functools import partial
from sqlalchemy import create_engine, func
from sqlalchemy.orm import scoped_session, sessionmaker
from create_receive_handler import ReceiveHandler
from wallet_notify_handler i... | from models import ForwardingAddress
forwarding_address = ForwardingAddress.get_by_id(self.db_session, forwarding_address_id)
if response.error:
self.log('ERROR', str(response.error))
forwarding_address.callback_number_of_errors += 1
self.db_session.add(forwarding_address)
self.db_sess... | ed_by_client = True
self.db_session.add(forwarding_address)
self.db_session.commit()
def log(self, command, key, value=None):
#if len(logging.getLogger().handlers):
# logging.getLogger().handlers = [] # workaround to avoid stdout logging from the root logger
log_msg = command + ',' + ... |
jsmesami/naovoce | src/fruit/migrations/0003_added_indexes.py | Python | bsd-3-clause | 702 | 0.002849 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.ti | mezone
class Migration(migrations.Migration):
dependencies = [
('fruit', '0002_fruit_cover_image'),
]
operations = [
migrations.AlterField(
model_name='fruit',
| name='created',
field=models.DateTimeField(verbose_name='created', db_index=True, editable=False, default=django.utils.timezone.now),
),
migrations.AlterField(
model_name='fruit',
name='deleted',
field=models.BooleanField(verbose_name='deleted',... |
debomatic/debomatic | docs/conf.py | Python | gpl-3.0 | 1,509 | 0 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2012-2021 Luca Falavigna
#
# Author: Luca Falavigna <[email protected]>
#
# 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; version 3 of the License.
#... | {
'classoptions': ',oneside',
'babel': '\\usepackage[english]{babel}'}
man_pages = [
('index', 'deb-o-matic', 'Deb-o-Matic Doc | umentation',
['Luca Falavigna'], 1)]
|
saltstack/salt | tests/pytests/functional/states/conftest.py | Python | apache-2.0 | 178 | 0 | import pytest
|
@pytest.fixture(scope="module")
def states(loaders):
return loaders.states
@pytest.fixture(scope="module")
def modules(loaders):
return loa | ders.modules
|
ooici/marine-integrations | mi/dataset/parser/flord_l_wfp_sio_mule.py | Python | bsd-2-clause | 8,191 | 0.021121 | #!/usr/bin/env python
"""
@package mi.dataset.parser.flord_l_wfp_sio_mule
@file marine-integrations/mi/dataset/parser/flord_l_wfp_sio_mule.py
@author Maria Lutz
@brief Parser for the flord_l_wfp_sio_mule dataset driver
Release notes:
Initial Release
"""
__author__ = 'Maria Lutz'
__license__ = 'Apache 2.0'
import re... | nd_point))
parse_end_point = parse_end_point-E_GLOBAL_SAMPLE_BYTES
# if the remaining bytes are less than data sample bytes, all we might have left is a status sample
| if parse_end_point != 0 and parse_end_point < STATUS_BYTES and parse_end_point < E_GLOBAL_SAMPLE_BYTES and parse_end_point < STATUS_BYTES_AUGMENTED:
self._exception_callback(UnexpectedDataException("Error sieving WE data, inferred sample/status alignment incorrect"))
return_list = []
return return_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.