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
snnn/tensorflow
tensorflow/contrib/distribute/__init__.py
Python
apache-2.0
2,737
0.001827
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
ard_tensorflow_server from tensorflow.python.training.distribute import * from tensorflow.python.training.distribution_strategy_context import * from tensorflow.python.util.all_util import remove_undocumented _allowed_symbols = [ 'AllReduceCrossTowerOps', 'CollectiveAllReduceStrategy', 'CrossTowerOps', ...
tributionStrategy', 'MirroredStrategy', 'Monitor', 'OneDeviceStrategy', 'ParameterServerStrategy', 'ReductionToOneDeviceCrossTowerOps', 'Step', 'StandardInputStep', 'StandardSingleLossStep', 'TowerContext', 'TPUStrategy', 'get_cross_tower_context', 'get_distribution_strat...
edx/course-discovery
course_discovery/apps/course_metadata/migrations/0150_curriculum_program.py
Python
agpl-3.0
545
0.001835
# Generated by Django 1.11.15 on 2019-01-29 15:32 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
dependencies = [ ('course_metadata', '0149_auto_20190201_1515'), ] operations = [ migrations.AddField( model_name='curriculum', name='program', field=models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.CASCADE, relat
ed_name='curricula', to='course_metadata.Program'), ), ]
simone-campagna/rubik
rubik/application/rubik.py
Python
apache-2.0
37,260
0.004321
#!/usr/bin/env python3 # # Copyright 2014 Simone Campagna # # 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 ...
es = visualizer_attributes self.vis
ualizer_attribute_files = visualizer_attribute_files def set_histogram_options(self, bins=10, length=80, range=None, mode=None, decimals=None): self.histogram_bins = bins self.histogram_range = range self.histogram_length = length self.histogram_mode = mode fmt_base = "{b}{s...
ngokevin/zamboni
mkt/developers/tests/test_views_versions.py
Python
bsd-3-clause
30,543
0
import datetime import os from django.conf import settings import mock from nose.tools import eq_, ok_ from pyquery import PyQuery as pq import amo import amo.tests from amo.tests import req_factory_factory from mkt.comm.models import CommunicationNote from mkt.constants.applications import DEVICE_TYPES from mkt.dev...
= fixture('group_admin', 'user_999', 'user_admin', 'user_admin_group', 'webapp_337141') def setUp(self): self.client.login(username='admin@mozilla.com', pa
ssword='password') self.webapp = self.get_webapp() self.url = self.webapp.get_dev_url('versions') def get_webapp(self): return Webapp.objects.get(id=337141) def test_nav_link(self): r = self.client.get(self.url) eq_(pq(r.content)('.edit-addon-nav li.selected a').attr('h...
mpdehaan/func
func/overlord/base_command.py
Python
gpl-2.0
1,892
0.006871
""" Copyright 2008, Red Hat, Inc Adrian Likins <alikins@redhat.com> also see AUTHORS This software may be freely redistributed under the terms of the GNU general public license. You should have received a copy of the GNU Gene
ral Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. """ import command import client from certmaster.config import read_config, BaseConfig, ListOption from func import commonconfig DEFAULT_PORT = 51234 DEFAULT_MAPLOC = "/var/lib/fu...
getOverlord() for getting a overlord client api handle""" interactive = False verbose=0 port=DEFAULT_PORT async=False forks=1 delegate=False mapfile=DEFAULT_MAPLOC # temporary work around FIXME # we really need a way to store what port each minion is # listening on, though th...
akegan/plasmoids
pplot.py
Python
mit
13,037
0.04794
import numpy import tables import scipy import matplotlib import matplotlib.pyplot as plt import collections import scipy.signal import csv import egan_vorpalUtil as egan import os from mpl_toolkits.axes_grid1 import host_subplot import mpl_toolkits.axisartist as AA import sys #sys.path.append('/scr_verus/wernerg/vrun/...
lors[i],marker=markerstyle[i],linestyle='',label="Stage "+str(i)) #plot pts for legend #print "i=%d"%i #print len(colors) elif TIME_PLOT: for i in numpy.arange(len(byHistTimes)): maxima=egan.findAzMax(Az[i,:],0,width,AVG=False,SHORTSTEP=True,DEBUG=False) minima=egan.findAzMin(Az[i,:],0,width,A...
rue) #print minima times=numpy.empty(len(maxima));times.fill(byHistTimes[i]*1E6) times2=numpy.empty(len(minima));times2.fill(byHistTimes[i]*1E6) ax.plot(minima,times2,linestyle='',marker='+',markersize=3,color='b') ax.plot(maxima,times,linestyle='',marker='.',markersize=1.5,...
nikitamarchenko/open-kilda
services/topology-engine-rest/app/app/tests/get_links.py
Python
apache-2.0
694
0.004323
""" get_links.py - get all the links The path is NB -> TER -> NEO4J. """ import re
quests from base64 import b64encode url = "http://localhost:8088/api/v1/links" headers = { 'Content-Type': 'application/json', 'Authorization': 'Basic %s' % b64encode(b"kilda:kilda").decode("ascii") } # # This models one of the first flows used by ATDD. It sends the request to teh NB API so that # kilda will ...
and ATDD has a separate source. # result = requests.get(url, headers=headers) print result.status_code print result.text
jameswenzel/billboard-charts
tests/test_greatest_hot_100_singles.py
Python
mit
1,451
0
import json import unittest import billboard class TestCurrentGreatestHot100Singles(u
nittest.TestCase): """Checks that the ChartData object for the current Greatest Hot 100 Singles chart has entries and instance variables that are valid and reasonable. Does not test whether the data i
s actually correct. The Greatest Hot 100 Singles chart is special in that there are no past charts (i.e., there is no historical data). """ def setUp(self): self.chart = billboard.ChartData('greatest-hot-100-singles') def test_date(self): self.assertIsNone(self.chart.date) # This...
ParrotPrediction/pyalcs
lcs/agents/xcs/Condition.py
Python
mit
616
0
from __future__ import annotations f
rom .. import ImmutableSequence class Condition(ImmutableSequence): def subsumes(self, other) -> bool: for ci, oi in zip(self, other):
if ci != self.WILDCARD and oi != self.WILDCARD and ci != oi: return False return True @property def wildcard_number(self) -> int: return sum(1 for c in self if c == self.WILDCARD) def is_more_general(self, other: Condition) -> bool: for ci, oi in zip(self, other): ...
mdhaman/superdesk-core
apps/archive/commands.py
Python
agpl-3.0
19,764
0.004453
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import funct...
{} Remove expired content task is already running.'.format(self.log_msg)) return logger.info('{} Removing expired content for expiry.'.format(self.log_msg)) # both functions should be called, even the first one throw exception, # so they are wrapped with log_ex
eption self._remove_expired_publish_queue_items() self._remove_expired_items(now) unlock(lock_name) push_notification('content:expired') logger.info('{} Completed remove expired content.'.format(self.log_msg)) remove_locks() @log_exeption def _remove_expired_pu...
anhstudios/swganh
data/scripts/templates/object/ship/shared_rebel_gunboat_tier5.py
Python
mit
416
0.050481
#### NOTICE
: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Ship() result.template = "object/ship/shared_rebel_gunboat_tier5.iff" result.attribute_template_id = -1 result.stfName("","...
n result
hackerspace-ntnu/website
news/migrations/0020_auto_20190512_1744.py
Python
mit
780
0.002564
# Generated by Django 2.0.10 on 2019-05-12 17:44 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.
Migration): dependencies = [ ('userprofile', '0020_auto_20190507_0150'), ('news', '0019_auto_
20190512_1608'), ] operations = [ migrations.AddField( model_name='article', name='author', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='userprofile.Profile'), ), migrations.AddField( mod...
bssrdf/leetcode-7
solutions/038.Count_and_Say/AC_simulation_n.py
Python
gpl-2.0
737
0.005427
#!/usr/local/bin/python # -*- coding: utf-8 -*- # Author: illuz <iilluzen[at]gmail.com> # File: AC_simulation_n.py # Create Date: 2015-07-30 09:41:51 # Usage: AC_simulation_n.py # Descripton: class Solution: # @param {integer} n # @return {string} def countAndSay(self, n): r
es = '1' for _ in xrange(n - 1):
res = self.helper(res) return res def helper(self, s): cnt, res = 1, '' for i in xrange(len(s) - 1): if s[i] == s[i + 1]: cnt += 1 else: res += str(cnt) + s[i] cnt = 1 res += str(cnt) + s[-1] return res...
kylef/pyppp
test.py
Python
bsd-2-clause
362
0
#!/usr/bin/env python import pyppp if __name__ == '__main__': print 'PyPPP Version: %s' % pyppp._
_version__ p = pyppp.PyPPP() print 'PPP Specification Version: %s' % p.__version__ p.generate_random_sequence_key() print 'PPP Key: %s' % p.key
passcode = 5 print 'Passcode: %d' % passcode print '%s' % p.retrieve_passcode(passcode)
binoculars/osf.io
osf/models/nodelog.py
Python
apache-2.0
7,092
0.002679
from include import IncludeManager from django.apps import apps from django.db import models from django.utils import timezone from osf.models.base import BaseModel, ObjectIDMixin from osf.utils.datetime_aware_jsonfield import DateTimeAwareJSONField from osf.utils.fields import NonNaiveDateTimeField from website.util ...
ED_INSTITUTION_ADDED = 'affiliated_institution_added' AFFILIATED_INSTITUTION_REMOVED = 'affiliated_institution_removed' PREPRINT_INITIATED = 'preprint_initiated' P
REPRINT_FILE_UPDATED = 'preprint_file_updated' PREPRINT_LICENSE_UPDATED = 'preprint_license_updated' SUBJECTS_UPDATED = 'subjects_updated' VIEW_ONLY_LINK_ADDED = 'view_only_link_added' VIEW_ONLY_LINK_REMOVED = 'view_only_link_removed' actions = ([CHECKED_IN, CHECKED_OUT, FILE_TAG_REMOVED, FILE_TA...
plotly/plotly.py
packages/python/plotly/plotly/validators/funnel/marker/colorbar/_nticks.py
Python
mit
466
0.002146
import _plotly_utils.basevalidators class NticksValidator(_plotly_
utils.basevalidators.IntegerValidator): def __init__( self, plotly_name="nticks", parent_name="funnel.marker.colorbar", **kwargs ): super(NticksValidator, self).__init__( plotly_name=plotly_name, p
arent_name=parent_name, edit_type=kwargs.pop("edit_type", "colorbars"), min=kwargs.pop("min", 0), **kwargs )
monkeypants/MAVProxy
MAVProxy/modules/mavproxy_map/mp_tile.py
Python
gpl-3.0
23,042
0.004427
#!/usr/bin/env python ''' access satellite map tile database some functions are based on code from mapUtils.py in gmapcatcher Andrew Tridgell May 2012 released under GNU GPL v3 or later ''' import collections import errno import hashlib import sys import math import threading import os import string import time impo...
lf._tile_cache = ordereddict.OrderedDict() def set_service(self, service): '''set tile service''' self.service = service def get_service(self): '''get tile service'''
return self.service def get_service_list(self): '''return list of available services''' service_list = TILE_SERVICES.keys() return sorted(service_list) def set_download(self, download): '''set download enable''' self.download = download def coord_to
heolin123/day_or_night
mainapp/migrations/0008_auto_20151023_1317.py
Python
gpl-2.0
650
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import djan
go.utils.timezone class Migration(migrations.Migration): dependencies = [ ('mainapp', '0007_auto_20151023_1012'), ] operations = [ migrations.AddField( model_name='documentclassification',
name='created_at', field=models.DateTimeField(default=django.utils.timezone.now), ), migrations.AddField( model_name='documentclassification', name='ip', field=models.CharField(default=b'', max_length=100), ), ]
tiborsimko/zenodo
zenodo/modules/deposit/config.py
Python
gpl-2.0
1,816
0
# -*- coding: utf-8 -*- # # This file is part of Zenodo. # Copyright (C) 2015 CERN. # # Zenodo is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later v...
to be auto-requested if record has g
rants.""" ZENODO_COMMUNITIES_ADD_IF_GRANTS = [] """Communities which are to be auto-added if record has grants.""" ZENODO_BUCKET_QUOTA_SIZE = 50 * 1000 * 1000 * 1000 # 50 GB """Maximum quota per bucket.""" ZENODO_MAX_FILE_SIZE = ZENODO_BUCKET_QUOTA_SIZE """Maximum file size accepted."""
manasapte/pants
contrib/python/tests/python/pants_test/contrib/python/checks/tasks/checkstyle/test_new_style_classes.py
Python
apache-2.0
1,026
0.004873
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) from pants_test.cont...
st_base import \ CheckstylePluginTestBase from pants.contrib.python.checks
.tasks.checkstyle.new_style_classes import NewStyleClasses class NewStyleClassesTest(CheckstylePluginTestBase): plugin_type = NewStyleClasses def test_new_style_classes(self): statement = """ class OldStyle: pass class NewStyle(object): pass """ self.assertNit(statement, ...
brendan-w/piHud
pihud/Page.py
Python
lgpl-2.1
846
0.004728
from PyQt4 import QtCore, QtGui class Page(QtGui.QWidget): """ A container and dropevent catcher for widgets """ def __init__(self, parent, pihud): super(Page, self).__init__(parent) self.setAcceptDrops(True) self.
pihud = pihud # normally, this would simply be the parent() self.widgets = [] self.show() de
f dragEnterEvent(self, e): e.accept() def dropEvent(self, e): # get relative position of mouse from mimedata mime = e.mimeData().text() x, y = map(int, mime.split(',')) e.source().move(e.pos() - QtCore.QPoint(x, y)) e.setDropAction(QtCore.Qt.MoveAction) e.a...
sdoran35/hate-to-hugs
venv/lib/python3.6/site-packages/nltk/translate/__init__.py
Python
mit
913
0
# -*- coding: utf-8 -*- # Natural Language Toolkit: Machine Translation # # Copyright (C) 2001-2017 NLTK Project # Author: Steven Bird <stevenbird1@gmail.com>, Tah Wei Hoon <hoon.tw@gmail.com> # URL: <http://nltk.org/> # For license information, see LICENSE.TXT """ Experimental features for machine translation. These ...
BMModel from nltk.translate.ibm1 import IBMModel1 from nltk.translate.ibm2 import IBMModel2 from nltk.translate.ibm3 import IBMModel3 from nltk.translate.ibm4 import IBMModel4 from nltk.translate.ibm5 import IBMModel5 from nltk.translate.bleu_score import sentence_bleu as bleu from nltk.translate.ribes_score import sen...
ecoder import StackDecoder
letuananh/intsem.fx
coolisf/dao/textcorpus.py
Python
mit
5,974
0.002009
# -*- coding: utf-8 -*- """ Raw Text Corpus manager """ # This code is a part of coolisf library: https://github.com/letuananh/intsem.fx # :copyright: (c) 2014 Le Tuan Anh <tuananh.ke@gmail.com> # :license: MIT, see LICENSE for more details. import os import json from texttaglib.chirptext import FileHelper from tex...
self.__corpuses} def add(self, corpus): self.__corpuses.append(corpus) self.__corpus_map[corpus.name] = corpus def __iter__(self): return iter(self.__corpuses) def __len__(self): return len(self.__
corpuses) def __getitem__(self, key): return self.__corpus_map[key] def __contains__(self, key): return key in self.__corpus_map class RawCorpus(MetaObject): def __init__(self, path, name='', title='', *args, **kwargs): super().__init__(path, *args, **kwargs) self.name =...
talipovm/terse
terse/Tools/file2.py
Python
mit
5,523
0.00163
import io import logging import os import re log = logging.getLogger(__name__) class file2(io.TextIOWrapper): """ Provides tools useful for navigating through and finding data in the output files """ def __init__(self, name, mode='r', *args, **kwargs): # super().__init__(*args, **kwargs)...
1 : - # Junk : 2 : - # Info : 3 : + # Info : : + # Info
:-1 : + # end_match : 0 : - # Other : 1 : - # Other : 2 : - # # In this case, only strings marked by '+' sign will be extracted # If start_match is not defined, block will start at current position+start_offset # If end_match is not define...
CanonicalLtd/landscape-client
landscape/client/manager/tests/test_store.py
Python
gpl-2.0
2,217
0
from landscape.client.tests.helpers import LandscapeTest from landscape.client.manager.store import ManagerStore class ManagerStoreTest(LandscapeTest): def setUp(self): super(ManagerStoreTest, self).setUp() self.filename = self.makeFile() self.store = ManagerStore(self.filename) ...
graph = self.store.get_graph(1) self.assertEqual(graph, (1, u"file 2", u"user2")) def test_remove_graph(self): se
lf.store.remove_graph(1) graphs = self.store.get_graphs() self.assertEqual(graphs, []) def test_remove_unknown_graph(self): self.store.remove_graph(2) graphs = self.store.get_graphs() self.assertEqual(graphs, [(1, u"file 1", u"user1")]) def test_get_accumulate_unknown_g...
openstack/octavia
octavia/amphorae/backends/agent/api_server/amphora_info.py
Python
apache-2.0
7,469
0
# Copyright 2015 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
meminfo = self._get_meminfo() cpu = self._cpu() st = os.statvfs('/') body = {'hostname': socket.gethostname(), 'haproxy_version': self._get_version_of_installed_package('haproxy'), 'api_version': api_server.VERSION, 'networ...
xy_processes(haproxy_listener_list), 'cpu': { 'total': cpu['total'], 'user': cpu['user'], 'system': cpu['system'], 'soft_irq': cpu['softirq'], }, 'memory': { 'total': meminfo['MemTotal'], ...
CloudServer/cinder
cinder/volume/drivers/san/hp/hpmsa_client.py
Python
apache-2.0
931
0
# Copyright 2014 Objectif Libre # Copyright 2015 DotHill Systems # # 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 # # U...
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 cinder.volume.drivers.dothill import dothill_client class HPMSAClient(dothill_client.DotH...
protocol)
CDE-UNIBE/qcat
apps/accounts/authentication.py
Python
apache-2.0
589
0
from django.contrib.auth.backends import ModelBackend from .client import remote_user_client class WocatCMSAuthenticationBackend(ModelBackend): """ Authentication against new (2017) wocat website. """ def authenticate(self, username=None, password=None, **kwargs): """ Custom authentic...
""" user_data = remote_user_client.remote_login(username, password) if not user_da
ta: return None return remote_user_client.get_and_update_django_user(**user_data)
salman-bhai/DS-Algo-Handbook
Algorithms/Graph_Algorithms/Bellman_Ford/bellman_ford.py
Python
mit
1,400
0.042857
from sys import maxin
t class BellmanFord( object ): def __init__( self ): ''' Constructor ''' def singleSourceShortestPath( self, weight, source ) : # auxiliary constants SIZE = len( weight ) EVE = -1; # to indicate no predecessor INFINITY = maxint # declare and initialize pred to EVE and min...
ce is 0 distance from itself. minDist[source] = 0 # relax the edge set V-1 times to find all shortest paths for i in range( 1, SIZE - 1 ): for v in range( SIZE ): for x in self.adjacency( weight, v ): if minDist[x] > minDist[v] + weight[v][x]: minDist[x] = minDist[v] + ...
Andrew-McNab-UK/DIRAC
AccountingSystem/scripts/dirac-accounting-report-cli.py
Python
gpl-3.0
788
0.013959
#!/usr/bin/env python ######################################################################## # $HeadURL$ # File : dirac-accounting-report-cli # Author : Adria Casajus ######################################################################## """ Command line i
nterface to DIRAC Accounting ReportGenerator Service. """ __RCSID__ = "$Id$" from DIRAC.Core.Base import Script Script.localCfg.addDefaultEntry( "LogLevel", "info" ) Script.setUsageMessage('\n'.join( [ __doc__.split( '\n' )[1], 'Usage:', ' %s [o...
_main__": reli = ReportCLI() reli.start()
radjkarl/dataArtist
dataArtist/gui.py
Python
gpl-3.0
20,228
0.000395
#!/usr/bin/env python # coding=utf-8 import sys import os from qtpy import QtGui, QtWidgets, QtCore from appbase.MultiWorkspaceWindow import MultiWorkspaceWindow from appbase.Application import Application from fancytools.os.PathStr import PathStr from imgProcessor.reader.qImageToArray import qImageToArray # from int...
(self, displaynumber): ''' close frame-less dis
play [displaynumber] ''' d = self.framelessDisplays.pop(displaynumber, None) if d: d.showTitleBar() d.embedd() else: print('displaynumber [%s] not known' % displaynumber) def runScriptFromName(self, name): ''' run an open s...
light940929/omics_api
bio/tools.py
Python
mit
2,096
0.000477
from oauth2_provider.settings import oauth2_settings from oauthlib.common import generate_token from django.http
import JsonResponse from oauth2_provider.models import AccessToken, Application, RefreshToken from django.utils.timezone import now, timedelta def get_token_json(access_token): """ Takes an AccessToken instance as an argument and returns a Jso
nResponse instance from that AccessToken """ token = { 'access_token': access_token.token, 'expires_in': oauth2_settings.ACCESS_TOKEN_EXPIRE_SECONDS, 'token_type': 'Bearer', 'refresh_token': access_token.refresh_token.token, 'scope': access_token.scope } retur...
aertoria/MiscCode
stack.py
Python
apache-2.0
585
0.080342
#!/usr/bin/python class Solution: # @param {string} s # @return {boolean} def isValid(self, s): slist=' '.join(s).split(' ') print slist stack=[] fo
r item in slist: if item in ('[','{','('): stack.append(item) else: if len(stack)==0: return False elif stack[-1:][0]==self.rev(item): stack = stack[:-1] else: return False if len(stack)==0: return True else: return False def rev(self,item): if item == ']': return...
== '}': return '{' else: return '(' s=Solution() print s.isValid(']')
yunify/qingcloud-sdk-python
qingcloud/iaas/actions/instance_groups.py
Python
apache-2.0
6,153
0.002438
# ========================================================================= # Copyright 2012-present Yunify, Inc. # ------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this work except in compliance with the Licens...
TION_DESCRIBE_INSTANCE_GROUPS valid_keys = ['instance_groups', 'relation', 'tags', 'owner', 'verbose', 'offset', 'limit'] body = filter_out_none(locals(), valid_keys) if not self.conn.req_checker.check_params(body, list_para...
): return None return self.conn.send_request(action, body)
romanz/trezor-agent
libagent/tests/test_server.py
Python
lgpl-3.0
3,380
0
import io import os import socket import tempfile import threading import mock import pytest from .. import server, util from ..ssh import protocol def test_socket(): path = tempfile.mktemp() with server.unix_domain_socket_server(path): pass assert not os.path.isfile(path) class FakeSocket: ...
dler, mutex) conn.
tx.seek(0) reply = util.read_frame(conn.tx) assert reply == util.pack('B', protocol.msg_code('SSH_AGENT_FAILURE')) conn_mock = mock.Mock(spec=FakeSocket) conn_mock.recv.side_effect = [Exception, EOFError] server.handle_connection(conn=conn_mock, handler=None, mutex=mutex) def test_server_thread()...
superpenshine/RipMyProfessor
gethint/urls.py
Python
mit
150
0.013333
from django.conf
.urls import url from . import views urlpatterns = [ url(r'^(?P<typed_letter>[a-zA-Z]+[0-9]{0,3})$', views.gethint, name='hint'), ]
sodhancha/Godown
purchase_orders/models.py
Python
gpl-3.0
480
0.027083
from django.db import models from inven
tory.models import Product_variant from suppliers.models import Supplier # Create your models here. class Purchase_order( models.Model ): supplier_id = models.ForeignKey(Supplier) created_at = models.DateTimeField('date published') class Item( models.Model ): purchase = models.ForeignKey(Purchase_order) produc...
riant) quantity = models.PositiveIntegerField() price = models.PositiveIntegerField()
waynesun09/tp-libvirt
libvirt/tests/src/virsh_cmd/virsh_connect.py
Python
gpl-2.0
8,185
0
import logging import os import re import shutil from autotest.client.shared import error from avocado.utils import process from virttest import libvirt_vm from virttest import utils_libvirtd from virttest import virsh from virttest import utils_conn def do_virsh_connect(uri, options): """ Execute connect ...
is: %s", connect_uri) logging.debug("actual uri after connect is: %s", uri) if not uri == connect_uri: raise error.TestFail("Command exit normally but the uri is " "
not setted as expected.") except process.CmdError, detail: if status_error == "no": raise error.TestFail("Connect failed in the case expected" "to success.\n" "Error: %s" % detail) finally: if trans...
oskgeek/liftpass
tests/pricing.py
Python
apache-2.0
10,307
0.036286
import unittest import json import requests import sys import string import random import config import core.content.errors as errors import core.api.main as main import core.content.content as content import core.pricing.pricing as pricing import core.storage as storage from core.util.test import * class TestPricin...
.setABTest(a.key, {'groupBPrices_key': jsonPricesB.key}) prici
ng = backend.getPricingEngine(a.key) pricesA = pricing.getPrices('a', [0]*32) pricesB = pricing.getPrices('b', [0]*32) self.assertEqual(pricesA[0], jsonPricesA.key) self.assertEqual(pricesB[0], jsonPricesB.key) self.assertEqual(pricesA[1]['sword'][0], 1000) self.assertEqual(pricesB[1]['sword'][0], 200...
nachtmaar/androlyze
androlyze/loader/exception/__init__.py
Python
mit
2,440
0.007377
# encoding: utf-8 __author__ = "Nils Tobias Schmidt" __email__ = "schmidt89 at informatik.uni-marburg.de" ''' Loader exceptions ''' from androlyze.error.WrapperException import WrapperException from androlyze.model.android.Cons
tants import MANIFEST_FILENAME from androlyze.error.AndroLyzeLabError import AndroLyzeLabError ############################################################ #---Apk ############################################################ class ApkImportErro
r(WrapperException): ''' Base class for import errors ''' pass class CouldNotOpenFile(ApkImportError): def __init__(self, file_path, caused_by = None): ''' Parameters ---------- file_path : str The path to the file that could not be opened. caused_by : E...
OCA/l10n-italy
l10n_it_fatturapa_out_sp/tests/__init__.py
Python
agpl-3.0
75
0
from . import fatturapa_common
from . import test_fattur
apa_xml_validation
lzkelley/zcode
zcode/inout/inout_core.py
Python
mit
30,163
0.00315
"""Functions for Input/Output (IO) Operations. Classes ------- - Keys - Provide convenience for classes used as enumerated dictionary keys. - StreamCapture - Class to capture/redirect output to stdout and stderr. Functions --------- - bytes_string - Return a humanized ...
not ent.startswith('__')] # Iterate over the list of attributes values def __iter__(se
lf): for val in self.__values__: yield val class Keys(six.with_metaclass(_Keys_Meta)): """Super class to provide convenience for classes used as enumerated dictionary keys. Uses the metaclass ``_Key_Meta`` to override the ``__iter__`` and ``__init__`` methods. The initializer simply ...
lintusj1/elfi
elfi/methods/bo/gpy_regression.py
Python
bsd-3-clause
12,384
0.001534
"""This module contains an interface for using the GPy library in ELFI.""" # TODO: make own general GPRegression and kernel classes import copy import logging import GPy import numpy as np logger = logging.getLogger(__name__) logging.getLogger("GP").setLevel(logging.WARNING) # GPy library logger class GPyRegress...
tional Names of parameter nodes. If None, sets dimension to 1. bounds : dict, optional The regi
on where to estimate the posterior for each parameter in model.parameters. `{'parameter_name':(lower, upper), ... }` If not supplied, defaults to (0, 1) bounds for all dimensions. optimizer : string, optional Optimizer for the GP hyper parameters Alter...
Yam-cn/potato
testcases/btcharts_test.py
Python
apache-2.0
4,240
0.003302
# PyAlgoTrade # # Copyright 2011-2015 Gabriel Martin Becedillas Ruiz # # 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 a...
.assertEquals(len(loaded), 646) self.asse
rtEquals(loaded[0][0], dt.as_utc(datetime.datetime(2012, 5, 29, 1, 47, 52))) self.assertEquals(loaded[0][1]["bitstampUSD"].getDateTime(), dt.as_utc(datetime.datetime(2012, 5, 29, 1, 47, 52))) self.assertEquals(loaded[0][1]["bitstampUSD"].getClose(), 5.07) self.assertEquals(loaded[0][1]["bitstamp...
liosha2007/temporary-groupdocs-python3-sdk
groupdocs/models/SignatureFormResourcesResponse.py
Python
apache-2.0
1,182
0.007614
#!/usr/bin/env python """ Copyright 2012 GroupDocs. 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...
to generated by the swagger code generator program. Do not edit the class manually.""" def __init__(self): self.swaggerTypes = { 'result': 'SignatureFormResourcesResult', 'status': 'str', 'error_message': 'str', 'composedOn': 'int' } s...
str self.composedOn = None # int
cgstudiomap/cgstudiomap
main/local_modules/res_partner_phone_missing_details/__openerp__.py
Python
agpl-3.0
1,443
0
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # This module copyright (C) cgstudiomap <cgstudiomap@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms...
s Partner phone: missing details', 'version': '0.2', 'author': 'cgstudiomap', 'maintainer': 'cgstudiomap', 'license': 'AGPL-3', 'category': 'Sales', 'summary': 'Set up for phone for missing details bot', 'depends': [ 'res_partner_missing_details', 'base_phone_validation', ...
e, }
google-research/google-research
kws_streaming/models/ds_tc_resnet_test.py
Python
apache-2.0
3,076
0.002276
# coding=utf-8 # Copyright 2022 The Google Research 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 applicab...
float32)) stream_out = inference.run_stream_inference_classification_tflite( self.params, interpreter, self.input_data, inputs) self.assertAllClose(stream_out, self.non_stream_out, atol=1e-5) if __name__ == '__main__': tf1.d
isable_eager_execution() tf.test.main()
BitcoinUnlimited/BitcoinUnlimited
qa/rpc-tests/pruning.py
Python
mit
18,143
0.005677
#!/usr/bin/env python3 # Copyright (c) 2014-2015 The Bitcoin Core developers # Copyright (c) 2015-2017 The Bitcoin Unlimited developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. import test_framework.loginit # # Test pruning ...
st_height_after_sync(self): self.nodes.append(start_node(3, self.options.tmpdir, ["-debug","-rpcservertimeout=0", "-maxreceivebuffer=20000","-blockmaxsize=999000", "-checkblocks=5", "-blockchain.maxReorgDepth=-
1"], timewait=900)) self.prunedir = self.options.tmpdir+"/node3/regtest/blocks/" connect_nodes(self.nodes[3], 1) # wait for the first blocks to arrive on node3 before mining the next # blocks. We have to make sure the first block file has a starting height # before doing any min...
drawquest/drawquest-web
website/drawquest/apps/content_metadata/migrations/0004_auto__add_field_contentmetadata_iphone_gallery_id.py
Python
bsd-3-clause
1,633
0.007961
# -*- 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 'ContentMetadata.iphone_gallery_id' db.add_column(u'content_metadata_contentmetadata', 'iphon...
t_id': ('django.db.models.fields.CharField', [], {'max_length': '40', 'db_index': 'True'}), 'gallery_id': ('django.db.models.fields.CharField', [], {'max_length': '40'}), 'homepage_featured_id': ('django.db.models.fields.CharField', [], {'max_length': '40', 'blank': 'True'}), u'id': ...
odels.fields.AutoField', [], {'primary_key': 'True'}), 'iphone_gallery_id': ('django.db.models.fields.CharField', [], {'max_length': '40', 'blank': 'True'}), 'original_id': ('django.db.models.fields.CharField', [], {'max_length': '40'}) } } complete_apps = ['content_metadata']
information-machine/information-machine-api-python
InformationMachineAPILib/Models/UserData.py
Python
mit
2,966
0.003034
# -*- coding: utf-8 -*- """ InformationMachineAPILib.Models.UserData """ from InformationMachineAPILib.APIHelper import APIHelper class UserData(object): """Implementation of the 'UserData' model. TODO: type model description here. Attributes: email (string): TODO: type description her...
Arguments in order to initialise the object. Any of the attributes in this object are able to be set through the **kwargs of the constructor. The values that can be supplied and their types are as follows:: email -- string -- Sets the attribute email...
owner_app_id -- string -- Sets the attribute owner_app_id created_at -- string -- Sets the attribute created_at """ # Set all of the parameters to their default values self.email = None self.zip = None self.user_id = None self.ow...
imminent-tuba/thesis
server/chatterbot/chatterbot/adapters/logic/weather.py
Python
mit
2,362
0.000847
from .logic import LogicAdapter from chatterbot.conversation import Statement from chatterbot.utils.pos_tagger import POSTagger import re import forecastio class WeatherLogicAdapter(LogicAdapter): """ A logic adapter that returns information regarding the weather and the forecast for a specific location....
bably a good idea). return 1, Statement("The forecast for tomorrow is: " + self.get_weather(latitude, longitude)) return 0, Statement("") def get_latitude(self, user_input): """ Returns
the latitude extracted from the input. """ for token in self.tagger.tokenize(user_input): if "latitude=" in token: return re.sub("latitude=", "", token) return "" def get_longitude(self, user_input): """ Returns the longitude extracted from the i...
abogushov/django-admin-json-editor
example/project/settings.py
Python
mit
2,826
0.001415
import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep th...
, 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_admin_json_editor', 'app', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'djan
go.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOption...
criloz/todo-app
todoapp/models.py
Python
mit
350
0.002857
from django.db import models
# Create your models here. class Task(models.Model): created_date = models.DateTimeField(auto_now_add=True) due_date = models.DateField(null=True, blank=True) description = models.CharField(max_length=100) completed = models.BooleanField(default=False) archived = models.BooleanFie
ld(default=False)
antiface/audiolazy
examples/dft_pitch.py
Python
gpl-3.0
3,525
0.013333
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of AudioLazy, the signal processing Python package. # Copyright (C) 2012-2014 Danilo de Jesus da Silva Bellini # # AudioLazy is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # ...
is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHAN
TABILITY 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, see <http://www.gnu.org/licenses/>. # # Created on Wed May 01 2013 # danilo [dot] bellini [at] gmail [dot] com """...
azaghal/ansible
test/support/integration/plugins/modules/k8s_info.py
Python
gpl-3.0
5,086
0.002359
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2018, Will Thames <@willthames> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', ...
='2.13', collection_name='ansible.builtin') def execute_module(self): self.client = self.get_api_client() self.exit_json(changed=False, **self.kubernetes_facts(self.params['kind'],
self.params['api_version'], self.params['name'], self.params['namespace'], self.params['label_selectors'], ...
meteoswiss-mdr/precipattractor
pyscripts/maple_machine-learning_predict-maps.py
Python
gpl-3.0
13,253
0.009658
#!/usr/bin/env python from __future__ import division from __future__ import print_function print('+++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++') print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++') import time_tools_attractor as ti ti.tic() import getpass usrName = getpass.getuser() import argparse import sys import os...
AnthonyBriggs/Python-101
hello_python_source_py3/chapter 06/3/item.py
Python
mit
357
0.011204
class Ite
m(object): def __init__(self, name, description, location): self.name = name self.description = description se
lf.location = location location.here.append(self) actions = ['look'] def look(self, player, noun): """ Looking at the object """ return [self.description]
Hellowlol/plexapi
tests/test_navigation.py
Python
bsd-3-clause
3,622
0.004694
# -*- coding: utf-8 -*- from utils import log, register from plexapi import CONFIG # TODO: test_navigation/test_navigate_to_movie # FAIL: (500) internal_server_error # @register() def test_navigate_to_movie(account, plex): result_library = plex.library.get(CONFIG.movie_title) result_movies = plex.library.sect...
vie navigation not consistent.' @register() def test_navigate_to_show(account, plex): result_shows = plex.library.section(CONFIG.show_section).get(CONFIG.show_title) log(2, 'Navigating to: %s' % CONFIG.show_title) log(2, 'Result Shows: %s' % result_shows)
assert result_shows, 'Show navigation not working.' # TODO: Fix test_navigation/test_navigate_around_show # FAIL: Unable to list season: Season 1 # @register() def test_navigate_around_show(account, plex): show = plex.library.section(CONFIG.show_section).get(CONFIG.show_title) seasons = show.seasons() ...
OpenBCI/OpenBCI_Python
openbci/plugins/csv_collect.py
Python
mit
1,932
0.000518
from __future__ import print_function import csv import timeit import datetime import plugin_interface as plugintypes class PluginCSVCollect(plugintypes.IPluginExtended): def __init__(self, file_name="collect.csv", delim=",", verbose=False): now = datetime.datetime.now() self.time_stamp = '%d-%d-...
) self.file_name = self.time_stamp self.start_time = timeit.default_timer() self.delim = delim self.verbose = verbose def activate(self): if len(self.args) > 0: if 'no_time' in self.args: self.file_name = self.args[0] else: ...
_name if 'verbose' in self.args: self.verbose = True self.file_name = self.file_name + '.csv' print("Will export CSV to:" + self.file_name) # Open in append mode with open(self.file_name, 'a') as f: f.write('%' + self.time_stamp + '\n') def d...
jdemel/gnuradio
gnuradio-runtime/python/gnuradio/gr/qa_hier_block2.py
Python
gpl-3.0
4,084
0.006856
# # Copyright 2014 Free Software Foundation, Inc. # # This file is part of GNU Radio # # SPDX-License-Identifier: GPL-3.0-or-later # # import time from gnuradio import gr_unittest, blocks, gr, analog from gnuradio.gr.hier_block2 import _multiple_endpoints, _optional_endpoints import pmt class test_hblk(gr.hier_bloc...
t" ) class test_hier_block2(gr_unittest.TestCase): def setUp(self): self.call_log = [] self.Block = type("Block", (), {"to_basic_block": lambda bl: bl}) def test_f(self, *args): """test doc""" self.call_log.append(args) multi = _multiple_endpoints(test_f) opt = _opti...
ertEqual(self.multi.__doc__, "test doc") self.assertEqual(self.multi.__name__, "test_f") def test_001(self): b = self.Block() self.multi(b) self.assertEqual((b,), self.call_log[0]) def test_002(self): b1, b2 = self.Block(), self.Block() self.multi(b1, b2) ...
ver228/tierpsy-tracker
tierpsy/analysis/vid_subsample/createSampleVideo.py
Python
mit
4,145
0.015923
# -*- coding: utf-8 -*- """ Created on Wed May 18 18:22:12 2016 @author: ajaver """ import os import cv2 import tables import numpy as np from tierpsy.helper.params import read_fps from tierpsy.helper.misc import TimeCounter, print_flush def getSubSampleVidName(masked_image_file): #used by AnalysisPoints.py an...
vid_writer.write(im_new) if frame_number % (500*time_factor) == 0: # calculate the progress and put it in a string print_flush(progressTime.get_str(frame_number)) vid_writer.release() print_flush(progressTime.get_str(frame_number) + ' DONE.') #%% if...
ning_101116/N2_N10_F1-3_Set1_Pos3_Ch6_12112016_002739.hdf5' #masked_image_file = '/Volumes/behavgenom_archive$/Avelino/Worm_Rig_Tests/Agar_Test/MaskedVideos/Agar_Screening_101116/unc-9_N3_F1-3_Set1_Pos3_Ch4_12112016_002739.hdf5' masked_image_file = r'C:\Users\wormrig\Documents\GitHub\Multiworm_Tracking\Tests\da...
praekeltfoundation/mc2-freebasics
freebasics/views.py
Python
bsd-2-clause
2,964
0
from django.core.urlresolvers import reverse from django.shortcuts import redirect from django.conf import settings from mc2.controllers.base.views import ControllerCreateView, ControllerEditView from mc2.views import HomepageView from mc2.organizations.models import Organization from mc2.organizations.utils import ac...
sControllerEditView(ControllerEditView): template_name = 'freebasics_controller_edit.html' permissions = ['controllers.
docker.add_dockercontroller']
SVilgelm/CloudFerry
cloudferry/condensation/utils.py
Python
apache-2.0
1,549
0
# Copyright (c) 2014 Mirantis Inc. # # Lic
ensed under the Apache License, Version 2.0 (the License); # you may not use this file except in compl
iance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an AS IS BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # imp...
deanishe/alfred-fakeum
src/libs/faker/providers/phone_number/pt_PT/__init__.py
Python
mit
1,053
0
from __future__ import unicode_literals from .. import Provider as PhoneNumberProvider class Provider(PhoneNumberProvider):
formats = ( '(351) 91# ### ###', '(351) 92# ### ###', '(351) 93# ### ###', '(351) 96# ### ###', '(351) 2## ### ###', '(351) 91#######', '(351) 92#######', '(351) 93#######', '(351) 96#######', '(351) 2########', '(351) 91# ### ###'...
', '(351) 2## ### ###', '(351) 91#######', '(351) 92#######', '(351) 93#######', '(351) 96#######', '(351) 2########', '+35191#######', '+35192#######', '+35193#######', '+35196#######', '+3512########', '91# ### ###', ...
Alexander-P/Isca
exp/python_gfdl/namelists.py
Python
gpl-3.0
6,032
0.008289
import f90nml # Adapted from the original core.nml and phys.nml files included in 2006 codebase. # where the value is the same as the default in the code base, it is commented out # and therefore not included in the namelist. # Where the value is different, the code default is shown in an inline comment basic = f90n...
y_nml'] = { 'do_entrain': False, # default: True 'do_simple': True, # default: False #'frac_inner': 0.1, #'rich_crit_pbl': 1.0 } # basic['monin_obukhov_nml'] = { # 'neutral': False, # 'rich_crit': 2.0, # 'stable_option': 1 # } basic['surface_flux_nml'] = { 'use_vir...
ectral_init_cond_nml'] = { # 'initial_temperature': 264.0 # } basic['two_stream_gray_rad_nml'] = { 'rad_scheme': 'frierson', # default: frierson 'do_seasonal': True, # default: False #'linear_tau': 0.1, #'solar_constant': 1360., #'solar_exponent': 4.0, #'ir_tau_pole...
255BITS/HyperGAN
hypergan/trainers/accumulate_gradient_trainer.py
Python
mit
3,338
0.003895
import numpy as np import torch import hyperchamber as hc import inspect from torch.autograd import Variable from hypergan.trainers.alternating_trainer import AlternatingTrainer class AccumulateGradientTrainer(AlternatingTrainer): """ G gradients accumulate over many D steps """ def _create(self): sel...
cumulated_g_grads)) self.accumulated_g_grads = None self.accumulation_steps = 0 else: gs = self.g_grads() if self.accumulated_g_grads is None: self.accumulated_g_grads = [g
.clone()/accumulate for g in gs] if self.config.type == 'variance': self.max_grads = [g.clone() for g in gs] self.min_grads = [g.clone() for g in gs] else: for i, g in enumerate(self.accumulated_g_grads): if self.con...
aronsky/home-assistant
homeassistant/components/fail2ban/__init__.py
Python
apache-2.0
30
0
"
""The fail2ban compon
ent."""
alepulver/changesets
patch_analyzer/patch_utils.py
Python
mit
562
0.007117
from subprocess import Popen, PIPE def is_class(file): return file.endswith(".class") and not file.startswith("META-INF") def modified_paths(patch): p = Popen(["jar", "-tf", patch], stdout=PIPE) output, _ = p.communicate() return filter(is_class, [file.decode() for file in output.split(b"\n")]) def ...
("$")[0] else: return path.replace(".class", "") def modified_classes(patch): classes = map(path_to_class, modified_paths(patc
h)) return list(set(classes))
trcm/stew
stew/views.py
Python
mit
9,961
0.002711
from rest_framework import generics from rest_framework.views import APIView from django.views.generic.base import TemplateView from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from rest_framework.response import Response from rest_framework.authentication import SessionA...
n as e: print e def delete(self, request, pk, format=None): print "delete" stewdent = getStewdent(pk) skill = getSkill(pk) user = stewdent.user user.delete()
stewdent.delete() skill.delete() try: dents = Stewdent.objects.all() serial = StewdentSerializer(dents, many=True) skills = Skill.objects.all() skillSerial = SkillSerializer(skills, many=True) ret = [serial.data, skillSerial.data] ...
foxmask/django-th
th_twitter/migrations/0003_fav.py
Python
bsd-3-clause
581
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migr
ations.Migration): """ this migration will be used to add 2 field to deal with things that will go wrong that will then trigger mail to admin and author of the triggers """ dependencies = [ ('th_twitter', '0002_int_to_bigint'), ] operations = [ migrations.Ad...
joerick/django-timecode
setup.py
Python
bsd-3-clause
546
0.001832
#!/usr/bin/env python # -*
- coding: utf-8 -*- from distutils.core import setup setup( name='django-timecode', version='0.1.4', description='Provides classes for working with timecodes (as used in the
video industry).', long_description=open('README.md').read(), author='Joe Rickerby', author_email='joerick@mac.com', url='http://github.com/joerick/django-timecode/', packages=[ 'timecode', 'timecode.test', ], license='LICENSE.txt', install_requires=[ "Django >= 1...
gannetson/django
django/db/models/sql/query.py
Python
bsd-3-clause
92,461
0.000908
""" Create SQL statements for QuerySets. The code in here encapsulates all of the SQL construction so that QuerySets themselves do not have to (and could be backed by things other than SQL databases). The abstraction barrier only works one way: this module has to know all about the internals of models in order to get ...
that annotations go to annotations dictionary. self.select = [] self.tables = [] # Aliases in the order they are created. self.where = where() self.where_class = where # The group_by attribute can have one of the following forms: # - None: no group by at all in the qu...
# - A list of expressions: group by (at least) those expressions. # String refs are also allowed for now. # - True: group by all select fields of the model # See compiler.get_group_by() for details. self.group_by = None self.order_by = [] self.low_mark, self.high_mar...
Urinx/SomeCodes
Python/others/practice/finding_if_prime.py
Python
gpl-2.0
995
0.074372
#!/usr/bin/python3 import math import random def finding_prime(number): num=abs(number) if num<4: return True for x in range(2,num): if num%x == 0: return False return True def finding_prime_sqrt(number): num=abs(number) if num<4: return True for x in range(2,int(math.sqrt(num))+1): if number%x == 0: ...
finding_prime_fermat(number): if number<=102: for a in range(2,number): if pow(a,number-1,number)!=1: return False return True else: for i in range(100): a=random.randint(2,number-1) if pow(a,number-1,number)!=1: return False return True def test_finding_prim
e(): number1=17 number2=20 assert(finding_prime(number1)==True) assert(finding_prime(number2)==False) assert(finding_prime_sqrt(number1)==True) assert(finding_prime_sqrt(number2)==False) assert(finding_prime_fermat(number1)==True) assert(finding_prime_fermat(number2)==False) print('Tests passed!') if __name__...
nisavid/bedframe
bedframe/auth/_spaces.py
Python
lgpl-3.0
4,671
0.000856
"""Spaces An authentication space is a directory of resources with a defined set of acceptable authentication realms, security provisions, and algorithms. """ __copyright__ = "Copyright (C) 2014 Ivan D Vasin" __docformat__ = "restructuredtext" import re as _re from spruce.collections import odict as _odict, uset a...
canners = _uset(scanners) self._supplicants = _uset(supplicants) def __repr__(self): return '{}({})'\ .format(self.__class__.__name__, ', '.join('{}={!r}'.format(property_, value) for property_, value ...
it_args(ordered=True).items())) def __str__(self): properties_strs = [] max_affordances = \ _affordances.FrozenProcessProspectiveAffordanceSet.max() for property_, value in self._init_args(ordered=True).items(): displayname = self._property_displayname(property_) ...
sam-m888/gprime
gprime/plug/menu/_note.py
Python
gpl-2.0
1,763
0.002836
# # gPrime - A web-based genealogy program # # Copyright (C) 2007-2008 Brian G. Matherly # Copyright (C) 2008 Gary Burton # # 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 ...
loor, Boston, MA 02110-1301 USA. # """ Option class representing a string. """ #------------------------------------------------------------------------- # # gramps modules # #------------------------------------------------------------------------- from . import StringOption #---------------------------------------...
------------ class NoteOption(StringOption): """ This class describes an option that allows a note from the database to be selected. """ def __init__(self, label): """ :param label: A friendly label to be applied to this option. Example: "Title Note" :type label: ...
OscarPDR/projects_morelab
manage.py
Python
gpl-3.0
259
0.003861
#!/usr/bin/env py
thon import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MO
DULE", "projects_morelab.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
praekelt/jmbo-foundry
foundry/urls.py
Python
bsd-3-clause
12,605
0.001428
from django.conf.urls import patterns, include, url from django.utils.translation import ugettext_lazy as _ from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf import settings from django.contrib.auth.decorators import login_required from django.views.ge...
arch.urls')), (r'^jmbo/', include('jmbo.urls')), (r'^comment
s/', include('django.contrib.comments.urls')), (r'^likes/', include('likes.urls')), (r'^object-tools/', include(object_tools.tools.urls)), (r'^ckeditor/', include('ckeditor.urls')), (r'^contact/', include('contact.urls')), (r'^post/', include('post.urls')), (r'^simple-autocomplete/', include('si...
traveloka/ansible
lib/ansible/modules/cloud/ovirt/ovirt_storage_domains.py
Python
gpl-3.0
17,259
0.001159
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2016 Red Hat, Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or #...
age." - "Note that these parameters are not idempotent." fcp: description: - "Dictionary with values for fibre channel storage type:" - "C(address) - Address of the fibre channel storage server." - "C(port) - Por
t of the fibre channel storage server." - "C(lun_id) - LUN id." - "Note that these parameters are not idempotent." destroy: description: - "Logical remove of the storage domain. If I(true) retains the storage domain's data for import." - "This parameter is rel...
tensorflow/datasets
tensorflow_datasets/text/openbookqa.py
Python
apache-2.0
4,817
0.002076
# coding=utf-8 # Copyright 2022 The TensorFlow Datasets 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 appl...
wal, Ashish}, journal={arXiv preprint arXiv:1809.02789}, year={2018} } """ _DESCRIPTION = """ The dataset contains 5,957 4-way multiple choice questions. Additionally, they provide 5,167 crowd-sourced common knowledge facts, and an expanded version of the train/dev/test questions where each question is associated ...
on knowledge facts.""" VERSION = tfds.core.Version('0.1.0') def _info(self): return tfds.core.DatasetInfo( builder=self, # This is the description that will appear on the datasets page. description=_DESCRIPTION, # tfds.features.FeatureConnectors features=tfds.features.F...
DWilburn/automate-your-page
html_generator.py
Python
mit
2,544
0.00511
def generate_concept_HTML(concept_title, concept_description): html_text_1 = ''' <div class="concept"> <div class="concept-title"> ''' + concept_title html_text_2 = ''' </div> <div class="concept-description"> ''' + concept_description html_text_3 = ''' </div> </di...
are used by programmers to tell a computer what to do. Python is one example of a programming language. TITLE: Python DESCRIPTION: When
you write Python code and "Run" the code, a Python Interpreter converts the written code into a set of instructions that the computer can understand and execute. TITLE: Python Expressions DESCRIPTION: In Python an "expression" is a legal Python statement. For example: print 2 + 2 is a valid expression, but print 2 +...
Topicos-3-2014/friendlyadvice
AfinidadeLikesEscolaELocalidades.py
Python
epl-1.0
12,463
0.012116
# coding: iso-8859-1 -*- """ Created on Wed Oct 22 21:49:24 2014 @author: fábioandrews """ import facebook from DadosDeAmigoEmComum import DadosDeAmigoEmComum class AfinidadeLikesEscolaELocalidades: def __init__(self,ACCESS_TOKEN_FACEBOOK): self.token_do_facebook = ACCESS_TOKEN_FACEBOOK self.meus...
DadosDeAmigoEmComum terah a nota associada e um arranjo com os likes que giovanni tem em comum com meuAmigo def acharCompatibilidadeEntreLikesDePaginas(self,meuAmigo): meuAmigo = meuAmigo.encode(encoding='utf_8',errors='ignore') pessoasDeMesmoInteresseDeMeuAmigoEQuaisInteresses = dict() for ...
uais likesEmComumEntreOsDois = [] for umLikeMeuAmigo in self.amigosECoisasQueGostam[meuAmigo]: for umLikeOutroAmigo in self.amigosECoisasQueGostam[outroAmigo]: if(umLikeMeuAmigo == umLikeOutroAmigo): #achamos um like...
nonemaw/pynet
pyth_ans_ecourse/class9/exercise6/mytest/world.py
Python
gpl-2.0
1,292
0.00387
''' Python class on writing reusable code ''' def func1(): '''Simple test function''' print "Hello world" class MyClass(object): '''Simple test class''' def __init__(self, var1, var2, var3): self.var1 = var1 self.var2 = var2 self.var3 = var3 def hello(self): '''Simp...
le test method''' print "Something else: {} {} {}".format(self.var1, self.var2, self.var3) if __name__ == "__main__": print "\nMain program - world" print "\nTesting MyClass:" my_obj = MyClass('SF', 'NYC', 'LA') print m
y_obj.var1, my_obj.var2, my_obj.var3 my_obj.hello() my_obj.not_hello() print "\nTesting MyChildClass:" new_obj = MyChildClass('X', 'Y', 'Z') new_obj.hello() new_obj.not_hello() print
justyns/home-assistant
tests/components/automation/test_mqtt.py
Python
mit
2,684
0
"""The tests for the MQTT automation.""" import unittest import homeassistant.components.automation as automation from tests.common import ( mock_mqtt_component, fire_mqtt_message, get_test_home_assistant) class TestAutomationMQTT(unittest.TestCase): """Test the event automation.""" def setUp(self): # ...
'payload': 'hello' }, 'action': { 'service': 'test.automation' } } })) fire_mqtt_message(self.hass, 'test-topic', 'hello') self.hass.pool.block_till_done() self.assertEqual(1, len(self.calls)) ...
ge is not fired on topic but no payload.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { 'platform': 'mqtt', 'topic': 'test-topic', 'payload': 'hello' }, 'ac...
youdar/work
work/NCS/ncs_paper/submit_model_vs_data_to_queue.py
Python
mit
4,061
0.006156
from __future__ import division import collect_ncs_files from libtbx.command_line import easy_qsub from glob import glob import sys import os class run_queue_tests(object): def __init__(self): """ Testing using: /work/NCS/ncs_paper/collect_ncs_files.py """ # set working environment paths = "/ne...
'2vf1', '2wws', '2xxa', '2w4b', '3gfq', '3gdu', '4fi3', '2frp', '3cz3', '3ze1', '3zjy', '4qvz', '2ft1', '3v4v'
, '2vq0', '4nko', '4gi2', '4hg4', '3uaj', '3zfg'] def get_commands(self): """ Build the command list get_commands process the command we want to run, with the options we want to use, on all the files we want the command to run on It produces a list of commands: list of strings, containing t...
Bathlamos/Project-Euler-Solutions
solutions/p425.py
Python
mit
1,249
0.030424
# # Solution to Project Euler problem 425 # Philippe Legault # # https://github.com/Bathlamos/Project-Euler-Solutions from lib import primes_up_to import heapq # Use Dijkstra's algorithm to identify # the path wit
h smallest maximum number, # based on the undirected graph of connected # primes def compute(): limit = 10 ** 7 primes = primes_up_to(limit + 1) neighbors = [set() for n in range(0, len(primes))] # Create an undirected graph which identifies all connected numbers similar = {} for p in range(0, len(primes)): pr...
t() for r in similar[t]: neighbors[r].add(p) neighbors[p].update(similar[t]) similar[t].add(p) # Use Dijkstra's algorithm to find 2's relative heap = [] # (cost, prime index) heapq.heappush(heap, (2, 0)) visited = set() s = 0 while heap: cost, p = heapq.heappop(heap) if p in visited: continu...
sparkslabs/kamaelia
Sketches/MPS/BugReports/FixTests/Kamaelia/Kamaelia/Apps/Europython09/BB/LineOrientedInputBuffer.py
Python
apache-2.0
2,466
0.005272
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License, Ver...
if self.dataReady("control"): raise GotShutdownMessage() # Send them the line, then rinse and repeat. self.send(line, "outbox")
yield 1 gotline = False line = "" except GotShutdownMessage: self.send(self.recv("control"), "signal") return self.send(producerFinished(), "signal")
VitalPet/hr
hr_employee_reference/models/__init__.py
Python
agpl-3.0
152
0
# -*- coding: utf-8 -*- # © 2
016 OpenSynergy In
donesia # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from . import hr_employee
internap/netman
netman/api/objects/vlan.py
Python
apache-2.0
2,413
0.000829
# Copyright 2015 Internap. # # 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, so...
access_groups={ "in": vlan.access_groups[IN], "out": vlan.access_groups[OUT] }, dhcp_relay_servers=[str(server) for server in vlan.dhcp_relay_servers], arp_routing=vlan.arp_routing, icmp_redirects=vlan.icmp_redirects, unicast_rpf_mode=vlan.unicast_rpf...
to_core(serialized): access_groups = serialized.pop('access_groups') ips = serialized.pop('ips') vrrp_groups = serialized.pop('vrrp_groups') dhcp_relay_servers = serialized.pop('dhcp_relay_servers') varp_ips = serialized.pop('varp_ips') return Vlan( access_group_in=access_groups['in'], ...
NPRA/EmissionCalculatorLib
emission/__init__.py
Python
bsd-2-clause
1,488
0.014113
"""Emission python module This module is for everyone who wants to build tools / systems for calculating vehicle emissions for various types of vehicles (Trucks, Buses, Cars, Vans, scooters, ..). The calculation and factors is provided by the EU EEA guidebook: http://www.eea.europa.eu/publications/emep-eea-guidebook-...
n. The module will also calculate the emission for all the pollutant types you have defined. You can then sort the various routes depending of which critieria that's most important (duration, pollution (NOx, CO, ..)). Fuel consumption is directly related to the emission - therefore the lower emission the lower f...
te import Extrapolate from .Interpolate import Interpolate from .Pollutants import Pollutants from .EmissionJSONReader import EmissionsJsonParser from .planner import Planner from .planner import PollutantTypes from .__version__ import __version__ __author__ = "NPRA - Norwegian Public Roads Administration" from .mo...
TurBoss/HostilPlanet
data/themes/itheme/build.py
Python
gpl-2.0
4,710
0.002335
import pygame from pygame.locals import * import glob # specify the image names
and how many slices they have # None for a icon # ([1...3],[1...3]) for the number of slices an image is cut into. IM
AGES = { 'box.png': (2, 2), 'check.png': 'color.png':None, 'desktop.png': None, 'dot.png': (2, 2), 'down.png': None, 'radio.png': None, 'right.png': None, 'up.png': None, 'x.png': None, } HUE = 190 # default hue, used for hue rotations # keywords set alterations of the source data ...
febert/DeepRL
q_learning_sarsa/dqn_learning.py
Python
gpl-3.0
22,540
0.00661
from __future__ import print_function from __future__ import division import numpy as np np.set_printoptions(threshold=np.inf) import matplotlib.pyplot as plt from matplotlib import cm # from mpl_toolkits.mplot3d import axes3d from matplotlib.colors import LogNorm # import time import math # import cPickle import gym...
size_hidden=nn_size_hidden, batch_size=nn_batch_size, learning_rate=nn_learning_rate, is_a_prime_external=self.is_a_prime_external, replay_memory_size=replay_memory_size,
descent_method=descent_method, keep_prob_val=dropout_keep_prob, ema_decay_rate=ema_decay_rate, normalization_mean=normalization_mean, normalization_var=normalization_var, ...
tkerola/chainer
chainer/links/normalization/decorrelated_batch_normalization.py
Python
mit
5,209
0
import numpy from chainer import configuration from chainer import functions from chainer import link from chainer.utils import argument class DecorrelatedBatchNormalization(link.Link): """Decorrelated batch normaliza
tion layer. This link wraps the :func:`~chainer.functions.decorrelated_batch_normaliz
ation` and :func:`~chainer.functions.fixed_decorrelated_batch_normalization` functions. It works on outputs of linear or convolution functions. It runs in three modes: training mode, fine-tuning mode, and testing mode. In training mode, it normalizes the input by *batch statistics*. It also mainta...
fluxw42/youtube-dl
test/test_compat.py
Python
unlicense
5,492
0.004066
#!/usr/bin/env python # coding: utf-8 from __future__ import unicode_literals # Allow direct execution import os import sys import unittest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from youtube_dl.compat import ( compat_getenv, compat_setenv, compat_etree_fromstrin...
de({b'abc': 'def'})
, 'abc=def') self.assertEqual(compat_urllib_parse_urlencode({b'abc': b'def'}), 'abc=def') self.assertEqual(compat_urllib_parse_urlencode([('abc', 'def')]), 'abc=def') self.assertEqual(compat_urllib_parse_urlencode([('abc', b'def')]), 'abc=def') self.assertEqual(compat_urllib_parse_urlenc...
yuvipanda/edit-stats
dmz/generate_dbnames.py
Python
mit
821
0.004872
"""Generate JSON files with dbnames per project Just generates for wikipedias for now""" from urllib2 import urlopen import unicodecsv as csv import
json def get_dbnames(wiki_class): """Return dbnames for all wikis in a particular wiki_class, such as 'wikipedias'""" URL = "https://wikistats.wmflabs.org/api.php?action=dump&table=%s&format=csv&s=good" % wiki_class data = csv.reader(urlopen(URL)) dbnames = [] is_first = True for row in dat...
f is_first: is_first = False continue # skip headers! # dbnames is just langcode with - replaced by _ and a 'wiki' suffix dbnames.append(u'%swiki' % (row[2].replace('-', '_'), )) return dbnames data = { 'wikipedias': get_dbnames("wikipedias") } json.dump(data, open('db...
ledtvavs/repository.ledtv
script.tvguide.Vader/stop.py
Python
gpl-3.0
386
0.010363
import sys import xbmc,xbmcaddon import sqlite3 ADDON = xbmcaddon.Addon(i
d='script.tvguide.Vader') channel = sys.argv[1] start = sys.argv[2] if ADDON.getSetting('playing.channel') != channel: quit() elif ADDON.getSetting('playing.start') != start: quit() ADDON.setSetting('playing.channel','') ADDON.setSetting('playing.start','') xbmc.executebuiltin('PlayerCont
rol(Stop)')
miptliot/edx-platform
lms/djangoapps/instructor_task/tasks_helper/module_state.py
Python
agpl-3.0
15,346
0.00417
""" Instructor Tasks related to module state. """ import json import logging from time import time from django.contrib.auth.models import User from opaque_keys.edx.keys import UsageKey from xblock.runtime import KvsFieldData import dogstats_wrapper as dog_stats_api from capa.responsetypes import LoncapaProblemError, ...
tion modules_to_update = StudentModule.objects.filter(course_id=course_id, module_state_key__in=usage_keys) # give the option of updating an individual student. If not specified, # then updates all students who have responded to a problem so far student = None if student_identifier is not None: ...
student_identifier: student = User.objects.get(email=student_identifier) elif student_identifier is not None: student = User.objects.get(username=student_identifier) if student is not None: modules_to_update = modules_to_update.filter(student_id=student.id) if filter_fc...
aborrero/pkg-rpmlint
ConfigCheck.py
Python
gpl-2.0
1,798
0.003893
# -*- coding: utf-8 -*- ############################################################################# # File : ConfigCheck.py # Package : rpmlint # Author : Frederic Lepied # Created on : Sun Oct 3 21:48:20 1999 # Purpose : ################################################################...
ked-as-conffile', """A file not in /etc or /var is marked as being a configuration file. Please put your conf files in /etc or /var.""", 'conffile-without-norepla
ce-flag', """A configuration file is stored in your package without the noreplace flag. A way to resolve this is to put the following in your SPEC file: %config(noreplace) /etc/your_config_file_here """, ) # ConfigCheck.py ends here # ex: ts=4 sw=4 et
chienlieu2017/it_management
odoo/addons/hw_scanner/controllers/main.py
Python
gpl-3.0
8,110
0.018989
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import time from os import listdir from os.path import join from Queue import Queue, Empty from select import select from threading import Thread, Lock from odoo import http import odoo.addons.hw_proxy.c...
if message != None and message != self.status['messages'][-1]: self.status['messages'].append(message) else: self.statu
s['status'] = status if message: self.status['messages'] = [message] else: self.status['messages'] = [] if status == 'error' and message: _logger.error('Barcode Scanner Error: '+message) elif status == 'disconnected' and message: ...
robwebset/script.ebooks
resources/lib/mobi/utils.py
Python
gpl-2.0
340
0.014706
#!/usr/bin/env python # encoding: utf-8 """ utils.py Created by Elliot Kroo on 2009-12-25. Copyright (c) 2009 Elliot Kroo. All rights reserved. """ import sys import os def toDict(tuples): result
sDict = {} for field, value
in tuples: if len(field) > 0 and field[0] != "-": resultsDict[field] = value return resultsDict;
JamesNickerson/py-junos-eznc
tests/unit/test_decorators.py
Python
apache-2.0
1,937
0.001549
__author__ = "Rick Sherman" import unittest2 as unittest from nose.plugins.attrib import attr from jnpr.junos.device import Device from jnpr.junos.decorators import timeoutDecorator from mock import patch, PropertyMock, call from ncclient.manager import Manager, make_device_handler from ncclient.transport import SS...
dev, dev_timeout=10) calls = [call(), call(10), call(30)] # verify timeout was set/reset mock_timeout.assert_has_calls(calls) def _mock_manager(self, *args, **kwargs): if kwargs: device_params = kwargs['device_params']
device_handler = make_device_handler(device_params) session = SSHSession(device_handler) return Manager(session, device_handler)