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
fangohr/oommf-python
dev/umm-exploration-inheritance.py
Python
bsd-2-clause
1,614
0.004337
class AbstractMicromagneticModell: def __init__(self, name, Ms): self.name = name self.Ms = Ms self.field = None self.energies = [] def __str__(self): return "AbstractMicromagneticModell(name={})".format(self.name) def relax(self): self._relax() #rai...
icromagneticModell): def __init__(self, name, Ms): AbstractMicromagneticModell.__init__(self, name, Ms) def __str__(self): return "OOMMFC(name={}, Ms={})".format(self.name, self.Ms) def _relax(self): print("Calling OOMMF to run relax() with H={}".format(self.field)) class FIDIMAG...
t__(self, name, Ms) def __str__(self): return "FIDIMAG(name={}, Ms={})".format(self.name, self.Ms) def _relax(self): print("Calling FIDIMAG to run relax() with H={}".format(self.field)) #a = AbstractMicromagneticModell('simulation-name', 10) #print(a) #a.hysteresis([10, 20]) o = OOMMFC(na...
alvaroribas/modeling_TDs
Herschel_mapmaking/scanamorphos/PACS/general_script_L1_PACS.py
Python
mit
2,499
0.012405
### This script fetches level-1 PACS imaging data, using a list generated by the ### archive (in the CSV format), attaches sky coordinates and masks to them ### (by calling the convertL1ToScanam task) and save them to disk in the correct ### format for later use by Scanamorphos. ### See important instructions below. ...
ctories contained in the dir_out variables (l. 57) ## before running this script. ####################################################### ## observations: table_obs = asciiTableReader(file=dir_root+'results_fast.csv', tableType='CSV', skipRows=1) list_obsids = table_obs[0].data list_names = table_obs[1].data for i...
ath+source+"_processed_obsids" # create directory if it does not exist if not(os.path.exists(dir_out)): os.system('mkdir '+dir_out) ## print "" print "Downloading obsid " + `num_obsid` obs = getObservation(num_obsid, useHsa=True, instrument="PACS", verbose=True) ### frames = obs.lev...
andela-ooshodi/django-photo-application
djangophotoapp/photoapp/models.py
Python
gpl-2.0
1,310
0
from time import time from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_delete from django.dispatch import receiver import os def upload_path(instance, filename): return 'uploads/user_{0}/{1}_{2}'.format( instance.owner.id
, str(time()).replace('.', '_'), filename ) class UserProfile(models.Model): user = models.OneToOneField(User) photo = models.TextField() class Images(models.Model): owner = models.ForeignKey(User) image = models.ImageField(upload_to=upload_path) image_file_name = models.Char...
t_delete, sender=Images) def delete_from_file_system(sender, instance, **kwargs): image_path = instance.image.path # split the image part filepath, ext = os.path.splitext(image_path) # create the filtered image path new_filepath = filepath + "filtered" + ext # delete from file directory i...
senttech/Cura
plugins/CuraProfileReader/__init__.py
Python
agpl-3.0
807
0.006196
# Copyright (c) 2015 Ultimaker B.V. # Cura is released under the ter
ms of the AGPLv3 or higher. from . import CuraProfileReader from UM.i18n import i18nCatalog catalog = i18nCatalog("cura") def getMetaData(): return { "plugin": { "name": catalog.i18nc("@label", "Cura Profile Reader"), "author": "Ultima
ker", "version": "1.0", "description": catalog.i18nc("@info:whatsthis", "Provides support for importing Cura profiles."), "api": 3 }, "profile_reader": [ { "extension": "curaprofile", "description": catalog.i18nc("@item:inli...
Yelp/paasta
paasta_tools/paastaapi/model/kubernetes_container.py
Python
apache-2.0
6,917
0.000578
# coding: utf-8 """ Paasta API No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 impor...
} @cached_property def discriminator(): return None attribute_map = { 'name': 'name', # noqa: E501 'tail_l
ines': 'tail_lines', # noqa: E501 } _composed_schemas = {} required_properties = set([ '_data_store', '_check_type', '_spec_property_naming', '_path_to_item', '_configuration', '_visited_composed_classes', ]) @convert_js_args_to_python_args def...
andim/scipy
scipy/linalg/lapack.py
Python
bsd-3-clause
6,884
0.000291
""" Low-level LAPACK functions (:mod:`scipy.linalg.lapack`) ======================================================= This module contains low-level functions from the LAPACK library. .. versionadded:: 0.12.0 .. warning:: These functions do little to no error checking. It is possible to cause crashes by mis-usi...
division, print_function, absolute_import __all__ = ['get_lapack_funcs'] import numpy as _np from .blas import _get_funcs # Backward compatibility: from .blas import find_best_blas_type as find_best_lapack_type from scipy.linalg import _flapack try: from scipy.linalg import _clapack except ImportError: _cl...
dImport clapack = _DeprecatedImport("scipy.linalg.blas.clapack", "scipy.linalg.lapack") flapack = _DeprecatedImport("scipy.linalg.blas.flapack", "scipy.linalg.lapack") # Expose all functions (only flapack --- clapack is an implementation detail) empty_module = None from scipy.linalg._flapack import * del empty_module ...
plotly/plotly.py
packages/python/plotly/plotly/validators/icicle/outsidetextfont/_color.py
Python
mit
469
0.002132
import _plotly_utils.basevalidators class ColorValidator(_plotly_utils.basevalidators.ColorValidator): def __init__( self, plotly_name="color", parent_name="icicle.outsidetextfont", **kwargs ): super(ColorValidator, self).__init__( plotly_
name=plotly_name, parent_name=parent_name, array_ok=kwargs.pop("array_ok", True), edi
t_type=kwargs.pop("edit_type", "plot"), **kwargs )
manuelgomezsuarez/practicasAII
practicasAII/Practica1/practica1.py
Python
gpl-3.0
2,831
0.020134
# encoding: latin1 import urllib2, re from Tkinter import * import tkMessageBox import sqlite3 def extraer_datos(): f = urllib2.urlopen("http://www.us.es/rss/feed/portada") s = f.read() l = re.findall(r'<item>\s*<title>(.*)</title>\s*<link>(.*)</link>\s*<description>.*</description>\s*<author>.*...
P TABLE IF EXISTS NOTICIAS") conn.execute('''CREATE TABLE NOTICIAS (ID INTEGER PRIMARY KEY AUTOINCREMENT, TITULO TEXT
NOT NULL, LINK TEXT NOT NULL, FECHA TEXT NOT NULL);''') l = extraer_datos() for i in l: conn.execute("""INSERT INTO NOTICIAS (TITULO, LINK, FECHA) VALUES (?,?,?)""",(i[0],i[1],i[3])) conn.commit() cursor = conn.execute("SELECT COUNT(*) FROM NOTICIAS") ...
Kaumer/html-minifier
test/test.py
Python
mit
999
0
import unittest from pathlib import Path from html_minifier import Minifier from html_minifier import DjangoMinifier class TestMinify(unittest.TestCase): ext_min = "_min" file_name
= "base" _file = "{0}.html" location = "html" def setUp(self): path = Path(__file__).parent file_name = "" names = (self.file_name, self.ext_min) html_vars = ["html", "html_min"] for i, name in enumerate(names): file_name =
''.join([file_name, name]) _file = self._file.format(file_name) f = path.joinpath(self.location, _file).open() setattr(self, html_vars[i], f.read()) f.close() def test_minifier(self): mini = Minifier(self.html) self.assertEqual(mini.minify(), self.ht...
victordomene/ram-paxos
workloads/workload_B.py
Python
mit
4,156
0.009625
""" This workload presents a simple interface that can be reused in other workloads. It summary, it runs several subprocesses using the multiprocessing package, makes the connections between them, and then starts working. This particular workload spawns NETWORK_SIZE machines, two of which are proposer. We can run wit...
vm(name, use_disk=True) # fetch the host/port information from the network for me host, port = network[name] # add other machines for friend_name, (friend_ho
st, friend_port) in network.iteritems(): # !# should we send it to ourselves? if friend_name == name: continue vm.add_destination(friend_name, friend_host, friend_port) # start serving vm.serve(host, port) return vm def proposer_entrypoint(name, network): """...
oihane/odoomrp-utils
crm_claim_extra_ref/model/crm_claim.py
Python
agpl-3.0
2,116
0
# -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models, fields, api class CrmClaim(mo...
Model 2', compute='_generate_ref_model_name2', store=True) ref_name2 = fields.Char( string='Ref. Name 2', compute='_generate_ref_name2', store=True) ref3 = fields.Reference(string='Reference 3', selection=_links_get) ref_model_name3 = fields.Char( string='Ref. Model 3', compute='_generate_re...
e3', store=True) ref_name3 = fields.Char( string='Ref. Name 3', compute='_generate_ref_name3', store=True)
ncrocfer/weevely3
testsuite/test_file_cd.py
Python
gpl-3.0
2,398
0.007506
from testfixtures import log_capture from testsuite.base_fs import BaseFilesystem from testsuite import config from core.sessions import SessionURL from core import modules import utils from core import messages import subprocess import os class FileCd(BaseFilesystem): def setUp(self): self.session = Sess...
self.run_argv([ new ]) self.assertEquals(self.folders[0], self.session['file_cd']['results']['cwd']) self.assertEqual( messages.module_file_cd.failed_directory_change_to_s % new, log_captured.records[-1].msg ) # new [1]/.././[1]/./ new = self.folders...
['cwd']) # new bogus new = 'bogus' self.run_argv([ new ]) self.assertEquals(self.folders[1], self.session['file_cd']['results']['cwd']) self.assertEqual( messages.module_file_cd.failed_directory_change_to_s % new, log_captured.records[-1].msg ) ...
d0ugal/readthedocs.org
readthedocs/builds/migrations/0015_add_privacy.py
Python
mit
11,730
0.007758
# -*- 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 'Version.privacy_level' db.add_column('builds_version', 'privacy_level', ...
jango.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', ...
{'default': 'datetime.datetime(2012, 10, 13, 23, 55, 6, 898075)'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fiel...
sebrandon1/neutron
neutron/tests/unit/ipam/test_requests.py
Python
apache-2.0
16,389
0.000732
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
allocation_pools=1) def test_subnet_request_bad_range(self): self.assertRaises(TypeError, ipam_req.SubnetRequest, self.tenant_id, self.subnet_id, allocation
_pools=['1.2.3.4']) def test_subnet_request_different_versions(self): pools = [netaddr.IPRange('0.0.0.1', '0.0.0.2'), netaddr.IPRange('::1', '::2')] self.assertRaises(ValueError, ipam_req.SubnetRequest, self.tenant_id, ...
zjj/trac_hack
contrib/checkwiki.py
Python
bsd-3-clause
3,475
0.003453
#!/usr/bin/python # # Check/update default wiki pages from the Trac project website. # # Note: This is a development tool used in Trac packaging/QA, not something # particularly useful for end-users. # # Author: Daniel Lundin <daniel@edgewall.com> import httplib import re import sys import getopt # Pages to inc...
ustomization", "TracLinks", "TracLogging", "TracModPython", "TracModWSGI", "TracNavigation", "TracNotification", "TracPermissions", "TracPlugins", "TracQuery", "TracReports", "TracRepositoryAdmin", "TracRevisionLog", "TracRoadmap", "TracRss", "TracSearch", "TracStandalone", "TracSupport",
"TracSyntaxColoring", "TracTickets", "TracTicketsCustomFields", "TracTimeline", "TracUnicode", "TracUpgrade", "TracWiki", "TracWorkflow", "WikiDeletePage", "WikiFormatting", "WikiHtml", "WikiMacros", "WikiNewPage", "WikiPageNames", "WikiProcessors", "WikiRestructuredText", "WikiRestructuredTextLinks" ]...
google/grumpy
third_party/pypy/_struct.py
Python
apache-2.0
12,831
0.012937
# # This module is a pure Python version of pypy.module.struct. # It is only imported if the vastly faster pypy.module.struct is not # compiled in. For now we keep this version for reference and # because pypy.module.struct is not ootype-backend-friendly yet. # """Functions to convert between Python values and C stru...
EXP MAX_EXP = 128 # FLT_MAX_EXP MANT_DIG = 24 # FLT_MANT_DIG BITS = 32 else: raise ValueError("invalid size value") sign = math.copysign(1.0, x) < 0.0 if math.isinf(x): mant = 0 exp = MAX_EXP - MIN_EXP + 2 elif
math.isnan(x): mant = 1 << (MANT_DIG - 2) # other values possible exp = MAX_EXP - MIN_EXP + 2 elif x == 0.0: mant = 0 exp = 0 else: m, e = math.frexp(abs(x)) # abs(x) == m * 2**e exp = e - (MIN_EXP - 1) if exp > 0: # Normal case. mant = round_to_nearest(m * (1 << MANT_DIG))...
dl1ksv/gnuradio
gnuradio-runtime/examples/network/audio_sink.py
Python
gpl-3.0
1,818
0.00055
#!/usr/bin/env python # # Copyright 2006,2007,2010 Free Software Foundation, Inc. # # This file is part of GNU Radio # # SPDX-License-Identifier: GPL-3.0-or-later # # from gnuradio import gr from gnuradio import blocks from argparse import ArgumentParser import sys try: from gnuradio import audio except ImportErr...
def __init__(self, host, port, pkt_size, sample_rate, eof): gr.top_block.__init__(self, "audio_sink") src = blocks.udp_source(gr.sizeof_float, host, port, pkt_size, eof=eof) dst = audio.sink(sample_rate) self.connect(src, dst) if __name__ == '__main__': parser = ArgumentParser()...
ort", type=int, default=65500, help="port value to listen to for connection") parser.add_argument("--packet-size", type=int, default=1472, help="packet size.") parser.add_argument("-r", "--sample-rate", type=int, default=32000, help="audio ...
privacyidea/privacyidea
privacyidea/lib/error.py
Python
agpl-3.0
5,601
0.00125
# -*- coding: utf-8 -*- # # privacyIDEA is a fork of LinOTP # May 08, 2014 Cornelius Kölbel # License: AGPLv3 # contact: http://www.privacyidea.org # # Copyright (C) 2010 - 2014 LSE Leading Security Experts GmbH # License: AGPLv3 # contact: http://www.linotp.org # http://www.lsexperts.de # ...
tion="token admin error!", id=ERROR.TOKENADMIN): privacyIDEAError.__i
nit__(self, description=description, id=id) class ConfigAdminError(privacyIDEAError): def __init__(self, description="config admin error!", id=ERROR.CONFIGADMIN): privacyIDEAError.__init__(self, description=description, id=id) class CAError(privacyIDEAError): def __init__(self, description="CA error...
knuu/nlp100
chap03/25.py
Python
mit
328
0.00625
import re with open('England.txt')
as f: data = f.read() pat = re.compile(r"\{\{基礎情報 (.*?)\n\}\}", re.S) baseInfo = '\n'.join(pat.findall(data)) print(baseInfo) pat = re.compile(r"\|(.*?) = (.*)") Info = pat.findall(baseInfo) dic = {key: cont for key, cont in Info} # print(dic)
tpazderka/pysaml2
src/saml2/mdbcache.py
Python
bsd-2-clause
6,873
0.000436
#!/usr/bin/env python import logging __author__ = 'rolandh' from pymongo import Connection #import cjson import time from datetime import datetime from saml2 import time_util from saml2.cache import ToOld from saml2.time_util import TIME_FORMAT logger = logging.getLogger(__name__) class Cache(object): def __i...
turn [] def receivers(self, subject_id): """ Another name for entities() just to make it more logic in the IdP scenario """ return self.entities(subject_id) def active(self, subject_id, entity_id): """ Returns the status of assertions from a specific entity_id. :pa...
ng on if the assertion is still valid or not. """ item = self._cache.find_one({"subject_id": subject_id, "entity_id": entity_id}) try: return time_util.not_on_or_after(item["timestamp"]) except ToOld: return False ...
youtube/cobalt
third_party/v8/tools/clusterfuzz/js_fuzzer/tools/fuzz_one.py
Python
bsd-3-clause
1,328
0.000753
#!/usr/bin/env python # Copyright 2020 the V8 project aut
hors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Helper script to execute a single-processed fuzzing session. Creates fuzz tests in workdir/output/dir-<dir number>/fuzz-XXX.js. Expects the <dir number> as single parameter. """ impor...
port time BASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) APP_DIR = os.path.join(BASE_PATH, 'workdir', 'app_dir') FUZZ_EXE = os.path.join(BASE_PATH, 'workdir', 'fuzzer', 'ochang_js_fuzzer') INPUT_DIR = os.path.join(BASE_PATH, 'workdir', 'input') TEST_CASES = os.path.join(BASE_PATH, 'workdir', '...
jalavik/inspire-next
inspire/modules/forms/fields/__init__.py
Python
gpl-2.0
999
0
# -*- coding: utf-8 -*- # # This file is part of INSPIRE. # Copyright (C) 2014, 2015 CERN. # # INSPIRE is free software: you can redistribu
te 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. # # INSPIRE is distributed in the hope that it will be use
ful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with INSPIRE. If not, see <http://www.gnu.org/licenses/>. # #...
gen1us2k/django-example
config/wsgi.py
Python
mit
1,453
0
""" WSGI config for django-example project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICA...
ocess. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.production" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production") # This application object is used by any WSGI
server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
AsherBond/MondocosmOS
grass_trunk/lib/python/ctypes/ctypesgencore/printer/printer.py
Python
agpl-3.0
11,921
0.011576
#!/usr/bin/env python import os, sys, time from ctypesgencore.descriptions import * from ctypesgencore.ctypedescs import * from ctypesgencore.messages import * import ctypesgencore.libraryloader # So we can get the path to it import test # So we can find the path to local files in the printer package def path_to_loc...
print >>self.file,"# No %s" % name print >>self.file def srcinfo(self,src): if src==None: print >>self.file else: filename,lineno = src if filename in ("<built-in>","<command line>"): print >>self.
file, "# %s" % filename else: if self.options.strip_build_path and \ filename.startswith(self.options.strip_build_path): filename = filename[len(self.options.strip_build_path):] print >>self.file, "# %s: %s" % (filename, lineno) ...
its-lab/MoniTutor
models/0tutordb.py
Python
gpl-3.0
7,838
0.004721
from gluon.contrib.appconfig import AppConfig import uuid app_conf = AppConfig(reload=True) DATABASE_NAME = app_conf.take("monitutor_env.database_name") DATABASE_USER = app_conf.take("monitutor_env.database_user") DATABASE_PASSWORD = app_conf.take("monitutor_env.database_password") DATABASE_HOST = app_conf.take("monitu...
min") tutordb.define_table('monitutor_scenarios', Field('scenario_id', type='id'), Field('uuid', length=64, default=lambda:str(uuid.uuid4())), Field('name', typ
e='string', requires=IS_ALPHANUMERIC()), Field('display_name', type='string', required=True), Field('description', type='text', required=True), Field('goal', type='text'), Field('hidden', type='boolean', default=True), Field('initiated', type='boolean', default=True)) tutordb.define_table('monituto...
taojy123/GoCMS
gocms/wsgi.py
Python
mit
1,300
0.000769
""" WSGI config for gocms project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` s...
er configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorld...
ication(application)
ContributeToScience/participant-booking-app
booking/message/migrations/0001_initial.py
Python
gpl-2.0
7,560
0.008466
# -*- 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 model 'Message' db.create_table(u'message_message', ( (u'id', self.gf('django.db.models...
'recipient': ('django.db.models.fields.related.Fo
reignKey', [], {'blank': 'True', 'related_name': "'received_messages'", 'null': 'True', 'to': u"orm['auth.User']"}), 'recipient_deleted_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'send_email': ('django.db.models.fields.BooleanField', [], {'default': 'F...
gabrielelanaro/solfege
solfege/const.py
Python
gpl-3.0
1,656
0.012681
# GNU Solfege - free ear training software # C
opyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 Tom Cato Amundsen # # 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 ...
f # 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, see <http://www.gnu.org/licenses/>. # Moved RHYTHMS here because is should be available from a modul...
nwjs/chromium.src
testing/libfuzzer/zip_sources.py
Python
bsd-3-clause
1,995
0.014035
#!/usr/bin/python2 # # Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Archive all source files that are references in binary debug info. Invoked by libfuzzer buildbots. Executes dwarfdump to parse debug...
it for line in out.splitlines(): if looking_for_unit and compile_unit_re.match(line): looking_for_unit = False elif not looking_for_unit: match = at_name_re.match(line) if match: compile_units.add(match.group(1)) looking_for_unit = True # Zip sources. with zipfile.ZipFil...
pile_unit)) print(src_file) z.write(src_file, os.path.relpath(src_file, args.srcdir)) if __name__ == '__main__': main()
richard-fisher/repository
system/base/fontconfig/actions.py
Python
gpl-2.0
410
0.014634
#!/usr/bin/python from pisi.actionsapi import shelltools, get, autotools, pisitools def
setup(): autotools.configure ("--prefix=/usr\ --disable-static\ --disable-docs\ --docdir=/usr/share/doc/fontconfig-2.10.2") def build(
): autotools.make () def install(): autotools.rawInstall ("DESTDIR=%s" % get.installDIR())
Mezgrman/mezgrmanDE
displays/urls.py
Python
agpl-3.0
511
0.027397
from django.conf.urls import patterns, include, url urlpatterns = patterns('displays.views', url(r'^$', 'index', name = 'index'), url(r'^(?P<id>\d+)/$', 'display', name = 'display'),
url(r'^(?P<id>\d+)/settings\.json$', 'ajax_settings', name = 'ajax-settings'), url(r'^(?P<id>\d+)/bitmap\.json$', 'aja
x_bitmap', name = 'ajax-bitmap'), url(r'^(?P<id>\d+)/states\.json$', 'ajax_states', name = 'ajax-states'), url(r'^(?P<id>\d+)/message\.json$', 'ajax_message', name = 'ajax-message'), )
creativcoder/AlgorithmicProblems
codeforces/long_words.py
Python
mit
227
0.057269
#http://codeforces.com/problemset/problem/71/A T = int(raw_input()) while(not T == 0): wor
d = str(raw_input()) if len(word)>10: print word[0]+str(len(word[1:len(word)-1]))+word[len(word)-1] els
e: print word T-=1
bevenky/dev-cms
dev_cms/loader.py
Python
mit
890
0.001124
# Template loader to retrieve templates from the database from django.template import TemplateDoesNotExist from django.template.loader import BaseLoader from pages.models import Page from appearance.mode
ls import Template class DBTemplateLoader(BaseLoader): is_usable = True def load_template_source(self, template_name, template_dirs=None): try: if template_name.startswith('preview/'): page = Page.objects.get(preview_url__exact=template_name) else: ...
l = Template.objects.get(path__exact=template_name) return tmpl.content, str(tmpl) except Template.DoesNotExist: raise TemplateDoesNotExist, template_name
wxs/subjective-functions
synthesize.py
Python
mit
7,775
0.013248
# Copyright 2017, Xavier Snelgrove import argparse import os import sys import numpy as np from scipy import ndimage import gram from gram import JoinMode if __name__ == "__main__": parser = argparse.ArgumentParser(description="Synthesize image from texture", formatter_class=argparse.ArgumentDefaultsHelpFormatter)...
default='valid', help="What
boundary condition to use for convolutions") parser.add_argument("--join-mode", "-j", type=JoinMode, choices = list(JoinMode), default=JoinMode.AVERAGE, help="How to combine gram matrices when multiple sources given") parser.add_argument("--count", "-c", type=int, default=1...
ychfan/tensorflow
tensorflow/contrib/nccl/python/ops/nccl_ops_test.py
Python
apache-2.0
6,643
0.007978
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
_ == '__main__'
: test.main()
cpennington/edx-platform
common/test/acceptance/pages/studio/index.py
Python
agpl-3.0
13,539
0.002807
""" Studio Index, home and dashboard pages. These are the starting pages for users. """ from bok_choy.page_object import PageObject from selenium.webdriver import ActionChains from selenium.webdriver.common.keys import Keys from common.test.acceptance.pages.studio import BASE_URL from common.test.acceptance.pages.st...
element.find_element_by_css_selector('a.course-link').get_attribute('href'), } course_list_selector = u'
.{} li.course-item'.format('archived-courses' if archived else 'courses') return self.q(css=course_list_selector).map(div2info).results def has_course(self, org, number, run, archived=False): """ Returns `True` if course for given org, number and run exists on the page otherwise `False` ...
googleapis/python-error-reporting
google/cloud/errorreporting_v1beta1/services/report_errors_service/client.py
Python
apache-2.0
22,790
0.001624
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
Returns: The transport class to use. """ # If a specific transport is requested, return that one. if label:
return cls._transport_registry[label] # No transport is requested; return the default (that is, the first one # in the dictionary). return next(iter(cls._transport_registry.values())) class ReportErrorsServiceClient(metaclass=ReportErrorsServiceClientMeta): """An API for reporti...
dragonfly-science/kokako
kokako/detectors/kiwi.py
Python
gpl-3.0
1,133
0.006178
import numpy as np from pylab import mean, log from matplotlib import mlab from kokako.score import Detector class SimpleKiwi(Detector): code = 'simple-north-island-brown-kiwi' description = 'Simple detector for north-island brown kiwi, based on energy between 1600 and 2200 Hz' version = '0.1.2' window...
e_specgram(nfft=nfft, noverlap=nfft/2) freqs = np.where((audio.specgram_freqs >= self.lower_call_frequency)*(audio.specgram_freqs <= self.upper_call_frequency)) spec2 = mlab.specgram(mean(log(audio.specgram[freqs[0],]), 0), NFFT=1024, noverlap=512, Fs=2/self.window) freqs2 = np.where((spec2[1] >...
mean_kiwi = np.exp(np.mean(np.mean(np.log(spec2[0][freqs2[0], :]), 0))) return max_kiwi/mean_kiwi
iwaseyusuke/ryu
ryu/services/protocols/bgp/base.py
Python
apache-2.0
19,278
0
# Copyright (C) 2014 Nippon Telegraph and Telephone Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
time.time()) self._child_thread_map = weakref.WeakValueDictionary() self._child_activity_map = weakref.WeakValueDictionary() self._asso_socket_map = weakref.WeakValueDictionary() self._timers = weakref.WeakValueDictionary() self._started = False @property def name(self):...
return self._name @property def started(self): return self._started def _validate_activity(self, activity): """Checks the validity of the given activity before it can be started. """ if not self._started: raise ActivityException(desc='Tried to spawn a ch...
phaethon/scapy
kamene/layers/can.py
Python
gpl-2.0
4,119
0.00437
#! /usr/bin/env python ## This file is part of Scapy ## See http://www.secdev.org/projects/scapy for more informations ## Copyright (C) Nils Weiss <nils@we155.de> ## This program is published under a GPLv2 lice
nse """ CANSocket. """ from kamene.packet import * from kamene.fields impo
rt * import kamene.sendrecv as sendrecv from kamene.supersocket import SuperSocket from kamene.arch.linux import get_last_packet_timestamp ############ ## Consts ## ############ CAN_FRAME_SIZE = 16 LINKTYPE_CAN_SOCKETCAN = 227 # From pcap spec CAN_INV_FILTER = 0x20000000 class CAN(Packet): name = 'CAN' field...
asedunov/intellij-community
python/testData/quickFixes/PyMakeMethodStaticQuickFixTest/usage_after.py
Python
apache-2.0
72
0.013889
class A: @staticmethod def m(x):
retu
rn x print A.m(1)
unioslo/cerebrum
testsuite/tests/test_core/test_utils/test_json.py
Python
gpl-2.0
1,860
0
# encoding: utf-8 # # Copyright 2018 University of Oslo, Norway # # This file is part of Cerebrum. # # Cerebrum 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 op...
e details. # # You should have received a copy of the GNU General Public License # along with Cerebrum; if not, write to the Free Software Foundation, # Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. from __future__ import unicode_literals import six from Cerebrum.utils import json from mx.DateTime im
port DateTime def test_mxdatetime(): assert json.dumps( DateTime(2018, 1, 1, 12, 0, 0)) == '"2018-01-01T12:00:00+01:00"' assert json.dumps(DateTime(2018, 1, 1, 0, 0, 0)) == '"2018-01-01"' def test_constants(factory): co = factory.get('Constants')(None) assert json.dumps(co.entity_account) ==...
seraphln/wheel
wheel/example.local_settings.py
Python
gpl-3.0
1,093
0.000915
# coding: utf-8 """ Wheel will try to read configur
ations from environment variables so you dont need this local_settings.py file if you have env vars. 1. You can set as a file export WHEEL_SETTINGS='/path/to/settings.py' 2. You can set individual values export WHEEL_MONGODB_DB="wheel_db" export WHEEL_MONGODB_HOST='localhost' export WHEEL_MONGODB_PORT='$int 27017' ...
e it to 'local_settings.py' """ # MONGO MONGODB_DB = "wheel_db" MONGODB_HOST = 'localhost' MONGODB_PORT = 27017 MONGODB_USERNAME = None MONGODB_PASSWORD = None # Debug and toolbar DEBUG = True DEBUG_TOOLBAR_ENABLED = False # Logger LOGGER_ENABLED = True LOGGER_LEVEL = 'DEBUG' LOGGER_FORMAT = '%(asctime)s %(name)-12s...
mstrader/MkidDigitalReadout
DarknessFilters/triggerPhotons.py
Python
gpl-2.0
7,378
0.013283
from matplotlib import rcParams, rc import numpy as np import sys from fitFunctions import gaussian import scipy.interpolate import scipy.signal from baselineIIR import IirFilter import pickle import smooth # common setup for matplotlib params = {'savefig.dpi': 300, # save figures to 300 dpi 'axes.labelsize'...
same units as input data) ''' data = np.array(data) med = np.median(data) trigMask = data > (med + np.std(data)*nSigmaTrig) if np.sum(trigMask) > 0: peakIndices = np.where(trigMask)[0] i = 0 p = peakIndices[i] while p < peakIndices[-1]: peakIndices = pea...
p = peakIndices[i] else: p = peakIndices[-1] else: return {'peakIndices':np.array([]),'peakHeights':np.array([])} peakHeights = data[peakIndices] return {'peakIndices':peakIndices,'peakHeights':peakHeights} def detectPulses(data,thresh...
odejesush/tensorflow
tensorflow/python/ops/gradients_test.py
Python
apache-2.0
23,474
0.011459
# 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...
ph().as_default() as g: t1 = constant(1.0) t2 = constant(2.0) _ = array_ops.stack([t1, t2]) t4 = constant(1.0) t5 = constant(2.0)
t6 = array_ops.stack([t4, t5]) # Elements of to_ops are always listed. self._assertOpListEqual([t6.op], _OpsBetween(g, [t6.op], [t1.op])) def testOpsBetweenCut(self): with ops.Graph().as_default() as g: t1 = constant(1.0) t2 = constant(2.0) t3 = array_ops.stack([t1, t2]) t4 = con...
pierreg/tensorflow
tensorflow/examples/how_tos/reading_data/fully_connected_preloaded.py
Python
apache-2.0
5,787
0.006566
# 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...
num_epochs) label = tf.cast(label, tf.int32) images, labels = tf.train.batch( [image, label], batch_size=FLAGS.batch_size) # Build a Graph that computes predictions from the inference model. logits = m
nist.inference(images, FLAGS.hidden1, FLAGS.hidden2) # Add to the Graph the Ops for loss calculation. loss = mnist.loss(logits, labels) # Add to the Graph the Ops that calculate and apply gradients. train_op = mnist.training(loss, FLAGS.learning_rate) # Add the Op to compare the logits to the lab...
RennesUsher/crawlAll
crawlAll/settings.py
Python
apache-2.0
3,379
0.007103
# -*- coding: utf-8 -*- # Scrapy settings for crawlAll project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # http://doc.scrapy.org/en/latest/topics/settings.html # http://scrapy.readthedocs.org/en/lates...
docs.org/en/latest/topics/item-pipeline.html #ITEM_PIPELINES = { # 'crawlAll.pipelines.SomePipeline': 300, #} # Enable and configure the AutoThrottle extension (disabled by default) # See http://doc.scrapy.org/en/latest/topics/autothrottle.html AUTOTHROTTLE_ENABLED = False # The initial download delay #AUTOTHROTTLE...
atencies #AUTOTHROTTLE_MAX_DELAY = 60 # The average number of requests Scrapy should be sending in parallel to # each remote server #AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0 # Enable showing throttling stats for every response received: #AUTOTHROTTLE_DEBUG = False # Enable and configure HTTP caching (disabled by default)...
rodrigoasmacedo/l10n-brazil
__unported__/l10n_br_account/__openerp__.py
Python
agpl-3.0
2,625
0.00381
# -*- encoding: utf-8 -*- ############################################################################### # # # Copyright (C) 2009-2013 Renato Lima - Akretion # # ...
# # # #This program is distributed in the hope that it will b
e 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. # # ...
pdarragh/Viper
viper/interactive/lexer.py
Python
apache-2.0
900
0
import viper.lexer as vl import cmd class InteractiveLexerException(Exception): def __init__(self, output: str): self.output = output class InteractiveLexer(cmd.Cmd): # pragma: no cover prompt = 'viper_lex> ' def default(self, line): lexe
mes = vl.lex_line(line) print(lexemes) def do_exit(self, arg): """Exit the interactive lexer.""" raise InteractiveLexerException(output='exit') def do_quit(self, arg): """Quit the interactive lexer.""" raise InteractiveLexerException(output='quit') def cmdloop(self...
Error as e: print(e) self.cmdloop(intro=intro) except InteractiveLexerException: return except KeyboardInterrupt: print('\b\bexit') return
googleapis/python-redis
google/cloud/redis_v1/types/cloud_redis.py
Python
apache-2.0
23,259
0.000516
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
Redis version 5.0 and newer: - stream-node-max-bytes - stream-node-max-entries tier (google.cloud.redis_v1.types.Instance.Tier): Required. The service tier of the instance. memory_size_gb (int): Required. Redis memory size in GiB. autho...
of the Google Compute Engine `network <https://cloud.google.com/vpc/docs/vpc>`__ to which the instance is connected. If left unspecified, the ``default`` network will be used. persistence_iam_identity (str): Output only. Cloud IAM identity used by import / export ...
aaiijmrtt/TENSORCHALK
tests/core.py
Python
mit
374
0.010695
import sys, os sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '.
.', 'code'))) import core, graphs graph = graphs.one print 'import tensorflow as tf' print core.__fill__(graph, 'add', dict(), 0)[0] print 'with tf.Session() as sess:' print '\tsess.run(tf.global_variables_initializer())' print '\tprint s
ess.run(add, {x: [[1, 2]], y: [[3, 4]]})'
JQIamo/artiq
artiq/test/lit/iodelay/loop.py
Python
lgpl-3.0
320
0.003125
# RUN: %python -m artiq.compiler.testbench.signature %s >%t # RUN: OutputCheck %s --file-to-check=%t # CHECK-L: f: ()->NoneType delay(30
mu) def f(): for _ in range(10): delay_mu(3) # CHECK-L: g: (
)->NoneType delay(60 mu) def g(): for _ in range(10): for _ in range(2): delay_mu(3)
solashirai/edx-platform
common/lib/xmodule/xmodule/modulestore/django.py
Python
agpl-3.0
12,834
0.001792
""" Module that provides a connection to the ModuleStore specified in the django settings. Passes settings.MODULESTORE as kwargs to MongoModuleStore """ from __future__ import absolute_import from importlib import import_module import gettext import logging from pkg_resources import resource_filename import re from...
almost no work. Its main job is to kick off the celery task that will do the actual work. """ pre_publish = django.dispatch.Signal(providing_args=["course_key"]) course_published = django.dispatch.Signal(providing_args=["course_key"]) course_deleted = django.dispatch.Signal(providing_args=["c...
patch.Signal(providing_args=["library_key"]) item_deleted = django.dispatch.Signal(providing_args=["usage_key", "user_id"]) _mapping = { "pre_publish": pre_publish, "course_published": course_published, "course_deleted": course_deleted, "library_updated": library_updated, ...
ministryofjustice/cla_frontend
cla_frontend/apps/core/testing/test_views.py
Python
mit
1,532
0.003916
from django.test import SimpleTestCase class MaintenanceModeTestCase(SimpleTestCase): def test_maintenance_mode_enabled_home_page(self): with self.settings(MAINTENANCE_MODE=True): response = self.client.get("/", follow=True) self.assertEqual(503, response.status_code) s...
ient.get("/maintenance", follow=False) self.assertEqual(503, response.status_code) self.assertIn("This service is down for maintenance", response.content) def test_maintenance_mode_disabled_home_page(self): with self.settings(MAINTENANCE_MODE=False): response = self.clie...
onse.status_code) self.assertNotIn("This service is down for maintenance", response.content) def test_maintenance_mode_disabled_maintenance_page(self): with self.settings(MAINTENANCE_MODE=False): response = self.client.get("/maintenance", follow=True) self.assertEqual(20...
pombredanne/parakeet
parakeet/ndtypes/fn_type.py
Python
bsd-3-clause
1,204
0.015781
from core_types import IncompatibleTypes, ImmutableT class FnT(ImmutableT): """Type of a typed function""" def __init__(self, input_types, return_type): self.input_types = tuple(input_types) self.return_type = return_type self._hash = hash(self.input_types + (return_type,)) def __str__(sel
f): input_str = ", ".join(str(t) for t in self
.input_types) return "(%s)->%s" % (input_str, self.return_type) def __repr__(self): return str(self) def __eq__(self, other): return other.__class__ is FnT and \ self.return_type == other.return_type and \ len(self.input_types) == len(other.input_types) and \ all(t1 ==...
ChameleonCloud/horizon
openstack_dashboard/dashboards/admin/volumes/views.py
Python
apache-2.0
11,089
0
# Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.ap
ache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or
agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Admin views for managing v...
cloud9ers/gurumate
environment/share/doc/ipython/examples/parallel/iopubwatcher.py
Python
lgpl-3.0
2,903
0.004823
"""A script for watching all traffic on the IOPub channel (stdout/stderr/pyerr) of engines. This connects to the default cluster, or you can pass the path to your ipcontroller-client.json Try running this script, and then running a few jobs that print (and call sys.stdout.flush), and you will see the print statements...
for line in c['traceback']: # indent lines print(' ' + line) if __name__ == '__main__': if len(sys.argv) > 1: cf = sys.argv[1] else: # This gets the security fi
le for the default profile: cf = get_security_file('ipcontroller-client.json') main(cf)
darthbhyrava/pywikibot-local
tests/api_tests.py
Python
mit
38,915
0.000437
# -*- coding: utf-8 -*- """API test module.""" # # (C) Pywikibot team, 2007-2015 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, unicode_literals __version__ = '$Id$' import datetime import types import pywikibot.data.api as api import pywikibot.family import pywikibot....
rs='foo') self.assertIn('parameters'
, req1._params) req2 = api.Request(site=self.site, parameters={'action': 'test', 'parameters': 'foo'}) self.assertEqual(req2['parameters'], ['foo']) self.assertEqual(req1._params, req2._params) class TestParamInfo(DefaultSiteTestCase): ...
safl/chplforpyp-docs
docs/source/examples/func_decl.py
Python
apache-2.0
71
0
def
abs(x): if x < 0: re
turn -x else: return x
misscindy/Interview
Graph/19_06_Bipartite.py
Python
cc0-1.0
1,033
0.001936
import collections class Vertex(object): def __init__(self, v): self.v = v self.d = -1 self.neighbors = set() def add_neighbor(self, v): self.neighbors.add(v) def __repr__(self): return str(self.v) + " " + str(self.d) + " " def is_bipartite(vertex): if not ...
q.append(n) elif n.d == cur_node.d: return False print vertex.neighbors return True if __name__ == "__main__": # graph = Vertex(
0) for i in range(1, 4): graph.add_neighbor(Vertex(i)) a = graph.neighbors.pop() graph.add_neighbor(a) a.add_neighbor(graph) print is_bipartite(graph) print graph.neighbors for i in graph.neighbors: print i.neighbors
ghchinoy/tensorflow
tensorflow/python/keras/layers/wrappers_test.py
Python
apache-2.0
37,589
0.009418
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
keras.layers.BatchNormalization(center=True, scale=True), name='bn', input_shape=(10, 2))) model.compile(optimizer='rmsprop', loss='mse') # Assert that mean and variance are 0 and 1. td = model.layers[0] self.assertAllClose(td.get_weights()[2], np.array([0, 0])) assert...
.train_on_batch(np.random.normal(loc=2, scale=2, size=(1, 10, 2)), np.broadcast_to(np.array([0, 1]), (1, 10, 2))) # Assert that mean and variance changed. assert not np.array_equal(td.get_weights()[2], np.array([0, 0])) assert not np.array_equal(td.get_weights()[3], np.array...
msarfati/InstaCommander
instacommander/tests/fixtures.py
Python
apache-2.0
657
0.003044
# -*- coding: utf-8 -
*- import os MODULE_PATH = os.path.split(os.path.realpath(__file__))[0] def typical_fixtures(): # models.User.add_system_users
() # typical_users() pass def typical_picture(): return open(os.path.join(MODULE_PATH, "data/led-hallway.jpg"), 'rb') # def typical_users(): # models.User.register( # email='joe', # name='Joe MacMillan', # password='aaa', # confirmed=True, # roles=["User"], # ...
duozhilin/Blog
blogs/migrations/0009_topic_owner.py
Python
unlicense
685
0.00146
# -*- coding: utf-8 -*- # Generated by Django
1.11.5 on 2017-09-30 08:44 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('blogs...
me='topic', name='owner', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), preserve_default=False, ), ]
pythonindia/junction
tests/utils.py
Python
mit
1,964
0.001018
# -*- coding: utf-8 -*- import functools from django.conf import settings from django.db.models import signals def signals_switch(): pre_save = signals.pre_save.receivers post_save = signals.post_save.receivers def disconnect(): signal
s.pre_save.receivers = [] signals.post_save.receivers =
[] def reconnect(): signals.pre_save.receivers = pre_save signals.post_save.receivers = post_save return disconnect, reconnect disconnect_signals, reconnect_signals = signals_switch() def set_settings(**new_settings): """Decorator for set django settings that will be only available dur...
nicole-a-tesla/meetup.pizza
pizzaplace/admin.py
Python
mit
99
0.010101
from django.contrib import admin from .models import PizzaPlace admin.site.regis
ter(P
izzaPlace)
ContributeToScience/participant-booking-app
booking/core/ip2geo/__init__.py
Python
gpl-2.0
10,628
0.001976
import math import mmap import gzip import os import codecs import pytz import const from util import ip2long from timezone import time_zone_by_country_and_region MMAP_CACHE = const.MMAP_CACHE MEMORY_CACHE = const.MEMORY_CACHE STANDARD = const.STANDARD class GeoIPError(Exception): pass class GeoIPMetaclass(t...
e, region_name, time_zone @rtype: dict """ seek_country = self._seek_country(ipnum) if seek_country == self._databaseSegments:
return None record_pointer = seek_country + (2 * self._recordLength - 1) * self._databaseSegments self._filehandle.seek(record_pointer, os.SEEK_SET) record_buf = self._filehandle.read(const.FULL_RECORD_LENGTH) record = {} record_buf_pos = 0 char = ord(record_buf[...
gonesurfing/Quisk_rpi_remote
softrock/conf_rx_tx_ensemble.py
Python
gpl-2.0
2,177
0.012402
# This is a sample quisk_conf.py configuration file for a SoftRock Rx/Tx Ensemble or # other SoftRock that has both transmit and receive capability. You need two sound # cards, a high quality card to capture radio samples and play microphone sound; and # a lower quality card to play radio sound and capture the microph...
, and should be used for soundcard capture. #name_of_s
ound_capt = "hw:0" #name_of_sound_capt = "hw:1" #name_of_sound_capt = "plughw" #name_of_sound_capt = "plughw:1" #name_of_sound_capt = "default" # Pulseaudio support added by Philip G. Lee. Many thanks! # For PulseAudio support, use the name "pulse" and connect the streams # to your hardware devices using a program li...
johnowhitaker/bobibabber
sklearn/dummy.py
Python
mit
11,519
0
# Author: Mathieu Blondel <mathieu@mblondel.org> # Arnaud Joly <a.joly@ulg.ac.be> # License: BSD 3 clause import numpy as np from .base import BaseEstimator, ClassifierMixin, RegressorMixin from .externals.six.moves import xrange from .utils import check_random_state from .utils.validation import safe_asarray...
elf.random_state = random_state self.constant = constant def fit(self, X, y): """Fit the random classifier. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] Training vectors, where n_samples is the number of samples ...
Returns ------- self : object Returns self. """ if self.strategy not in ("most_frequent", "stratified", "uniform", "constant"): raise ValueError("Unknown strategy type.") y = np.atleast_1d(y) self.output_2d...
punalpatel/st2
st2actions/tests/unit/test_rescheduler.py
Python
apache-2.0
4,718
0.004663
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use th...
tion import LiveActionDB from st2common.persistence.action import Action, LiveAction from st2common.persistence.runner import RunnerType from st2common.services import executions from st2common.transport.liveacti
on import LiveActionPublisher from st2common.transport.publishers import CUDPublisher from st2common.util import date as date_utils from st2tests import DbTestCase, fixturesloader from tests.unit.base import MockLiveActionPublisher from st2tests.mocks.runner import MockActionRunner TEST_FIXTURES = { 'runners': [ ...
archiechen/miami
tests/models_tests.py
Python
mit
1,133
0.010591
import unittest import os os.environ['MIAMI_ENV'] = 'test' import simplejson as json from miami.models import Team, User, Task class ModelsTest(unittest.TestCase): def test_team_toJSON(self): team = Team('Log') team.id = 1 self.assertEquals({'id':1, 'name': 'Log', 'colo
r': '2a33d8'}, team.toJSON()) def test_user_toJSON(self): user = User('Mike') self.assertEquals({'name': 'Mike', 'gravater': '91f376c4b36912e5075b6170d312eab5'}, user.toJSON()) def test_task_toJSON(self): team = Team('Log') team.id = 1 task = Task('title1', 'detail', s...
ask.id = 1 task.owner = User('Mike') self.assertEquals({'id': 1, 'title': 'title1', 'detail': 'detail', 'status': 'DONE', 'price': 1, 'estimate': 4,'priority': 100,'time_slots': [], 'consuming': '0','created_time': 'just now', 'last_updated': 'just now', 'team': { 'name': 'Log...
abhattad4/Digi-Menu
tests/schema/tests.py
Python
bsd-3-clause
61,911
0.001179
import datetime import itertools import unittest from copy import copy from django.db import ( DatabaseError, IntegrityError, OperationalError, connection, ) from django.db.models import Model from django.db.models.fields import ( BigIntegerField, BinaryField, BooleanField, CharField, DateTimeField, Intege...
new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field, strict=True) # Make sure the new FK constraint is present constraints = self.get_constraints(Book._meta.db_table) for name, details in co...
self.assertEqual(details['foreign_key'], ('schema_tag', 'id')) break else: self.fail("No FK constraint for author_id found") @unittest.skipUnless(connection.features.supports_foreign_keys, "No FK support") def test_fk_db_constraint(self): "Tests that the ...
forcaeluz/easy-fat
feeding/migrations/0006_auto_20170701_2013.py
Python
gpl-3.0
1,270
0.002362
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-07-01 20:13 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('flocks', '0015_auto_20170624_1312'), ('feeding', '000...
ate', models.DateField()), ('end_date', models.DateField(null=True)), ('feed_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='feeding.FeedType')), ('flock', models.ForeignKey(on_delete=django.db.models.deletion.CASCAD
E, to='flocks.Flock')), ], ), migrations.RemoveField( model_name='feedingperiodforroom', name='feed_type', ), migrations.RemoveField( model_name='feedingperiodforroom', name='room', ), migrations.DeleteModel( ...
akosel/incubator-airflow
tests/models.py
Python
apache-2.0
100,341
0.000897
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the #...
l_list[3] == op1) dag = DAG( 'dag', start_date=DEFAULT_DATE, default_args={'owner': 'owner1'}) # C -> (A u B) -> D # C -> E # ordered: E | D, A | B, C
with dag: op1 = DummyOperator(task_id='A') op2 = DummyOperator(task_id='B') op3 = DummyOperator(task_id='C') op4 = DummyOperator(task_id='D') op5 = DummyOperator(task_id='E') op1.set_downstream(op3) op2.set_downstream(op3) ...
kyokley/MediaConverter
tests/functional/test_path.py
Python
mit
800
0.00125
import unittest import tempfile import shutil import os from path import Path class TestGetLocalPathsFunctional(unittest.TestCase): def setUp(self): self.temp_dir = tempfile.mkdtemp() self.path = Path('localpat
h', 'remotepath') def tearDown(self): shutil.rmtree(self.temp_dir) def test_path_does_not_exist(self): filepath = os.path.join(self.temp_dir, 'test_file') expected = set() actual = self.path._buildLocalPaths([filepath]) self.assertEqual(expected, actual) def test_p...
ected = files actual = self.path._buildLocalPaths([self.temp_dir]) self.assertEqual(expected, actual)
ifwe/tasr
test/pyunit/test_all.py
Python
apache-2.0
1,248
0
''' Created on Apr 8, 2014 @author: cmills ''' from unittest import TestLoader, TextTestRunner from test_tasr import TestTASR from test_app_topic import TestTASRTopicApp from test_app_core import TestTASRCoreApp from test_app_subject import TestTASRSubjectApp from test_client_legacy_methods import TestTASRLegacyClien...
s from test_client_legacy_object import TestTASRLegacyClientObject from test_client_methods import TestTASRClientMethods from test_client_object import TestTASRClientObject from test_registered_schema import TestRegisteredAvroSchema if __name__ ==
"__main__": SUITE = TestLoader().loadTestsFromTestCase(TestTASR) SUITE = TestLoader().loadTestsFromTestCase(TestTASRTopicApp) SUITE = TestLoader().loadTestsFromTestCase(TestTASRCoreApp) SUITE = TestLoader().loadTestsFromTestCase(TestTASRSubjectApp) SUITE = TestLoader().loadTestsFromTestCase(TestTASR...
rohitranjan1991/home-assistant
homeassistant/components/overkiz/cover_entities/__init__.py
Python
mit
61
0
"""
Cover entities for the Overkiz (by Somfy) integration."""
dcsch/pyif
pyif/parser.py
Python
mit
3,790
0.006596
#from . import action from . import glk from . import message from .debug import log #from . import * NOUN_TOKEN = 1 HELD_TOKEN = 2 MULTI_TOKEN = 3 MULTIHELD_TOKEN = 4 MULTIEXCEPT_TOKEN = 5 MULTIINSIDE_TOKEN = 6 TOPIC_TOKEN = 7 CREATURE_TOKEN = 8 def tokenise_string(string): "Tran...
s them. At the moment this is very simple -- just enough to get us going. """ def __init__(self, story, grammar): self.story = story self.grammar = grammar
def read_input(self): """ Parser strategy: * Break input into tokens * Match the initial token with a verb definition in the grammar """ glk.put_string("\n>") line = glk.get_string() tokens = tokenise_string(line) if len(token...
materials-commons/materialscommons.org
backend/scripts/demo-project/build_project.py
Python
mit
1,400
0.005
#!/usr/bin/python import argparse from os import path as os_path import demo_project as demo import traceback def set_host_url_
arg(): parser.add_argument('--host', required=True, help='the url for the Materials Commons server') def set_datapath_arg(): parser.add_argument('--datapath', required=True, help='the path to the directory containing the files used by the build') def set_apikey_ar...
nt('--apikey', required=True, help='rapikey for the user building the demo project') parser = argparse.ArgumentParser(description='Build Demo Project.') set_host_url_arg() set_datapath_arg() set_apikey_arg() args = parser.parse_args() host = args.host path = os_path.abspath(args.datapath) key = args.apikey # log_me...
qedsoftware/commcare-hq
custom/ewsghana/views.py
Python
bsd-3-clause
11,616
0.002497
import json from django.contrib import messages from django.core.exceptions import PermissionDenied from django.forms.formsets import formset_factory from django.http import HttpResponse, HttpResponseRedirect from django.http.response import Http404 from django.utils.decorators import method_decorator from django.views...
ET from django.views.generic.base import RedirectView from corehq.apps.commtrack.models import StockState from corehq.apps.commtrack.views import BaseCommTrackManageView from corehq.apps.consumption.shortcuts import get_default_monthly_consumption, \ set_default_consumption_for_supply_point from corehq.apps.domain....
any_location from corehq.apps.products.models import Product from corehq.apps.locations.models import SQLLocation from corehq.apps.users.models import WebUser from custom.common import ALL_OPTION from custom.ewsghana.forms import InputStockForm, EWSUserSettings from custom.ewsghana.handlers.web_submission_handler impor...
laurentb/weboob
modules/airparif/pages.py
Python
lgpl-3.0
3,898
0.000257
# -*- coding: utf-8 -*- # Copyright(C) 2019 Vincent A # # This file is part of a weboob module. # # This weboob module is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the Licen...
ob.browser.filters.standard
import ( Env, Format, Regexp, DateTime, CleanDecimal, Lower, Map, ) from weboob.browser.filters.json import Dict from weboob.capabilities.address import GeoCoordinates, PostalAddress from weboob.capabilities.gauge import Gauge, GaugeSensor, GaugeMeasure SENSOR_NAMES = { 'PM25': 'PM 2.5', 'PM10': 'PM 10',...
tianrui/FlappyClone
test_dtree.py
Python
mit
440
0.034091
import numpy as np import pdb #from dtree import * import model def main(): # detree = DTree(np.zeros(3), [1., 2., 3.]) # # inputs = [0.2, 0.6, 0.1] #
print detree.infer(inputs) # detree.feedback(inputs, 1) # pdb.set_trace() # cuts = detree.save() # print
cuts # detree.feedback(inputs, 0) # print detree.infer(inputs) testmod = model.Model(12) testmod.train() if __name__ == '__main__': main()
mikenawrocki/rtslib-fb
rtslib/root.py
Python
apache-2.0
10,297
0.002137
''' Implements the RTSRoot class. This file is part of RTSLib. Copyright (c) 2011-2013 by Datera, Inc Copyright (c) 2011-2014 by Red Hat, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at h...
ttributes default_save_file = "/etc/target/saveconfig.json" class RTSRoot(CFSNode): ''' This is an interface to the root of the configFS object tree. Is allows one to start browsing Target and StorageObjects, as well as helper
methods to return arbitrary objects from the configFS tree. >>> import rtslib.root as root >>> rtsroot = root.RTSRoot() >>> rtsroot.path '/sys/kernel/config/target' >>> rtsroot.exists True >>> rtsroot.targets # doctest: +ELLIPSIS [...] >>> rtsroot.tpgs # doctest: +ELLIPSIS [...
Venturi/oldcms
env/lib/python2.7/site-packages/sortedm2m/forms.py
Python
apache-2.0
4,668
0.001714
# -*- coding: utf-8 -*- import django import sys from itertools import chain from django import forms from django.conf import settings from django.db.models.query import QuerySet from django.template.loader import render_to_string from django.utils.encoding import force_text from django.utils.html import conditional_es...
: attrs = super(SortedCheckboxSelectMultiple, self).\ build_attrs(attrs, **kwargs) classes = attrs.setdefault('class', '').split() classes.append('sortedm2m') attrs['class'] = ' '.join(classes) return attrs def r
ender(self, name, value, attrs=None, choices=()): if value is None: value = [] has_id = attrs and 'id' in attrs final_attrs = self.build_attrs(attrs, name=name) # Normalize to strings str_values = [force_text(v) for v in value] selected = [] unselected = [] ...
GrandmasterShadowMorgue/KerfuffleOfTheDandelions
pronounce.py
Python
mit
662
0.04236
# # pronounce.py # Record pronunciations for word entries # # Jonatan H Sundqvist # May 18 2015 # # TODO | - # - # SPEC | - # - import mozart import sqlite3 import queue import tkinter as tk class Pronounce(object): ''' Docstring goes here ''' def __init__(self): ''' Docstring goes ...
self.window.geometry('{width}x{height}'.format(width=self.size[0], height=self.size[1]))§ def run(self): return self.window.mainloop() def main(): app = Pronounce() app.run
() if __name__ == '__main__': main()
ggravlingen/pytradfri
pytradfri/mood.py
Python
mit
400
0
"""Represent a mood on the gateway.""" from .const import ROOT_MOODS from .resource import ApiResource class Mood(ApiResource): def __init__(self, raw, parent): super().__in
it__(raw) self._parent = parent @pro
perty def path(self): return [ROOT_MOODS, self._parent, self.id] def __repr__(self): return "<Mood {} {}>".format(self._parent, self.name)
MyRobotLab/myrobotlab
src/main/resources/resource/Servo/Servo.py
Python
apache-2.0
2,843
0.006331
######################################### # Servo.py # categories: servo # more info @: http://myrobotlab.org/service/Servo ######################################### # uncomment for virtual hardware Platform.setVirtual(True) # Every settings like limits / port number / controller are saved after initial use # so you c...
st position :{}".format(servo01.getRest())) print("servo speed :{}".format(servo01.getSpeed())) print("servo is inverted :{}".format(s
ervo01.isInverted())) print("servo min :{}".format(servo01.getMin())) print("servo max :{}".format(servo01.getMax())) # sync servo02 with servo01 # now servo2 will be a slave to servo01 print("syncing servo02 with servo01") servo02.sync(servo01) servo01.moveTo(10) sleep(0.5) servo01.moveTo(179) sleep(0.5) servo01....
UMN-Hydro/GSFLOW_pre-processor
python_scripts/MODFLOW_scripts/print_MODFLOW_inputs_res_NWT.py
Python
gpl-3.0
3,667
0.011181
# -*- coding: utf-8 -*- """ Created on Sun Sep 17 22:06:52 2017 Based on: print_MODFLOW_inputs_res_NWT.m @author: gcng """ # print_MODFLOW_inputs import numpy as np import MODFLOW_NWT_lib as mf # functions to write individual MODFLOW files import os # os functions from ConfigParser import SafeConfigParser parser ...
) fl_BoundConstH = 0 # 1 for const head at high elev boundary, needed for numerical # convergence for AGU2016 poster. Maybe resolved with MODFLOW-NWT? if sw_2005_NWT == 1: # MODFLOW input files GSFLOW_indir = GSFLOW_DIR + '/inputs/MODFLOW_2005/' # MODFLOW output files GSFLOW_outd...
W output files GSFLOW_outdir = GSFLOW_DIR + '/outputs/MODFLOW_NWT/' infile_pre = 'test2lay_py'; NLAY = 2; DZ = [100, 50] # [NLAYx1] [m] ***testing # DZ = [350, 100] # [NLAYx1] [m] ***testing # length of transient stress period (follows 1-day steady-state period) [d] # perlen_tr = 365; # [d], ok if too long # per...
Pavaka/Pygorithms
input_checkers/TP_input_checker.py
Python
gpl-2.0
1,080
0
def check_input_data(costs, vector_a, vector_b): if not _is_list(vector_a): raise VectorANotListError if not _is_list(vector_b):
raise VectorBNotListError if not _is_list(costs): raise CostsNotListError if 0 in (len(costs), len(vector_a), len(vector_b)): raise EmptyListError _check_all_values_positive_integers(costs) _check_all_values_positive_integers(vector_a) _check_all_values_positive_integers(...
EmptyListError(Exception): pass class VectorANotListError(Exception): pass class VectorBNotListError(Exception): pass class CostsNotListError(Exception): pass class ListContainsNaN(Exception): pass class NegativeValueError(Exception): pass def _is_list(item): if isinstance(item, ...
jakemathai/computer-vision
label_detect.py
Python
apache-2.0
437
0.029748
#Pass in a photo u
rl to the script and it performs 5 label detection on the photo. import sys import argparse import io from google.cloud import vision #capture the argument passed in to script url=sys.argv[1] client = vision.Client() #pass commange line url into uri image = client.image(source_uri=url) labels = image.detect_labels...
print x print y
atareao/nautilus-imgur-uploader
src/imgurpython/imgur/models/comment.py
Python
gpl-3.0
342
0
class Comment(object): # See do
cumentation at https://api.imgur.com/ for a
vailable fields def __init__(self, *initial_data, **kwargs): for dictionary in initial_data: for key in dictionary: setattr(self, key, dictionary[key]) for key in kwargs: setattr(self, key, kwargs[key])
ROS-PSE/arni
arni_countermeasure/tests/test_storage.py
Python
bsd-2-clause
5,630
0
#!/usr/bin/env python import unittest from arni_countermeasure.rated_statistic_storage import * from rosgraph_msgs.msg import Clock from arni_countermeasure.outcome import * import rospy import time import arni_countermeasure.helper as helper PKG = "arni_countermeasure" class TestStorage(unittest.TestCase): pub ...
e.get_outcome("n!node3", "cpu"), Outcome.HIGH)
TestStorage.set_time(120) self.assertEqual( store.get_outcome("n!node3", "cpu"), Outcome.UNKNOWN) def test_add_new_than_old(self): """Test adding a statistic and then another one of the same type but older.""" TestStorage.set_timeout(20) TestStorage.set_time(100...
xiangcai/todother
module/user.py
Python
lgpl-3.0
344
0.008721
import os import sys impor
t logging class UserEntity(object): def __init__(self,
user_id): self.user_id = user_id #self.prefs = {"locale": "zh_CN"} self.prefs = {} def load(self, entity): self.nickname = entity.nickname self.prefs['locale'] = entity.language self.email = entity.email
lipschultz/diabicus
src/numeric_tools.py
Python
gpl-3.0
8,003
0.003124
""" Diabicus: A calculator that plays music, lights up, and displays facts. Copyright (C) 2016 Michael Lipschultz 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 (...
377, 610, 987, 1597, 2584,
4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269 ] LUCAS_NUMBERS = (2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199, 322, 521, 843, 1364, 2207, 3571, 5778, 9349, 15127, 24476, 39603, 64079, ...
foobacca/django-cms
cms/test_utils/testcases.py
Python
bsd-3-clause
12,223
0.001964
# -*- coding: utf-8 -*- from cms.models import Page from cms.test_utils.util.context_managers import (UserLoginContext, SettingsOverride) from django.conf import settings from django.contrib.auth.models import User, AnonymousUser from django.contrib.sites.models import Site from django.core.exceptions import Object...
age_data['pagepermission_set-2-INITIAL_FORMS'] = 0 page_data['pagepermission_set-2-MAX_NUM_FORMS'] = 0 return page_data def print_page_structure(self, qs): """Just a helper to see the page struct. """ for page in qs.order
_by('tree_id', 'lft'): ident = " " * page.level print "%s%s (%s), lft: %s, rght: %s, tree_id: %s" % (ident, page, page.pk, page.lft, page.rght, page.tree_id) def print_node_structure(self, nodes, *extra): def _rec(nodes, level=0): ide...
lgiordani/slack_hangman
tests/test_guess_manager.py
Python
mit
5,541
0.000361
from main import GuessManager def test_init_uppercase(): g = GuessManager('SOMEWORD') assert g.word == 'SOMEWORD' assert g.mask == [False]*8 def test_init_mask(): mask = [True, False, True, False, True, False, True, False] g = GuessManager('SOMEWORD', mask=mask) assert g.word == 'SOMEWORD' ...
) g.guess('o') res = g.guess_word('someword') assert g.guessed_letters == set(['S', 'O', 'M', 'E', 'W', 'O', 'R', 'D']) assert g.tried_letters == set(['S', 'O']) assert g.guessed == 8 assert res == 5 assert g.missing == 0 assert g.status == list('someword'.upper()) def test_guess_word...
ameward') assert g.guessed_letters == set() assert g.tried_letters == set() assert res == 0 assert g.missing == 8 assert g.status == [None, None, None, None, None, None, None, None] def test_guess_word_unsuccessful_after_guessed_letters(): g = GuessManager('someword') g.guess('s') g.g...
e2crawfo/dps
dps/datasets/load/emnist.py
Python
apache-2.0
11,445
0.001922
import shutil import numpy as np import dill import gzip import os import subprocess import struct from array import array import warnings from dps import cfg from dps.utils import image_to_string, cd, resize_image # This link seems not to work anymore... # emnist_url = 'https://cloudstor.aarnet.edu.au/plus/index.ph...
re stored on disk as uint8. """ if shape == (28, 28): return shape_dir = os.path.join(path, 'emnist_{}_by_{}'.format(*shape)) if os.path.isdir(shape_dir): return emnist_dir = os.path.join(path, 'emnist') print("Converting (28, 28) EMNIST dataset to {}...".format(shape)) ...
edirs(shape_dir, exist_ok=False) classes = ''.join( [str(i) for i in range(10)] + [chr(i + ord('A')) for i in range(26)] + [chr(i + ord('a')) for i in range(26)] ) for i, cls in enumerate(sorted(classes)): with gzip.open(os.path.join(emnist_dir, str(cls) + '.pklz'), 'rb') a...
bleachbit/bleachbit
tests/TestWindows.py
Python
gpl-3.0
19,770
0.000304
# vim: ts=4:sw=4:expandtab # -*- coding: UTF-8 -*- # BleachBit # Copyright (C) 2008-2021 Andrew Ziem # https://www.bleachbit.org # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version...
e bin""" self._test_link_helper('/d', True) def test_delete_locked_file(self): """Unit test for delete_locked_file""" tests = ('regular', 'unicode-emdash-u\u2014', 'long' + 'x' * 100) for test
in tests: f = tempfile.NamedTemporaryFile( prefix='bleachbit-delete-locked-file', suffix=test, delete=False) pathname = f.name f.close() import time time.sleep(5) # avoid race condition self.assertExists(pathname) ...
eduNEXT/edunext-platform
import_shims/lms/instructor_task/tests/test_base.py
Python
agpl-3.0
416
0.009615
"""Deprecated import support. Auto-generated by import_shims/generate_shims.sh.""" # pylint: disable=redefined-builtin,wrong-import-position,wildcard-import,useless-suppression,line-too-long from import_shims.warn import warn_deprecated_import warn
_deprecated_import('instructor_task.tests.test_base', 'lms.djangoapps.in
structor_task.tests.test_base') from lms.djangoapps.instructor_task.tests.test_base import *
Yasumoto/commons
src/python/twitter/common/__init__.py
Python
apache-2.0
957
0
# ================================================================================================== # Copyright 2013 Twitter, Inc. # -------------------------------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use thi...
the LICENSE file, or at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unle
ss required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ========...
Letractively/spiff
src/pkg.py
Python
gpl-2.0
7,448
0.005505
import sys, os, os.path import MySQLdb, SpiffGuard, config, shutil from sqlalchemy import * from SpiffIntegrator import PackageManager, \ version_is_greater, \ InvalidDescriptor from ConfigParser import RawConfigParser from services import Extension...
ckage sys.exit(1) # Read config. if not os.path.exists(config.cfg_file): print "Please configure Spiff before using this tool." sys.exit(1) config.cfg.read(config.cfg_file) dbn = config.cfg.get('database', 'dbn') # Connect to MySQL and set up Spiff Guard. db = create_engine(dbn) guard = SpiffGu...
= ExtensionApi(object, guard = guard, page_db = page_db, request = request) # Init the package manager. pm = PackageManager(guard, api, package = SpiffPackage) pm.set_package_dir(config.package_dir) def pkg_check_dependencies(pm, package): ...