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
godlike64/typhon
typhon/views.py
Python
gpl-3.0
468
0.004274
from
django.contrib.auth.models import User from django.views.generic.edit import CreateView, FormView from django.shortcuts import rende
r from django.views.decorators.csrf import csrf_exempt from django.utils.decorators import method_decorator from django.core.context_processors import csrf from django.http import HttpResponse, JsonResponse from django.contrib.auth.decorators import login_required def test_page(request): return render(request, "...
cxsjabc/basic
python/message.py
Python
agpl-3.0
308
0.061688
#!/usr/bin/python def message(to, text): print "this is ", to, ":\n", text def add(a, b): return a + b; message
('xichen', 'eyu') print add(1,2); def mul(a, b): return a * b;
print mul(2, 3); print mul('a', 3); print mul(b=2, a='dd'); print 2 ** 100; print message; func = add; print func(1, 2);
minlexx/pyevemon
esi_client/models/get_universe_moons_moon_id_position.py
Python
gpl-3.0
4,328
0.000231
# coding: utf-8 """ EVE Swagger Interface An OpenAPI for EVE Online OpenAPI spec version: 0.4.6 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class GetUniverseMoonsMoonIdPosition(object): """ NOTE: ...
return self._x @x.setter def x(self, x): """ Sets the x of this GetUniverseMoonsMoonIdPosition. x number :param x: The x of
this GetUniverseMoonsMoonIdPosition. :type: float """ if x is None: raise ValueError("Invalid value for `x`, must not be `None`") self._x = x @property def y(self): """ Gets the y of this GetUniverseMoonsMoonIdPosition. y number :ret...
noirbizarre/bumpr
bumpr/hooks.py
Python
lgpl-3.0
6,499
0.001077
from __future__ import annotations import logging from os.path import exists from typing import TYPE_CHECKING from .helpers import BumprError, execute if TYPE_CHECKING: from typing import Optional logger = logging.getLogger(__name__) __all_ = ( "Hook", "ReadTheDocHook", "ChangelogHook", "Comman...
, replacements): pass class ReadTheDocHook(Hook): """ This hook set the readthedoc url corresponding to the version """ key = "readthedoc" defaults = { "id": None, "url": "https://{id}.readthedocs.io/en/{tag}", "badge": "https://readthedocs.org/projects/{id}/badge/...
def badge(self, tag): return self.config.badge.format(id=self.config.id, tag=tag) def bump(self, replacements): replacements.insert(0, (self.badge("latest"), self.badge(self.releaser.tag_label))) replacements.insert(0, (self.url("latest"), self.url(self.releaser.tag_label))) def p...
andrewhanlon/QCD_scripts
sigmond/channel.py
Python
gpl-3.0
7,175
0.012683
import abc import subprocess import logging from observables import BLOperator, MCObservable from data import BLDataChannel, GIDataChannel import util class Channel(metaclass=abc.ABCMeta): ISOSPIN_MAP = { 'singlet': "0", 'doublet': "1h", 'triplet': "1", 'quartet': "3h", 'quintet': "2"...
strangeness=operator.strangeness, flavor=operator.flavor,
laph_query=laph_query, sigmond_query=sigmond_query) elif operator.psq > 0: return MovingChannel(particle_type=operator.particle_type, isospin=operator.isospin, strangeness=operator.strangeness, psq=operator.psq, lg_irrep=operator...
lukas-bednar/jenkins-job-builder
tests/cmd/subcommands/test_delete.py
Python
apache-2.0
1,878
0
import os from jenkins_jobs import cmd from tests.base import mock from tests.cmd.test_cmd import CmdTestsBase @mock.patch('jenkins_jobs.builder.Jenkins.get_plugins_info', mock.MagicMock) class DeleteTests(CmdTestsBase): @mock.patch('jenkins_jobs.cmd.Builder.delete_job') def test_delete_single_job(self, del...
.parse_args(['delete', 'test_job1', 'test_job2']) cmd.execute(args, self.config) # passes if executed without error @mock.patch('jenkins_jobs.builder.Jenkins.delete_job') def test_delete_using_glob_params(self, delete_job_mock): """ Test handling
the deletion of multiple Jenkins jobs using the glob parameters feature. """ args = self.parser.parse_args(['delete', '--path', os.path.join(self.fixtures_path, 'cmd...
donce/django-cms
cms/admin/pageadmin.py
Python
bsd-3-clause
67,669
0.002941
# -*- coding: utf-8 -*- import copy from functools import wraps import json import sys import django from django.contrib.admin.helpers import AdminForm from django.conf import settings from django.conf.urls import url from django.contrib import admin, messages from django.contrib.admin.models import LogEntry, CHANGE f...
ry: return func(*args, **kwargs) except: exception = True if not self.__exit__(*sys.exc_info()): raise
finally: if not exception: self.__exit__(None, None, None) return do_revision_context def create_revision(): return ReversionContext() PUBLISH_COMMENT = "Publish" INITIAL_COMMENT = "Initial version." class PageAdmin(PlaceholderAdminMixin, Mo...
Sarsate/compute-image-packages
google_compute_engine/instance_setup/tests/instance_setup_test.py
Python
apache-2.0
14,219
0.004009
#!/usr/bin/python # Copyright 2016 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 appli...
IPE) mock_process.poll.assert
_called_once_with() def testGetInstanceId(self): self.mock_setup.metadata_dict = {'instance': {'attributes': {}, 'id': 123}} self.assertEqual( instance_setup.InstanceSetup._GetInstanceId(self.mock_setup), '123') self.mock_logger.warning.assert_not_called() def testGetInstanceIdNotFound(self): ...
HyperloopTeam/FullOpenMDAO
lib/python2.7/site-packages/traits-4.3.0-py2.7-macosx-10.10-x86_64.egg/traits/trait_base.py
Python
gpl-2.0
19,017
0.018089
#------------------------------------------------------------------------------ # # Copyright (c) 2005, Enthought, Inc. # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in enthought/LICENSE.txt and may be redistributed only # under the conditions d...
needed by the Traits package. """ #------------------------------------------------------------------------------- # Imports: #------------------------------------------------------------------------------- from __future__ import absolute_import import os import sys from os import getcwd from os.path import dirname...
Type, StringType, UnicodeType, IntType, LongType, FloatType, ComplexType, ClassType, TypeType) # Set the Python version being used: vi = sys.version_info python_version = vi[0] + (float( vi[1] ) / 10.0) try: from traits.etsconfig.api import ETSConfig except: # If the ETSConfig package is not available, f...
hjanime/VisTrails
vistrails/core/modules/basic_modules.py
Python
bsd-3-clause
69,112
0.002879
############################################################################### ## ## Copyright (C) 2014-2015, New York University. ## Copyright (C) 2011-2014, NYU-Poly. ## Copyright (C) 2006-2011, University of Utah. ## All rights reserved. ## Contact: contact@vistrails.org ## ## This file is part of VisTrails. ## ## ...
and output ports. """ mod = type.__new__(cls, name, bases, dct) if '_
input_ports' in mod.__dict__: input_ports = mod._input_ports if not any(get_port_name(port_info) == 'value' for port_info in input_ports): mod._input_ports = [('value', mod)] mod._input_ports.extend(input_ports) else: mod...
xcyan/models
ptn/model_ptn.py
Python
apache-2.0
8,258
0.004481
# 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 applicab...
ath = os.path.join(log_dir, '%s.jpg' % str(global_step))
utils.save_image(grid, img_path) return grid save_op = tf.py_func(write_grid, [ input_images, gt_projs, pred_projs, global_step, input_voxels, output_voxels ], [tf.uint8], 'write_grid')[0] slim.summaries.add_image_summary( tf.expand_dims(save_op, axis=0), name='grid_vis') ...
prior/webinars
webinars_web/webinars/views/hub_syncs.py
Python
apache-2.0
1,234
0.010535
from django.shortcuts import render_to_response from django.template import RequestContext from webinars_web.webinars.views import syncs def show(request, sync_id): from webinars_web.webinars import models as wm return syncs._show(request, 'hub', wm.HubSync.objects.select_related('hub').get(pk=sync_id)) def n...
binars import models as wm return syncs._interrupt(request, 'hub', wm.Hub.objects.get(pk=hub_id)) def list(request, hub_id): from webinars_web.webinars import models as wm hub = wm.Hub.objects.get(pk=hub_id) hub_syncs = wm.HubSync.objects.filter(hub=hub).order_by('-started_at') account_syncs = wm.A...
c.objects.filter(account__hub=hub, parent__isnull=True).order_by('-started_at') event_syncs = wm.EventSync.objects.filter(event__account__hub=hub, parent__isnull=True).order_by('-started_at') return render_to_response('hub_syncs/list.djml', {'hub':hub, 'hub_syncs':hub_syncs, 'account_syncs':account_syncs, 'even...
apoorva-sharma/deep-frame-interpolation
tensorflow_tutorials-master/python/09_convolutional_autoencoder.py
Python
mit
5,033
0.000199
"""Tutorial on how to create a convolutional autoencoder w/ Tensorflow. Parag K. Mital, Jan 2016 """ import tensorflow as tf import numpy as np import math from libs.activations import lrelu from libs.utils import corrupt # %% def autoencoder(input_shape=[None, 784], n_filters=[1, 10, 10, 10], ...
put = output # %% # now have the reconstruction through the network y = current_input # cost function measures pixel-wise difference cost = tf.reduce_sum(tf.square(y - x_tensor)) # %% return {'x': x, 'z': z, 'y': y, 'cost': cost} # %% def test_mnist(): """Test the convolutional autoe...
import matplotlib.pyplot as plt # %% # load MNIST as before mnist = input_data.read_data_sets('MNIST_data', one_hot=True) mean_img = np.mean(mnist.train.images, axis=0) ae = autoencoder() # %% learning_rate = 0.01 optimizer = tf.train.AdamOptimizer(learning_rate).minimize(ae['cost']...
dwillmer/numpy
numpy/distutils/system_info.py
Python
bsd-3-clause
85,113
0.000881
#!/bin/env python """ This file defines a set of system_info classes for getting information about various resources (libraries, library directories, include directories, etc.) in the system. Currently, the following classes are available: atlas_info atlas_threads_info atlas_blas_info atlas_blas_threads_info ...
sr/local/include',
'/opt/include', '/usr/include', # path of umfpack under macports '/opt/local/include/ufsparse', '/opt/local/include', '/sw/include', '/usr/include/suitesparse'] default_src_dirs ...
gklyne/annalist
src/annalist_root/annalist/tests/test_recordview.py
Python
mit
56,603
0.010918
from __future__ import unicode_literals from __future__ import absolute_import, division, print_function """ Tests for RecordView module and view Note: this module tests for rendering specifically for RecordView values, using view description sitedata files, and as such duplicates some tests covered by module test_en...
from annalist.models.collection import Collection from annalist.models.recordview import RecordView from annalist.models.recordfield import RecordField f
rom annalist.views.uri_builder import uri_with_params from annalist.views.recordviewdelete import RecordViewDeleteConfirmedView from annalist.views.form_utils.fieldchoice import FieldChoice from .AnnalistTestCase import AnnalistTestCase from .tests import ( TestHost, TestHostUri, TestBasePath, ...
rcosnita/fantastico
fantastico/oauth2/models/tests/__init__.py
Python
mit
1,175
0.00766
''' Copyright 2013 Cosnita Radu Viorel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modif
y, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTW...
CLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE ...
BitWriters/Zenith_project
zango/lib/python3.5/site-packages/django/middleware/security.py
Python
mit
1,753
0.001141
import re from django.conf import settings from django.http import HttpResponsePermanentRedirect class SecurityMiddleware(object): def __init__(self): self.sts_seconds = settings.SECURE_HSTS_SECONDS self.sts_include_subdomains = settings.SECURE_HSTS_INCLUDE_SUBDOMAINS self.content_type_no...
er = "max-age=%s" % self.sts_seconds
if self.sts_include_subdomains: sts_header = sts_header + "; includeSubDomains" response["strict-transport-security"] = sts_header if self.content_type_nosniff and 'x-content-type-options' not in response: response["x-content-type-options"] = "nosniff" if self....
taikoa/wevolver-server
wevolve/projects/migrations/0006_auto__add_field_userproject_drive_auth.py
Python
agpl-3.0
8,173
0.007708
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'UserProject.drive_auth' db.add_column(u'user_project', 'drive_auth', s...
assword': ('django.db.models.fields.CharField', []
, {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'cont...
zbanks/shmooze
setup.py
Python
mit
1,029
0.013605
#!/usr/bin/env python import fnmatch import glob import os import sys from setuptools import setup with open("requirements.txt") as f: required = f.read().splitlines() VERSION = "1.2.4" setup( name='shmooze', version=VERSION, description='Framework for processed-backed web applications', author...
://github.com/zbanks/shmooze', packages=[ 'shmooze', 'shmooze.wsgi', 'shmooze.modules', 'shmooze.lib', ], download_url="https://github.com/zbanks/shmooze/tarball/{}".format(VERSION), zip_safe=False, install_requires=required, scripts=[ "bin/sh
mooze", "bin/shmz", ], package_dir = { }, package_data={ 'musicazoo': [ "../supervisord.conf", "../requirements.txt", "../settings.json", '../static/settings.json', '../static/*.js', '../static/*.html', ...
prasannav7/ggrc-core
src/ggrc/fulltext/mysql.py
Python
apache-2.0
16,137
0.00471
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: david@reciprocitylabs.com # Maintained By: david@reciprocitylabs.com from ggrc import db from ggrc.login import get_current_user from ggrc.models i...
operty = db.Column(db.String(64), prim
ary_key=True) content = db.Column(db.Text) @declared_attr def __table_args__(self): return ( # NOTE # This is here to prevent Alembic from wanting to drop the index, but # the DDL below or a similar Alembic migration should be used to create # the index. db.Index('{}_t...
joelstanner/electrum
plugins/trezor/qt_generic.py
Python
gpl-3.0
24,003
0.00025
from functools import partial import threading from PIL import Image from PyQt4.Qt import Qt from PyQt4.Qt import QGridLayout, QInputDialog, QPushButton from PyQt4.Qt import QVBoxLayout, QLabel, SIGNAL from electrum_gui.qt.main_window import StatusBarButton from electrum_gui.qt.password_dialog import PasswordDialog fr...
return ' '.join(text.split()) if method in [TIM_NEW, TIM_RECOVER]: gb = QGroupBox() vbox1 = QVBoxLayout() gb.setLayout(vbox1) vbox.addWidget(gb) gb.setTitle(_("Select your seed length:")) choices = [ _("12 words...
words"), _("24 words"), ] bg = QButtonGroup() for i, choice in enumerate(choices): rb = QRadioButton(gb) rb.setText(choice) bg.addButton(rb) bg.setId(rb, i) vbox1.addWidget(rb) ...
felipenaselva/repo.felipe
plugin.video.salts/scrapers/onlinedizi_scraper.py
Python
gpl-2.0
4,998
0.005002
""" SALTS XBMC Addon Copyright (C) 2014 tknorris This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. T...
.base_url = kodi.get_setting('%s-base_url' % (self.get_name())) @classmethod def provides(cls): return frozenset([VIDEO_TYPES.TVSHOW, VIDEO_TYPES.EPISODE]) @classmethod def get_name(cls): return 'OnlineDizi' def get_sources(self, video): source_url = self.get_url(video) ...
sources = [] if source_url and source_url != FORCE_NO_MATCH: page_url = urlparse.urljoin(self.base_url, source_url) html = self._http_get(page_url, cache_limit=.25) fragment = dom_parser.parse_dom(html, 'ul', {'class': 'dropdown-menu'}) if fragment: ...
mbayon/TFG-MachineLearning
venv/lib/python3.6/site-packages/scipy/interpolate/tests/test_interpolate.py
Python
mit
102,313
0.000958
from __future__ import division, print_function, absolute_import import itertools from numpy.testing import (asse
rt_, assert_equal, assert_almost_equal, assert_array_almost_equal, assert_array_equal, assert_allclose) from pytest import raises as assert_raises from numpy import mgrid, pi, sin, ogrid, poly1d, linspace import numpy as np from scipy._lib.si
x import xrange from scipy._lib._numpy_compat import _assert_warns, suppress_warnings from scipy.interpolate import (interp1d, interp2d, lagrange, PPoly, BPoly, splrep, splev, splantider, splint, sproot, Akima1DInterpolator, RegularGridInterpolator, LinearNDInterpolator, NearestNDInterpolator, ...
wh-acmer/minixalpha-acm
LeetCode/Python/best_time_to_buy_and_sell_stock.py
Python
mit
708
0.008475
#!/usr/bin/env python #coding: utf-8 class Solution: # @param prices, a list of integer # @return an integer def maxProfit(self, prices):# if not prices: return 0 n = len(prices) min_p = prices[0]
max_profict = 0 for i in range(1, n): if prices[i] < min_p: min_p = prices[i] cur_profit = prices[i] - min_p if cur_profit > max_profict: max_pr
ofict = cur_profit return max_profict if __name__ == '__main__': s = Solution() assert 0 == s.maxProfit([1]) assert 1 == s.maxProfit([1, 2]) assert 0 == s.maxProfit([2, 1]) assert 8 == s.maxProfit([1,3,9])
caktus/rapidsms-decisiontree-app
decisiontree/utils.py
Python
bsd-3-clause
4,043
0
from django.utils.encoding import force_text from .models import Tree def get_survey(trigger, connection): """Returns a survey only if it matches the connection's tenant.""" from decisiontree.multitenancy.utils import multitenancy_enabled queryset = Tree.objects.filter(trigger__iexact=trigger) if mul...
ppend(u''.join(buffer)) buffer = [] # Find the matching quote open_quote = True c = i.next() while c != u'"': buffer.append(c) c = i.next(
) if buffer: word = u''.join(buffer).strip() if word: words.append(word) buffer = [] open_quote = False else: if not saw_loose_comma and c == u',': saw_loos...
agry/NGECore2
scripts/mobiles/corellia/greck_mugger.py
Python
lgpl-3.0
1,920
0.022917
import sys from services.spawn import MobileTemplate from services.spawn import WeaponTemplate from resources.datatables import WeaponType from resources.datatables import Difficulty from resources.datatables import Options from java.util import Vector def addTemplate(core): mobileTemplate = MobileTemplate...
/mobile/shared_greck_thug_m_03.iff') templates.add('object/mobile/shared_greck_thug_m_04.iff') templates.add('object/mobile/shared_greck_thug_m_05.iff') mobileTemplate.setTemplates(templates) weaponTemplates = Vector() weapontemplate = WeaponTemplate('object/weapon/melee/unarmed/shared_unarmed_default.iff',...
plate.setDefaultAttack('meleeHit') mobileTemplate.setAttacks(attacks) lootPoolNames_1 = ['Junk'] lootPoolChances_1 = [100] lootGroupChance_1 = 100 mobileTemplate.addToLootGroups(lootPoolNames_1,lootPoolChances_1,lootGroupChance_1) core.spawnService.addMobileTemplate('greck_mugger', mobileTemplate) r...
iScienceLuvr/PPP-CAS
ppp_cas/mathematicaTree.py
Python
mit
6,347
0.019064
class BinaryOperator: def __init__(self, left, right): self.left = left self.right = right def __str__(self): return '%s(%s, %s)' % (self.__class__.__name__, self.left, self.right) def toCalchas(self, op): return '(%s%s%s)' % (self.left.toCalchas(), op, self.right.toCalchas...
turn self.list[index] def __add__(self, other): return List(self.list+other.list) def __len__(self): return len(self.list) def getList(self): return self.list def toCalchas(self): if len(self.list)==0: return '' s = self
.list[0].toCalchas() for e in self.list[1:]: s = s + ', ' + e.toCalchas() return s class FunctionCall: def __init__(self, function, args): self.function = function self.args = args def __str__(self): return 'FunctionCall('+str(self.function)+','+str(self.arg...
pombredanne/Rusthon
src/runtime/builtins_webworker.py
Python
bsd-3-clause
10,276
0.041845
class __WorkerPool__: def create_webworker(self, cpuid): ## this is lazy because if the blob is created when the js is first executed, ## then it will pick all functions of `window` but they will be `undefined` ## if their definition comes after the construction of this singleton. print 'creating blob' ## ...
if `proto` was given (user static return type) if evt.data.proto: msg.__proto__ = eval(evt.data.proto + '.prototype') if evt.data.GET: ww._get_callback( msg ) elif evt.data.CALL: ww._call_callback( msg ) elif evt.data.CALLMETH: ww._callmeth_callback( msg ) else: id = evt.data.i...
cks = ww._stream_callbacks[id] if len(callbacks): cb = callbacks.pop() cb( msg ) else: ww._stream_triggers[id].push( msg ) else: raise WebWorkerError('invalid id:' + id) ww.onmessage = onmessage_update return ww def __init__(self, src, extras): ## note: src is an a...
w1ll1am23/home-assistant
homeassistant/util/dt.py
Python
apache-2.0
12,636
0.000554
"""Helper methods to handle the time in Home Assistant.""" from __future__ import annotations from contextlib import suppress import datetime as dt import re from typing import Any, cast import ciso8601 import pytz import pytz.exceptions as pytzexceptions import pytz.tzinfo as pytzinfo from homeassistant.const impor...
dt.timezone.utc UTC = pytz.utc DEFAULT_TIME_ZONE: dt.tzinfo = pytz.utc # Copyri
ght (c) Django Software Foundation and individual contributors. # All rights reserved. # https://github.com/django/django/blob/master/LICENSE DATETIME_RE = re.compile( r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})" r"[T ](?P<hour>\d{1,2}):(?P<minute>\d{1,2})" r"(?::(?P<second>\d{1,2})(?:\.(?P<micros...
apple/swift-lldb
packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-skip-summary/TestDataFormatterSkipSummary.py
Python
apache-2.0
7,621
0.002099
""" Test lldb data formatter subsystem. """ from __future__ import print_function import os import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class SkipSummaryDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) ...
'm_child4 = Level 3', '}']) # Now skip 2 levels of summaries self.expect('frame variable --no-summary-depth=2', substrs=['(DeepData_1) dat
a1 = {', 'm_child1 = 0x', '}', '(DeepData_2) data2 = {', 'm_child1 = {', 'm_child1 = 0x', 'Level 4', 'm_child2 = {', ...
Diego999/Social-Recommendation-System
event_analyse/event_analysis.py
Python
mit
2,010
0.002985
from tf_idf import * class EventAnalysis: """ Class that contains all the necessary operation to process to a text analysis """ @staticmethod def get_id_website(id_doc, is_website): """ Apply the processing to have a website id """ return id_doc if not...
= TfIdf(self.corpus) def compute_tf_idf(self, term, id_doc): """ The id is as follow : - A descr
iption : Event's id - A website : Event's id + "_" """ return self.tf_idf.get_tf_idf(term, id_doc) def get_tf_idf_the_k_most_important(self, k, id_doc): """ Return a OrderedDict that contains the k most important term (sorted by frequences). If there are less...
psionin/smartcoin
qa/rpc-tests/pruning.py
Python
mit
21,037
0.005371
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Test pruning code # ******** # WARNING: # This test uses 4GB of disk space. # This test takes 30 mins...
blockmaxsize=999000", "-checkblocks=5"], timewait=900)) # Create node 2 to test pruning self.nodes.append(start_node(2, self.options.tmpdir, ["-debug","-maxreceivebuffer=20000","-prune=550"], timewait=900)) self.prunedir = self.options.tmpdir+"/node2/regtest/blocks/" # Create nodes 3 a...
be re-started with manual pruning later) self.nodes.append(start_node(3, self.options.tmpdir, ["-debug=0","-maxreceivebuffer=20000","-blockmaxsize=999000"], timewait=900)) self.nodes.append(start_node(4, self.options.tmpdir, ["-debug=0","-maxreceivebuffer=20000","-blockmaxsize=999000"], timewait=900)) ...
pollitosabroson/pycarribean
src/books/models.py
Python
apache-2.0
515
0
from django.db import models # Create your models here. class Autor(models.Model): nombre = models.TextField(max_length=100) apellido = models.TextField(max_length=100) class Libro(models.Model): nombre = models.TextField(max_length=100) editorial = models.TextField(max_
length=100) genero = models.TextField(max_length=100) descripcion = models.TextField() autor = models.ForeignKey( Autor, null=True ) def __unicode__(self): ret
urn self.editorial
Apogaea/voldb
volunteer/core/views.py
Python
gpl-3.0
481
0
from django.views.generic import TemplateView from django.conf import settings from volunteer.apps.events.utils import get_active_event class SiteIndexView(TemplateView): template_name = 'home.html' def get_context_data(self, **kwargs): context = super(SiteIndexView, self).get_context_data(**kwargs)...
MAIL return context
tedlaz/pyted
pymiles/pyMiles2.old/pymiles/sqlite/diasql.py
Python
gpl-3.0
5,065
0.001579
# PyDia SQL.py : SQL dump. # Copy it to /usr/share/dia/python import dia # import sys # import os import string import re import datetime class SQLRenderer: def __init__(self): self.f = None
def begin_render(self, data, filename): self.f = open(filename, "w") # name = os.path.split(filename)[1] self.f.write('''BEGIN TRANSACTION;\n''') for layer in data.layers: self.WriteTables(layer) de
f WriteTables(self, layer): tables = {} appdata = 'appdata' priority = {'fields': 0, 'foreign_keys': 100} # value for id z = ["INSERT INTO zf VALUES ('id', 'No', 'INTEGER', '1');"] z.append("INSERT INTO z VALUES('diadate', '%s');" % datetime.date.today().isoformat()) ...
janelia-flyem/neuroglancer
python/neuroglancer/tool/filter_bodies.py
Python
apache-2.0
6,932
0.001587
from __future__ import division import json import os import copy import collections import argparse import csv import neuroglancer import neuroglancer.cli import numpy as np class State(object): def __init__(self, path): self.path = path self.body_labels = collections.OrderedDict() def loa...
list of bodies to proofread') ap.add_a
rgument('--labels', nargs='+', help='Labels to use') ap.add_argument('--prefetch', type=int, default=10, help='Number of bodies to prefetch') args = ap.parse_args() neuroglancer.cli.handle_server_arguments(args) bodies = [] with open(args.bodies, 'r') as f: csv_reader = csv.DictReader(f) ...
Teamxrtc/webrtc-streaming-node
third_party/webrtc/src/chromium/src/third_party/tlslite/tlslite/__init__.py
Python
mit
904
0.002212
# Author: Trevor Perrin # See the LICENSE file for legal information regarding use of this file. """TLS Lite is a free python library that implements SSL and TLS. TLS Lite supports RSA and SRP ciphersuites. TLS Lite is
pure python, however it can use other libraries for faster crypto operations. TLS Lite integrates with several stdlib neworking libraries. API documentation is available in the 'docs' directory. If you have questions or feedback, feel free to contact me. To use, do:: from tlslite import TLSConnection, ... ...
tion.TLSConnection} class with a socket. (Or, use one of the integration classes in L{tlslite.integration}). @version: 0.4.8 """ from tlslite.api import * from tlslite.api import __version__ # Unsure why this is needed, but it is
anderson89marques/PyFixedFlatFile
pyFixedFlatFile/exceptions.py
Python
mit
476
0.002101
class ParamsException(Exception): """Exception raised when tp, fmt
and size values are wrongs""" pass class LineSizeException(Exception): """Exception raised when line size is bigger then specified""" pass class LineIdentifierException(Exception): """Exception raised when line indentifier rased from the file is different to the line identifier used in the speci...
nction """ pass
huran2014/huran.github.io
wot_gateway/usr/lib/python2.7/posixfile.py
Python
gpl-2.0
8,003
0.004748
"""Extended file operations available in POSIX. f = posixfile.open(filename, [mode, [bufsize]]) will create a new posixfile object f = posixfile.fileopen(fileobject) will create a posixfile object from a builtin file object f.file() will return the original builtin file object f.dup() will r...
open(name, mode, bufsize)) def fileopen(self, file): import types if repr(type(file)) != "<type 'file'>": raise TypeError, 'posixfile.fileopen() arg must be file object' self._file_
= file # Copy basic file methods for maybemethod in dir(file): if not maybemethod.startswith('_'): attr = getattr(file, maybemethod) if isinstance(attr, types.BuiltinMethodType): setattr(self, maybemethod, attr) return self # ...
teroc/Otero
tests/run_tests.py
Python
mit
1,499
0.002668
# -*- coding: utf-8 -*- # Copyright (c) 2014 Tampere University of Technology, # Intel Corporation, # OptoFidelity, # and authors # # 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 res...
AR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # pylint: disable = ...
914, R0915 # pylint: disable = W0212 import unittest _testloader = unittest.TestLoader() _testsuite = _testloader.discover(".") _testresult = unittest.TextTestRunner(verbosity = 2).run(_testsuite)
IEEEDTU/CMS
manage.py
Python
mit
246
0
#!/us
r/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE"
, "CMS.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
miurahr/seahub
seahub/file_tags/migrations/0002_remove_filetags_parent_folder_uuid.py
Python
apache-2.0
360
0
# -*- coding: utf-8 -*- # Generated by Django 1.11.15
on 2019-03-01 02:16 from django.db imp
ort migrations class Migration(migrations.Migration): dependencies = [ ('file_tags', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='filetags', name='parent_folder_uuid', ), ]
davidshepherd7/Landau-Lifshitz-Gilbert-ODE-model
llg/mallinson.py
Python
gpl-3.0
4,251
0.000235
"""Calculate exact solutions for the zero dimensional LLG as given by [Mallinson2000] """ from __future__ import division from __future__ import absolute_import from math import sin, cos, tan, log, atan2, acos, pi, sqrt import scipy as sp import matplotlib.pyplot as plt import functools as ft import simpleode.core.u...
s, pols)] # Calculate switching times for these positions times = [calculate_switching_time(mag_params, start_angle, p) for p in pols] return (sphs, times)
def plot_dynamics(magnetic_parameters, start_angle=pi/18, end_angle=17*pi/18, steps=1000): """Plot exact positions given start/finish angles and magnetic parameters. """ sphs, times = generate_dynamics(magnetic_parameters, start_angle, ...
pgmmpk/cslavonic
cslavonic/ucs_decode.py
Python
mit
9,501
0.001053
''' Created on Feb 4, 2016 Decoding tables taken from https://github.com/typiconman/Perl-Lingua-CU @author: mike kroutikov ''' from __future__ import print_function, unicode_literals import codecs def ucs_decode(input_, errors='strict'): return ''.join(decoding_table[x] for x in input_), len(input_) def ucs_e...
aed a ) def _build_decoding_table(fname): '''unitily to build decoding_table from Perl's ucsequivs file. we base on cp1251 and overlay data from ucsequi
vs''' from encodings import cp1251 decode_table = list(cp1251.decoding_table) comments = [None] * 256 with codecs.open(fname, 'r', 'utf-8') as f: for line in f: line = line.strip() if not line or line == 'use utf8;' or line.startswith('#'): ...
pchretien/btiswatchingu
python/bt_device.py
Python
gpl-2.0
1,349
0.004448
## BTisWatchingU ## # # This program scans for bluetooth devices and add their address and name to a # centralized database. This database
have some simple facilities to determine # where and when the device have been spotted. # Copyright (C) 2008,2009 Philippe Chretien # # This program is free software; you can redistribute it and/or # modify it under
the terms of the GNU General Public License Version 2 # # 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 re...
balloob/home-assistant
homeassistant/components/rest/sensor.py
Python
apache-2.0
9,072
0.000882
"""Support for RESTful API sensors.""" import json import logging from xml.parsers.expat import ExpatError import httpx from jsonpath import jsonpath import voluptuous as vol import xmltodict from homeassistant.components.sensor import DEVICE_CLASSES_SCHEMA, PLATFORM_SCHEMA from homeassistant.const import ( CONF_...
rs will be None content_type = self.rest.headers.get("content-type") if content_type and ( content_type.startswith("text/xml") or content_type.startswith("application/xml") ): try: value = json.dumps(xmltodic
t.parse(value)) _LOGGER.debug("JSON converted from XML: %s", value) except ExpatError: _LOGGER.warning( "REST xml result could not be parsed and converted to JSON" ) _LOGGER.debug("Erroneous XML: %s",...
davidam/python-examples
sparql/dbpedia-asturias.py
Python
gpl-3.0
416
0.002404
from SPARQLWrapper import SPARQLWrapper, JSON sparql = SPARQLWrapper("http://dbpedia.org/sparql") sparql.setQuery(""" PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> SELECT ?label WHERE { <http://dbpedia.org/resource/Asturias> rdfs:label ?label } """) sparql.
setReturnFormat(JSON) results = sparql.query().convert() for result in results["results"]["bindings"]: print(result
["label"]["value"])
Ilias95/apts
setup.py
Python
gpl-3.0
1,102
0.024501
#!/usr/bin/env python3 import apts from distutils.core import setup setup( name = apts.__name__, packages = [apts.__name__], scripts = ['bin/ap
ts'], version = apts.__version__, description = ap
ts.__description__, author = apts.__author__, author_email = apts.__author_email__, license = apts.__license__, platforms = apts.__platforms__, url = apts.__url__, download_url = apts.__download_url__, keywords = ['tftp', 'server', 'file transfer'], classifiers = [ 'Programming L...
Digilent/u-boot-digilent
test/py/tests/test_zynqmp_secure.py
Python
gpl-2.0
3,375
0.001778
# Copyright (c) 2018, Xilinx Inc. # # Siva Durga Prasad Paladugu # # SPDX-License-Identifier: GPL-2.0 import pytest import re import random import u_boot_utils """ Note: This test relies on boardenv_* containing configuration values to define the network available and files to be used for testing. Without this, this ...
%s' % (addr, fn)) assert expected_tftp in output expected_zynqmpsecure = 'Verified image at' output = u_boot_console.run_command('zynqmp
secure %x $filesize %x' % (addr, keyaddr)) assert expected_zynqmpsecure in output output = u_boot_console.run_command('pri zynqmp_verified_img_addr') assert "Error" not in output
joaquimrocha/Rancho
rancho/message/management.py
Python
agpl-3.0
1,442
0.002774
######################################################################## # Rancho - Open Source Group/Project Management Tool # Copyright (C) 2008 The Rancho Team # # This program is fr
ee software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope tha
t it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see...
shigmas/django-push-notifications
push_notifications/apns.py
Python
mit
5,297
0.020578
""" Apple Push Notification Service Documentation is available on the iOS Developer Library: https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html """ import time from apns2 import client as apns2_client from apns2 import credentials as apns2_c...
reate_socket(creds=None, application_id=None): if creds is None: if not get_manager().has_auth_token_creds(application_id): cert = get_manager().get_apns_certificate(application_id) creds = apns2_credentials.CertificateCredentials(cert) else: keyPath, keyId, teamId = get_manager().get_apns_auth_creds(appl...
d # algorithm. Neither of those settings are exposed in the # settings API at the moment. creds = creds or apns2_credentials.TokenCredentials(keyPath, keyId, teamId) client = apns2_client.APNsClient( creds, use_sandbox=get_manager().get_apns_use_sandbox(application_id), use_alternative_port=get_manager(...
jbwhit/OSCON-2015
deliver/coal_data_cleanup.py
Python
mit
2,214
0.006323
# coding: utf-8 # # Clean the raw data # # ## Data from U.S. Energy Information Administration # # Data URL: [eia.gov](http://www.eia.gov/coal/data.cfm) # # Combining and cleaning the raw csv files into a cleaned data set and coherent database. # # Generally a good idea to have a separate data folder with the ra...
# In[5]: df1 = pd.read_csv("../data/coal_prod_2002.csv", index_col="MSHA_ID") df2 = pd.read_csv("../data/coal_prod_2003.csv", index_col="MSHA_ID") df3 = pd.read_csv("../data/coal_prod_2004.csv", index_col="MSHA_ID") df4 = pd.read_csv("../data/coal_prod_2005.csv", index_col="MSHA_ID") df5 = pd.read_csv("../data/coal...
dex_col="MSHA_ID") df7 = pd.read_csv("../data/coal_prod_2008.csv", index_col="MSHA_ID") df8 = pd.read_csv("../data/coal_prod_2009.csv", index_col="MSHA_ID") df9 = pd.read_csv("../data/coal_prod_2010.csv", index_col="MSHA_ID") df10 = pd.read_csv("../data/coal_prod_2011.csv", index_col="MSHA_ID") df11 = pd.read_csv("../d...
magnastrazh/NEUCOGAR
nest/GDP/scripts/parameters.py
Python
gpl-2.0
3,431
0.001749
from property import * # Neuron common parameters iaf_neuronparams = {'E_L': -70., 'V_th': -50., 'V_reset': -67., 'C_m': 2., 't_ref': 2., 'V_m': -60., 'tau_syn_ex': 1., 'tau_syn_i...
'low': 0.8, 'high': 2.5}, 'lambda': 0.5 } # Glutamate synapse STDP_synparams_Glu = dict({'delay': {'distribu
tion': 'uniform', 'low': 1, 'high': 1.3}, 'weight': w_Glu, 'Wmax': 70.}, **STDP_synapseparams) # GABA synapse STDP_synparams_GABA = dict({'delay': {'distribution': 'uniform', 'low': 1., 'high': 1.3}, 'weight': w_GABA, ...
warkanum/warkanums-pi-device-snippets
build1/boot_special.py
Python
mit
8,959
0.018306
#!/opt/python3.3/bin/python3.3 from threading import Thread import RPi.GPIO as GPIO import time import datetime import os import sys import dht11_sensor import psycopg2 import copy ###-----------------Hardware Settings----------------------- PIN_LC=25 #Light Sensor (GPIO.IN, pull_up_down=GPIO.PUD_UP) PIN_MC=17 #Mo...
, G
PIO.LOW) time.sleep(0.1) GPIO.setup(RCpin, GPIO.IN) # This takes about 1 millisecond per loop cycle while (GPIO.input(RCpin) == GPIO.LOW): reading += 1 return reading def TempsensorRead(): ### Loop through the temp sensor library until we get a valid reading ### for i in range(1,100): ...
michalliu/OpenWrt-Firefly-Libraries
staging_dir/target-mipsel_1004kc+dsp_uClibc-0.9.33.2/usr/lib/python3.4/test/test_importlib/import_/test_caching.py
Python
gpl-2.0
3,643
0.000823
"""Test that sys.modules is used properly by import.""" from .. import util from . import util as import_util import sys from types import MethodType import unittest class UseCache: """When it comes to sys.modules, import prefers it over anything else. Once a name has been resolved, sys.modules is checked t...
module = self.__import__('some_module') self.assertEqual(id(module_to_use), id(module)) def test_None_in_cache(self): #[None in cache] n
ame = 'using_None' with util.uncache(name): sys.modules[name] = None with self.assertRaises(ImportError) as cm: self.__import__(name) self.assertEqual(cm.exception.name, name) Frozen_UseCache, Source_UseCache = util.test_both( UseCache, __import__=imp...
mrakitin/sirepo
sirepo/job_api.py
Python
apache-2.0
8,078
0.002723
u"""Entry points for job execution :copyright: Copyright (c) 2019 RadiaSoft LLC. All Rights Reserved. :license: http://www.apache.org/licenses/LICENSE-2.0.html """ from __future__ import absolute_import, division, print_function from pykern import pkinspect, pkjson from pykern.pkcollections import PKDict from pykern....
e = 'unable to connect to supervisor' except Exception as e: pkdlog(e) e = 'unexpected exception' return PKDict(state='error', error=e) @api_perm.require_user def api_runCancel(): try: return _request() except Exception as e: pkdlog('ignoring exception={}
stack={}', e, pkdexc()) # Always true from the client's perspective return sirepo.http_reply.gen_json({'state': 'canceled'}) @api_perm.require_user def api_runSimulation(): r = _request_content(PKDict(fixup_old_data=True)) # TODO(e-carlin): This should really be done in job_supervisor._lib_dir_symlink...
oculusstorystudio/kraken
Python/kraken/ui/preference_editor.py
Python
bsd-3-clause
7,028
0.001565
# # Copyright 2010-2014 Fabric Technologies Inc. All rights reserved. # import os import json import collections from kraken.ui.Qt import QtGui, QtWidgets, QtCore class PreferenceEditor(QtWidgets.QDialog): """A widget providing the ability to nest """ def __init__(self, parent=None): # constructo...
') fileDialog.setDefaultSuffix('json') if fileDialog.exec_() == QtWidgets.QFileDialog.Accepted: filePath = fileDialog.selectedFiles()[0] preferences = self.parentWidg
et().window().preferences.getPreferences() with open(filePath, "w+") as savePrefFile: json.dump(preferences, savePrefFile) def updatePrefValues(self): """Updates the preference widgets with the values from the preferences. This is used when loading preferences from a f...
fsschneider/DeepOBS
docs/conf.py
Python
mit
5,559
0
# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup ------------------------------------------------------------...
sion, including alpha/beta/rc tags release = u'1.1.0' # -- General configuration --------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions comi...
ons = [ 'sphinx.ext.napoleon', 'sphinx.ext.viewcode', 'sphinxarg.ext' ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_s...
emirot/codefights
python/primesSum.py
Python
apache-2.0
136
0.014706
def primesSum(a, b): return sum([a for
a in range(a, b+1) if not (a < 2 or any(a % x == 0 for x in range
(2, int(a ** 0.5) + 1))) ])
Azure/azure-sdk-for-python
sdk/testbase/azure-mgmt-testbase/azure/mgmt/testbase/aio/__init__.py
Python
mit
524
0.003817
# 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 may cause incorrect behavior and will b...
tBase __all__ = ['TestBase']
alsrgv/tensorflow
tensorflow/python/keras/utils/generic_utils.py
Python
apache-2.0
19,553
0.007978
# 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...
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. # ===================================================...
"" from __future__ import absolute_import from __future__ import division from __future__ import print_function import binascii import codecs import marshal import os import re import sys import time import types as python_types import numpy as np import six from tensorflow.python.util import nest from tensorflow.py...
ElliottMiller/python-azuread-sample
manage.py
Python
mit
336
0
#!/usr/bin/env python """
Command-line utility for administrative tasks. """ import os import sys if __name__ == "__main__": os.environ.setdefault( "DJANGO_SETTINGS_MODULE
", "AzureAuthSample.settings" ) from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
hyperion-rt/hyperion
hyperion/grid/tests/test_io.py
Python
bsd-2-clause
6,744
0.000148
from copy import deepcopy import h5py import numpy as np import pytest import six from ...util.functions import virtual_file from .. import (CartesianGrid, CylindricalPolarGrid, SphericalPolarGrid, AMRGrid, OctreeGrid) ALL_GRID_TYPES = ['car', 'sph', 'c...
tion) as exc: h.read(f) if grid_type == 'car': assert exc.value.args[0] == "Grid is not cartesian" elif grid_type == 'cyl': assert exc.value.args[0] == "Grid is not cylindrical polar" elif grid_type == 'sph': assert exc.value.args[0] == "Grid is no...
elif grid_type == 'amr': assert exc.value.args[0] == "Grid is not an AMR grid" elif grid_type == 'oct': assert exc.value.args[0] == "Grid is not an octree" @pytest.mark.parametrize(('grid_type'), ALL_GRID_TYPES) def test_write_read_hash_mismatch(self, grid_type): g = s...
OpenGenus/cosmos
code/mathematical_algorithms/src/perfect_number/perfect_number.py
Python
gpl-3.0
235
0
def is_perfect_number(n): sum = 0
for x in range(1, n): if n % x == 0: sum += x return sum == n num = int(input("Please enter a number to check if it is perfect o
r not")) print(is_perfect_number(num))
lorien/user_agent
setup.py
Python
mit
1,599
0.000625
import os from setuptools import setup ROOT = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(ROOT, 'README.rst'), encoding='utf-8') as inp: LONG_DESCRIPTION = inp.read() setup( # Meta data name='user_agent', version='0.1.10', author="Gregory Petukhov", author_email='lorie...
'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: Implementation :: CPython', 'License :: OSI Approved :: MIT License', #'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', ...
'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Internet :: WWW/HTTP', ], )
jiayisuse/cs73
wp-admin/data_delete.py
Python
gpl-2.0
2,483
0.024567
#!/usr/bin/env python import nltk import os import sys import include title = sys.argv[1].lower() html = sys.argv[2].lower() cate_id = sys.argv[3] def do_read_train(uni_dict, bi_dict, file): lines = file.readlines() for line in lines: words = line.split() bi_dict[words[0]] = int(words[2]) uni_dict[words[0].s...
new_uni_dict[token] if uni_dict[to
ken] == 0: del uni_dict[token] # update bi dict for key in new_bi_dict: if bi_dict.has_key(key): bi_dict[key] -= new_bi_dict[key] if bi_dict[key] == 0: del bi_dict[key] def sort_dict_to(uni_dict, bi_dict, n, sorted_list): for key in bi_dict: first = key.split("|")[0] second = key.split("|")[1] ...
alirazabhayani/django_workshop_poll_app
polls/urls.py
Python
bsd-3-clause
424
0.007075
from django.conf.
urls import patterns, url from . import views urlpattern
s = patterns('', url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'), url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(), name='results'), url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'), url(r'^test/$' , views.test...
zsiki/ulyxes
pyapps/measurematrix.py
Python
gpl-2.0
4,051
0.005431
#!/usr/bin/env python # -*- coding: UTF-8 -*- """ .. module:: measurematrix.py .. moduleauthor:: Jozsef Attila Janko, Bence Takacs, Zoltan Siki (code optimalization) Sample application of Ulyxes PyAPI to measure within a rectangular area :param argv[1] (int): number of horizontal intervals (between measurements), ...
l port, default COM5 :param argv[5]: output file, default stdout usage: python measurematrix.py 9 3 1100 COM5 """ import re import sys sys.path.append('../pyapi/') from angle import Angle from serialif
ace import SerialIface from totalstation import TotalStation from echowriter import EchoWriter from filewriter import FileWriter from leicatps1200 import LeicaTPS1200 from leicatcra1100 import LeicaTCRA1100 from trimble5500 import Trimble5500 if __name__ == "__main__": if sys.version_info[0] > 2: # Python 3 compa...
immenz/pyload
module/plugins/accounts/SimplyPremiumCom.py
Python
gpl-3.0
1,650
0.008485
# -*- coding: utf-8 -*- from module.common.json_layer import json_loads from module.plugins.Account import Account class SimplyPremiumCom(Account): __name__ = "SimplyPremiumCom" __type__ = "account" __version__ = "0.05" __description__ = """Simply-Premium.com account plugin""" __license__ ...
self.logDebug("JSON data: %s" % json_data) json_data = json_loads(json_data) if 'vip' in json_data['result'] and json_data['result']['vip']: premium = True if 'timeend' in json_data['result'] and json_data['result']['timeend']: validuntil = fl
oat(json_data['result']['timeend']) if 'remain_traffic' in json_data['result'] and json_data['result']['remain_traffic']: trafficleft = float(json_data['result']['remain_traffic']) / 1024 #@TODO: Remove `/ 1024` in 0.4.10 return {"premium": premium, "validuntil": validuntil, "trafficleft"...
willysbrewing/willys_website
willys_website/core/migrations/0002_auto_20170129_1714.py
Python
apache-2.0
7,007
0.001284
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-01-29 16:14 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import modelcluster.fields import wagtail.wagtailcore.blocks import wagtail.wagtailcore.fields import wagtail.wagtailimages.blocks ...
options={ 'ordering': ['sort_order'], 'abstract': False, }, bases=('willys_website.heroitem', models.Model), ), migrations.RenameField( model_name='productpage', old_name='cost', new_name='price', ...
ductpage', name='bg_image', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='wagtailimages.Image'), ), migrations.AddField( model_name='productpage', name='ibu', field=models.Cha...
tensorflow/neural-structured-learning
research/gam/gam/trainer/trainer_classification_gcn.py
Python
apache-2.0
38,149
0.004351
# Copyright 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
g the path to a directory where to save the variable summaries. logging_step: Integer repres
enting the number of iterations after which we log the loss of the model. eval_step: Integer representing the number of iterations after which we evaluate the model. warm_start: Whether the model parameters are initialized at their best value in the previous cotrain iteration. If False, they a...
bwhmather/python-payment-terminal
payment_terminal/tests/__init__.py
Python
bsd-3-clause
320
0
import unittest from payment_terminal.tests imp
ort test_loader import payment_terminal.drivers.bbs.tests as test_bbs def suite(): loader = unittest.TestLoader() suite = unittest.TestSuite(( loader.loadTestsFromModule(test_bbs), loader.loadTestsFromModule(test_loader), ))
return suite
ryfeus/lambda-packs
Tensorflow_Pandas_Numpy/source3.6/tensorboard/plugins/beholder/beholder.py
Python
mit
7,267
0.007706
# 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...
config.pkl'):
tf.gfile.MakeDirs(self.PLUGIN_LOGDIR) write_pickle(DEFAULT_CONFIG, '{}/{}'.format(self.PLUGIN_LOGDIR, CONFIG_FILENAME)) self.visualizer = Visualizer(self.PLUGIN_LOGDIR) def _get_config(self): '''Reads the config file from disk or creates a new one.'''...
expfactory/expfactory
expfactory/database/relational.py
Python
bsd-3-clause
8,107
0.000617
""" Copyright (c) 2017-2022, Vanessa Sochat All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the f...
resh_token(self, subid): """refresh or generate a new token for a user""" from expfactory.database.models import Participant
p = Participant.query.filter(Participant.id == subid).first() if p is not None: p.token = str(uuid.uuid4()) self.session.commit() return p def save_data(self, session, exp_id, content): """save data will obtain the current subid from the session, and save it depending on the database typ...
jfinkels/flask-restless
flask_restless/search/drivers.py
Python
agpl-3.0
6,012
0
# drivers.py - high-level functions for filtering SQLAlchemy queries # # Copyright 2011 Lincoln de Sousa <lincoln@comum.org>. # Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein # <jeffrey.finkelstein@gmail.com> and contributors. # # This file is part of Flask-Restless. # # Flask-Restless is distribu...
direction = getattr(field, direction_name) query = query.order_by(direction()) else: pks = primary_key_names(model) pk_order = (getattr(model, field).asc() for field in pks) query = query.order_by(*pk_order) # Group the query. if group_by: for field_name ...
field_name, field_name_in_relation = field_name.split('.') relation_model = aliased(get_related_model(model, field_name)) field = getattr(relation_model, field_name_in_relation) query = query.join(relation_model) query = query.group_by(field) ...
sjsucohort6/openstack
python/venv/lib/python2.7/site-packages/cliff/tests/test_interactive.py
Python
mit
1,743
0
# -*- encoding: utf-8 -*- from cliff.interactive import InteractiveApp class FakeApp(object): NAME = 'Fake' def make_interactive_app(*command_names): fake_command_manager = [(x, None) for x in command_names] return InteractiveApp(FakeApp, fake_command_manager, stdin=None, stdo...
efine do_hi and do_history methods _test_completenames(['hi', 'history', 'hips', 'hippo'], 'hi') def _test_completedefault(expecteds, line, begidx): command_names = set(['show file', 'show folder', 'show long', 'list all']) app = make_interactive_app(*command_names) observeds = app.completedefault(No...
ty_text_completedefault(): # line = 'show ' + begidx = 5 implies text = '' _test_completedefault(['file', 'folder', ' long'], 'show ', 5) def test_nonempty_text_completedefault2(): # line = 'show f' + begidx = 6 implies text = 'f' _test_completedefault(['file', 'folder'], 'show f', 5) def test_long_...
thetoine/eruditorg
erudit/core/subscription/rules.py
Python
gpl-3.0
748
0.001337
import rules from rules.predicates import is_staff, is_superuser from .models import Policy @rules.predicate def is_policy_manager(user, policy=None): if policy is None:
return bool(Policy.objects.filter(managers=user).count()) else: return bool(policy.managers.filter(id=user.id).count()) @rules.predicate def is_account
_manager(user, account=None): if account is None: return bool(Policy.objects.filter(managers=user).count()) else: return is_policy_manager(user, account.policy) rules.add_perm('subscription.manage_policy', is_superuser | is_staff | is_policy_manager) rules.add_perm('subscription....
wpoa/wiki-imports
lib/python2.7/site-packages/pywikibot-2.0b1-py2.7.egg/pywikibot/families/incubator_family.py
Python
gpl-3.0
373
0
# -*- coding: utf-8 -*- __version__ = '$Id: 11c92177ab93084552b8d68021da6545c4b7674f $' from pywikibot import family # The Wikimedia Incubator family class Family(family.WikimediaFamily): def __init__(self): super(Family, self).__init__() self.name = 'incubator'
sel
f.langs = { 'incubator': 'incubator.wikimedia.org', }
mgaitan/waliki_flask
waliki/markup.py
Python
bsd-3-clause
7,181
0.003343
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2013-2014, Martín Gaitán # Copyright (c) 2012-2013, Alexander Jung-Loddenkemper # This file is part of Waliki (http://waliki.nqnwebs.com/) # License: BSD (https://github.com/mgaitan/waliki/blob/master/LICENSE) #============================================...
>`_``. They turn into `Wiki <https://github.c
om/alexex/wiki>`_. Headers are just any underline (and, optionally, overline). For example:: Level 1 ******* Level 2 ------- Level 3 +++++++ .. _reStructuredText: http://docutils.sourceforge.net/rst.html """ ...
mlperf/inference_results_v0.7
closed/Intel/code/resnet/resnet-ov/py-bindings/convert.py
Python
apache-2.0
2,497
0.007609
import sys import errno import json import os from argparse import ArgumentParser sys.path.insert(1, 'py-bindings') from squad import SQUADConverter def get_samples(test_file, vocab_file, output_dir): print("Test file:", test_file) print("Vocab file:", vocab_file) print("Output dir:", output_dir) max_s...
s() def main(): args = get_arguments() if not os.path.isfile(args.test_file): raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), args.test_file) if not os.path.isfile
(args.vocab_file): raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), args.vocab_file) sqd = SQUADConverter(args.test_file, args.vocab_file, args.max_seq_length, args.max_query_length, args.doc_stride, args.lower_case) # Convert examples print("--Reading samples--") samples = sqd...
saltstack/salt
salt/modules/aptpkg.py
Python
apache-2.0
105,007
0.001
""" Support for APT (Advanced Packaging Tool) .. important:: If you feel that Salt should be using this module to manage packages on a minion, and it is using a different module (or gives an error similar to *'pkg.install' is not available*), see :ref:`here <module-provider-override>`. For reposit...
) repo_line = repo_line + [self.uri, self.dist, " ".join(self.comps)]
if self.comment: repo_line.append("#{}".format(self.comment)) return " ".join(repo_line) + "\n" def _parse_sources(self, line): """ Parse lines from sources files """ self.disabled = False repo_line = self.line.strip()...
frac/celery
celery/utils/serialization.py
Python
bsd-3-clause
4,836
0.000414
import inspect import sys import types from copy import deepcopy import pickle as pypickle try: import cPickle as cpickle except ImportError: cpickle = None if sys.version_info < (2, 6): # pragma: no cover # cPickle is broken in Python <= 2.5. # It unsafely and incorrectly uses relative instead of a...
fine. """ #: The module of the original exception. exc_module = None #: The name of the ori
ginal exception class. exc_cls_name = None #: The arguments for the original exception. exc_args = None def __init__(self, exc_module, exc_cls_name, exc_args): self.exc_module = exc_module self.exc_cls_name = exc_cls_name self.exc_args = exc_args Exception.__init__(self...
shoopio/shoop
shuup/core/cache/__init__.py
Python
agpl-3.0
1,316
0
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2021, Shuup Commerce Inc. All rights reserved. # # This source code is licensed under the OSL-3.0 license found in the # LICENSE file in the root directory of this source tree. """ Utilities for versioned caching and automatic timeout determin...
within the cache, within the ``_version`` namespace. (As an implementation detail, this allows one to invalidate _all_ versioned keys by bumping the version of ``_version``. Very meta!) """ from .impl import VersionedCache __all__ = [ "bump_version", "clear", "get", "set", "VersionedCache",
] _default_cache = None get = None set = None bump_version = None clear = None def init_cache(): global _default_cache, get, set, bump_version, clear _default_cache = VersionedCache(using="default") get = _default_cache.get set = _default_cache.set bump_version = _default_cache.bump_version c...
Groutcho/exii
tests/instructions/test_pop.py
Python
gpl-2.0
762
0
from unittest import TestCase from instructions.pop import Pop from context import Context from registers import AX, SP __author__ = "Sébastien Guimmara" class TestPop(TestCase): def test_execute(self): p = Pop.parse(['ax']) ctx = Context(None) ctx.registers.set(SP, 0xFFFE) self.a...
ctx.stack.set(0xFFFE, 0x0022) p.execute(ctx) self.assertEqual(ctx.registers.get(AX).value, 0x0022) self.assertEqual(ctx.registers.get(SP).value, 0xFFFF) def test_parse_bad_number_of_arguments(self): self.assertRaises(SyntaxError, lambda: Pop.parse(['ax,', '2'])) def te...
sInstance(Pop.parse(['ax']), Pop)
skuda/client-python
kubernetes/test/test_v1beta1_network_policy_ingress_rule.py
Python
apache-2.0
991
0.004036
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.6.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys im...
ressRule(unittest.TestCase): """ V1beta1NetworkPolicyIngressRule unit test stubs """ def setUp(self): pass def tearDown(self): pass def testV1beta1NetworkPolicyIngressRule(self): """ Test V1beta1NetworkPolicyIngressRule """ model = kubernetes.client.mod...
unittest.main()
olipratt/swagger-conformance
swaggerconformance/response.py
Python
mit
1,388
0
""" A response received to a Swagger API operation. """ import logging __all__ = ["Response"] log = logging.getLogger(__name__) class CaseInsensitiveDict(dict): """Dictionary with case insensitive lookup of string keys.""" def __getitem__(self, key): return {k.lower(): v for k, v in self.items()}[k...
w_response): self._raw_response = raw_response @pro
perty def status(self): """HTTP status code of the response. :rtype: int """ return self._raw_response.status @property def body(self): """Parsed response body converted to objects via the codec in use.""" return self._raw_response.data @property de...
rpm-software-management/dnf
dnf/yum/misc.py
Python
gpl-2.0
11,251
0.001867
# misc.py # Copyright (C) 2012-2016 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later
version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY exp
ressed or implied, including the implied warranties 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; if not, write to the # Free Software Foundation, Inc., 51 Fr...
Digilent/u-boot-digilent
test/py/tests/test_md.py
Python
gpl-2.0
1,426
0.001403
# SPDX-License-Identifier: GPL-2.0 # Copyright (c) 2015 Stephen Warren # Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved. import pytest import u_boot_utils @pytest.mark.buildconfigspec('cmd_memory') def test_md(u_boot_console): """Test that md reads memory as expected, and that memory can be modi...
expected_response = addr + ': ' + val u_boot_console.run_command('mw ' + addr + ' 0 10') response = u_boot_console.run_command('md ' + addr + ' 10') assert(not (expected_response in response)) u_boot_console.run_command('mw ' + addr + ' ' + val) response = u_boot_console.run_command('md ' + addr ...
'cmd_memory') def test_md_repeat(u_boot_console): """Test command repeat (via executing an empty command) operates correctly for "md"; the command must repeat and dump an incrementing address.""" ram_base = u_boot_utils.find_ram_base(u_boot_console) addr_base = '%08x' % ram_base words = 0x10 ad...
afimb/gtfslib-python
gtfslib/orm.py
Python
gpl-3.0
22,956
0.008059
# -*- coding: utf-8 -*- # This file is part of Gtfslib-python. # # Gtfslib-python 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...
=_feedinfo_id_column == foreign(_zone_feed_id_column)) })) _stop_feed_id_column = Column('feed_id', String, ForeignKey('feed_info.feed_id'), primary_key=True) _stop_id_column = Column('stop_id', String, primary_key=True) _stop_parent_id_column = Column('parent_station_id', String, nulla...
'zone_id', String, nullable=True) _stop_mapper = Table('stops', self._metadata, _stop_feed_id_column, _stop_id_column, _stop_parent_id_column, Column('location_type', Integer, nullable=False), Column('stop_name',...
yuncliu/Learn
python/decorator.py
Python
bsd-3-clause
299
0.013378
#!/usr/bin/python3 #-*- coding:utf-8
-*- from functools import wraps def xxx(func): @wraps(func) def my(n): func(n*100)
return return my @xxx def abc(n): print(n) if __name__ == '__main__': abc(10) abc.__wrapped__(10) xx = abc.__wrapped__ xx(1234)
blrm/openshift-tools
docker/oso-psad/src/scripts/check_psad.py
Python
apache-2.0
5,322
0.004134
#!/bin/env python # vim: expandtab:tabstop=4:shiftwidth=4 """ This script is used to check the psad logs for positive port scanning traffic and report its findings to Zabbix. """ from __future__ import print_function from datetime import datetime import os import re import boto3 import botocore import yaml # Rea...
= config_dict['opsad_cluster_name'] os.environ["AWS_SHARED_CREDENTI
ALS_FILE"] = credsfile s3_session = boto3.resource('s3') exists = True try: s3_session.meta.client.head_bucket(Bucket=bucket) except botocore.exceptions.ClientError as client_exception: error_code = int(client_exception.response['Error']['Code']) i...
martiert/bitbake
lib/bb/fetch2/osc.py
Python
gpl-2.0
4,506
0.00466
# ex:ts=4:sw=4:sts=4:et # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- """ Bitbake "Fetch" implementation for osc (Opensuse build service client). Based on the svn "Fetch" implementation. """ import os import sys import logging import bb from bb import data from bb.fetch2 import Fetch...
is "fetch", "update", "info" """ basecmd = data.expand('${FETCHCMD_osc}', d) proto = ud.parm.get('protocol', 'ocs') options = [] config = "-c %s" % self.generate_config(ud, d) if ud.revision: options.append("-r %s" % ud.revision) coroot = self._...
co %s/%s %s" % (basecmd, config, coroot, ud.module, " ".join(options)) elif command == "update": osccmd = "%s %s up %s" % (basecmd, config, " ".join(options)) else: raise FetchError("Invalid osc command %s" % command, ud.url) return osccmd def download(self, loc, ud...
PyCQA/astroid
tests/testdata/python3/data/conditional.py
Python
lgpl-2.1
87
0.011494
from data.conditional_i
mport i
mport ( dump, # dumps, # load, # loads, )
kreatorkodi/repository.torrentbr
plugin.video.yatp/libs/client/actions.py
Python
gpl-2.0
8,310
0.003851
# coding: utf-8 # Module: actions # Created on: 27.07.2015 # Author: Roman Miroshnychenko aka Roman V.M. (romanvm@yandex.ua) # Licence: GPL v.3: http://www.gnu.org/copyleft/gpl.html import os import xbmcgui import xbmcplugin from simpleplugin import Plugin import json_requests as jsonrq from buffering import buffer_to...
info_hash=torrent['info_hash']))) item['context_menu'] = context_menu yield item def _build_file_list(files, info_hash): """ Create the list of videofiles in a torrent :param files: :param info_hash:
:return: """ videofiles = get_videofiles(files) for file_ in videofiles: ext = os.path.splitext(file_[1].lower())[1] if ext == '.avi': thumb = os.path.join(icons, 'avi.png') elif ext == '.mp4': thumb = os.path.join(icons, 'mp4.png') elif ext == '.mkv...
sem-geologist/hyperspy
hyperspy/tests/misc/test_test_utils.py
Python
gpl-3.0
5,176
0
# -*- coding: utf-8 -*- # Copyright 2007-2016 The HyperSpy developers # # This file is part of HyperSpy. # # HyperSpy 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...
with assert_warns(message="Warning [AB]!"): warnsC() except ValueError: pass else: raise AssertionError("ValueError expected!") with all_warnings(): warnings.simplefilter("err
or") try: with assert_warns(message="Warning A! Too much"): warnsA() except ValueError: pass else: raise ValueError("ValueError expected!") def test_assert_warns_type(): with all_warnings(): warnings.simplefilter("error") ...
Parlin-Galanodel/scrapy
tests/test_pipeline_files.py
Python
bsd-3-clause
17,823
0.002749
import os import random import time import hashlib import warnings from tempfile import mkdtemp from shutil import rmtree from six.moves.urllib.parse import urlparse from six import BytesIO from twisted.trial import unittest from twisted.internet import defer from scrapy.pipelines.files import FilesPipeline, FSFilesS...
S_URLS_FIELD": "file_urls", "FILES_RESULT_FIELD": "files"
} file_cls_attr_settings_map = { ("E
radiosilence/pip
tests/test_vcs_backends.py
Python
mit
5,930
0.003373
from tests.test_pip import (reset_env, run_pip, _create_test_package, _change_test_package_version) from tests.local_repos import local_checkout def test_install_editable_from_git_with_https(): """ Test cloning from Git with https. """ reset_env() result = run_pip('install', ...
e('\\', '/'))) version = env.run('version_pkg') assert 'some different
version' in version.stdout def test_git_with_tag_name_as_revision(): """ Git backend should be able to install from tag names """ env = reset_env() version_pkg_path = _create_test_package(env) env.run('git', 'tag', 'test_tag', expect_stderr=True, cwd=version_pkg_path) _change_test_package...
synth3tk/the-blue-alliance
helpers/event_insights_helper.py
Python
mit
6,320
0.002848
import logging from collections import defaultdict class EventInsightsHelper(object): @classmethod def calculate_event_insights(cls, matches, year): INSIGHTS_MAP = { 2016: cls.calculate_event_insights_2016 } if year in INSIGHTS_MAP: return INSIGHTS_MAP[year](ma...
'C_SallyPort': [0, 0, 0], 'C_Drawbridge': [0, 0, 0], 'D_RoughTerrain': [0, 0, 0], 'D_RockWall': [0, 0, 0], 'average_high_goals': float(high_goals) / (2 * finished_matches), '
average_low_goals': float(low_goals) / (2 * finished_matches), 'breaches': [breaches, opportunities_1x, 100.0 * float(breaches) / opportunities_1x], # [# success, # opportunities, %] 'scales': [scales, opportunities_3x, 100.0 * float(scales) / opportunities_3x], 'challenges': [chall...
brunorijsman/coding-katas
bank-ocr-python/bank-ocr.py
Python
mit
3,837
0.019547
import copy pattern_raw_digits = [ [' _ ', '| |', '|_|'], [' ', ' |', ' |'], [' _ ', ' _|', '|_ '], [' _ ', ' _|', ' _|'], [' ', '|_|', ' |'], [' _ ', '|_ ', ' _|'], [' _ ', '|_ ', '|_|'], [' _ ', ' |', ' |'], [' _ ', '|_|', '|_|'], [' ...
return " ILL" def change_one_char(raw_number, row, col, new_char): new_raw_number = copy.copy(raw_number) new_raw_number[row] = raw_number[row][:col] + new_char + raw_number[row][col+1:] return new_ra
w_number def find_all_guesses(raw_number): guesses = [] for row in range(3): for col in range(27): char = raw_number[row][col] if (char == '_') or (char == '|'): guess_raw_number = change_one_char(raw_number, row, col, ' ') guess_number = parse_raw_number(guess_raw_number) i...
Tanmay28/coala
coalib/tests/bears/LocalBearTest.py
Python
agpl-3.0
585
0.005128
import sys sys.path.insert(0, ".") import unittest from coalib.settings.Section import Section from coalib.bears.L
ocalBear import LocalBear, BEAR_KIND class LocalBearTest(unittest.TestCase): def test_api(self): test_object = LocalBear(Section("name"), None) self.assertRaises(NotImplementedError, test_object.run, "filename", ["file\n...
BEAR_KIND.LOCAL) if __name__ == '__main__': unittest.main(verbosity=2)