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 |
|---|---|---|---|---|---|---|---|---|
admgrn/Switcharoo | scraper/scraper/entryqueue.py | Python | gpl-3.0 | 2,041 | 0.00147 | # Copyright 2015 Adam Greenstein <adamgreenstein@comcast.net>
#
# Swit | charo | o Cartographer 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.
#
# Switcharoo Cartographer is distributed in the hope that it will be u... |
kdwink/intellij-community | python/testData/inspections/PyPep8NamingInspection/overridden.py | Python | apache-2.0 | 142 | 0.070423 | cla | ss A:
def <weak_warning descr="Function name sho | uld be lowercase">fooBar</weak_warning>(self): pass
class B(A):
def fooBar(self): pass |
olemoudi/tweetdigest | tweepy/tweepy/binder.py | Python | apache-2.0 | 7,174 | 0.001812 | # Tweepy
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
import httplib
import urllib
import time
import re
from tweepy.error import TweepError
from tweepy.utils import convert_to_utf8_str
from tweepy.models import Model
re_path_template = re.compile('{\w+}')
def bind_api(**config):
class AP... | kargs.items():
if arg is None:
continue
if k in se | lf.parameters:
raise TweepError('Multiple values for parameter %s supplied!' % k)
self.parameters[k] = convert_to_utf8_str(arg)
def build_path(self):
for variable in re_path_template.findall(self.path):
name = variable.strip('{}')
... |
colinsullivan/bingo-board | bingo_board/tastypie/resources.py | Python | mit | 58,556 | 0.007121 | from django.conf import settings
from django.conf.urls.defaults import patterns, url
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from django.core.urlresolvers import NoReverseMatch, reverse, resolve, Resolver404
from django.db.models.sql.constants import QUERY_TERMS, LOOKUP_SEP
from d... | return HttpBadRequest(e.args[0])
except Exception, e:
if hasattr(e, 'response'):
return e.response
# A real, non-expecte | d exception.
# Handle the case where the full traceback is more helpful
# than the serialized error.
if settings.DEBUG and getattr(settings, 'TASTYPIE_FULL_DEBUG', False):
raise
# Rather than re-raising, we're going to ... |
anselmobd/fo2 | src/systextil/urls/table.py | Python | mit | 540 | 0.001852 | from django.urls import re_path
from systextil.views import apoio_index
from systextil.views.table import (
deposito,
colecao, |
estagio,
periodo_confeccao,
unidade,
)
urlpatterns = [
re_path(r'^colecao/$', colecao.view, name='colecao'),
re_path(r'^deposito/$', deposito.deposito, name='deposito'),
re_path(r'^estagio/$ | ', estagio.view, name='estagio'),
re_path(r'^periodo_confeccao/$', periodo_confeccao.view, name='periodo_confeccao'),
re_path(r'^unidade/$', unidade.view, name='unidade'),
]
|
tmerrick1/spack | var/spack/repos/builtin/packages/r-futile-options/package.py | Python | lgpl-2.1 | 1,636 | 0.001834 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | 1, February 1999.
#
# 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 terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have rece... | emple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class RFutileOptions(RPackage):
"""A scoped options management framework"""
homepage = "https://cran.rstudio.com/web/packages/futile.options/index.html"
url... |
the13fools/Bokeh_Examples | pandas/dataframe.py | Python | bsd-3-clause | 318 | 0.006289 | import numpy as np
import pandas as pd
from bokeh import mpl
ts = pd.S | eries(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()
df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD'))
df = df.cumsum()
df.plot(le | gend=False)
mpl.to_bokeh(name="dataframe")
|
heytrav/drs-project | domain_api/migrations/0010_topleveldomain_slug.py | Python | mit | 478 | 0 | # -*- coding: utf-8 | -*-
# Generated by Django 1.10.5 on 2017-04-04 22:45
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('domain_api', '0009_remove_topleveldomain_slug'),
]
operations = [
migrations.AddField(
... | rue),
),
]
|
zibawa/zibawa | simulator/forms.py | Python | gpl-3.0 | 76 | 0 | ' | ''
Created on Nov 21, 2016
@author: julimatt
'''
from django import forms | |
codewarrior0/pymclevel | setup_nbt.py | Python | isc | 344 | 0.02907 |
from distutils.co | re import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [Extension("_nbt", ["_nbt.pyx"])]
import numpy
setup(
name = 'NBT library (Cython implementation)',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules,
include_dirs = numpy.get_include | ()
)
|
diorcety/translate | translate/storage/projstore.py | Python | gpl-2.0 | 14,767 | 0.000339 | # -*- coding: utf-8 -*-
#
# Copyright 2010 Zuza Software Foundation
#
# This file is part of the Translate Toolkit.
#
# 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 Lice... | Check if we can get an real file name
realfname = fname
if realfname is None or not os.path.isfile(realfname):
realfname = getattr(afile, 'name', None)
if realfname is None or not os.path.isfile(realfname):
realfname = getattr(afile, 'filename', None)
if not real... | to get the file name from the file object, if it was not given:
if not fname:
fname = getattr(afile, 'name', None)
if not fname:
fname = getattr(afile, 'filename', None)
fname = self._fix_type_filename(ftype, fname)
if not fname:
raise ValueError('C... |
hnikolov/pihdf | pihdf/printers/ip_wrapper_gen.py | Python | mit | 6,357 | 0.016045 | from myhdl import *
from str_builder import StrBuilder
import os
import sys
class GenWrapperFile(object):
'''|
| This class is used to generate a python wrapper of a verilog design
|________'''
def __init__(self):
self.module_name = ''
self.interface = [] # keeps the order of the d... | .initialize(args.file_name)
g | wf.generateWrapperFile()
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Create a myhdl wrapper file.')
parser.add_argument('-f', '--file', dest='file_name', default="",
help='top-level verilog (.v) file')
args = parser.parse_ar... |
h4ck3rm1k3/letter-to-editor | newspaper/letter_to_editor/migrations/0005_newspaper_sister_newspapers.py | Python | agpl-3.0 | 478 | 0.002092 | # encoding: utf8
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('letter_to_editor', '0004_company_newspaper_webcache_wikipediapage'),
]
operations = [
| migrations.AddField(
model_name='newspaper',
name='sister_newspapers',
field=models.ForeignKey(to='letter_to_editor.Newspaper', to_field='newspaper_name'),
preserve_default=True | ,
),
]
|
shyamalschandra/scikit-learn | sklearn/neighbors/tests/test_dist_metrics.py | Python | bsd-3-clause | 8,002 | 0.0005 | import itertools
import pickle
import numpy as np
from numpy.testing import assert_array_almost_equal
import pytest
from scipy.spatial.distance import cdist
from sklearn.neighbors import DistanceMetric
from sklearn.neighbors import BallTree
from sklearn.utils import check_random_state
from sklearn.utils._testing imp... | al(D1, D2)
assert_array_almost_equal(haversine.dist_to_rdist(D1), np.sin(0.5 * D2) ** 2)
def test_pyfunc_metric():
X = np.random.random((10, 3))
euclidean = DistanceMetric.get_metric("euclidean")
pyfunc = DistanceMetric.get_metric("pyfunc", func=dist_func, p=2)
| # Check if both callable metric and predefined metric initialized
# DistanceMetric object is picklable
euclidean_pkl = pickle.loads(pickle.dumps(euclidean))
pyfunc_pkl = pickle.loads(pickle.dumps(pyfunc))
D1 = euclidean.pairwise(X)
D2 = pyfunc.pairwise(X)
D1_pkl = euclidean_pkl.pairwise(X)
... |
kjwilcox/digital_heist | src/engine.py | Python | gpl-2.0 | 1,911 | 0.005756 | #!/usr/bin/python3
import exhibition
import inputdevice
import data
from levels import level1
import os
import pygame
import logging
log = logging.getLogger(__name__)
class Engine:
""" Main class responsible for running the game.
Controls game setup and runs the main loop.
Passes input to game... | self.main_loop()
pygame.quit()
def main_loop(self):
clock = pygame.time.Clock()
|
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
if event.type == pygame.KEYUP:
if event.key == pygame.K_ESCAPE:
return
# game... |
google-research/exoplanet-ml | exoplanet-ml/astronet/ops/metrics.py | Python | apache-2.0 | 5,503 | 0.005452 | # Copyright 2018 The Exoplanet ML 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 t... | RANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the | License for the specific language governing permissions and
# limitations under the License.
"""Functions for computing evaluation metrics."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
def _metric_variable(name, shape, dtyp... |
pedrotari7/advent_of_code | py/2017/22B.py | Python | mit | 600 | 0.013333 | weakened, flagged = set(), set()
infected = {(i,j) for i,a in enumerate(open('22.in')) for j,b in enumerate(a.strip('\n')) if b=='#'}
s = len(open('22.in').readlines())/2
p = (s,s)
total = 0
d = (-1,0)
for _ in xrange(10**7):
if p in infected:
d = d[1], -1*d[0]
infected.remove(p)
flagged.... | 1
weakened.remove(p)
infected. | add(p)
elif p in flagged:
d = -1*d[0], -1*d[1]
flagged.remove(p)
else:
d = -1*d[1], d[0]
weakened.add(p)
p = p[0]+d[0], p[1]+d[1]
print total |
thelabnyc/django-oscar-wfrs | sandbox/basket/utils.py | Python | isc | 128 | 0.007813 | from osc | arbluelight.basket_uti | ls import BluelightLineOfferConsumer as LineOfferConsumer
__all__ = [
"LineOfferConsumer",
]
|
bashu/django-feedback-form | feedback_form/south_migrations/0001_initial.py | Python | bsd-3-clause | 4,849 | 0.008043 | # -*- 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):
# Adding model 'Feedback'
db.create_table('feedback_form_feedback', (
... | ps': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
... | nField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_leng... |
macbre/mobify | mobify/sources/oreilly.py | Python | mit | 1,627 | 0.003697 | # -*- coding: utf-8 -*-
import re
from mobify.source import MobifySource
class OReillySource(MobifySource):
HEADER = u"""
<h1>{title}</h1>
<p><strong>{lead}</strong></p>
<p><small>{author} @ oreilly.com</small><br></p>
"""
@staticmethod
def is_my_url(url):
# https://www.oreilly.com/ideas/the-ev... | s(article, xpaths)
html = self.get_node_html(article)
return html
d | ef get_html(self):
# add a title and a footer
return '\n'.join([
self.HEADER.format(title=self.get_title(), author=self.get_author(), lead=self.get_lead()).strip(),
self.get_inner_html()
]).strip()
def get_title(self):
# <meta property="og:title" content="Rad... |
easyw/kicad-3d-models-in-freecad | cadquery/FCAD_script_generator/Fuse/main_generator.py | Python | gpl-2.0 | 8,654 | 0.012364 | # -*- coding: utf-8 -*-
#!/usr/bin/python
#
# This is derived from a cadquery script for generating PDIP models in X3D format
#
# from https://bitbucket.org/hyOzd/freecad-macros
# author hyOzd
# This is a
# Dimensions are from Microchips Packaging Specification document:
# DS00000049BY. Body drawing is the same as QFP ... | *
#* cadquery script for generating QFP/SOIC/SSOP/TSSOP models in STEP AP214 *
#* Copyright (c) 2015 *
#* Maurice https://launchpad.net/~easyw *
#* All trademarks within this guide belong to their legitimate owners. ... | |
GISPPU/GrenadaLandInformation | geonode/context_processors.py | Python | gpl-3.0 | 2,437 | 0.010669 | #########################################################################
#
# Copyright (C) 2012 OpenPlans
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
#... | ver_settings.MAPFISH_PRINT_ENABLED,
PRINTNG_ENABLED = ogc_ | server_settings.PRINTNG_ENABLED,
GS_SECURITY_ENABLED = ogc_server_settings.GEONODE_SECURITY_ENABLED,
PROXY_URL = getattr(settings, 'PROXY_URL', '/proxy/?url='),
SOCIAL_BUTTONS = getattr(settings, 'SOCIAL_BUTTONS', True),
USE_DOCUMENTS = 'geonode.documents' in settings.INSTALLED_APPS
... |
abstrakraft/repo | subcmds/forall.py | Python | apache-2.0 | 7,450 | 0.010604 | #
# Copyright (C) 2008 The Android Open Source Project
#
# 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 la... | sfd(p.stderr, sys.stderr | )]
for s in s_in:
flags = fcntl.fcntl(s.fd, fcntl.F_GETFL)
fcntl.fcntl(s.fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
while s_in:
in_ready, out_ready, err_ready = select.select(s_in, [], [])
for s in in_ready:
buf = s.fd.read(4096)
if not bu... |
MusculoskeletalAtlasProject/mapclient-tests | test_resources/updater_test/mayaviviewerstep-master/mapclientplugins/mayaviviewerstep/widgets/ui_mayaviviewerwidget.py | Python | apache-2.0 | 12,774 | 0.004619 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mayaviviewerwidget.ui'
#
# Created: Mon Nov 11 18:02:00 2013
# by: pyside-uic 0.2.13 running on PySide 1.1.0
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore, QtGui
class Ui_Dialog(object):
def se... | ))
self.slicePlaneRadioZ.setSizePolicy(sizePolicy)
self.slicePlaneRadioZ.setObjectName("slicePlaneRadioZ")
self.horizon | talLayout.addWidget(self.slicePlaneRadioZ)
self.verticalLayout.addWidget(self.sliceplanegroup)
self.screenshotgroup = QtGui.QGroupBox(self.widget1)
self.screenshotgroup.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.screenshotgroup.setObjectName("scr... |
akvo/akvo-rsr | akvo/iati/exports/elements/participating_org.py | Python | agpl-3.0 | 1,717 | 0.00233 | # -*- coding: ut | f-8 -*-
# Akvo RSR is covered by the GNU Affero General Public License.
# See more details in the license.txt file located at the root fo | lder of the Akvo RSR module.
# For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.
from lxml import etree
def participating_org(project):
"""
Generate the participating-org element.
:param project: Project object
:return: A list of Etree elements
"""
... |
treasure-data/td-client-python | tdclient/client.py | Python | apache-2.0 | 32,550 | 0.001505 | #!/usr/bin/env python
import json
from tdclient import api, models
class Client:
"""API Client for Treasure Data Service
"""
def __init__(self, *args, **kwargs):
self._api = api.API(*args, **kwargs)
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
... | schema (list): a dictionary object represents the schema definition (will
be converted to JSON)
e.g.
.. code-blo | ck:: python
[
["member_id", # column name
"string", # data type
"mem_id", # alias of the column name
],
["row_index", "long", "row_ind"],
...
... |
teltek/edx-platform | lms/djangoapps/badges/api/views.py | Python | agpl-3.0 | 6,051 | 0.003966 | """
API views for badges
"""
from edx_rest_framework_extensions.auth.session.authentication import SessionAuthenticationAllowInactiveUser
from opaque_keys import InvalidKeyError
from opaque_keys.edx.django.models import CourseKeyField
from opaque_keys.edx.keys import CourseKey
from rest_framework import generics
from r... | # a user managed to get a specific award on.
course_id = None
elif provided_course_id:
try:
course_id = CourseKey.from_string(provided_course_id)
except InvalidKeyError:
raise InvalidCourseKeyError
elif 'slug' not in self.request... | e_id = None
else:
# Django won't let us use 'None' for querying a ForeignKey field. We have to use this special
# 'Empty' value to indicate we're looking only for badges without a course key set.
course_id = CourseKeyField.Empty
if course_id is not None:
... |
ryfeus/lambda-packs | Keras_tensorflow_nightly/source2.7/tensorflow/tools/api/generator/api/resource_loader/__init__.py | Python | mit | 532 | 0.003759 | """Imports for Python API.
This file is MACHINE GENE | RATED! Do not edit.
Generated by: tensorflow/tools/api/generator/create_python_api.py script.
"""
from tensorflow.python.platform.resource_loader import get_data_files_path
from tensorflow.python.platform.resource_loader import get_path_to_datafile
from tensorflow.python.platform.resource_loader import get_root_dir_wit... | loader import readahead_file_path |
DramaFever/sst | src/sst/selftests/keys.py | Python | apache-2.0 | 1,307 | 0 | import sst
import sst.actions
# tests for simulate_keys
sst.actions.set_base_url('http://localhost:%s/' % sst.DEVSERVER_PORT)
sst.actions.go_to('/')
sst.actions.assert_title('The Page Title')
sst.actions.write_textfield('text_1', 'Foobar..')
sst.actions.simulate_keys('text_1', 'BACK_SPACE')
sst.actions.simulate_ke... | 'SPACE')
sst.actions.simulate_keys('text_1', 'Space')
sst.actions.assert_ | text('text_1', 'Foobar ')
# available keys (from selenium/webdriver/common/keys.py):
#
# 'NULL'
# 'CANCEL'
# 'HELP'
# 'BACK_SPACE'
# 'TAB'
# 'CLEAR'
# 'RETURN'
# 'ENTER'
# 'SHIFT'
# 'LEFT_SHIFT'
# 'CONTROL'
# 'LEFT_CONTROL'
# 'ALT'
# 'LEFT_ALT'
# 'PAUSE'
# 'ESCAPE'
# 'SPACE'
# 'PAGE_UP'
# 'PAGE_DO... |
amonmoce/corba_examples | omniORBpy-4.2.1/build/python/COS/CosTradingDynamic/__init__.py | Python | mit | 251 | 0.003984 | # DO NO | T EDIT THIS FILE!
#
# Python module CosTradingDy | namic generated by omniidl
import omniORB
omniORB.updateModule("CosTradingDynamic")
# ** 1. Stub files contributing to this module
import CosTradingDynamic_idl
# ** 2. Sub-modules
# ** 3. End
|
yangsibai/SiteMiner | test/util_test.py | Python | mit | 229 | 0.004367 | # -*- coding: utf-8 -*- |
__author__ = 'massimo'
import unittest
class UtilTestFunctions(unittest.TestCase):
def test_verify_url(self):
self.assertTrue(True)
if __name__ == "__main__":
UtilTestFunctions.mai | n()
|
Frojd/wagtail-systemtext | wagtailsystemtext/models.py | Python | mit | 791 | 0 | from __future__ import unicode_literals
from django.db import models
from wagtail.core.models import Site
class SystemString(models.Model):
D | EFAULT_GROUP = 'general'
identifier = models.CharField(max_length=1024)
string = models.CharField(max_length=1024, blank=True, null=True)
group = models.CharField(max_length=255, default=DEFAULT_GROUP)
site = models.ForeignKey(Site, on_delete= | models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(null=True, blank=True)
accessed = models.DateTimeField(null=True, blank=True)
modified = models.BooleanField(default=False)
class Meta:
unique_together = ['identifier', 'site', 'group']
d... |
vertical-knowledge/ripozo | ripozo/adapters/siren.py | Python | gpl-2.0 | 6,055 | 0.001156 | """
Siren protocol adapter. See `SIREN specification <https://github.com/kevinswiber/siren>`_.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from ripozo.adapters import AdapterBase
from ripozo.utilities import t... | source.linked_resources:
links.append(dict(rel=[link_name],
href=self.combine_base_url_with_resource_url(link.url)))
return links
def get_entities(self):
"""
Gets a list of related entities in an appropriate SIREN format
:return: A list of ... | ated_resources:
for ent in self.generate_entity(resource, name, embedded):
entities.append(ent)
return entities
def generate_entity(self, resource, name, embedded):
"""
A generator that yields entities
"""
if isinstance(resource, list):
... |
mattBrzezinski/Hydrogen | robot-controller/Study/BaseStudy.py | Python | mit | 6,141 | 0.006676 | from PyQt4 import QtCore
from PyQt4 import QtGui
from Action import Speech
from UI.ActionPushButton import ActionPushButton
class BaseStudy(QtGui.QWidget):
def __init__(self):
super(BaseStudy, self).__init__()
self._actionQueue = None
self._nao = None
self._widgets = None
s... | nnected.disconnect(self.on_nao_disconnected)
#END if
self._nao = nao
if self._nao is not None:
self._nao.connected.connect(self.on_nao_connected)
self._nao.disconnected.connect(self.on_nao_disconnected)
#END if
#END setNao()
def speech(self, txt, speed, s... | s(self.sender().getRobotActions())
#END if
#END on_button_clicked()
def on_nao_connected(self):
pass
#END on_nao_connected()
def on_nao_disconnected(self):
pass
#END on_nao_disconnected()
def on_runSpeech_clicked(self):
if self._actionQueue is not None:
... |
Teamxrtc/webrtc-streaming-node | third_party/webrtc/src/chromium/src/build/android/devil/android/decorators.py | Python | mit | 5,401 | 0.007036 | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Function/method decorators that provide timeout and retry logic.
"""
import functools
import itertools
import sys
from devil.android import device_erro... | *a, **kw: kw.get('retries', default_retries)
return _TimeoutRetryWrapper(f, get_timeout, get_retries, pass_values=True)
return decora | tor
def WithTimeoutAndRetriesFromInstance(
default_timeout_name=DEFAULT_TIMEOUT_ATTR,
default_retries_name=DEFAULT_RETRIES_ATTR,
min_default_timeout=None):
"""Returns a decorator that handles timeouts and retries.
The provided |default_timeout_name| and |default_retries_name| are used to
get the de... |
baike21/blog | blog/settings.py | Python | gpl-3.0 | 4,119 | 0.002444 | # -*- coding: utf-8 -*-
"""
Django settings for blog project.
Generated by 'django-admin startproject' using Django 1.11.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/set... | {
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_ | validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LA... |
slowkid/EulerProject | solutions/problem11.py | Python | unlicense | 5,822 | 0.009275 | #!/usr/bin/env python
"""
Largest product in a grid
Problem 11
Published on 22 February 2002 at 06:00 pm [Server Time]
In the 20x20 grid below, four numbers along a diagonal line have been marked in red.
The product of these numbers is 26 * 63 * 78 * 14 = 1788696.
What is the greatest product of four adjac... | un_length+1):
for column in range(width-run_length+1):
| for i in range(run_length):
for y_dir in (0, 1):
for x_dir in (0,1):
print THE_GRID[row+(y_dir*i)][column+x_dir*i]
def solve(run_length):
height = len(THE_GRID)
width = len(THE_GRID[0])
highest ... |
ktbyers/pynet-ons-mar17 | json_yaml/json_test.py | Python | apache-2.0 | 335 | 0 | #!/usr/bin/env python
import json
my_list = range(10)
my_list.append('whatever')
my_list.append('some thing')
my_dict = {
'key1': 'val1',
'key2': 'val2',
'key3': 'va | l3'
}
my_dict['key4'] = my_list
my_dict['key5'] = False
print my_dict
print json.dumps(my_dict)
with open("my_file.json", "w") as f | :
json.dump(my_dict, f)
|
dsavoiu/kafe2 | kafe2/fit/representation/model/__init__.py | Python | gpl-3.0 | 353 | 0.005666 | """This submodule contains objects for handl | ing different representations of models and model functions.
:synopsis: This submodule contains objects for handling different representations of models and model functions.
.. moduleauthor:: Johannes Gaessler <johannes.gaessler@student.kit.edu>
"""
from ._base import *
from . | yaml_drepr import *
|
AlgoLab/pygfa | pygfa/serializer/utils.py | Python | mit | 1,690 | 0.006509 | from pygfa.graph_element.parser import line, field_validator as fv
SERIALIZATION_ERROR_MESSAGGE = "Couldn't serialize object identified by: "
def _format_exception(identifier, exception):
return SERIALIZATION_ERROR_MESSAGGE + identifier \
+ "\n\t" + repr(exception)
def _remove_common_edge_fields(edge_dict)... | e_dict.pop('eid')
edge_dict.pop('from_node')
edge_dict.pop('from_orn')
edge_dict.pop('to_node')
edge_dict.pop('to_orn')
edge_dict.pop('from_positions')
edge_dict.pop('to_positions')
edge_dict.pop('al | ignment')
edge_dict.pop('distance')
edge_dict.pop('variance')
def _serialize_opt_fields(opt_fields):
fields = []
for key, opt_field in opt_fields.items():
if line.is_optfield(opt_field):
fields.append(str(opt_field))
return fields
def _are_fields_defined(fields):
try:
... |
SheepDogInc/django-base | project_name/urls.py | Python | bsd-3-clause | 294 | 0.003401 | from django.con | f.urls import patterns, include, url
from django.views.generic import TemplateView
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^$', TemplateView. | as_view(template_name='base.html'))
)
|
AnishShah/tensorflow | tensorflow/contrib/data/__init__.py | Python | apache-2.0 | 5,193 | 0.002696 | # Copyright 2017 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... | nd
# limitations under the License.
# ============ | ==================================================================
"""Experimental API for building input pipelines.
This module contains experimental `Dataset` sources and transformations that can
be used in conjunction with the `tf.data.Dataset` API. Note that the
`tf.contrib.data` API is not subject to the same bac... |
dola/Telesto | tools/protocol/telesto/plot/phases.py | Python | mit | 718 | 0.001393 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from telesto import plot
OFFSET = 1000 # REMEMBER TO CALCULATE MANUALLY!
def main():
path = sys.argv[1]
mean = plot.mean(
plot.rows(path, plot.parse_middleware_line),
("waiting", "parsing", "database", "r | esponse")
)
dev = plot.standard_deviation(
plot.rows(path, plot.parse_middleware_line), mean
)
print "#",
for key in mean:
print key,
print
for key in mean:
print mean[key],
print
for key in mean:
print 100.0 * mean[key] / sum(mean.itervalues()),
... |
if __name__ == "__main__":
main()
|
kili/playbooks | filter_plugins/netmask_conversion.py | Python | gpl-3.0 | 1,194 | 0 | def len2mask(len):
"""Convert a bit length to a dotted netmask (aka. CIDR to netmask)"""
mask = ''
if not isinstance(len, int) or len < 0 or len > 32:
print "Illegal subnet length: %s (w | hich is a %s)" % \
(str(len), type(len).__name__)
return None
for t in range(4):
if len > 7:
mask += '255.'
else:
dec = 255 - (2**(8 - len) - 1)
mask += str(dec) + '.'
len -= 8
if len < 0:
len = 0
return mask[:... | ets = [int(x) for x in subnet.split(".")]
count = 0
for octet in octets:
highest_bit = 128
while highest_bit > 0:
if octet >= highest_bit:
count = count + 1
octet = octet - highest_bit
highest_bit = highest_bit / 2
else:
... |
zwffff2015/stock | task/GetStockHistoryInfoTask.py | Python | mit | 7,619 | 0.004191 | # coding=utf-8
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), "..")))
from db.MysqlUtil import initMysql, execute, select, batchInsert, disconnect
from common.JsonHelper import loadJsonConfig
from api.tushareApi import getSimpleHistoryData
from datetime import datetime, timedelta
f... | etcwd(), "../config/newStockList.json")))
updateStockHistoryInfoByTHS(stockList)
def updateAllStockHistoryInfo():
sql = unicode("select code,name from s_stock_info order by code asc")
data = select(sql)
updateStockHistoryInfoByTHS(data)
def updateStockOtherInfo():
sql = unicode("select code,name... | 1126:
continue
selectInfoSql = unicode("select date,closePrice from s_stock where code='{0}' order by date asc").format(code)
data = select(selectInfoSql)
writeLog(unicode("更新股票其他指标数据: code: {0}").format(code))
updataStockBias(code, data, 6)
updataStockBias(code, dat... |
luskaner/wps-dict | wps_dict/wps_dict/providers/offline/list.py | Python | gpl-3.0 | 81 | 0 | fr | om . import *
offline_providers = {
'builtin': builtin.ProviderBuilti | n,
}
|
tiancj/emesene | emesene/e3/xmpp/SleekXMPP/sleekxmpp/plugins/xep_0085/chat_states.py | Python | gpl-3.0 | 1,636 | 0 | """
SleekXMPP: The Sleek XMPP Library
Copyright (C) 2011 Nathanael C. Fritz, Lance J.T. Stout
This file is part of SleekXMPP.
See the file LICENSE for copying permissio
"""
import logging
import sleekxmpp
from sleekxmpp.stanza import Message
from sleekxmpp.xmlstream.handler import Callback
from sleek... | _0085(BasePlugin):
"""
XEP-0085 Chat State Notifications
"""
name = 'xep_0085'
description = 'XEP-0085: Chat State Notifications'
dependencies = set(['xep_0030'])
stanza = stanza
def plugin_init(self):
self.xmpp.register_handler(
Callback('Chat State',
... | stanza.Active)
register_stanza_plugin(Message, stanza.Composing)
register_stanza_plugin(Message, stanza.Gone)
register_stanza_plugin(Message, stanza.Inactive)
register_stanza_plugin(Message, stanza.Paused)
def plugin_end(self):
self.xmpp.remove_handler('Chat State')
de... |
aequitas/home-assistant | homeassistant/components/sonos/media_player.py | Python | apache-2.0 | 37,431 | 0 | """Support to interface with Sonos players."""
import asyncio
import datetime
import functools as ft
import logging
import socket
import time
import urllib
import async_timeout
import pysonos
import pysonos.snapshot
from pysonos.exceptions import SoCoUPnPException, SoCoException
from homeassistant.components.media_pl... | specified UPnP errors from logs and avoid exceptions."""
def decorator(funct):
"""Decorate functions."""
@ft.wraps(funct)
def wrapper(*args, **kwargs):
"""Wrap for all soco UPnP exception."""
try:
return funct(*args, **kwargs)
| except SoCoUPnPException as err:
if errorcodes and err.error_code in errorcodes:
pass
else:
_LOGGER.error("Error on %s with %s", funct.__name__, err)
except SoCoException as err:
_LOGGER.error("Error on %s with %s", fu... |
jantman/webhook2lambda2sqs | webhook2lambda2sqs/version.py | Python | agpl-3.0 | 1,938 | 0.000516 | """
The latest version of this package is available at:
<http://github.com/jantman/webhook2lambda2sqs>
####################################### | #########################################
Copyright 2016 Jason Antman <jason@j | asonantman.com> <http://www.jasonantman.com>
This file is part of webhook2lambda2sqs, also known as webhook2lambda2sqs.
webhook2lambda2sqs is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, e... |
JamesTFarrington/hendrix | hendrix/defaults.py | Python | mit | 209 | 0 | import os
CACHE_PORT = 80 | 80
HTTP_PORT = 8000
HTTPS_PORT = 4430
DEFAULT_MAX_AGE = 3600
DEFAULT_LOG_PATH = os.path.dirname(__file__)
DEFAULT_ | LOG_FILE = os.path.join(DEFAULT_LOG_PATH, 'default-hendrix.log')
|
jonathanmorgan/reddit_collect | examples/praw_testing.py | Python | gpl-3.0 | 5,265 | 0.02754 | # SET THE FOLLOWING EITHER BEFORE RUNNING THIS FILE OR BELOW, BEFORE INITIALIZING
# PRAW!
# set variables for interacting with reddit.
# my_user_agent = ""
# my_username = ""
# my_password = ""
# reddit_post_id = -1
# import praw - install: pip install praw
# Praw doc: https://praw.readthedocs.org/en/latest/index... | int( "==> Created reddit instance." )
# retrieve post
# - post with lots of comments - 1bvkol has 22014
#reddit_post_id = "1bvkol"
post = r.get_submission( submission_id = reddit_post_id, comment_limit = 1500, comment_sort = "old" )
print( | "Retrieved post " + str( reddit_post_id ) )
# output number of comments based on post
print( "==> post.permalink: " + post.permalink )
print( "==> post.num_comments: " + str( post.num_comments ) )
# use the replace_more_comments() method to pull in as many comments as possible.
post.replace_more_comments( limit = Non... |
garrettkatz/directional-fibers | dfibers/examples/lorenz.py | Python | mit | 3,181 | 0.019491 | """
Fiber-based fixed point location in the Lorenz system
f(v)[0] = s*(v[1]-v[0])
f(v)[1] = r*v[0] - v[1] - v[0]*v[2]
f(v)[2] = v[0]*v[1] - b*v[2]
Reference:
http://www.emba.uvm.edu/~jxyang/teaching/Math266notes13.pdf
https://en.wikipedia.org/wiki/Lorenz_system
"""
import numpy as np
import matplotlib.pyp... | lect attractor points
t = np.arange(0,40,0.01)
v = np.ones((N,1))
A = si.odeint(lambda v, t: f(v.reshape((N,1))).flatten(), v.flatten(), t).T
# Set up fiber arguments
v = np.zeros((N,1))
# c = np.random.randn(N,1)
c = np.array([[0.83736021, -1.87848114, 0.43935044]]).T
fiber_kwargs = {
... | "c": c,
"terminate": lambda trace: (np.fabs(trace.x[:N,:]) > 50).any(),
"max_step_size": 1,
"max_traverse_steps": 2000,
"max_solve_iterations": 2**5,
}
print("using c:")
print(c.T)
# Visualize strange attractor
ax = pt.gca(projection="3d")
ax.plot(*A, color='g... |
carpyncho/feets | feets/datasets/synthetic.py | Python | mit | 10,431 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# The MIT License (MIT)
# Copyright (c) 2017 Juan Cabral
# 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 withou... | ta.
ds_name : str (default="feets-synthetic")
Name of the dataset
description : str (default="Lightcurve created with random numbers")
Description of the data
bands : tuple of strings (default=("B", "V"))
The bands to be created
metadata : dict-like or None (default=None)
... | --------
.. code-block:: pycon
>>> from numpy import random
>>> create_random(
... magf=random.normal, magf_params={"loc": 0, "scale": 1},
... errf=random.normal, errf_params={"loc": 0, "scale": 0.008})
Data(id=None, ds_name='feets-synthetic', bands=('B', 'V'))
... |
obiwanus/django-qurl | qurl/models.py | Python | mit | 22 | 0 | # Say hell | o to Dj | ango
|
0ppen/introhacking | code_from_book.py | Python | mit | 16,192 | 0.000628 | # Python Code From Book
# This file consists of code snippets only
# It is not intended to be run as a script
raise SystemExit
####################################################################
# 3. Thinking in Binary
####################################################################
import magic
print magic.f... | 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128)
file = """潍楪慢敫椠桴慧扲敬整瑸琠慨⁴獩琠敨爠獥汵⁴景琠硥⁴敢湩敤潣敤獵湩湡甠楮瑮湥敤档
牡捡整湥潣楤杮楷桴挠浯汰瑥汥⁹湵敲慬整湯獥景整牦浯愠搠晩敦敲瑮眠楲楴杮猠獹整‧⠊慔敫
牦浯攠 | 楷楫数楤牯⥧"""
print file.decode('utf8').encode('utf16')
# ??Mojibake is the garbled text that is the result of text being decoded using an
# unintended character encoding with completely unrelated ones, often from a
# different writing system.' (Taken from en.wikipedia.org)
import ftfy
ftfy.fix_text(u"“Mojibakeâ€... |
schreiberx/sweet | mule_local/python/mule_local/postprocessing/shtnsfiledata.py | Python | mit | 3,227 | 0.008057 | #! /usr/bin/env python3
import math, sys
import shtns
import numpy as np
class shtnsfiledata:
#
# Adopted from https://bitbucket.org/nschaeff/shtns/src/master/examples/shallow_water.py
#
def __init__(
self,
rsphere = 1.0
):
self.rsphere = rsphere
def setup(sel... | set_grid(nlats,nlons,shtns.sht_gauss_fly|shtns.SHT_PHI_CONTIGUOUS, 1.e-10)
self._shtns.set_grid(nlats, nlons, shtns.sht_quick_init|shtns.SHT_PHI_CONTIGUOUS, 0)
elif file_info['grid_type'] == 'REGULAR':
#self._shtns.set_grid(nlats,nlons,shtns.sht_reg_dct|shtns.SHT_PHI_CONTIGUOUS, 1.e-10)... |
raise Exception("Grid type '"+file_info['grid_type']+"' not supported!")
self.lats = np.arcsin(self._shtns.cos_theta)
self.lons = (2.*np.pi/nlons)*np.arange(nlons)
self.nlons = nlons
self.nlats = nlats
self.ntrunc = ntrunc
self.nlm = self._shtns.nlm
... |
math-a3k/django-ai | django_ai/base/views.py | Python | lgpl-3.0 | 2,787 | 0 | # -*- coding: utf-8 -*-
import inspect
import random
import numpy as np
from django.contrib import messages
from django.views.generic import RedirectView
from django.contrib.contenttypes.models import ContentType
from django.http import Http404
from django.contrib.auth.mixins import UserPassesTestMixin
class RunAct... | if kwargs['action'] not in self.ACTIONS:
raise Http404("Action not Found")
if self.ACTIONS[kwargs['action']]["type"] == 'object':
action_object = self.get_ct_object(kwargs['content_type'],
| kwargs['object_id'])
else:
action_object = None
self.run_action(self.ACTIONS[kwargs['action']], action_object)
return(self.request.META.get('HTTP_REFERER', '/'))
|
ghutchis/cclib | src/cclib/writer/cjsonwriter.py | Python | lgpl-2.1 | 4,465 | 0.000896 | # This file is part of cclib (http://cclib.github.io), a library for parsing
# and interpreting the results of computational chemistry packages.
#
# Copyright (C) 2014, the cclib development team
#
# The library is free software, distributed under the terms of
# the GNU Lesser General Public version 2.1 or later. You s... | = self.ccdata.moenergies[0][homo_idx_alpha + 1]
energy_alpha_gap = energy_alpha_lumo - energy_alpha_homo
energy_beta_homo = self.ccdata.moenergies[-1][homo_idx_beta]
energy_beta_lumo = self.ccdata.moenergies[-1][homo_idx_beta + 1]
energy_beta_gap = energy_beta_lumo - energy_beta_homo
... | [-1]
cjson_dict['energy']['alpha'] = dict()
cjson_dict['energy']['alpha']['homo'] = energy_alpha_homo
cjson_dict['energy']['alpha']['lumo'] = energy_alpha_lumo
cjson_dict['energy']['alpha']['gap'] = energy_alpha_gap
cjson_dict['energy']['beta'] = dict()
cjson_dict['energy... |
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/sklearn/tests/test_hmm.py | Python | agpl-3.0 | 26,383 | 0.000493 | import numpy as np
from numpy.testing import assert_array_equal, assert_array_almost_equal
from unittest import TestCase
from sklearn.datasets.samples_generator import make_spd_matrix
from sklearn import hmm
from sklearn import mixture
from sklearn.utils.extmath import logsumexp
from sklearn.utils import check_random... | tprob.sum()
self.transmat = prng.rand(n_components, n_components)
self.transmat /= np.tile(self.transmat.sum(axis=1)[:, np.new | axis],
(1, n_components))
self.means = prng.randint(-20, 20, (n_components, n_features))
self.covars = {
'spherical': (1.0 + 2 * np.dot(prng.rand(n_components, 1),
np.ones((1, n_features)))) ** 2,
'tied': (make_spd_matrix... |
jdemon519/cfme_tests | cfme/configure/access_control.py | Python | gpl-2.0 | 24,877 | 0.001729 | from functools import partial
from navmazing import NavigateToSibling, NavigateToAttribute
from cfme import Credential
from cfme.exceptions import CandidateNotFound, OptionNotAvailable
import cfme.fixtures.pytest_selenium as sel
import cfme.web_ui.toolbar as tb
from cfme.web_ui import (
AngularSelect, Form, Selec... | me.login import logout
logger.info('Restoring to old user: %s', self._restore_user.credential.principal)
logout()
self.appliance.user = self._restore_user
self._restore_user = None
def create(self):
navigate_to( | self, 'Add')
fill(self.user_form, {'name_txt': self.name,
'userid_txt': self.credential.principal,
'password_txt': self.credential.secret,
'password_verify_txt': self.credential.verify_secret,
... |
mitodl/micromasters | discussions/signals.py | Python | bsd-3-clause | 2,043 | 0.004405 | """
Signals for user profiles
"""
from django.conf import settings
from django.db import transaction
from django.db.models.signals import post_delete, post_save
from django.dispatch import receiver
from discussions import tasks
from profiles.models import Profile
from roles.models import Role
from roles.roles import P... | eturn
transaction.on_commit(
lambda: tasks.add_user_as_moderator_to_channel.delay(
instance.user_id,
instance.program_id,
)
)
@receiver(post_delete, sender=Role, dispatch_uid="delete_staff_as_moderator")
def delete_staff_as_moderator(sender, instance, **kwargs): # pyl... | R_SYNC', False):
return
if instance.role not in Role.permission_to_roles[Permissions.CAN_CREATE_FORUMS]:
return
transaction.on_commit(
lambda: tasks.remove_user_as_moderator_from_channel.delay(
instance.user_id,
instance.program_id,
)
)
|
googleads/google-ads-python | google/ads/googleads/v8/services/services/ad_service/client.py | Python | apache-2.0 | 21,991 | 0.000909 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | onent segments."""
m = re.match(
r"^customers/(?P<customer_id>.+?)/ads/(?P<ad_id>.+?)$", path
)
return m.groupdict() if m else {}
@staticmethod
def common_billing_account_path(billing_account: str,) -> str:
"""Return a fully-qualified billing_account string."""
... | billing_account=billing_account,
)
@staticmethod
def parse_common_billing_account_path(path: str) -> Dict[str, str]:
"""Parse a billing_account path into its component segments."""
m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path)
return m.groupdict() i... |
adini121/oneanddone | oneanddone/users/tests/test_mixins.py | Python | mpl-2.0 | 3,843 | 0.001041 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from django.core.exceptions import PermissionDenied
from mock import Mock, patch
from nose.tools import eq_, raises
fro... | eq_(self.view.dispatch(request), 'fakemixin')
@raises(PermissionDenied)
def test_not_staff(self):
"""
If the user is not staff, raise a PermissionDenied exception.
"""
request = Mock()
request.user = UserFactory.create(is_staff=False)
self.view.dispatch(request)
... | _privacy_policy(self):
"""
If the user has created a profile, and has accepted privacy policy
call the parent class's dispatch method.
"""
request = Mock()
request.user = UserProfileFactory.create(privacy_policy_accepted=True).user
eq_(self.view.dispatch(request)... |
gangadhar-kadam/hrerp | erpnext/patches/4_0/fix_employee_user_id.py | Python | agpl-3.0 | 491 | 0.028513 | import frappe
from frappe.utils import get_fullname
def execute():
for user_id in frappe.db.sql_list("""select distinct user_id from `tabEmployee`
where ifnul | l(user_id, '')!=''
group by user_i | d having count(name) > 1"""):
fullname = get_fullname(user_id)
employee = frappe.db.get_value("Employee", {"employee_name": fullname, "user_id": user_id})
if employee:
frappe.db.sql("""update `tabEmployee` set user_id=null
where user_id=%s and name!=%s""", (user_id, employee)) |
liqd/a4-meinberlin | meinberlin/apps/votes/apps.py | Python | agpl-3.0 | 132 | 0 | from django.apps import AppConfig
|
cl | ass VotesConfig(AppConfig):
name = 'meinberlin.apps.votes'
label = 'meinberlin_votes'
|
StanczakDominik/PythonPIC | pythonpic/tests/test_FieldSolver.py | Python | bsd-3-clause | 9,551 | 0.003036 | # coding=utf-8
import matplotlib.pyplot as plt
import numpy as np
import pytest
from ..classes import Simulation, PeriodicTestGrid, NonperiodicTestGrid
from ..visualization.time_snapshots import FieldPlot, CurrentPlot
@pytest.fixture(params=(64, 128, 256, 512))
def _NG(request):
return request.param
@pytest.fi... | l=r"$E$")
xspace.plot(x, anal_field, "b-", lw=6, alpha=0.5, label=r"$E_a$")
xspace.set_xlim(0, _L)
xspace.set_xlabel("$x$")
xspace.grid()
xspace.legend(loc='best')
fig2, fspace = plt.subplots()
fspace.plot(g.k_plot, g.energy_per_mode, "bo--", label=r"electric ene... | ace.set_title("Fourier space")
fspace.grid()
fspace.legend(loc='best')
plt.show()
return "test_PoissonSolver_complex failed!"
energy_correct = np.allclose(energy_fourier, energy_direct)
assert energy_correct, plots()
field_correct = np.allclose(g.electric_field[1:-1, 0], an... |
jmwenda/hypermap | hypermap/aggregator/tests/test_warper.py | Python | mit | 1,877 | 0.001598 | # -*- coding: utf-8 -*-
"""
Tests for the WMS Service Type.
"""
import unittest
from httmock import with_httmock
import mocks.warper
from aggregator.models import Service
class TestWarper(unit | test.TestCase):
@with_httmock(mocks.warper.resource_get)
def test_create_wms_service(self):
# create the service
service = Service(
type='WARPER',
url='http://warper.example.com/warper/m | aps',
)
service.save()
# check layer number
self.assertEqual(service.layer_set.all().count(), 15)
# check layer 0 (public)
layer_0 = service.layer_set.all()[0]
self.assertEqual(layer_0.name, '29568')
self.assertEqual(layer_0.title, 'Plate 24: Map bounded... |
wufangjie/leetcode | 735. Asteroid Collision.py | Python | gpl-3.0 | 882 | 0 | class Solution(object):
def asteroidCollision(self, asteroids):
"""
:type asteroids: List[int]
:rtype: List[int]
"""
ret = []
for elem in asteroids:
if elem > 0:
ret.append(elem)
else:
while ret:
... | olution().asteroidCollision([5, 10, -5]))
print(Solution().asteroidCollision([8, -8]))
p | rint(Solution().asteroidCollision([10, 2, -5]))
print(Solution().asteroidCollision([-2, -1, 1, 2]))
|
google-research/tensorflow-coder | tf_coder_colab_logging/serialization.py | Python | apache-2.0 | 6,543 | 0.004585 | # Copyright 2021 The TF-Coder 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... | ot work in Python 2 because its ast.literal_eval do | es not
support sets.
Args:
to_serialize: The object to serialize. This may be a Python literal (int,
float, boolean, string, or None), Tensor, SparseTensor, or
possibly-nested lists/tuples/sets/dicts of these.
Returns:
A string representation of the object.
"""
return repr(_object_to_lit... |
InfoSec-CSUSB/club-websystem | src/events/models.py | Python | mit | 10,430 | 0.020997 | from datetime import date, timedelta
from django.db import models
from django.contrib.sites.models import Site
from django.core.validators import MinValueValidator
from clubdata.models import Club
def range_date_inclusive(start_date, end_date):
for n in range((end_date - start_date).days+1):
yield start_da... | rt = self.rule_type
for t in self.rule_type_choices:
if t[0] == rt:
rt = t[1]
break
return "%s Event, %s to %s, Criteria=\"%s\"" % (rt, self.starts_on, self.ends_on, self.criteria)
def dates_per_rule_iter(self):
if self.rule_type == self.WEEKLY:
# criteria = Must be a comm... | # of the week. Ex: mo,we,fr,su
# repeat_each = If this is 2, then every other week will be skipped. If it is 3,
# then two weeks will be skipped between each filled week. etc...
# Deconstruct the criteria
criteria = decode_weekly_criteria(self.criteria)
# Generate a list of dates t... |
kawamon/hue | desktop/core/ext-py/Django-1.11.29/tests/check_framework/tests_1_10_compatibility.py | Python | apache-2.0 | 688 | 0.001453 | from django.core.checks.compatibility.django_1_10 import (
check_duplicate_middleware_settings,
)
from django.test import SimpleTestCase
from django.test.utils import override_settings
class CheckDuplicateMiddlwareSettingsTest(SimpleTestC | ase):
@override_settings(MIDDLEWARE=[], MIDDLEWARE_CLASSES=['django.middle | ware.common.CommonMiddleware'])
def test_duplicate_setting(self):
result = check_duplicate_middleware_settings(None)
self.assertEqual(result[0].id, '1_10.W001')
@override_settings(MIDDLEWARE=None)
def test_middleware_not_defined(self):
result = check_duplicate_middleware_settings(No... |
rtucker-mozilla/inventory | migrate_dns/management/commands/dns_migrate.py | Python | bsd-3-clause | 204 | 0.004902 | f | rom django.core.management.base import BaseCommand
from migrate_dns.import_utils import do_import
class Command(BaseCommand):
args = ''
def handle(self, *args, **options):
| do_import()
|
wisechengyi/pants | tests/python/pants_test/binaries/test_binary_tool.py | Python | apache-2.0 | 6,038 | 0.003478 | # Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
from pants.binaries.binary_tool import BinaryToolBase
from pants.binaries.binary_util import (
BinaryToolFetcher,
BinaryToolUrlGenerator,
BinaryUtil,
HostPlatfor... | name = "replacing_legacy_options_tool"
default_version = "a2f4ab23a4c"
replaces_scope = "old_tool_scope"
replaces_name = "old_tool_version"
class BinaryUtilFakeUname(BinaryUtil):
def host_platform(self):
return HostPlatform("xxx", "yyy")
class CustomUrlGenerator(BinaryToolUrlGenerator):
... | host_platform):
base = self._DIST_URL_FMT.format(
version=version, system_id=self._SYSTEM_ID[host_platform.os_name]
)
return [
base,
f"{base}-alternate",
]
class CustomUrls(BinaryToolBase):
options_scope = "custom-urls"
name = "custom_urls_to... |
pexip/meson | test cases/common/229 custom_target source/x.py | Python | apache-2.0 | 132 | 0 | #! /usr/bi | n/env python3
with open('x.c', 'w') as f:
print('int main(void) { return 0; }', file=f)
with open('y', 'w'):
pass | |
e1ven/Waymoot | libs/tornado-2.2/build/lib/tornado/curl_httpclient.py | Python | mit | 18,106 | 0.000663 | #!/usr/bin/env python
#
# Copyright 2009 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | grading "
"libcurl and pycurl will improve performance")
self._socket_action = \
lambda fd, action: self._multi.socket_all()
# libcurl has bugs that sometimes cause it to not report all
# relevant file des | criptors and timeouts to TIMERFUNCTION/
# SOCKETFUNCTION. Mitigate the effects of such bugs by
# forcing a periodic scan of all active requests.
self._force_timeout_callback = ioloop.PeriodicCallback(
self._handle_force_timeout, 1000, io_loop=io_loop)
self._force_timeout_cal... |
nmichaud/enable-mapping | mapping/enable/api.py | Python | bsd-3-clause | 273 | 0 |
from canvas import Mappi | ngCa | nvas
from viewport import MappingViewport
try:
from geojson_overlay import GeoJSONOverlay
except ImportError:
# No geojson
pass
# Tile managers
from mbtile_manager import MBTileManager
from http_tile_manager import HTTPTileManager
|
stackArmor/security_monkey | migrations/versions/ea2739ecd874_.py | Python | apache-2.0 | 646 | 0.003096 | """Ensures that account.identifier is unique.
Revision ID: ea2739ecd874
Revises: 5bd631a1b748
Create Date: 2017-09-29 09:16:09.436339
"""
# revision | identifiers, used by Alembic.
revision = 'ea2739ecd874'
down_revision = '5bd631a1b748'
from alembic import | op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_unique_constraint(None, 'account', ['identifier'])
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(N... |
Iconik/eve-suite | src/model/static/sta/services.py | Python | gpl-3.0 | 624 | 0.00641 | from model.flyweight import Flyweight
from model.static.database import database
class Service(Flyweight):
def __init__(self,service_id):
#prevents reinitializing
if "_in | ited" in self.__dict__:
return
self._inited = None
#prevents reinitializing
self.service_id = service_id
cursor = database.get_cursor(
"select * from staServices where serviceID={};".format(
s | elf.service_id))
row = cursor.fetchone()
self.service_name = row["serviceName"]
self.description = row["description"]
cursor.close()
|
IBT-FMI/SAMRI | samri/fetch/test/test_local.py | Python | gpl-3.0 | 2,202 | 0.052225 | import numpy as np
def test_prepare_abi_connectivity_maps():
from samri.fetch.local import prepare_abi_connectivity_maps
prepare_abi_connectivity_maps('Ventral_tegmental_area',
invert_lr_experiments=[
"127651139",
"127796728",
"127798146",
"127867804",
"156314762",
"160539283",
"160540751",
... | e_as='/var/tmp/samri_testing/pytest/vta_127651139.nii.gz',
)
def test_summary_atlas():
from samri.fetch.local import summary_atlas
mapping='/usr/share/mouse-brain-templates/d | surqe_labels.csv'
atlas='/usr/share/mouse-brain-templates/dsurqec_40micron_labels.nii'
summary={
1:{
'structure':'Hippocampus',
'summarize':['CA'],
'laterality':'right',
},
2:{
'structure':'Hippocampus',
'summarize':['CA'],
'laterality':'left',
},
3:{
'structure':'Cortex',
'summari... |
crosswalk-project/crosswalk-test-suite | apptools/apptools-android-tests/apptools/manifest_xwalk_target_platforms.py | Python | bsd-3-clause | 6,310 | 0.000792 | #!/usr/bin/env python
#
# Copyright (c) 2016 Intel Corporation.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of works must retain the original copyright notice, this
# list of conditions and t... | if comm.BIT == "6 | 4":
self.assertIn("64", apks[i])
apkLength = apkLength + 1
self.assertEquals(apkLength, 2)
else:
for i in range(len(apks)):
if apks[i].endswith(".apk") and "shared" in apks[i]:
apkLength = apkLength + 1
... |
seryl/Nodetraq | nodetraq/tests/functional/test_pools.py | Python | mit | 200 | 0.005 | from nodetraq.tests import *
class | TestPoolsController(TestController):
def test_index(self):
response = self.app.get(url(controller='pools', action='index'))
# T | est response...
|
ajylee/gpaw-rtxs | gpaw/test/cmr_append.py | Python | gpl-3.0 | 2,763 | 0.003257 | # this example shows how to append new calculated results to an already
# existing cmr file, illustrated for calculation of PBE energy on LDA density
import os
import cmr
# set True in order to use cmr in parallel jobs!
cmr.set_ase_parallel(enable=True)
from ase.structure import molecule
from ase.io import read, wri... | the *cmr file below)
if 1: # not used in this example
calc2.write(formula + '.db', cmr_params=cmr_params)
# write the information 'as in' corresponding trajectory file into cmr file
write(cmrfile, system2, cmr_params=cmr_params)
# add the xc tag to the cmrfile
assert os.path.exists(cmrfile)
data = cmr.read(cmrfil... | ults to the cmrfile
assert os.path.exists(cmrfile)
data = cmr.read(cmrfile)
data.set_user_variable('PBE', data['ase_potential_energy'] + ediff)
data.write(cmrfile)
# analyse the results with CMR
# cmr readers work only in serial!
from cmr.ui import DirectoryReader
if rank == 0:
reader = DirectoryReader(director... |
GovReady/govready-q | guidedmodules/migrations/0011_modulequestion_answer_type_module.py | Python | gpl-3.0 | 1,551 | 0.002579 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.8 on 2016-08-22 16:03
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
def forwards_func(apps, schema_editor):
# We get the model from the versioned app registry;
# if we directly import it, it'l... | ls.deletion.PROTECT,
related_name='is_type_of_answer_to',
| to='guidedmodules.Module',
),
),
migrations.RunPython(forwards_func, migrations.RunPython.noop),
]
|
balajikris/autorest | src/generator/AutoRest.Python.Azure.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/microsoftazuretesturl/credentials.py | Python | mit | 731 | 0 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | enerated.
# --------------------------------------------------------------------------
from msrest.authentication import (
BasicAut | hentication,
BasicTokenAuthentication,
OAuthTokenAuthentication)
from msrestazure.azure_active_directory import (
InteractiveCredentials,
ServicePrincipalCredentials,
UserPassCredentials)
|
hillwoodroc/deepin-music-player | src/widget/combo.py | Python | gpl-3.0 | 10,334 | 0.009386 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 ~ 2012 Deepin, Inc.
# 2011 ~ 2012 Hou Shaohui
#
# Author: Hou Shaohui <houshao55@gmail.com>
# Maintainer: Hou Shaohui <houshao55@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the ter... | icon_group |
if widget.state == gtk.STATE_NORMAL:
bg_image = bg_normal_dpixbuf.get_pixbuf()
fg_image = fg_normal_dpixbuf.get_pixbuf()
elif widget.state == gtk.STATE_PRELIGHT:
bg_image = bg_hover_dpixbuf.get_pixbuf()
fg_image = fg_hover_dpixbuf.get_pixbuf()
... |
maximumG/exscript | tests/Exscript/AccountPoolTest.py | Python | mit | 4,218 | 0.000948 | from builtins import range
import sys
import unittest
import re
import os.path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
from Exscript import Account
from Exscript.account import AccountPool
from Exscript.util.file import get_accounts_from_file
class AccountPoolTest(unittest.TestCase):
... | def testAcquireAccount(self):
| self.testAddAccount()
self.accm.acquire_account(self.account1)
self.account1.release()
self.accm.acquire_account(self.account1)
self.account1.release()
# Add three more accounts.
filename = os.path.join(os.path.dirname(__file__), 'account_pool.cfg')
self.acc... |
AutorestCI/azure-sdk-for-python | azure-mgmt-datafactory/azure/mgmt/datafactory/models/sap_hana_linked_service.py | Python | mit | 3,345 | 0.001495 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | type to be used to connect
to t | he SAP HANA server. Possible values include: 'Basic', 'Windows'
:type authentication_type: str or
~azure.mgmt.datafactory.models.SapHanaAuthenticationType
:param user_name: Username to access the SAP HANA server. Type: string (or
Expression with resultType string).
:type user_name: object
:par... |
franck-talbart/codelet_tuning_infrastructure | ctr-common/plugins/4e7420cd-904e-4c2a-b08f-02c867ba4cd8/wiki2man.py | Python | gpl-3.0 | 27,388 | 0.005226 | # -*- coding: UTF-8 -*-
import sys
WorkList = None
def SH(i):
"""reformatting .SH"""
global WorkList
string = WorkList[i]
l = len(string) - 2
r = 0
while string[0] == '=' and string[l] == '=':
WorkList[i] = string[1:l]
string = WorkList[i]
l = len(string) - 1
r... | tab2 = tab2 - 1
elif string[:8] == '|valign=' and tab2 > 0:
j = 9
while len(string) > j and string[j]!='|':
j = j + 1
if string[j] == '|':
if co... | WorkList[i] = '\n.TP\n' + string[j+1:]
col = 1
elif col > 0:
WorkList[i] = string[j+1:]
col = 2
elif col > 1:
WorkList[i] = '... |
kubeflow/kfp-tekton-backend | samples/core/condition/condition.py | Python | apache-2.0 | 2,572 | 0.001555 | #!/usr/bin/env python3
# Cop | yright 2019 Google LLC
#
# Licensed under | the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is di... |
sindresf/The-Playground | Python/Machine Learning/ScikitClassifiers/Classifiers/Random_Forrest_Classification.py | Python | mit | 724 | 0.008287 | import pandas as pd
from sklearn import model_selection
from sklearn.ensemble import RandomForestClassifier
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data"
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
df = pd.read_c... | 0
max_features = 3
kfold = model_selection.KFold(n_splits=10, random_state=seed)
model = RandomForestClassifier(n_estimators=num_trees, max_features=max_features)
results = model_selection.cross_val_score(model, X, y, | cv=kfold)
print('results: ')
print(results)
print()
print('mean: ' + str(results.mean())) |
saguas/jasperserverlib | jasperserverlib/core/ResourcesTypeResolverUtil.py | Python | mit | 2,430 | 0.017284 | from resource_media_types import *
from ClientFile import ClientFile
from ClientFolder import ClientFolder
from queryResource import ClientQuery
class ResourcesTypeResolverUtil(object):
classes = {}
#classes[ClientAdhocDataView.__name__] = ResourceMediaType.ADHOC_DATA_VIEW_MIME
#classes[ClientAw... | E_MIME
#classes[ClientDataType.__name__] = ResourceMediaType.DATA_TYPE_MIME
classes[ClientFile.__name__] = TYPE_FILE
classes[ClientFolder.__name__] = TYPE_FOLDER
#classes[ClientInputControl.__name__] = ResourceMediaType.INPUT_CONTROL_MIME
#classes[ClientJdbcDataSource.__name__] = Re | sourceMediaType.JDBC_DATA_SOURCE_MIME
#classes[ClientJndiJdbcDataSource.__name__] = ResourceMediaType.JNDI_JDBC_DATA_SOURCE_MIME
#classes[ClientListOfValues.__name__] = ResourceMediaType.LIST_OF_VALUES_MIME
#put(ClientMondrianConnection.class, ResourceMediaType.MONDRIAN_CONNECTION_MIME);
#put(ClientMond... |
ryfeus/lambda-packs | pytorch/source/caffe2/python/operator_test/onnx_while_test.py | Python | mit | 3,154 | 0.000951 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from caffe2.proto import caffe2_pb2
from caffe2.python import core, workspace
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
from hypothesis ... | def ref(max_trip_count, condition, first_init, second_init):
first = 1
second = 1
results = []
if condition:
for _ in range(max_trip_count):
third = first + second
first = s | econd
second = third
results.append(third)
if third > 100:
break
return (first, second, np.array(results).astype(np.float32))
self.assertReferenceChecks(
gc,
while_op,
[max_trip_c... |
changyuheng/code-jam-solutions | 2014/Round 1B/A.py | Python | mit | 1,248 | 0.004006 | # -*- coding: utf-8 -*-
import sys
def get_skeleton(N, strings):
skeletons = []
for i in range(N):
skeleton = [strings[i][0]]
skeleton += [strings[i][j] for j in range(1, len(strings[i])) if strings[i][j] != strings[i][j-1]]
skeletons.append(skeleton)
for i in range(1, N):
... | if len(skeleton) == 0:
return 'Fegla Won'
lengths = []
for | c in skeleton:
length = dict()
for i in range(N):
for j in range(len(strings[i])):
if strings[i][j] != c:
break
length[j] = length.get(j, 0) + 1
strings[i] = strings[i][j:] if j < len(strings[i]) else ''
lengths.append(leng... |
lzw120/django | django/db/models/base.py | Python | bsd-3-clause | 39,705 | 0.002393 | import copy
import sys
from functools import update_wrapper
from future_builtins import zip
import django.db.models.manager # Imported to register signal handler.
from django.conf import settings
from django.core.exceptions import (ObjectDoesNotExist,
MultipleObjectsReturned, FieldError, ValidationError, NON_F... | tr_meta:
meta = getattr(new_class, 'Meta', None)
else:
meta = attr_meta
base_meta = getattr(new_class, '_meta', None)
if getattr(meta | , 'app_label', None) is None:
# Figure out the app_label by looking one level up.
# For 'django.contrib.sites.models', this would be 'sites'.
model_module = sys.modules[new_class.__module__]
kwargs = {"app_label": model_module.__name__.split('.')[-2]}
else:
... |
deeso/python_scrirpts | tax stuff.py | Python | apache-2.0 | 15,594 | 0.026549 | import urllib
import urllib2
import threading
BaseProp = 361995
EndProp = 362044
proxies = {'http': 'http://localhost:8080'}
# handles getting the owner pdf listing of the home
class DoNothingRedirectHandler(urllib2.HTTPRedirectHandler):
def http_error_302(self, req, fp, code, msg, headers):
... | ).read()
def get_pdf_listing(propId, ownerId, owner_name):
fname = owner_name.replace(" ","_").replace(",","").replace("&","and")+".pdf"
x = get_data_location(propId, ownerId)
if x.headers:
url = x.getheader('Location')
if url == "":
return
url = "http://.org/"+url.split("#")[0]
pdf = get_data_... | .append('R%d'%i)
CurrentYear = 2010
EndYear = 2006
history_url = "http://.org/appraisal/publicaccess/PropertyHistory.aspx?PropertyID=%s&PropertyOwnerID=%s&NodeID=11&FirstTaxYear=%d&LastTaxYear=%d"
get_history_page = lambda propId,ownerId,eyear,syear:urllib.urlopen(history_url%(propId,ownerId,syear,eyear))... |
taimir/keras-layers | setup.py | Python | mit | 367 | 0 | from setuptools import setup
| from setuptools import find_packages
setup(name='Keras-layers',
version='0.0.1',
description='Collection of useful non-standard layers for keras',
author='Atanas Mirchev',
author_email='taimir93@gmail.com',
ur | l='https://github.com/taimir/keras-layers',
license='MIT',
packages=find_packages())
|
Kasai-Code/Kinesis | settings/hyperparameters.py | Python | mit | 268 | 0 | nb_epoch = 100
batch_size = 64
optimizer = 'adam'
hidden_units = 3000
nb_val_samples = 462
embedding_size = 10
dropout_percentag | e = 0.3
embedding_GRU_size = 100
maximum_line_length = 500
samples_per_epoch = 4127 * maximum_line_length
l | oss = 'categorical_crossentropy'
|
SneakersInc/Pandora | modules/exportgraph.py | Python | mit | 2,370 | 0.002532 | #!/usr/bin/env python
# Original code was created by Nadeem Douba as part of the Canari Framework
from collections import OrderedDict
from xml.etree.cElementTree import XML
from zipfile import ZipFile
def mtgx2json(graph):
zipfile = ZipFile(graph)
graphs = filter(lambda x: x.endswith('.graphml'), zipfile.n... | record.update(props)
s = ' - '.join(['%s: %s' % (key, value) for ( | key, value) in record['Data'].items()])
record.pop('Data')
data = {'Data': s}
record.update(data)
link = {'Links': {}}
i_link = {'Incoming': links.get(node_id, {}).get('in_', 0)}
link['Links'].update(i_link)
o_link = {'Outgoing': links.... |
hasgeek/coaster | tests/test_logger.py | Python | bsd-2-clause | 2,411 | 0.001659 | from io import StringIO
from coaster.logger import RepeatValueIndicator, filtered_value, pprint_with_indent
def test_filtered_value():
"""Test for filtered values."""
# Doesn't touch normal key/value pairs
assert filtered_value('normal', 'value') == 'value'
assert filtered_value('also_normal', 123) =... | 'secret-here')) == '[Filtered]'
# Filters are case insensitive
assert repr(filtered_value('TELEGRAM_ERROR_APIKEY', 'api:key')) == '[Filtered]'
# Keys with 'token' as a word are also filtered
assert repr(filtered_value('SMS_TWILIO_TOKEN', 'api:key')) == '[Filtered]'
# Numbers that look like card nu... | aces and dashes within the number
assert (
filtered_value('anything', 'My number is 1234 5678-90123456')
== 'My number is [Filtered]'
)
def test_pprint_with_indent():
"""Test pprint_with_indent does indentation."""
out = StringIO()
data = {
12: 34,
'confirm_passwor... |
ivano666/tensorflow | tensorflow/python/kernel_tests/bitcast_op_test.py | Python | apache-2.0 | 2,305 | 0.007375 | # Copyright 2015 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 a... | e(self):
x = np.random.rand(3, 4)
shape = [3, 4]
self._testBitcast(x, x.dtype, shape)
def testSameSize(self):
x = np.random.rand(3, 4)
shape = [3, 4]
self._testBitcast(x, tf.int64, shape)
def testErrors(self):
| x = np.zeros([1, 1], np.int8)
datatype = tf.int32
with self.assertRaisesRegexp(ValueError, "Cannot bitcast due to shape"):
tf.bitcast(x, datatype, None)
def testEmpty(self):
x = np.ones([], np.int32)
datatype = tf.int8
shape = [4]
self._testBitcast(x, datatype, shape)
def testUnk... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.