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
krafczyk/spack
var/spack/repos/builtin/packages/r-seqinr/package.py
Python
lgpl-2.1
1,941
0.000515
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
protein) data. Includes also utilities for sequence data management under the ACNUC system.""" homepage = "http://seqinr.r-forge.r-project.org" url = "https://cran.r-project.org/src/contrib/seqinr_3.3-6.tar.gz" list_url = "https://cran.r-project.org/src/contrib/Archive/seginr" version(
'3.4-5', 'd550525dcea754bbd5b83cb46b4124cc') version('3.3-6', '73023d627e72021b723245665e1ad055') depends_on('r@2.10:') depends_on('r-ade4', type=('build', 'run')) depends_on('r-segmented', type=('build', 'run')) depends_on('zlib')
kushsharma/GotAPI
manage.py
Python
apache-2.0
804
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "gotapi.settings") try: from django.core.management import execute_from_command_line
except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Co...
PATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
idan/oauthlib
tests/openid/connect/core/endpoints/test_userinfo_endpoint.py
Python
bsd-3-clause
2,522
0
# -*- coding: utf-8 -*- import json from unittest import mock from oauthlib.oauth2.rfc6749 import errors from oauthlib.openid import RequestValidator, UserInfoEndpoint from tests.unittest import TestCase def set_scopes_valid(token, scopes, request): request.scopes = ["openid", "bar"] return True class Use...
or.validate_bearer_token.side_effect = set_scopes_invalid with self.assertRai
ses(errors.InsufficientScopeError) as context: self.endpoint.create_userinfo_response(self.uri) def test_userinfo_json_response(self): h, b, s = self.endpoint.create_userinfo_response(self.uri) self.assertEqual(s, 200) body_json = json.loads(b) self.assertEqual(self.clai...
Selfnet/dashboard
cgi/latest.json.py
Python
bsd-2-clause
232
0
#!/usr/bin/python import memcache import json
print "Content-Type: application/json" print mc = memcache.Client(['127.0.0.1:11211'], debug=0) data = mc.get_multi(["meta", "latest"]) print(json.dumps(data, separ
ators=(",", ":")))
HuayraLinux/cuaderno
cuaderno/team/admin.py
Python
gpl-2.0
260
0
from django.contrib import admin from team.models import Member # Register your model
s here. class MemberAdmin(admin.ModelAdmin): fields = ['last_name', 'first_name'] ordering = ['last_name', 'first_n
ame'] admin.site.register(Member, MemberAdmin)
megcunningham/django-diesel
tests/engine.py
Python
bsd-3-clause
5,088
0.000786
from subprocess import call from os import path import hitchpostgres import hitchselenium import hitchpython import hitchserve import hitchredis import hitchtest import hitchsmtp # Get directory above this file PROJECT_DIRECTORY = path.abspath(path.join(path.dirname(__file__), '..')) class ExecutionEngine(hitchtest...
"""Stop. IPython time.""" if hasattr(self, 'services'): self.se
rvices.start_interactive_mode() self.ipython(message) if hasattr(self, 'services'): self.services.stop_interactive_mode() def load_website(self): """Navigate to website in Firefox.""" self.driver.get(self.services['Django'].url()) def click(self, on): """Cli...
uclouvain/osis_louvain
base/forms/learning_unit_specifications.py
Python
agpl-3.0
3,409
0.002054
############################################################################## # # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core ...
dgets import CKEditorWidget class LearningUnitSpecificationsForm(forms.Form): learning_unit_year = language = None def __init__(self, learning_unit_year, language, *args, **kwargs): self.learning_unit_year = learning_unit_year self.language = language self.refresh_data() super...
lf.language[0] texts_list = translated_text.search(entity=entity_name.LEARNING_UNIT_YEAR, reference=self.learning_unit_year.id, language=language_iso) \ .exclude(text__isnull=True) set_trans_txt(self, te...
lizardsystem/lizard-efcis
lizard_efcis/migrations/0091_auto_20160315_0924.py
Python
gpl-3.0
1,198
0.000835
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('lizard_efcis', '0090_auto_20160222_1439'), ] operations = [ migrations.AlterField( model_name='mappingfield', ...
'Eenheid'), ('FCStatus', 'FCStatus'), ('Hoedanigheid', 'Hoedanigheid'), ('Locatie', 'Locatie'), ('Meetnet', 'Meetnet'), ('MeetStatus', 'MeetStatus'), ('Parameter', 'Parameter'),
('ParameterGroep', 'ParameterGroep'), ('Status', 'Status'), ('StatusKRW', 'StatusKRW'), ('WNS', 'WNS'), ('WNSStatus', 'WNSStatus'), ('Waterlichaam', 'Waterlichaam'), ('Watertype', 'Watertype')]), preserve_default=True, ), ]
isandlaTech/cohorte-demos
temper/src/aggregator/aggregator.py
Python
apache-2.0
6,713
0.00283
#!/usr/bin/env python # -- Content-Encoding: UTF-8 -- """ An aggregator of sensors values Created on 10 juil. 2012 :author: Thomas Calmant """ # ------------------------------------------------------------------------------ from pelix.ipopo import constants from pelix.ipopo.decorators import ComponentFactory, Prov...
self._lock = threading.Lock() self._thread_stop = threading.Event() self._thread = None def get_history(self): """ Retrieves the whole known history as a dictionary. Result is a dictionary, with sensor name as entry and a list of HistoryEntry (Pyt...
or_history(self, sensor): """ Retrieves the known history for the given sensor :param sensor: The name of a sensor :return: The history of the sensor. Can be None """ with self._lock: return self._history.get(sensor, None) def get_sensor_lastent...
1ukash/horizon
horizon/dashboards/project/images_and_snapshots/views.py
Python
apache-2.0
3,222
0.001241
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Nebula, Inc. # Copyright 2012 OpenStack LLC # # Licensed under the Apache License, Version 2.0 (...
le to retrieve snapshots.")) return snaps def get_volume_snapshots_data(self): try: snapshots = api.volume_snapshot_list(self.request) except: snapshots = [] exceptions.handle(self.request, _("Unable t
o retrieve " "volume snapshots.")) return snapshots class DetailView(tabs.TabView): tab_group_class = SnapshotDetailTabs template_name = 'project/images_and_snapshots/snapshots/detail.html'
garr741/mr_meeseeks
rtmbot/plugins/hmm.py
Python
mit
322
0.003106
hmm = [ "https://media3.giphy.com/media/TPl5N4Ci49ZQY/giphy.gif", "https://media0.giphy.com/media/l14qxlCgJ0zUk/giphy.gif", "https://media4.giphy.com/media/MsWnkCVSXz73i/giphy.gif", "https://media1.giphy.com/media/l2
JJEIMLgrXPEbDGM/giphy.gif", "https://media0.gi
phy.com/media/dgK22exekwOLm/giphy.gif" ]
arturocastro/portable-performance
previous_work/PURE-C/timings/plot.py
Python
mit
107
0
#!/usr/bin/env python import
fileinput from pylab import * for line in fileinput.input(): print line
pombredanne/Rusthon
regtests/go/maps.py
Python
bsd-3-clause
359
0.116992
""
"map types""" def main(): a = map[string]int{ 'x': 1, 'y': 2, 'z': 3, } print( a['x'] ) assert a['x']==1 b = map[int]string{ 0:'a', 1:'b' } print( b[0] ) print( b[1] ) assert b[0]=='a' assert b[1]=='b' ## infers type of key and value ## c = {'x':100, 'y':200} print( c['x'] ) print( c['y'] ) ass...
0
NetApp/manila
manila/tests/share/drivers/netapp/dataontap/client/test_client_base.py
Python
apache-2.0
6,186
0
# Copyright (c) 2014 Alex Meade. All rights reserved. # Copyright (c) 2014 Clinton Knight. 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://w...
ble law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CON
DITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import ddt import mock from oslo_log import log from manila.share.drivers.netapp.dataontap.client import api as netapp_api from manila.share.drivers.netapp.datao...
sndrtj/afplot
afplot/variation.py
Python
mit
2,720
0
""" afplot.variation ~~~~~~~~~~~~~~~~ :copyright: (c) 2017 Sander Bollen :copyright: (c) 2017 Leiden University Medical Center :license: MIT """ def get_all_allele_freqs(record, sample_name): fmt = record.genotype(sample_name) if not hasattr(fmt.data, 'AD'): return [] ad = fmt.data.AD
if not ad: return [] if len(ad) == 0: return
[] if sum(ad) == 0: return [0.0 for _ in ad] return [float(x)/sum(ad) for x in ad] def get_variant_type(record, sample_name): fmt = record.genotype(sample_name) if not fmt.called: return "no_call" elif hasattr(fmt.data, "GQ") and fmt.data.GQ == 0: return "no_call" elif...
LamCiuLoeng/jcp
ordering/controllers/master.py
Python
mit
23,382
0.013942
# -*- coding: utf-8 -*- from datetime import datetime as dt import copy import random import os import traceback from tg import redirect, flash, expose, request, override_template from tg.decorators import paginate from ordering.controllers.basicMaster import * from ordering.model import * from ordering.util.common i...
if f in kw.keys() and f
not in combo_mapping_fields: params[f]=kw[f] if f in kw.keys() and len(kw[f]) > 0 and f in combo_mapping_fields:
dhermes/google-cloud-python
bigquery_datatransfer/google/cloud/bigquery_datatransfer_v1/gapic/enums.py
Python
apache-2.0
5,008
0.001997
# -*- coding: utf-8 -*- # # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
DOUBLE (int): Do
uble precision floating point parameter. BOOLEAN (int): Boolean parameter. RECORD (int): Record parameter. PLUS_PAGE (int): Page ID for a Google+ Page. """ TYPE_UNSPECIFIED = 0 STRING = 1 INTEGER = 2 DOUBLE = 3 BOOLEAN = 4 RECORD = 5...
cvrebert/TritonScraper
src/triton_scraper/cape.py
Python
mit
11,607
0.008529
# Copyright (c) 2010 Christopher Rebert <code@rebertia.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, mod...
m urllib import urlencode as _urlencode import triton_scraper.config from triton_scraper.util import RELATIVE_PREFIX, XPath from triton_scraper.fetchparse import make
_tree4url from lxml import etree CAPE_SEARCH_URL = "http://www.cape.ucsd.edu/stats.html" _tree4url = make_tree4url() def url2tree(url): tree, _url = _tree4url(url) return tree #FIXME: enable # self_cape = XPath(RELATIVE_PREFIX+"/div[@align='right' and text() = 'SelfCAPE']") search_forms = XPath(RELATIVE_PRE...
javihernandez/accerciser-mirror
src/lib/accerciser/prefs_dialog.py
Python
bsd-3-clause
6,660
0.008859
''' Defines the preferences dialog. @author: Eitan Isaacson @organization: Mozilla Foundation @copyright: Copyright (c) 2006, 2007 Mozilla Foundation @license: BSD All rights reserved. This program and the accompanying materials are made available under the terms of the BSD which accompanies this distribution, and ...
'#' + hex(color_val).replace('0x', '').replace('L', '').rjust(6, '0') def get_alpha_float(self): ''' Get the current alpha as a value from 0.0 to 1.
0. ''' return self.get_alpha()/float(0xffff)
evernym/plenum
plenum/test/view_change/test_no_future_view_change_while_view_change.py
Python
apache-2.0
1,825
0.003836
import pytest from plenum.test.delayers import icDelay from plenum.test.helper import checkViewNoForNodes from plenum.test.node_catchup.helper import ensure_all_nodes_have_same_data from plenum.test.stasher import delay_rules from plenum.test.test_node import checkProtocolInstanceSetup from plenum.test.view_change.hel...
= \ lagged_node.view_changer.spylog.count(lagged_node.view_changer.process_future_view_vchd_msg.__name__) # delay INSTANCE CHANGE on lagged nodes, so all nodes except the lagging one finish View Change with delay_rules(lagged_node.nodeIbStasher, icDelay()): # mak
e sure that View Change happened on all nodes but the lagging one ensure_view_change(looper, other_nodes) checkProtocolInstanceSetup(looper=looper, nodes=other_nodes, instances=range(2)) ensure_all_nodes_have_same_data(looper, nodes=other_nodes) # check that lagged node recived 3 Future...
mozilla/kitsune
kitsune/users/migrations/0004_auto_add_contrib_email_flags.py
Python
bsd-3-clause
897
0.00223
# -*- coding: utf-8 -*- """ Add first_answer_email_sent and first_l10n_email_sent fields to Profile. """ from __future__ import unicode_literals from django.db import models, migrations import kitsune.sumo.models # noqa class Migration(migrations.Migration): dependencies = [ ('users', '0003_auto_201504...
st answer contribution email.'), preserve_default=True, ), migrations.AddField( model_name=
'profile', name='first_l10n_email_sent', field=models.BooleanField(default=False, help_text='Has been sent a first l10n contribution email.'), preserve_default=True, ), ]
iHamsterball/stellaris_tech_tree
stellaris_tech_tree/views.py
Python
gpl-2.0
508
0
from django.core import serializers from django.http import HttpResp
onse from django.template import loader from django.utils import translation from django import http from dj
ango.conf import settings from .versions import versions def index(request): template = loader.get_template('index.html') return HttpResponse(template.render({'version_list': versions}, request)) def about(request): template = loader.get_template('about.html') return HttpResponse(template.render({}...
Kallehz/Python
Verkefni 2/Transpose.py
Python
apache-2.0
55
0.018182
def
transpose(a): return list(map(list, zip(*a)
))
google/starthinker
cloud_function/main.py
Python
apache-2.0
1,752
0.005137
########################################################################### # # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/l...
Optional Cloud User JSON credentials when task uses user. } }, "tasks":[ # list of recipe tasks to execute, see StarThinker scripts for examples. {
"hello":{ "auth":"user", # not used in demo, for display purposes only. "say":"Hello World" }} ] } Documentation: https://github.com/google/starthinker/blob/master/tutorials/deploy_cloudfunction.md """ from starthinker.util.configuration import Configuration from starthinker.u...
Null01/detect-polygons-from-image
src/generate-polygons/vectorize-img-03.py
Python
gpl-3.0
1,108
0.01083
''' This program illustrates the use of findContours and drawContours. The original image is put up along with the image of drawn contours. Usage: contours.py A trackbar is put up which controls the contour level from -3 to 3 ''' import numpy as np import cv2 name_file_tile = "0.45-nd.png" file_tile = "../../wp-...
et, thresh = cv2.threshold(imgray, 127, 255, 0) _, contours0, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) contours = [cv2.approxPolyDP(cnt, 3, True) for cnt in contours0] #def update(levels): vis = np.zeros((h, w, 3), np.uint8) levels = 0 #cv2.drawContours( vis, contours, (-1, 2)[level...
contours, -1, (255, 255, 255), 1, 1, hierarchy ); cv2.imshow('contours', vis) #update(3) #cv2.createTrackbar( "levels+3", "contours", 3, 7, update ) #cv2.imshow('image', img) cv2.waitKey() cv2.destroyAllWindows()
statlab/permute
permute/tests/test_stratified.py
Python
bsd-2-clause
3,861
0.003108
import numpy as np import math from numpy.random import RandomState import pytest from cryptorandom.cryptorandom import SHA256 from ..stratified import stratified_permutationtest as spt from ..stratified import stratified_permutationtest_mean as sptm from ..stratified import corrcoef, sim_corr, stratified_two_sample ...
reps=1000, seed=42) res1 = spt(group, conditi
on, response, alternative='less', reps=1000, seed=42) assert res[0] < 0.01 assert res[1] == res1[1] np.testing.assert_almost_equal(res[0], 1-res1[0]) res2 = spt(group, condition, response, alternative='two-sided', reps=1000, seed=42) assert res2[0] < 0.02 group = np.array([1, 1, 1]) conditi...
serbyy/MIDAS
midas/modules/example_analyzeplist.py
Python
mit
7,999
0.000125
#!/usr/bin/env python """ This is an example MIDAS module """ from os.path import isfile from os import chmod from time import time, gmtime, strftime import logging from sys import argv from lib.ty_orm import TyORM from lib.plist import read_plist, get_plist_key from lib.config import Config from lib.data_science imp...
lpers.utilities import to_ascii, encode, error_running_file from lib.tables.example import tables class AnalyzePlist(object): """AnalyzePlist analyzes property list files installed on the system""" def __init__(self): self.data
= {} self.pre_changed_files = [] self.post_changed_files = [] self.pre_new_files = [] self.post_new_files = [] self.check_keys = Config.get("plist_check_keys") self.check_keys_hash = Config.get("plist_check_keys_hash") self.hashes = self.gather_hashes() se...
joachimwolff/minHashNearestNeighbors
sparse_neighbors_search/neighbors/wtaHashClassifier.py
Python
mit
15,173
0.003691
# Copyright 2016, 2017, 2018, 2019, 2020 Joachim Wolff # PhD Thesis # # Copyright 2015, 2016 Joachim Wolff # Master Thesis # Tutor: Fabrizio Costa # Winter semester 2015/2016 # # Chair of Bioinformatics # Department of Computer Science # Faculty of Engineering # Albert-Ludwigs-University Freiburg im Breisgau __author_...
acy_optimized=accuracy_optimized) def __del__(self): del self._wtaHash def fit(self, X, y): """Fit the model using
X as training data. Parameters ---------- X : {array-like, sparse matrix} Training data, shape = [n_samples, n_features] y : {array-like, sparse matrix} Target values of shape = [n_samples] or [n_samples, n_outputs]""" self._wtaHa...
Azure/azure-sdk-for-python
sdk/compute/azure-mgmt-compute/azure/mgmt/compute/v2021_07_01/operations/_virtual_machine_images_operations.py
Python
mit
21,016
0.00452
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
'str'), } url = _format_url_section(url, **path_format_arguments) # Construct parameters query_parameters = kwargs.pop("params"
, {}) # type: Dict[str, Any] query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') # Construct headers header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') return HttpReques...
derekluo/scrapy-cluster
crawler/crawling/redis_retry_middleware.py
Python
mit
1,117
0.008953
from scrapy.downloadermiddlewares.retry import RetryMiddleware import logging logger = logging.getLogger(__name__) class RedisRetryMiddleware(RetryMiddleware): def __init__(self, settings): RetryMiddleware.__init__(self, settings) def _retry(self, request, reason, spider): retries = request....
ty'] = retryreq.meta['priority'] - 10 return retryreq else:
logger.debug("Gave up retrying {request} "\ "(failed {retries} times): {reason}".format( spider=spider, request=request, retries=retries, reason=reason))
eduNEXT/edunext-ecommerce
ecommerce/core/migrations/0042_siteconfiguration_enable_partial_program.py
Python
agpl-3.0
612
0.001634
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-08-04 14:50 from django.db import migrations, models cl
ass Migration(migrations.Migration): dependencies = [ ('core', '0041_remove_siteconfiguration__allowed_segment_events'), ] operations = [ migrations.AddField( model_name='siteconfiguration', name='enable_partial_program', field=models.Boolea
nField(default=False, help_text='Enable the application of program offers to remaining unenrolled or unverified courses', verbose_name='Enable Partial Program Offer'), ), ]
jnewland/home-assistant
tests/components/dyson/test_vacuum.py
Python
apache-2.0
6,611
0
"""Test the Dyson 360 eye robot vacuum component.""" import unittest from unittest import mock from libpurecool.const import Dyson360EyeMode, PowerMode from libpurecool.dyson_360_eye import Dyson360Eye from homeassistant.components.dyson import vacuum as dyson from homeassistant.components.dyson.vacuum import Dyson36...
device_non_vacuum]
dyson.setup_platform(self.hass, {}, _add_device) def test_on_message(self): """Test when message is received.""" device = _get_vacuum_device_cleaning() component = Dyson360EyeDevice(device) component.entity_id = "entity_id" component.schedule_update_ha_state = mock.Mock(...
PyBossa/pybossa
test/test_importers/test_s3_importer.py
Python
agpl-3.0
6,099
0.003771
# -*- coding: utf8 -*- # This file is part of PYBOSSA. # # Copyright (C) 2016 Scifabric LTD. # # PYBOSSA is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your op...
h_context def test_tasks_attributes_for_pdf_files(self): #For pdf file extension: link, filename, url, pdf_url pdf_file_data = 'mypdf.pdf' form_data = { 'files': [pdf_file_data], 'bucket': 'mybucket' } tasks = B
ulkTaskS3Import(**form_data).tasks() assert tasks[0]['info']['filename'] == "mypdf.pdf" assert tasks[0]['info']['link'] == "https://mybucket.s3.amazonaws.com/mypdf.pdf" assert tasks[0]['info']['url'] == "https://mybucket.s3.amazonaws.com/mypdf.pdf" assert tasks[0]['info']['pdf_url'] == ...
matthagy/Jamenson
jamenson/compiler/bind.py
Python
apache-2.0
9,851
0.004061
from __future__ import absolute_import if __name__ == '__main__': import jamenson.compiler.bind jamenson.compiler.bind.test() exit() from ..runtime.ports import (Port, PortList, connect, disconnect, disconnect_all, replace_connection, count_connections, get_cell, get_cells, ...
Macrolet(sym, macro)) def register_symbolmcrole
t(self, sym, form): return self.register(sym, SymbolMacrolet(sym, form)) def use_symbol(self, sym): scope, binding_or_macro = self.find_binding_or_macro(sym) if binding_or_macro is None: #global, non-scoped return BindingUse(Binding(sym)) if isinstance(bindin...
rogerhil/flaviabernardes
flaviabernardes/flaviabernardes/newsletter/migrations/0006_auto_20151110_2139.py
Python
apache-2.0
1,147
0.001744
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('cms', '0008_auto_20151028_1931'), ('newsletter', '0005_auto_20150927_1517'), ] operations = [ migrations.AddField( ...
age', field=models.ForeignKey(null=True, blank=True, to='cms.Page'), preserve_default=True, ), migrations.AddField( model_name='list', na
me='email_message', field=models.TextField(default="<p>Hello %(name)s,</p>\n<p>Please follow the link below.</p>\n<p>If you can't click it, please copy the entire link and paste it into your\nbrowser.</p>\n<p>%(link)s</p>\n<p>Thank you,</p>\n<p>Flavia Bernardes</p>\n"), preserve_default=True, ...
BeeeOn/server
tools/zmqdump.py
Python
bsd-3-clause
1,577
0.039315
#! /usr/bin/env python3 import json import logging import sys import zmq def msg_loop(sock): while True: try: message = sock.recv_json() except Exception as e: logging.error(e) continue logging.info(str(message)) def start_sub(addr): ctx = zmq.Context() sock = ctx.socket(zmq.SUB) logging.info("c...
ltipart() message = json.loads(payload) except Exception as e: logging.error(e) continue logging.info("%s - %s" % (str(header), str(message))) if __name__ == "__main__": logging.basicConfig(level = logging.DEBUG) logging.info("libzmq %s" % zmq.zmq_version()) type = "pull" addr = "ipc://publish.zerom...
ddr = sys.argv[2] if type == "sub": start_sub(addr) elif type == "pull": start_pull(addr) elif type == "pair": start_pair(addr) elif type == "router": start_router(addr) else: raise Exception("unrecognized type: " + type)
ellisonbg/altair
altair/vegalite/v2/examples/scatter_with_labels.py
Python
bsd-3-clause
517
0
""" Simple Scatter
Plot with Labels =============================== This example shows a basic scatter plot with labels created with Altair. """ # category: scatter plots import altair as alt import pandas as pd data = pd.DataFrame({ 'x': [1, 3, 5, 7, 9], 'y': [1, 3, 5, 7, 9], 'label': ['A', 'B', 'C', 'D', '
E'] }) bars = alt.Chart(data).mark_point().encode( x='x:Q', y='y:Q' ) text = bars.mark_text( align='left', baseline='middle', dx=7 ).encode( text='label' ) bars + text
Bysmyyr/chromium-crosswalk
tools/telemetry/catapult_base/dependency_manager/dependency_info_unittest.py
Python
bsd-3-clause
19,819
0.001716
# Copyright 2015 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. import unittest from catapult_base.dependency_manager import dependency_info class DependencyInfoTest(unittest.TestCase): def testInitRequiredInfo(self):...
f.assertEqual('dep', dep_info.dependency) self.assertEqual('platform', dep_info.platform) self.assertEqual(['config_file'], dep_info.config_files) self.assertEqual('cs_hash', dep_info.cs_hash) self.assertEqual('cs_bucket', dep_info.cs_bucket) self.assertEqual('cs_re
mote_path', dep_info.cs_remote_path) self.assertEqual('download_path', dep_info.download_path) self.assertEqual('version_in_cs', dep_info.version_in_cs) self.assertEqual(['path'], dep_info.local_paths) def testInitWithArchivePath(self): self.assertRaises(ValueError, dependency_info.DependencyInfo, 'd...
mattjhayes/nmeta2
nmeta2/api.py
Python
apache-2.0
36,008
0.004832
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the...
rn in the message body 'location': a new location for the resource 'status': HTTP status code to return """ result = dict() try: result = func(*args, **kwargs) except SyntaxError as e: status = 400 details = e.msg pr...
"msg ", details msg = {REST_RESULT: REST_NG, REST_DETAILS: details} return Response(status=status, body=json.dumps(msg)) except (ValueError, NameError) as e: status = 400 details = e.message print "ERROR: ValueError or NameError in _...
mozilla/spark-eol
apps/eol/urls.py
Python
bsd-3-clause
644
0.003106
from django.conf.urls.defaults import patterns, url from commons.views import redirect_to from . import views urlpatterns = patterns('', url(r'^$', redirect_to, {'url': 'eol.home'}), url(r'^home$', views.home, name='eol.home'), url(r'^newsletter', vi
ews.newsletter, name='eol.newsletter'), url(r'^m/$', redirect_to, {'url': 'eol.home_mobile'}), url(r'^m/home$', views.home_mobile, name='eol.home_mobile'), url(r'^m/sharing-the-spark$', views.spar
k_sharing, name='eol.sharing'), url(r'^m/around-the-globe$', views.spark_around, name='eol.around'), url(r'^m/hall-of-fame$', views.spark_hall, name='eol.hall'), )
jayme-github/CouchPotatoServer
couchpotato/core/providers/nzb/nzbclub/main.py
Python
gpl-3.0
2,892
0.00657
from bs4 import BeautifulSoup from couchpotato.core.helpers.encoding import toUnicode, tryUrlencode from couchpotato.core.helpers.rss import RSS from couchpotato.core.helpers.variable import tryInt from couchpotato.core.logger import CPLog from couchpotato.core.providers.nzb.base import NZBProvider from dateutil.parser...
on = toUnicode(nfo_pre.text) if nfo_pre else '' item['description'] = description return item def extraCheck(self, item): full_description = self.getCache('nzbclub.%s' % item['id'], item['detail_url'], cache_timeout = 25920000) if 'ARCHIVE inside ARCHIVE' in full_description: ...
rn True
tobybreckon/python-examples-ml
decisiontrees/dtree1.py
Python
lgpl-3.0
4,168
0.016315
##################################################################### # Example : decision tree learning # basic illustrative python script # For use with test / training datasets : car.{train | test} # Author : Toby Breckon, toby.breckon@durham.ac.uk # Version : 0.4 (OpenCV 3 / Python 3 fixes) # Copyright (c) 2014...
rithm for larger numbers) dtree.setMaxDepth(8); # max tree depth dtree.setMinSampleCount(25); # min sample count dtree.setPrio
rs(np.float32([1,1,1,1])); # the array of priors, the bigger weight, the more attention to the assoc. class # (i.e. a case will be judjed to be maligant with bigger chance)) dtree.setRegressionAccuracy(0); # regression accuracy: N/A here dtree.setTruncatePrunedTree(True); #...
scavarda/mysql-dbcompare
mysql-utilities-1.6.0/mysql/fabric/failure_detector.py
Python
apache-2.0
8,960
0.000446
# # Copyright (c) 2013,2014, Oracle and/or its affiliates. All rights reserved. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; version 2 of the License. # # This program is distributed in the...
id: Group's id. """ _LOGGER.info("Monitoring group (%s).", group_id) with FailureDetector.LOCK: if
group_id not in FailureDetector.GROUPS: detector = FailureDetector(group_id) detector.start() FailureDetector.GROUPS[group_id] = detector @staticmethod def unregister_group(group_id): """Stop a failure detector for a group. :param group_id: Group...
dnguyen0304/mfit_service
mfit/mfit/resources/__init__.py
Python
mit
1,041
0.000961
# -*- coding: utf-8 -*- from .base import _Base, Bas
e from .base_collection import BaseCollection from .habit_groups import HabitGroups from .habit_groups_collection import HabitGroupsCollection from .habits import Habits from .habits_
collection import HabitsCollection from .users import Users from .users_collection import UsersCollection from .attempts import Attempts from .attempts_collection import AttemptsCollection from .routines import Routines from .routines_collection import RoutinesCollection from .attempts_logs import AttemptsLogs from .at...
s20121035/rk3288_android5.1_repo
external/chromium_org/chrome/common/extensions/docs/server2/redirector_test.py
Python
gpl-3.0
7,651
0.00183
#!/usr/bin/env python # Copyright 2013 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. import json import unittest from compiled_file_system import CompiledFileSystem from object_store_creator import ObjectStoreCreator fr...
port Redirector from test_file_system import TestFileSystem from third_party.json_schema_compiler.json_parse import Parse HOST = 'http://localhost/' file_system = TestFileSystem({ 'redirects.json': json.dumps({ 'foo/...': 'apps/...', '': '/index.html', 'home': 'index.html', 'index.html': 'http://som...
': 'about_apps.html', 'foo.html': '/bar.html', }) }, 'extensions': { 'redirects.json': json.dumps({ 'manifest': 'manifest.html', 'tabs': 'tabs.html', 'dev/...': '...', 'a/very/long/dir/chain/...': 'short/...', '_short/...': 'another/long/chain/...', 'r1/...': 'r2/r1...
maropu/spark
python/pyspark/mllib/feature.py
Python
apache-2.0
28,134
0.001102
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
lg.Vector` or :py:class:`pyspark.RDD` normalized vector(s). If the norm of the input is zero, it will return the input vector. """ if isinstance(vector, RDD): vector = vector.map(_convert_to_vector) else: vector = _convert_to_vector(vector) ...
aVectorTransformer(JavaModelWrapper, VectorTransformer): """ Wrapper for the model in JVM """ def transform(self, vector): """ Applies transformation on a vector or an RDD[Vector]. Parameters ---------- vector : :py:class:`pyspark.mllib.linalg.Vector` or :py:cla...
icaoberg/cellorganizer-galaxy-tools
datatypes/dataproviders/chunk.py
Python
gpl-3.0
2,581
0.020922
""" Chunk (N number of bytes at M offset to a source's beginning) provider. Primarily for file sources but usable by any iterator that has both seek and read( N ). """ import os import base64 import base import exceptions import logging log = logging.getLogger( __name__ ) # -----------------------------------------...
s to re
turn (gen. in bytes). """ super( ChunkDataProvider, self ).__init__( source, **kwargs ) self.chunk_size = int( chunk_size ) self.chunk_pos = int( chunk_index ) * self.chunk_size def validate_source( self, source ): """ Does the given source have both the ...
funbaker/astropy
astropy/convolution/convolve.py
Python
bsd-3-clause
35,929
0.001169
# Licensed under a 3-clause BSD style license - see LICENSE.rst import warnings import numpy as np from functools import partial from .core import Kernel, Kernel1D, Kernel2D, MAX_NORMALIZATION from ..utils.exceptions import AstropyUserWarning from ..utils.console import human_file_size from ..utils.decorators impor...
0, True) new_kernel = Kernel1D(array=new_array) elif isinstance(array, Kernel2
D) and isinstance(kernel, Kernel2D): new_array = convolve2d_boundary_fill(array.array, kernel.array, 0, True) new_kernel = Kernel2D(array=new_array) else: raise Exception("Can't convolve 1D and 2D kernel.") ...
TomMinor/mesh-surface-spawner
FreeformAttributes.py
Python
gpl-2.0
15,123
0.009588
# Terrain Data [ Tools ] # -> PencilCurves [ ToolList ] # -> Tool Data [ Radius, Distribution(Uniform(Min/Max), Gaussian(Mean, Falloff)), Scale(Min/max), Rotation(Min/Max), Offset, TypeData ] # -> Type Data [ Density, (Scale, Rotation, Offset)Absolute, ObjectData ] # -> Object Data [...
nstancedObject, instanceList ] # -> instanceList # - instance0.... instanceN # -> RadialBound [ ToolList ] #
-> Tool Data [ Radius, Distribution(Uniform(Min/Max), Gaussian(Mean, Falloff)), Scale(Min/max), Rotation(Min/Max), Offset, TypeData ] # -> Type Data [ Density, (Scale, Rotation, Offset)Absolute, ObjectData ] # -> Object Data [ instancedObject, instanceList ] # -> inst...
pymber/algorithms
algorithms/sorting/insertion_sort.py
Python
mit
336
0.008929
#!/usr/bin/env python from lib.swap import * def insertion_sort(L=[]): ''' Unstable implementation of insertion sort. :param L: list of sortable elements. ''' if len(L) < 2: return L for i in range(len(L)): j = i while j and L[j] < L[j-1]: swap(L, j, j-1)
j -= 1 return L
kennedyshead/home-assistant
tests/components/climacell/test_weather.py
Python
apache-2.0
15,479
0
"""Tests for Climacell weather entity.""" from __future__ import annotations from datetime import datetime import logging from typing import Any from unittest.mock import patch import pytest from homeassistant.components.climacell.config_flow import ( _get_config_schema, _get_unique_id, ) from homeassistant....
t_unique_id(hass, data), version=1, ) config_entry.add_to_hass(hass) assert await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() for entity_name i
n ("hourly", "nowcast"): _enable_entity(hass, f"weather.climacell_{entity_name}") await hass.async_block_till_done() assert len(hass.states.async_entity_ids(WEATHER_DOMAIN)) == 3 return hass.states.get("weather.climacell_daily") async def test_v3_weather( hass: HomeAssistant, ...
ANR-COMPASS/shesha
guardians/__init__.py
Python
gpl-3.0
138
0
"""
GuARDIANs (packaGe for Ao eRror breakDown estImation And exploitatioN) """ __all__ = ["groot", "gamora",
"roket", "drax", "starlord"]
marcuskd/pyram
pyram/Tests/TestPyRAMmp.py
Python
bsd-3-clause
4,888
0.001432
''' TestPyRAMmp unit test class. Uses configuration file TestPyRAMmp_Config.xml. Computational range and depth steps and number of repetitions are configurable. Number of PyRAM runs = number of frequencies * number of repetitions. Tests should always pass but speedup will depend upon computing environment. ''' import ...
self.pyram_args = dict(zs=50., zr=50., z_ss=numpy.array([0., 100, 400]), rp_ss=numpy.array([0., 25000]), cw=numpy.array([[1480., 153
0], [1520, 1530], [1530, 1530]]), z_sb=numpy.array([0.]), rp_sb=numpy.array([0.]), cb=numpy.array([[1700.]]), ...
colab/colab
colab/utils/tests/test_conf.py
Python
gpl-2.0
4,536
0
import sys import os from django.test import TestCase, override_settings, Client from django.conf import settings from ..conf import (DatabaseUndefined, validate_database, InaccessibleSettings, _load_py_file, load_py_settings, load_colab_apps, load_widgets_settings) from mock ...
def test_blacklist(sel
f): client = Client() response = client.get('/test_blacklist') self.assertEquals(403, response.status_code)
molmod/yaff
yaff/analysis/test/test_blav.py
Python
gpl-3.0
1,509
0.001325
# -*- coding: utf-8 -*- # YAFF is yet another force-field code. # Copyright (C) 2011 Toon Verstraelen <Toon.Verstraelen@UGent.be>, # Louis Vanduyfhuys <Louis.Vanduyfhuys@UGent.be>, Center for Molecular Modeling # (CMM), Ghent University, Ghent, Belgium; all rights reserved unless otherwise # stated. # # This file is pa...
licenses/> # # -- from __future__ import division import tempfile, shutil, os, numpy as np from yaff import * from molmod.test.common import tmpdir def test_blav(): # generate a time-correlated random signal n = 50000 eps0 = 30.0/n eps1 = 1.0 y = np.sin(np.random.normal(0, eps0, n).cumsum() + ...
blav(y, 100, fn_png) assert os.path.isfile(fn_png)
apsun/AniConvert
aniconvert.py
Python
mit
34,380
0.001716
#!/usr/bin/env python ############################################################### # AniConvert: Batch convert directories of videos using # HandBrake. Intended to be used on anime and TV series, # where files downloaded as a batch tend to have the same # track layout. Can also automatically select a single audio # ...
pe, codec_name, language_code, metadata): self.stream_index = stream_index self.codec_type = codec_type self.codec_name = codec_name s
elf.language_code = language_code self.metadata = metadata class HandBrakeAudioInfo(object): pattern1 = re.compile(r"(\d+), (.+) \(iso639-2: ([a-z]{3})\)") pattern2 = re.compile(r"(\d+), (.+) \(iso639-2: ([a-z]{3})\), (\d+)Hz, (\d+)bps") def __init__(self, info_str): match = self.pattern1...
dmordom/nipype
nipype/interfaces/mrtrix/tests/test_auto_DiffusionTensorStreamlineTrack.py
Python
bsd-3-clause
3,157
0.029142
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from nipype.testing import assert_equal from nipype.interfaces.mrtrix.tracking import DiffusionTensorStreamlineTrack def test_DiffusionTensorStreamlineTrack_inputs(): input_map = dict(args=dict(argstr='%s', ), cutoff_value=dict(argstr='-cutoff %s', ...
ile', 'exclude_spec'], ), gradient_encoding_file=dict(argstr='-grad %s', mandatory=True, position=-2, ),
ignore_exception=dict(nohash=True, usedefault=True, ), in_file=dict(argstr='%s', mandatory=True, position=-2, ), include_file=dict(argstr='-include %s', xor=['include_file', 'include_spec'], ), include_spec=dict(argstr='-include %s', position=2, sep=',', units='mm...
jmacmahon/invenio
modules/bibformat/lib/elements/bfe_year.py
Python
gpl-2.0
1,262
0.003962
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2007, 2008, 2009, 2010, 2011 CERN. # # Invenio 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 version. # # Invenio is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a c...
111-1307, USA. """BibFormat element - Prints the publication year """ __revision__ = "$Id$" import re def format_element(bfo): """ Prints the publication year. @see: pagination.py, publisher.py, reprints.py, imprint.py, place.py """ for date_field in ['773__y', '260__c', '269__c', '909C4y', '925__...
angelapper/edx-platform
common/lib/capa/capa/safe_exec/tests/test_lazymod.py
Python
agpl-3.0
2,041
0.00049
"""Test lazymod.py""" import sys import unittest from capa.safe_exec.lazymod import LazyModule class ModuleIsolation(object): """ Manage changes to sys.modules so that we can roll back imported modules. Create this object, it will snapshot the currently imported modules. When you call `clean_up()`,...
or m in sys.modules if m not in self.mods] # and delete them all so another import will run code for real again. for m in new_mods: del sys.modules[m] class TestLazyMod(unittest.TestCase): def setUp(self): super(TestLazyMod, self).setUp() # Each test will remove module...
ModuleIsolation().clean_up) def test_simple(self): # Import some stdlib module that has not been imported before module_name = 'colorsys' if module_name in sys.modules: # May have been imported during test discovery, remove it again del sys.modules[module_name] ...
hunter-87/binocular-dense-stereo
cpp_pcl_visualization/pcl_visualization_pcd/pcl_test.py
Python
gpl-2.0
190
0.015789
import pcl p = pcl.PointCloud() p.from_file("test_pcd.pcd") fil = p.make_statistical
_outlier_filter() fil.set_mean_k (50) fil.se
t_std_dev_mul_thresh (1.0) fil.filter().to_file("inliers.pcd")
peterayeni/django-smsgateway
smsgateway/backends/mobileweb.py
Python
bsd-3-clause
2,600
0.002692
import datetime import re from django.http import HttpResponse from django.utils.http import urlencode import smsgateway from smsgateway.models import SMS from smsgateway.backends.base import SMSBackend from smsgateway.utils import check_cell_phone_number class MobileWebBackend(SMSBackend): def get_send_url(self...
_using=None): request_dict = request.POST if request.method == 'POST' else request.GET # Check whether we've gotten a SendDateTime if not 'SendDateTime' in request_dict: return HttpResponse('') # Check whether we've already received this message if SMS.objects.filte...
teway_ref=request_dict['MessageID']).exists(): return HttpResponse('OK') # Parse and process message year, month, day, hour, minute, second, ms = map(int, re.findall(r'(\d+)', request_dict['SendDateTime'])) sms_dict = { 'sent': datetime.datetime(year, month, day, hour, m...
FinnStutzenstein/OpenSlides
server/openslides/users/management/commands/createinitialuser.py
Python
mit
1,391
0.002157
from django.core.management.base import BaseCommand from django.db import connection from .createopenslidesuser import Command as CreateOpenslidesUser class Command(BaseCommand): """ Command to create an OpenSlides user. """ help = "Creates an OpenSlides user with id=2 if no other user than the admi...
parser.add_argument("last_name", help="The last name of the new user.") parser.add_argument("username", help="The username of the new user.") parser.add_argument("password", help="The password of the new user.") parser.add_argument("groups_id", help="The group id of the new user.") parse...
ptions["userid"] = 2 with connection.cursor() as cursor: cursor.execute("SELECT last_value FROM users_user_id_seq;") last_id = cursor.fetchone()[0] if last_id > 1: self.stdout.write( self.style.NOTICE( "There have u...
keedio/sahara
sahara/utils/openstack/heat.py
Python
apache-2.0
10,597
0
# Copyright (c) 2013 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
ts(ng), 'security_groups': security_groups} yield _load_template('instance.heat', fields) for idx in range(0, ng.volumes_per_node): yield self._serialize_volume(inst_name, idx, ng.volumes_size) def _serialize_port(s
elf, port_name, fixed_net_id, security_groups): fields = {'port_name': port_name, 'fixed_net
remybaranx/qtaste
tools/jython/lib/Lib/encodings/cp437.py
Python
gpl-3.0
7,146
0.039603
""" Python Character Mapping Codec generated from 'CP437.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,error...
TIN SMALL LETTER O WITH GRAVE 0x0096: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX 0x0097: 0x00f9, # LATIN SMALL LETTER U WITH GRAVE 0x0098: 0x00ff, # LATIN SMALL LETTER Y WITH DIAERESIS 0x0099: 0x00d6
, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x009b: 0x00a2, # CENT SIGN 0x009c: 0x00a3, # POUND SIGN 0x009d: 0x00a5, # YEN SIGN 0x009e: 0x20a7, # PESETA SIGN 0x009f: 0x0192, # LATIN SMALL LETTER F WITH HOOK 0x00a0: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE 0...
mozilla/captain
vendor/lib/python/commonware/request/tests.py
Python
mpl-2.0
2,104
0
from django.conf import settings import mock from nose.tools import eq_ from test_utils import RequestFactory from commonware.request.middleware import (SetRemoteAddrFromForwardedFor, is_valid) mw = SetRemoteAddrFromForwardedFor() def get_req(): req = RequestFactory(...
" req = get_req() req.META['HTTP_X_FORWARDED_FOR'] = '2.3.4.5' mw.process_request(req) eq_('2.3.4.5', req.META['REMOTE_ADDR']) def test_is_valid(): """IPv4 and IPv6 addresses are OK.""" tests = ( ('1.2.3.4', True), ('2.3.4.5', True), ('foobar', False), ('4.256.4...
5:56e0', True), ('fe80::a00:277ff:fed5:56e0', False), ('fe80::a00:27ff:ged5:56e0', False), ) def _check(i, v): eq_(v, is_valid(i)) for i, v in tests: yield _check, i, v
jeh/mopidy-gmusic
mopidy_gmusic/library.py
Python
apache-2.0
11,350
0.00141
from __future__ import unicode_literals import logging import hashlib from mopidy.backends import base from mopidy.models import Artist, Album, Track, SearchResult logger = logging.getLogger('mopidy.backends.gmusic') class GMusicLibraryProvider(base.BaseLibraryProvider): def find_exact(self, query=None, uris=...
is None: query = {} self._validate_query(query) result_tracks = self.tracks.values() for (field, values) in query.iteritems(): if not hasattr(values, '__iter__'): values = [values] # FIXME this is bound to be slow for large libraries ...
rt_to_int(value) else: q = value.strip() uri_filter = lambda t: q == t.uri track_name_filter = lambda t: q == t.name album_filter = lambda t: q == getattr(t, 'album', Album()).name artist_filter = lambda t: filter( ...
nkgilley/home-assistant
homeassistant/components/simulated/sensor.py
Python
apache-2.0
4,609
0.000434
"""Adds a simulated sensor.""" from datetime import datetime import logging import math from random import Random import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import CONF_NAME import homeassistant.helpers.config_validation as cv from homeassistant.helpe...
self._start_time = ( datetime(1970, 1, 1, tzinfo=dt_util.UTC) if relative_to_epoch else dt_util.utcnow() ) self._relative_to_epoch = relative_to_epoch self._state = None def time_delta(self): """Return the time delta.""" dt0 = self._start...
me_delta = self.time_delta().total_seconds() * 1e6 # to milliseconds period = self._period * 1e6 # to milliseconds fwhm = self._fwhm / 2 phase = math.radians(self._phase) if period == 0: periodic = 0 else: periodic = amp * (math.sin((2 * math.pi * time_d...
molmod/zeobuilder
share/plugins/basic/point.py
Python
gpl-3.0
7,413
0.002698
# -*- coding: utf-8 -*- # Zeobuilder is an extensible GUI-toolkit for molecular model construction. # Copyright (C) 2007 - 2012 Toon Verstraelen <Toon.Verstraelen@UGent.be>, Center # for Molecular Modeling (CMM), Ghent University, Ghent, Belgium; all rights # reserved unless otherwise stated. # # This file is part of Z...
ent if parent == None: return False # C) passed all tests: return True def do(self): cache = context.application.cache parent = cache.common_parent while not parent.check_add(Point): parent = parent.parent vector_sum = numpy.zeros(3, float) ...
vector_sum += node.get_frame_relative_to(parent).t num_vectors += 1 point = Point(name="Average", transformation=Translation(vector_sum / num_vectors)) primitive.Add(point, parent) nodes = { "Point": Point } actions = { "AddPoint": AddPoint, "CalculateAverage": Ca...
semk/iDiscover
idiscover/discover.py
Python
mit
1,840
0.00163
# -*- coding: utf-8 -*- # # Discover the target host types in the subnet # # @author: Sreejith Kesavan <sreejithemk@gmail.com> import arp import oui import ipcalc import sys class Discovery(object): """ Find out the host types in the Ip range (CIDR) NOTE: This finds mac ad
dresses only within the subnet. It doesn't fetch mac addresses for routed network ip's. """ def __init__(self): self.__arp = arp.ARP() self.__oui = oui.OUI() def discover(self, address): """ Traverse the IP subnets and return manufacturer info. """ netwo...
for ip in network: ip = str(ip) # Ignore broadcast IP Addresses if '/' in address and ip == str(network.broadcast()): print 'Ignoring broadcast ip: {broadcast}'.format(broadcast=str(network.broadcast())) continue mac = self.__arp.f...
CounterpartyXCP/counterblock
counterblock/lib/modules/dex/__init__.py
Python
mit
32,660
0.004195
""" Implements counterwallet asset-related support as a counterblock plugin DEPENDENCIES: This module requires the assets module to be loaded before it. Python 2.x, as counterblock is still python 2.x """ import os import sys import time import datetime import logging import decimal import urllib.request import urlli...
e end_ts = now_ts if not start_ts: # default to 30 days before the end date start_ts = end_ts - (30 * 24 * 60 * 60) data = {} results = {} #^ format is result[market_cap_as][asset] = [[block_time, market_cap], [block_time2, market_cap2], ...] for market_cap_as in (config.XCP, confi...
: { "market_cap_as": market_cap_as, "block_time": { "$gte": datetime.datetime.utcfromtimestamp(start_ts) } if end_ts == now_ts else { "$gte": datetime.datetime.utcfromtimestamp(start_ts), "$lte": datetime.datetim...
sirmarcel/floq
benchmark/museum_of_evolution/uncompiled_floq/parametric_system.py
Python
mit
2,852
0.002454
import floq.core.fixed_system as fs import floq.evolution as ev import floq.errors as er import floq.helpers.index as h class ParametricSystemBase(object): """ Base class to specify a physical system that still has open parameters, such as the control amplitudes, the control duration, or other arbitrary ...
, t) and self.nz-step > 3: self.nz -= h.make_even(step) class ParametricSystemWithFunctions(ParametricSystemBase): """ A system with parametric hf and dhf, which are passed as callables to the constructor. hf has to have the form hf(a,parameters) """ def __init__(self, hf, dhf, nz,...
tonian nz: number of Fourier modes to be considered during evolution parameters: a data structure that holds parameters for hf and dhf (dictionary is probably the best idea) """ self.hf = hf self.dhf = dhf self.omega = omega self.nz = nz self.param...
Swabboy/ImageDateSort
ImageDateSort.py
Python
gpl-3.0
7,213
0.014973
# Copyright 2015 Ian Lynn # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distribute...
numImagesProcessed += 1 #***Complete*** print "Finished" print "Number of images processed: " + str(numImagesProcessed) else: print "Processing Image" exifData = ProcessFile(fileName,modelDir) ...
if exifData == 0: print "No EXIF data found to sort image" else: SortImage(outputDir,exifData[0],exifData[1],fileName,delOriginal) print "Finished" except getopt.error, msg: raise Usage(msg) except...
anhstudios/swganh
data/scripts/templates/object/tangible/mission/quest_item/shared_surlin_rolei_q1_recruitment_disk.py
Python
mit
511
0.043053
#### 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 = Tangible() result.template = "object/tangible/mission/quest_item/shared_surlin_rolei_q1_recruitment_disk.iff" result.attribute_template_id = -1 result.s...
ATIONS #### return result
tiagofrepereira2012/tensorflow
tensorflow/python/util/nest.py
Python
apache-2.0
21,628
0.00504
# 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...
n of the input. """ if is_sequence(nest): return list(_yield_flat_nest(nest)) else: return [nest] def _recursive_assert_same_structure(nest1, nest2, check_types): """Helper function for `assert_same_structure`.""" is_sequence_nest1 = is_sequence(nest1) if is_sequence_nest1 != is_sequence(nest2): ...
ucture.\n\n" "First structure: %s\n\nSecond structure: %s." % (nest1, nest2)) if not is_sequence_nest1: return # finished checking if check_types: type_nest1 = type(nest1) type_nest2 = type(nest2) if type_nest1 != type_nest2: raise TypeError( "The two structures don't have...
nebril/fuel-web
nailgun/nailgun/test/integration/test_node_allocation_stats_handler.py
Python
apache-2.0
1,552
0
# -*- coding: utf-8 -*- # Copyright 2013 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file e
xcept in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b
y 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. from nailg...
pycket/pycket
pycket/prims/struct_structinfo.py
Python
mit
11,050
0.006063
#! /usr/bin/env python # -*- coding: utf-8 -*- from pycket import impersonators as imp from pycket import values from pycket import values_parameter, values_struct from pycket.arity import Arity from pycket.error import SchemeException from pycket.prims.expose import...
) if (isinstance(w_super_type, values_struct.W_StructType) and w_super_type.prop_sealed): raise SchemeException("make-struct-type: cannot make a subtype of a sealed type") init_field_count = w_init_field_count.value auto_field_count = w_auto_field_count.value immutables = [] for i in...
if not isinstance(i, values.W_Fixnum) or i.value < 0: raise SchemeException("make-struct-type: expected list of positive integers for immutable fields") immutables.append(i.value) return values_struct.W_StructType.make(w_name=w_name, w_super_type=w_super_type, init_field_count=...
dragonrider23/rabbithole
modules/cmd_wrappers.py
Python
bsd-3-clause
673
0.001486
# -*- coding: utf-8 -*- """ This module allows running system
commands directly from Rabbithole. This can be good for simple commands such as ping. There is currently no way to filter arguments given to wrapped commands. For that kind of functionali
ty, a separate module should be created, """ import rh.common as common def _create_wrappers(config): cmds = config.get('core', 'wrappedCommands').split(',') for cmd in cmds: func = lambda _, args, cmd=cmd: common.start_process( "{} {}".format(cmd, args)) common.register_cmd( ...
cieplak/morf
morf/morphism.py
Python
mit
2,478
0
from .path import Path class Morphism(object): def __init__(self, arrows): self.arrows = arrows def __call__(self, domain): codomain = {} for arrow in self.arrows: codomain = arrow.apply(domain, codomain) return codomain @classmethod def compile(cls, *exp...
for token in tokens: if token[0] == '/': source_paths.append(Path.parse(token)) else: callable_tokens.append(token) callables = [] for token in callable_tokens: if token in ctx: callables.append(ctx[token]) ...
ken[4:]) if not callable(python_function): raise Exception( 'Token %s is not a callable in expression %s' % (token, representation) ) callables.append(python_function) ...
msteinhoff/foption-bot
src/python/tools/cleandb.py
Python
mit
1,658
0.001809
# -*- coding: UTF-8 -*- """ $Id$ $URL$ Copyright (c) 2010 foption Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modif...
license, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS",
WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHER...
kYc0o/RIOT
dist/tools/dhcpv6-pd_ia/pkg/apt.py
Python
lgpl-2.1
703
0
# -*- coding: utf-8 -*- # v
im:fenc=utf-8 # # Copyright (C) 2020 Freie Universität Berlin # # This file is subject to the terms and conditions of the GNU Lesser # General Public License v2.1. See the file LICENSE in the top level # directory for more details. import subprocess from .base import Installer __author__ = "Martine S. Lenders" __cop...
rlin" __credits__ = ["Martine S. Lenders"] __license__ = "LGPLv2.1" __maintainer__ = "Martine S. Lenders" __email__ = "m.lenders@fu-berlin.de" class Apt(Installer): def _install(self, package): subprocess.run(["apt-get", "-y", "install", package[self.os]["name"]])
poldrack/openfmri
pipeline/fs_setup.py
Python
bsd-2-clause
2,291
0.030554
#!/usr/bin/env python """ fs_setup.py - set up directories for freesurfer analysis """ ## Copyright 2011, Russell Poldrack. All rights reserved. ## Redistribution and use in source and binary forms, with or without modification, are ## permitted provided that the following conditions are met: ## 1. Redistributions...
epl/utexas/poldracklab/openfmri/subdir' outfile=open('fs_setup.sh','w') #subdir=basedir+'subdir' if not basedir[-1]=='/': basedir=basedir+'/' if not os.path.exists(basedir+dataset): print '%s/%s does not exist'%(basedir
,dataset) sys.exit(2) #for d in os.listdir(basedir+ds): # if d[0:3]=='sub': for root,dirs,files in os.walk(basedir+dataset): if root.find(dataset)>-1: for f in files: if f.rfind('highres001.nii.gz')>-1: f_split=root.split('/') outfile.write('recon-all -i %s/%s -subjid %s_%s -...
KamranMackey/readthedocs.org
readthedocs/projects/migrations/0006_add_imported_file.py
Python
mit
8,964
0.008701
# encoding: 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 'ImportedFile' db.create_table('projects_importedfile', ( ('id', self.gf('djang...
Revision'}, 'comment': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'created_date': ('dj
ango.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'diff': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'file': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'revisions'", 'to': "orm['projects.File']"}), 'id':...
BeardedPlatypus/capita-selecta-ctf
ctf/players/admin.py
Python
mit
126
0.007937
from django.contrib import
admin from .models
import Question # Register your models here. admin.site.register(Question)
Collisionc/sickbeard_mp4_automator
postCouchPotato.py
Python
mit
2,496
0.002804
#!/usr/bin/env python import sys import os import logging from extensions import valid_tagging_extensions from readSettings import ReadSettings from mkvtomp4 import MkvtoMp4 from tmdb_mp4 import tmdb_mp4 from autoprocess import plex from post_processor import PostProcessor from logging.config import fileConfig logpat...
'File is valid') output = converter.process(inputfile, original=original) if output: # Tag with metadata if settings.tagfile and output['output_extension'] in
valid_tagging_extensions: log.info('Tagging file with IMDB ID %s', imdbid) try: tagmp4 = tmdb_mp4(imdbid, original=original, language=settings.taglanguage) tagmp4.setHD(output['x'], output['y']) tagmp4.writeTags(output['output']...
supert-is-taken/film-sorter
film_sorter.py
Python
gpl-3.0
3,764
0.005579
#!/usr/bin/env python ''' Files and renames your films according to genre using IMDb API supert-is-taken 2015 ''' from imdb import IMDb import sys import re import os import errno import codecs db=IMDb() def main(argv): for filename in sys.argv[1:]: print filename movie_list=db.search_movie( c...
s.replace(".H.", " ") s = s.replace(".", " ") s = s.rep
lace("mkv", "") s = s.replace("X264", "") s = s.replace("x264", "") s = s.replace("avi", "") s = s.replace("mp4", "") s = s.replace("720p", "") s = s.replace("1080p", "") s = s.replace("BluRay", "") s = s.replace("Bluray", "") s = s.replace("bluray", "") s = s.replace("DTS", "") ...
rohitranjan1991/home-assistant
homeassistant/components/mazda/diagnostics.py
Python
mit
1,836
0.000545
"""Diagnostics support for the Mazda integration.""" from __future__ import annotations from typing import Any from homeassistant.components.diagnostics.util import async_redact_data from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_EMAIL, CONF_PASSWORD from homeassistant.core ...
helpers.device_registry import DeviceEntry from .const import DATA_COORDINATOR, DOMAIN TO_REDACT_INFO = [CONF_EMAIL, CONF_PASSWORD] TO_REDACT_DATA = ["vin", "id", "latitude", "longitude"] asy
nc def async_get_config_entry_diagnostics( hass: HomeAssistant, config_entry: ConfigEntry ) -> dict[str, Any]: """Return diagnostics for a config entry.""" coordinator = hass.data[DOMAIN][config_entry.entry_id][DATA_COORDINATOR] diagnostics_data = { "info": async_redact_data(config_entry.data, ...
edu-zamora/inimailbot
cron_updater.py
Python
gpl-3.0
2,032
0.02313
# ### # Copyright (c) 2010 Konstantinos Spyropoulos <inigo.aldana@gmail.com> # # This file is part of inimailbot # # inimailbot 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, ...
e.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from receive_ankicrashes import Bug class ScanIssues(webapp.RequestHandler): def get(self): bugs_query = Bug.all() bugs_query.filter('linked =', False) bugs = [] bugs = bugs_query.fetch(1000) for bg in bugs: issues =...
) + " to issue " + str(bg.issueName)) bg.put() class UpdateStatusesPriorities(webapp.RequestHandler): def get(self): bugs_query = Bug.all() #bugs_query.filter('issueName !=', None) bugs_query.filter('linked =', True) bugs = [] bugs = bugs_query.fetch(1000) logging.debug("Cron job updater, found " + st...
trustedhousesitters/roster-python
setup.py
Python
mit
860
0.003488
from setuptools import setup, find_packages setup( name='roster', version='1.0', description='Roster: A library for simple service discovery using Dynamodb for Python', long_description=open('README.md').read(), author='Tim Rijavec', author_email='tim@trustedhousesitters.com',
url='https://github.com/trustedhousesitters/roster-python', license='MIT', packages=find_packages(exclude=('example', 'examples', )), include_package
_data=True, zip_safe=False, classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Service Discovery', '...
porimol/django-blog
cms/migrations/0004_auto_20160508_2117.py
Python
mit
468
0
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-05-08 21:17 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cms', '0003_auto_20160508_2115'), ] operations = [ m
igrations.AlterField( model_name='post', name='featured_photo', field=models.ImageFiel
d(upload_to='/featured_photos'), ), ]
gjwajda/Computational-Tools-For-Big-Data
Exercise2/exercise2_1.py
Python
mit
449
0.062361
#!/usr/bin/python #First Method taking in file "matrix.txt" and printing list of lists #Function1 def readmatrix( file ): list = open( file, 'r' ) return list.readlines(); #Calling function print readmatrix( 'matrix.txt' ) #Funtio
n2 def reverse( list, matrixfile ): file = open( matrixfile, 'w'
) for i in list: file.write(i) file.close() return file; #Calling function reverse( readmatrix('matrix.txt'), 'output.txt' )
okadate/romspy
example/OB500/hview_ob500_grd.py
Python
mit
263
0
# -*- coding: utf-8 -*- import romspy romspy.hview('nc/ob500_grd-v5.nc
', 'ob500_grd-v5.png', vname='h', cblabel='Depth[m]', vmax=0, vmin=-120, interval=20, cff=-1, obsfile='nc/ob500_obs_tsdc.nc')
AxiaCore/django-extlog
django_extlog/middleware.py
Python
mit
2,967
0
from django.db.models import signals from django.utils.functional import curry from django.contrib.contenttypes.models import ContentType from django.core import serializers from django.contrib.admin.models import LogEntry from django.contrib.sessions.models import Session from django_extlog.models import ExtLog cla...
, user) else: self._save_to_log(instance, ExtLog.ACTION_TYPE_UPDATE, user) def _update_post_delete_info( self, user, session, sender, instance
, **kwargs ): if sender in [LogEntry, Session]: return self._save_to_log(instance, ExtLog.ACTION_TYPE_DELETE, user)
diogocs1/facebookexplorer
teste.py
Python
apache-2.0
144
0.020833
f
rom appkit.api.v0_2_8 import App app = App(__name__) @app.route("/") def home(): return '<a href="#" target="_blank">Clique</a>'
app.run()
soft-matter/mr
customized_trackpy/tracking.py
Python
gpl-3.0
24,253
0.001938
#Copyright 2012 Thomas A Caswell #tcaswell@uchicago.edu #http://jfi.uchicago.edu/~tcaswell # #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) an...
''' :rtype: bool Retu
rns if a point is associated with a track ''' return self._track is not None @property def track(self): """Returns the track that this :class:`Point` is in. May be `None` """ return self._track class PointND(Point): ''' :param t: a time-like variable. :param pos: position...
dtaht/ns-3-dev
src/flow-monitor/bindings/modulegen__gcc_LP64.py
Python
gpl-2.0
411,996
0.015158
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers import pybindgen.settings import warnings class ErrorHandler(pybindgen.settings.ErrorHandler): def handle_error(self, wrapper, exception, traceback_): warnings.warn("exception %r in wrapper %s" % (exception, wrapper)) ...
k'): ns3::Ipv4Address [class] module.add_class('Ipv4Address', import_from_module='ns.network') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Inte...
net') ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e [enumeration] module.add_enum('InterfaceAddressScope_e', ['HOST', 'LINK', 'GLOBAL'], outer_class=root_module['ns3::Ipv4InterfaceAddress'], import_from_module='ns.internet') ## ipv4-address.h (module 'ne...
tommeagher/pythonGIJC15
scripts/completed/quakes_complete.py
Python
mit
980
0.006122
import requests import unicodecsv from io import StringIO #what country has the most serious earthquakes lately? url = "http://python-gijc15.s3.eu-central-1.amazonaws.com/all_month.csv" r = requests.get(url) text = StringIO(r.text) reader = unicodecsv.DictReader(text, dialect='excel') new_collection = [] for row i...
rip() #write the results to a new csv filename = "serious_quakes.csv" print new_collection[0].keys() fieldnames = [u'time', u'latitude', u'longitude', u'mag', u'type', u'id', u'place', u'nearest'] with open(filename, "wb") as f: writer = unicodecsv.DictWriter(f, fieldnames=fieldnames, extrasaction='ignore') ...
writer.writeheader() for item in new_collection: writer.writerow(item)
echevemaster/fedora-college
docs/source/conf.py
Python
bsd-3-clause
8,753
0.004798
#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- coding: utf-8 -*- # # This file is based upon the file generated by sphinx-quickstart. However, # where sphinx-quickstart hardcodes values in this file that you input, this # file has been changed to pull from your module's metadata module. # # This file is execfile(...
description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base nam...
eX output ------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Groupin...
tmerr/bank_wrangler
bank_wrangler/report/__init__.py
Python
gpl-3.0
2,519
0.000794
import os from glob import glob from itertools import chain from typing import Iterable import json import jinja2 import shutil from bank_wrangler import schema def _generate_data_json(transactions, accounts): transactions = [list(map(str, row)) for row in transactions] return json.dumps({...
} # used by base.html env.globals = { 'cssimports': css_names, 'jsimports': js_names, 'pages': [{'name': title, 'url': filename} for title, filename
in pages.items()], } return {filename: env.get_template(filename).render(selectedpage=filename) for filename in pages.values()} def generate(root, transactions, accounts: Iterable[str]): """Write the report to <root>/report directory.""" reportdir = os.path.dirname(os.path.abspath(__file_...
rpm-software-management/dnf
dnf/subject.py
Python
gpl-2.0
1,150
0.00087
# subject.py # Implements Subject. # # Copyright (C) 2012-2016 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is ...
# source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from __future__ import absolute_import from __future__ import print_function from __future__ impo
rt unicode_literals from hawkey import Subject # :api
HybridF5/jacket
jacket/tests/compute/unit/virt/disk/test_inject.py
Python
apache-2.0
11,880
0.000084
# Copyright (C) 2012 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
import fixtures from jacket.compute import exception from jacket.compute import test from jacket.tests.compute.unit.virt.disk.vfs import fakeguestfs from jacket.compute.virt.disk import api as diskapi from jacket.compute.virt.disk.vfs import guestfs as vfsguestfs from jacket.compute.virt.image import model as imgmodel...
s.guestfs.guestfs', fakeguestfs)) self.file = imgmodel.LocalFileImage("/some/file", imgmodel.FORMAT_QCOW2) def test_inject_data(self): self.assertTrue(diskapi.inject_data( imgmodel.LocalFileImage("/some/fil...