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
tonyli71/designate
designate/dnsutils.py
Python
apache-2.0
13,265
0.000075
# Copyright 2014 Hewlett-Packard Development Company, L.P. # # Author: Endre Karlson <endre.karlson@hp.com> # # 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/lice...
response = self.application(request) return self.process_response(response) def _build_error_response(self): response = dns.message.make_response( dns.message.make_query('unknown', dns.rdatatype.A))
response.set_rcode(dns.rcode.FORMERR) return response class SerializationMiddleware(DNSMiddleware): """DNS Middleware to serialize/deserialize DNS Packets""" def __init__(self, application, tsig_keyring=None): self.application = application self.tsig_keyring = tsig_keyring d...
open-mmlab/mmdetection
mmdet/datasets/pipelines/formating.py
Python
apache-2.0
293
0
#
Copyright (c) OpenMMLab. All rights reserved. # flake8: noqa import warnings from .formatting import * warnings.warn('DeprecationWarning: mmdet.datasets.pipelines.formating will be ' 'deprecated, please replace it
with ' 'mmdet.datasets.pipelines.formatting.')
JshWright/home-assistant
tests/components/sensor/test_statistics.py
Python
apache-2.0
3,733
0
"""The test for the statistics sensor platform.""" import unittest import statistics from homeassistant.setup import setup_component from homeassistant.const import (ATTR_UNIT_OF_MEASUREMENT, TEMP_CELSIUS) from tests.common import get_test_home_assistant class TestStatisticsSensor(unittest.TestCase): """Test the...
for value in self.values: self.hass.states.set('sensor.test_monitored', value, {ATTR_UNIT_OF_MEASUREMENT: TEM
P_CELSIUS}) self.hass.block_till_done() state = self.hass.states.get('sensor.test_mean') self.assertEqual(3.8, state.attributes.get('min_value')) self.assertEqual(14, state.attributes.get('max_value'))
liukaijv/XlsxWriter
xlsxwriter/test/comparison/test_image_anchor05.py
Python
bsd-2-clause
1,181
0
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2015, John McNamara, jmcnamara@cpan.org # from ..excel_comparsion_test import ExcelComparisonTest from ...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest): """...
et': 1, '
y_offset': 2, 'positioning': 2}) workbook.close() self.assertExcelEqual()
melangemark/exif-py
exifread/__init__.py
Python
bsd-3-clause
11,014
0.001725
""" Read Exif metadata from tiff and jpeg files. """ from .exif_log import get_logger from .classes import * from .tags import * from .utils import ord_ __version__ = '2.1.1' logger = get_logger() def increment_base(data, base): return ord_(data[base + 2]) * 256 + ord_(data[base + 3]) + 2 def process_file(f,...
logger.debug(" APP14 Adobe segment at base 0x%X", base) logger.debug(" Length: 0x%X 0x%X", ord_(data[base + 2]), ord_(data[base + 3])) logger.debug(" Code: %s", data[base + 4:base + 8]) increment = increme
nt_base(data, base) logger.debug(" Increment base by %s", increment) base += increment logger.debug(" There is useful EXIF-like data here, but we have no parser for it.") elif data[base:base + 2] == b'\xFF\xDB': logger.debug(" JPEG image data...
jessekl/flixr
fbone/modules/user/__init__.py
Python
mit
146
0
# -
*- coding: utf-8 -*- from .models import User from .views import user from .constants import USER_ROLE, ADMIN, USER, USER_STATUS, NEW, ACTI
VE
phinexus/jenkins-job-builder
jenkins_jobs/registry.py
Python
apache-2.0
18,370
0.000054
#!/usr/bin/env python # Copyright (C) 2015 OpenStack, 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...
nonempty_component_list_types: self._expand_macros_for_component_list_type( jobish, component_list_type, template_data) def _expand_macros_for_component_list_type(self, jobish,
component_list_type, template_data=None): """In-place expansion of macros on jobish. :arg dict jobish: A job-like JJB data structure. Could be anything that might provide JJB "components" that get expanded to XML configuration. ...
anthonygarvan/wordgalaxy
processing/main.py
Python
mit
1,256
0.012739
import json import
random #from sklearn.manifold import TSNE from tsne import bh_sne from numpy.random import rand from sklearn.preprocessing import MinMaxScaler from time import time import numpy as np start_time = ti
me() n_samples = 20000 #wordlist = ["word-%d" % i for i in range(n_samples)] #print "creating random samples..." #X_raw = rand(n_samples,250) f = open("data/vectors0.txt", 'r') isHeader = True X_list = [] word_list = [] for line in f: if not isHeader: entries = line.strip().split(' ') #print "length: %d" % ...
unrza72/qplotutils
qplotutils/ui/resources_rc.py
Python
mit
38,372
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Resource object code # # Created by: The Resource Compiler for PyQt5 (Qt v5.11.1) # # WARNING! All changes made in this file will be lost! from qtpy import QtCore qt_resource_data = b"\ \x00\x00\x01\x65\ \x3c\ \x73\x76\x67\x20\x78\x6d\x6c\x6e\x73\x3d\x22\x68\x74\x74\x...
x73\x74\x79\x6c\x65\x3e\ \x0a\x20\x20\x3c\x2f\x64\x65\x66\x73\x3e\x0a\x20\x3c\x70\x61\x74\ \x68\x20\x73\x74\x79\x6c\x65\x3d\x22\x66\x69\x6c\x6c\x3a\x63\x75\ \x72\x72\x65\x6e\x7
4\x43\x6f\x6c\x6f\x72\x3b\x66\x69\x6c\x6c\x2d\ \x6f\x70\x61\x63\x69\x74\x79\x3a\x31\x3b\x73\x74\x72\x6f\x6b\x65\ \x3a\x6e\x6f\x6e\x65\x22\x0a\x20\x20\x20\x20\x20\x64\x3d\x22\x6d\ \x20\x34\x20\x34\x20\x30\x20\x31\x36\x20\x4c\x20\x31\x32\x20\x31\ \x32\x20\x5a\x20\x4d\x20\x31\x32\x20\x31\x32\x20\x31\x32\x20\x32\ \x30\x20\...
ryfeus/lambda-packs
pytorch/source/caffe2/python/scope_test.py
Python
mit
5,113
0.001173
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import scope, core, workspace from caffe2.proto import caffe2_pb2 import unittest import threading import time SUCCESS_COUNT = 0 def thread_runner(...
: t.start() with scope.NameS
cope("master"): self.assertEquals(scope.CurrentDeviceScope(), None) self.assertEquals(scope.CurrentNameScope(), "master/") for t in threads: t.join() self.assertEquals(scope.CurrentNameScope(), "master/") self.assertEquals(scope.CurrentDeviceS...
gjbex/atools
lib/areduce.py
Python
gpl-3.0
5,227
0
#!/usr/bin/env python from argparse import ArgumentParser import os import shlex import subprocess import sys from vsc.atools.int_ranges import int_ranges2set, InvalidRangeSpecError from vsc.atools.config import (get_var_config, get_mode_config, ConfigFileError) if __name__ == '__main...
ern', help='file name pattern') arg_parser.add_argument('--mode', choices=['text', 'csv', 'body'], help='predefined reduction mode to use') script_
group = arg_parser.add_argument_group(title='reduction scripts') script_group.add_argument('--empty', help='script to create empty ' 'output file to use') script_group.add_argument('--empty_args', help='additional command line arguments...
nickromano/django-slow-tests
_examples/django17/firstapp/wsgi.py
Python
mit
389
0.002571
""" WSGI co
nfig for mysite project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "firstapp.settings") from django.core.wsgi import ...
n()
online-behaviour/machine-learning
combineCsv.py
Python
apache-2.0
3,006
0.013639
#!/usr/bin/python -W all """ combineCsv.py: adapt values in a csv file based on values in a second file usage: combineCsv.py [-c] -k column -v column -F file2 -K column -V column < file1 notes: changes values in column v of file1 to value in column V of file2 when values in key columns k and K match optio...
: print all) 20170608 erikt(at)xs4all.nl """ import csv import getopt import re import sys # definition constants COMMAND = sys.argv.pop(0) NONE = -1 USAGE = COMMAND+": -k column -v column -F file2 -K column -V column < file1" # definition variables file1keyColumn = NONE file1valueColumn = NONE file2name = "" file2ke...
n = NONE changedSelect = False def readCsv(fileName,keyColumn,valueColumn): data = {} with open(fileName,"rb") as csvfile: csvreader = csv.reader(csvfile,delimiter=',',quotechar='"') for row in csvreader: if len(row) < keyColumn or len(row) < valueColumn: sys.exit(CO...
anchore/anchore-engine
tests/functional/clients/standalone/package_list/test_debian.py
Python
apache-2.0
2,618
0.000382
import pytest from . import path_params from .fixtures import debian class TestDebianPaths: @pytest.mark.parametrize("path", path_params(debian.pkgfiles_all)) def test_pkgfiles_all(self, analyzed_data, path): result = analyzed_data("stretch-slim") pkgs = result["image"]["imagedata"]["analysis...
ort"]["package_list"][ "pkgs.allinfo" ]["base"] loaded = pkgs.get(pkg, {}) # a separate test exists just for the licenses attribute, leave this out of the assertion loaded = dict(loaded) loaded.pop("license") metadata = dict(metadata) metadata.pop("li...
rted(metadata["cpes"]) assert loaded == metadata @pytest.mark.parametrize("pkg,metadata", debian.pkgs_allinfo.items()) def test_pkgs_allinfo_license(self, analyzed_data, pkg, metadata): result = analyzed_data("stretch-slim") pkgs = result["image"]["imagedata"]["analysis_report"]["packa...
robertbasic/perfi-flask
perfi.py
Python
mit
1,220
0.002459
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from flask import Flask, request, render_template, session, url_for, flash,\ redirect from function_decorators import login_required, redirect_if_logged_in from forms import LoginForm import appconfig app = Flask(__name__) @app.route("/...
T" and form.validate(): email = form.email.data password = form.password.data # TODO: needs proper login here if email == "test@perfi.local" and password == "test":
session['logged_in'] = True flash("Logged in!") return redirect(url_for("index")) return render_template('login.html', form=form) @app.route('/logout/') @login_required def logout(): session.pop('logged_in', None) flash("Logged out!") return redirect(url_for('login')) def...
interlegis/sigi
sigi/apps/eventos/urls.py
Python
gpl-2.0
830
0.001205
# coding: utf-8 from django.conf.urls import patterns, url urlpatterns = patterns( 'sigi.apps.eventos.views', # Painel de ocorrencias url(r'^calendario/$', 'calendario', name='eventos-calendario'), url(r'^alocacaoequipe/$', 'alocacao_equipe', name='eventos-alocacaoequipe'), # Carrinho url(r'^e...
inho/excluir_carrinho/$', 'excluir_carrinho', name='excluir-carrinho-evento'), # Error url(r'^evento/carrinho/deleta_itens_carrinho$', 'deleta_itens_carrinho', name='deleta-itens-carrinho-evento'), # Error url(r'^e
vento/csv/$', 'export_csv', name='evento-export-csv'), # Error url(r'^evento/(?P<id>\w+)/declaracao/$', 'declaracao', name='evento-declaracao'), )
rochacbruno/dynaconf
example/issues/449_django_lazy_path/foo/urls.py
Python
mit
996
0
"""foo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based vie...
1. Add an import:
from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.conf import settings from d...
KillingJacky/CloudPan
pan2mqtt.py
Python
mit
12,826
0.009512
#!/usr/bin/python # -*- coding:utf-8 -*- #dependence: paho-mqtt (pip install paho-mqtt) # XBee (pip install XBee) # PyYAML (pip install PyYaml) # pyserial (pip install pyserial) import os import sys import time import logging import yaml from serial import Serial from factory import *...
self.pan = Factory(
self.config['pan']['driver_class']) if not self.pan: self.__log(logging.ERROR, "Can't instant pan driver") sys.exit(2) self.pan.logger = logger self.pan.on_message = self.on_message_from_pan self.stdout = self.config['general']['stdout'] self.stderr = sel...
eduherraiz/naniano
src/apconf/mixins/filerconf.py
Python
gpl-2.0
5,114
0.001955
# -*- coding: utf-8 -*- from os.path import join, abspath from apconf import Options from configurations import Settings opts = Options() def get(value, default): return opts.get(value, default, section='Filer') class FilerMixin(object): """Settings para django-filer y easy_thumbnails""" THUMBNAIL_PR...
'thumbnails': { 'ENGINE': 'filer.server.backends.nginx.NginxXAccelRedirectServer', 'OPTIONS': {
'location': self.filer_private_thumbnails_path, 'nginx_location': '/nginx_filer_private_thumbnails', }, }, }, } @property def FILER_STORAGES(self): """Filer config to set custom private media ...
biocore/qiita
qiita_db/test/test_util.py
Python
bsd-3-clause
56,304
0
# ----------------------------------------------------------------------------- # Copyright (c) 2014--, The Qiita Development Team. # # Distributed under the terms of the BSD 3-clause License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
ases self.assertFalse(qdb.util.exists_table("sample_2")) self.assertFalse(qdb.util.exists_table("prep_3")) self.assertFalse(qdb.util.exists_table("foo_table")) self.assertFalse(qdb.util.exists_table("bar_table"))
def test_convert_to_id(self): """Tests that ids are returned correctly""" self.assertEqual( qdb.util.convert_to_id("directory", "filepath_type"), 8) self.assertEqual( qdb.util.convert_to_id("private", "visibility", "visibility"), 3) self.assertEqual( ...
OiNutter/rivets
rivets/utils.py
Python
mit
481
0.029106
import codecs import re UTF8_BOM_PATTERN = re.compile("\\A(\\xFE\\xFF|\\xFF\\xFE)".encode('utf-8')) def read_unicode(filename,external_encoding='utf8'): data = codecs.open(filename,encoding=external_encoding).read() i
f UTF8_BOM_PATTERN.match(data): return unicode(UTF8_BOM_PATTERN.sub('',data)).encode('utf8') else: return unicode(data).encode('utf8'
) def unique_list(seq): seen = set() seen_add = seen.add return [x for x in seq if x not in seen and not seen_add(x)]
great-expectations/great_expectations
great_expectations/expectations/metrics/column_map_metrics/column_values_not_match_like_pattern_list.py
Python
apache-2.0
1,597
0.001252
import logging from great_expectations.execution_engine.sqlalchemy_execution_engine import ( SqlAlchemyExecutionEngine, ) from great_expectations.expectations.metrics.impor
t_manager import sa from great_expectations.expectations.metrics.map_metric_provider import ( ColumnMapMetricProvider, column_condition_partial, ) from great_expectations.expectations.metrics.util import ( get_dialect_like_pattern_expression, ) logger = logging.getLogger(__name__) class ColumnValuesNotMa...
st(ColumnMapMetricProvider): condition_metric_name = "column_values.not_match_like_pattern_list" condition_value_keys = ("like_pattern_list", "match_on") @column_condition_partial(engine=SqlAlchemyExecutionEngine) def _sqlalchemy(cls, column, like_pattern_list, _dialect, **kwargs): if len(like_...
mapsme/subways
process_subways.py
Python
apache-2.0
12,971
0.002004
#!/usr/bin/env python3 import argparse import json import logging import os import re import sys import time import urllib.parse import urllib.request from processors import processor from subway_io import ( dump_yaml, load_xml, make_geojson, read_recovery_data, write_recovery_data, ) from subway_st...
thout_center: if not calculate_relation_center(rel): new_relations_without_center.append(rel)
if len(new_relations_without_center) == len(relations_without_center): break relations_without_center = new_relations_without_center if relations_without_center: logging.error("Cannot calculate center for the relations (%d in total): %s%s", len(relations_without_c...
veger/ansible
lib/ansible/modules/network/f5/bigip_virtual_server.py
Python
gpl-3.0
117,586
0.002415
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright: (c) 2017, F5 Networks Inc. # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', ...
directly to the destination IP address specified in the client request. - When C(performance-http), specifies a virtual server with which you associate a Fast HTTP profile. Together, the virtual server and profile increase the speed at which the virtual serve
r processes HTTP requests. - When C(performance-l4), specifies a virtual server with which you associate a Fast L4 profile. Together, the virtual server and profile increase the speed at which the virtual server processes layer 4 requests. - When C(stateless), specifies a virtual server that...
dsavransky/EXOSIMS
EXOSIMS/Prototypes/ZodiacalLight.py
Python
bsd-3-clause
18,611
0.009511
# -*- coding: utf-8 -*- from EXOSIMS.util.vprint import vprint from EXOSIMS.util.get_dirs import get_cache_dir import numpy as np import astropy.units as u import os try: import cPickle as pickle except: import pickle import sys from astropy.time import Time # Python 3 compatibility: if sys.versi...
and methods necessary to perform Zodiacal Light Module calculations in exoplanet mission simulation. Args: specs: user specified values Attributes: magZ (float): 1 zodi brightness magnitude (per arcsec2) magEZ (float): 1 exo-z...
ight variation (variance of log-normal distribution) fZ0 (astropy Quantity): default surface brightness of zodiacal light in units of 1/arcsec2 fEZ0 (astropy Quantity): default surface brightness of exo-zodiacal light in units of 1/arcsec2 cachedir (str): ...
DGA-MI-SSI/YaCo
deps/swig-3.0.7/Examples/test-suite/python/li_std_except_as_class_runme.py
Python
gpl-3.0
657
0
from li_std_except_as_class import * # This test is expected to fail with -builtin option. # Throwing builtin classes as exceptions not supported if is_python_builtin():
try: test_domain_error() except RuntimeError: pass try: test_domain
_error() except RuntimeError: pass try: test_domain_error() except RuntimeError: pass else: # std::domain_error hierarchy try: test_domain_error() except domain_error: pass try: test_domain_error() except logic_error: pass try: ...
opendatateam/udata
udata/tests/dataset/test_dataset_actions.py
Python
agpl-3.0
741
0
import pytest from udata.core.dataset.actions import archive from udata.core.dataset.factories import VisibleDatasetFactory from udata.core.discussions.models import D
iscussion from udata.core.user.factories import UserFactory @pytest.mark.usefixtures('clean_db') class DatasetActionsTest: def test_dataset_archive(self, app): user = UserFactory() app.config['ARCHIVE_COMMENT_USER_ID'] = user.id dataset = VisibleDatasetFactory() archive(dataset,...
) assert len(discussions) == 1 assert 'archived' in discussions[0].discussion[0].content
gstiebler/odemis
src/odemis/dataio/__init__.py
Python
gpl-2.0
4,684
0.002564
# -*- coding: utf-8 -*- """ Created on 17 Aug 2012 @author: Éric Piel Copyright © 2012 Éric Piel, Delmic This file is part of Odemis. Odemis is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. Odemis is...
O_WRONLY, allowlossy=False): """ Find the most fitting exporter according to a filename (actually, its extension) filename (string): (path +) filename with extension default (dataio. Module): default exporter to pick if no re
ally fitting exporter is found mode: cf get_available_formats() allowlossy: cf get_available_formats() returns (dataio. Module): the right exporter """ # Find the extension of the file basename = os.path.basename(filename).lower() if basename == "": raise ValueError("Filename s...
kubernetes-client/python
kubernetes/client/models/v1_server_address_by_client_cidr.py
Python
apache-2.0
5,238
0
# coding: utf-8 """ Kubernetes No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: release-1.23 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import si...
hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() ...
lt def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if ...
robinandeer/puzzle
puzzle/plugins/vcf/mixins/variant_extras/genotype.py
Python
mit
1,708
0.014052
import logging from vcftoolbox import Genotype from puzzle.models import Genotype as puzzle_genotype logger = logging.getLogger(__name__) class GenotypeExtras(object): """Class to store methods that deals with genotyping""" def _add_genotype_calls(self, variant_obj, variant_line, case_obj): """Add ...
#if there is gt calls we have no individuals to add if len(variant_line) > 8: gt_format = variant_line[8].split(':') for individual in case_obj.individuals: sample_id = individual.ind_id index = individual.ind_index gt_call = variant_line...
gt_call)) genotype = Genotype(**raw_call) variant_obj.add_individual(puzzle_genotype( sample_id = sample_id, genotype = genotype.genotype, case_id = case_obj.name, phenotype = individual.phenotype, ...
klahnakoski/SpotManager
vendor/jx_elasticsearch/rollover_index.py
Python
mpl-2.0
13,558
0.003393
# encoding: utf-8 # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # # Contact: Kyle Lahnakoski (kyle@lahnakoski.com) # from __future__ import unicode_literals import ...
t Date, unicode2Date, unix2Date from mo_times.durations import Duration from mo_times.timer import Timer from pyLibrary.aws.s3 import KEY_IS_WRONG_FORMAT, strip_extension MAX_RECORD_LENGTH = 400000 DATA_TOO_OLD = "data is too old to be indexed" DEBUG = False class RolloverIndex(object): """ MIMIC THE elastic...
rollover_field, # the FIELD with a timestamp to use for determining which index to push to rollover_interval, # duration between roll-over to new index rollover_max, # remove old indexes, do not add old records schema, # es schema queue_size=10000, # numb...
tgalal/yowsup
yowsup/layers/protocol_calls/__init__.py
Python
gpl-3.0
41
0
from .laye
r import
YowCallsProtocolLayer
szibis/ansible-modules-core
cloud/amazon/iam.py
Python
gpl-3.0
28,918
0.003666
#!/usr/bin/python # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed...
- Luigi register: new_groups - name: iam: iam_type: user name: jdavila state: update groups: "{{ item.created_group.group_na
me }}" with_items: new_groups.results ''' import json import itertools import sys try: import boto import boto.iam import boto.ec2 HAS_BOTO = True except ImportError: HAS_BOTO = False def boto_exception(err): '''generic error message handler''' if hasattr(err, 'error_message'): e...
xiongerqi/enki
sample/cookbook/chapter1/5priority_quene.py
Python
bsd-2-clause
717
0.026499
#! /usr/bin/env python import heapq class PriorityQueue: def __init__(self): self._queue=[] self._index=0 def push(self,item,priority): heapq.heappush(self._queue
,(-priority,self._index,item)) self._index += 1 def pop(self): return heapq.heappop(self._queue)[-1] class Item:
def __init__(self,name): self.name = name def __repr__(self): return 'Item({!r})'.format(self.name) if __name__ == '__main__': q = PriorityQueue(); item = Item('foo') q.push(item,1) q.push(Item('bar'),5) q.push(Item('spam'),4) q.push(Item('gork'),1) print q.pop() ...
williezh/hotelbooksystem
DJangoHotel/viewspackage/roomInfoView.py
Python
mit
584
0.023973
# -*- coding: utf-8 -*- from django.shortcuts import render from qiniuyun.backend import QiniuPush from qiniuyun.models import ImageAtQiniu from .indexView import ImgList from DJangoHotel.m
odels import RoomInfo def roomInfo(request): rooms=RoomInfo.objects.all() imgObjs=ImageAtQiniu.objects.all() imgUrls=[QiniuPush.private_download_url(i.fullname) for i in imgObjs] imgs=ImgList() for i in imgUrls: if 'hotel-logo' in i: imgs.logo=i
return render(request,'roominfo.html',{'roomInfoList':rooms,'img':imgs})
praekelt/seed-stage-based-messaging
contentstore/management/commands/sync_schedules.py
Python
bsd-3-clause
656
0
from django
.core.management.base import BaseCommand from contentstore.models import Schedule from contentstore.tasks import sync_schedule class Command(BaseCommand): help = "Synchronises all schedules with the scheduler" def handle(self, *args, **kwargs): count = 0 self.stdout.write("Fetching schedules...
erator(): self.stdout.write("Synchronising schedule {}".format(schedule.id)) sync_schedule(str(schedule.id)) count += 1 self.stdout.write( self.style.SUCCESS("Synchronised {} schedule/s".format(count)) )
qsnake/h5py
h5py/tests/low/test_h5r.py
Python
bsd-3-clause
1,721
0.005811
#+ # # This file is part of h5py, a low-level Python
interface to the HDF5 library. # # Copyright (C) 2008 Andrew Collette # http://h5py.alfven.org # License: BSD (See LICENSE.txt for full license) # # $Date$ # #- from h5py import tests from h5py import * class TestBasic(tests.HTest): def setUp(self): self.fid, self.name = tests.gettemp() self....
mport os self.fid.close() os.unlink(self.name) def test_obj(self): """ (H5R) Object reference round-trip """ ref = h5r.create(self.id, '/', h5r.OBJECT) self.assertIsInstance(ref, h5r.Reference) self.assertEqual(h5r.dereference(ref, self.fid), self.id) def test_r...
mikalstill/nova
nova/tests/functional/notification_sample_tests/test_instance.py
Python
apache-2.0
83,743
0.000155
# 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...
'instance-live_migration_rollback_dest-start', replacements={ 'reservation_id': server['reservation_id'], 'uuid': server['id']}, actual=fake_notifier.VERSIONED_N
OTIFICATIONS[2]) self._verify_notification( 'instance-live_migration_rollback_dest-end', replacements={ 'reservation_id': server['reservation_id'], 'uuid': server['id']}, actual=fake_notifier.VERSIONED_NOTIFICATIONS[3]) def _test_live_migr...
davgibbs/movies-spa
apps/spa_movies/settings.py
Python
gpl-3.0
3,710
0.001078
""" Django settings for spa_movies project. Generated by 'django-admin startproject' using Django 1.9.7. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os...
ages) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") # User uploaded files "Media" MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # Expire
session after 3 hours SESSION_COOKIE_AGE = 60 * 60 * 3 REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticatedOrReadOnly', ) }
edmundgentle/schoolscript
SchoolScript/bin/Debug/pythonlib/Lib/distutils/errors.py
Python
gpl-2.0
3,710
0.005121
"""distutils.errors Provides exceptions used by the Distutils modules. Note that Distutils modules may raise standard exceptions; in particular,
SystemExit is usually raised for errors that are obviously the end-user's fault (eg.
bad command-line arguments). This module is safe to use in "from ... import *" mode; it only exports symbols whose names start with "Distutils" and end with "Error".""" __revision__ = "$Id$" class DistutilsError (Exception): """The root of all Distutils evil.""" pass class DistutilsModuleError (D...
lukas-hetzenecker/home-assistant
homeassistant/components/switchbot/cover.py
Python
apache-2.0
4,846
0.001032
"""Support for SwitchBot curtains.""" from __future__ import annotations import logging from typing import Any from switchbot import SwitchbotCurtain # pylint: disable=import-error from homeassistant.components.cover import ( ATTR_CURRENT_POSITION, ATTR_POSITION, DEVICE_CLASS_CURTAIN, SUPPORT_CLOSE,...
he coordinator.""" self._attr_current_cover_position = self.data["data"]["position"] self._attr_is_closed = self.data["data"]["position"] <= 20 self.async_wri
te_ha_state()
rishubhjain/commons
tendrl/commons/tests/utils/ssh/test_generate_key.py
Python
lgpl-2.1
2,380
0.007143
import pytest from tendrl.commons.utils.ssh.generate_key import GenerateKey from tendrl.commons.utils import ansible_module_runner import mock import maps import __builtin__ from mock import patch def ansible_run(*args): if args[0]: return {"ssh_private_key":"test_ssh_private_key"},"" elif not args[0]...
__', mock.Mock(return_value=None)) @
mock.patch('tendrl.commons.message.Message.__init__', mock.Mock(return_value=None)) def test_constructor(): generate_key = GenerateKey() assert generate_key.attributes["name"] == "root" assert "group" not in generate_key.attributes generate_key = GenerateKey("user_name","User") assert ge...
research-team/NEUCOGAR
NEST/cube/noradrenaline/scripts/parameters.py
Python
gpl-2.0
2,793
0.00179
from property import * # Neuron common parameters iaf_neuronparams = {'E_L': -70., 'V_th': -50., 'V_reset': -67., 'C_m': 2., 't_ref': 2., 'V_m': -60., 'tau_syn_ex': 1., 'tau_syn_i...
or links static_syn = { 'model': 'static_synapse', 'weight': w_Glu * 5, 'delay': pg_delay } # Connection parameters conn_dict = {'rule': 'all_to_all', 'multapses': True} # Device parameters multimeter_param = {'to_memory': True, 'to_file': False, 'witht...
m = {'label': 'spikes', 'withtime': True, 'withgid': True, 'to_file': False, 'to_memory': True, 'scientific': True}
zstackio/zstack-woodpecker
integrationtest/vm/multihosts/vm_snapshots/paths/xsky_path23.py
Python
apache-2.0
1,415
0.016254
import zstackwoodpecker.test_state as ts_header import os TestAction = ts_header.TestAction def path(): return dict(initial_formation="template5", checking_point=8, path_list=[ [TestAction.create_vm, 'vm1', ], [TestAction.create_volume, 'volume1', 'flag=scsi'], [TestAction.attach_volume, 'vm1', 'volume1'], ...
ume3'] Detached:['volume1'] Deleted:['vm1-snapshot1', 'volume1-snapshot1', 'volume2-snapshot1', 'volume3-snapshot1', 'vm1-snapshot8', 'volume2-snapshot8', 'vo
lume3-snapshot8'] Expunged:[] Ha:[] Group: '''
SKIRT/PTS
modeling/config/adapt_fit.py
Python
agpl-3.0
2,495
0.005213
#!/usr/bin/env python # -*- coding: utf8 -*- # ***************************************************************** # ** PTS -- Python Toolkit for working with SKIRT ** # ** © Astr
onomical Observatory, Ghent University ** # ***************************************************************** # Import the relevant PTS classes and modules from pts.modeling.core.environment import load_modeling_environment_cwd from pts.modeling.config.component import definition # --------------------------...
------- # Load environment and model suite environment = load_modeling_environment_cwd() runs = environment.fitting_runs # ----------------------------------------------------------------- properties = ["representation", "filters", "ranges", "genetic", "grid", "units", "types"] # -----------------------------------...
kivy/pyjnius
jnius/reflect.py
Python
mit
18,170
0.004898
from __future__ import absolute_import from __future__ import unicode_literals from __future__ import division from collections import defaultdict from logging import getLogger, DEBUG from six import with_metaclass, PY2 from .jnius import ( JavaClass, MetaJavaClass, JavaMethod, JavaStaticMethod, JavaField, Ja...
for sup, lvl in identify_hierarchy(supercls, level + 1, concrete=concrete): yield sup, lvl # we could use yield from when we drop python2 interfaces = cls.getInterfaces() for interface in interfaces or []: for sup, lvl in identify_hierarchy(interface, level + 1, concrete=concrete): ...
all object extends Object, so if this top interface in a hierarchy, yield Object if not concrete and cls.isInterface() and not interfaces: yield find_javaclass('java.lang.Object'), level +1 yield cls, level # NOTE: if you change the include_protected or include_private default values, # you also must...
vagonbar/GNUnetwork
gwn/scripts/top_block1.py
Python
gpl-3.0
2,723
0.031583
#!/usr/bin/env python ################################################## # GNU Wireless Network Flow Graph # Title: Top Block1 # Generated: Wed Nov 19 11:39:58 2014 ################################################## import os os.chdir("../../scripts/") print os.getcwd() import sys sys.path +=['..'] import blocks.frame...
ct((self.deframer80211_0, 0), (self.eventconsumer_0, 0)) self.connect((self.framer80211_0, 0), (self.psk_0, 0)) self.connect((self.psk_0, 0), (self.deframer80211_0, 0)) ################################################## # Starting Bloks ######################
############################ self.psk_0.start() self.framer80211_0.start() self.eventsim_0.start() self.eventconsumer_0.start() self.deframer80211_0.start() def stop(self): ################################################## # Ending Bloks ################################################## self.psk...
lepture/pydouban
setup.py
Python
bsd-3-clause
336
0.047619
#!/usr/bin/env python from distutils.core
import setup setup( name = 'pydouban', version = '1.0.0', description = 'Lightweight Python Douban API Library', auth
or = 'Marvour', author_email = 'marvour@gmail.com', license = 'BSD License', url = 'http://i.shiao.org/a/pydouban', packages = ['pydouban'], )
rshipp/python-appassure
appassure/api.py
Python
bsd-3-clause
2,430
0.002881
"""Python wrapper for the AppAssure 5 REST API. Provides an abstraction layer for using the AppAssure 5 API. Sends well-formed XML requests through a given AppAssureSession object. """ from collections import OrderedDict class AppAssureAPI(object): """Allows us to request data from the API as a logged-in user.""...
+= self._getXML(item, objname) elif (type(data) == type(dict())) or (type(data) == type(OrderedDict())): # if data is a dict xml = "<%s>" % objname for key, value in data.items(): xml += self._getXML(value, key) xml += "</%s>" % self._getXMLEndTag(...
# assume data is a str xml = '<%s>%s</%s>' % (objname, data, self._getXMLEndTag(objname)) return xml def getXML(self, data, objname=None): """Convert a Python object into XML in the format expected by the AppAssure server. data should be a dict, and objname sh...
ruud-v-a/rhythmbox
plugins/lyrics/JlyricParser.py
Python
gpl-2.0
2,517
0.01907
# -*- Mode: python; coding: utf-8; tab-width: 8; indent-tabs-mode: t; -*- # # Copyright (C) 2012 He Jian <hejian.he@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2,...
f, result, callback, *data): if result is None: callback (None, *data) return result = result.decode('utf-8') m = re.search('<div class=\'title\'><a href=\'(/artist/[^\.]*\.html)\'>', result) if m is None: callback (None, *data) return loader = rb.Loader() loader.get_url ('http://j-lyric.net' ...
e_lyrics (self, result, callback, *data): if result is None: callback (None, *data) return result = result.decode('utf-8') lyrics = re.split ('<p id=\'lyricBody\'>', result)[1] lyrics = re.split ('</p>', lyrics)[0] lyrics = re.sub('<br />', '', lyrics) lyrics = self.title + "\n\n" + lyrics lyrics ...
openpolis/open_municipio
open_municipio/data_import/utils.py
Python
agpl-3.0
9,167
0.006327
""" A misc set of utilities useful in the data-import domain. """ import logging from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned from open_municipio.people.models import Person, municipality from open_municipio.data_import.models import LookupInstitutionCharge, LookupCompanyCharge, Lookup...
nding on the RDBMS of choice. """ sql = "CREATE TABLE %s \n" % table_name sql += "(\n" for (col_name, col_type) in table_schema.items(): sql += " %(col_name)s\t%(col_type)s,\n" % {'col_name': col_name, 'col_type': col_type} # remove last comma (otherwise RBDMS may complain) sql = sql[:...
) def lookup_person(self, external, provider): return LookupPerson.lookup(external, provider) class ChargeMapCache: cache = {} @staticmethod def lookup(external, provider, as_of): if provider in ChargeMapCache.cache: if external in ChargeMapCache.cache[provide...
HopeFOAM/HopeFOAM
ThirdParty-0.1/ParaView-5.0.1/VTK/Rendering/Annotation/Testing/Python/xyPlot3.py
Python
gpl-3.0
6,465
0.012993
#!/usr/bin/env python import vtk from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # create pipeline # pl3d = vtk.vtkMultiBlockPLOT3DReader() pl3d.SetXYZFileName("" + str(VTK_DATA_ROOT) + "/Data/combxyz.bin") pl3d.SetQFileName("" + str(VTK_DATA_ROOT) + "/Data/combq....
enderWindow(renWin) ren1.SetBackground(0.6784,0.8471,0.9020) ren1.SetViewport(0,0,.5,1) ren1.AddActor(outlineActor) ren1.AddActor(lineActor) ren2.SetBackground(1,1,1) re
n2.SetViewport(0.5,0.0,1.0,1.0) ren2.AddActor2D(xyplot) ren2.AddActor2D(xyplot3) renWin.SetSize(790,400) cam1 = ren1.GetActiveCamera() cam1.SetClippingRange(3.95297,100) cam1.SetFocalPoint(8.88908,0.595038,29.3342) cam1.SetPosition(-12.3332,31.7479,41.2387) cam1.SetViewUp(0.060772,-0.319905,0.945498) iren.Initialize() ...
oihane/odoo-addons
contract_school/models/contract_line.py
Python
agpl-3.0
2,130
0
# Copyright 2019 Alfredo de la Fuente - AvanzOSC # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class ContractLine(models.Model): _inherit = 'contract.line' payment_percentage = fields.Float(string='Percentage', default=100.0) user_id = fields....
tner", string="Student", related="contract_id.child_id", store=True) course_id = fields.Many2one( comodel_name="education.course", string="Education Course", related="contract_id.course_id", store=True) school_id = fields.Many2one( comodel_name="res.partner", string="Education Ce...
school_id", store=True) academic_year_id = fields.Many2one( comodel_name="education.academic_year", string="Academic Year", related="contract_id.academic_year_id", store=True) pricelist_id = fields.Many2one( comodel_name="product.pricelist", string="Pricelist", related="contract_...
rainiera/health-hack
models/prep_patient_data.py
Python
unlicense
129
0.007752
__author__ = 'rainierab
abao' """Generates fake patient data. Primary features are height and weight. Primar
y labels are """
victor-o-silva/db_file_storage
demo_and_tests/model_filefields_example/migrations/0002_auto_20180826_0054.py
Python
mit
1,197
0.003342
# Generated by Django 2.1 on 2018-08-26 00:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('model_filefields_example', '0001_initial'), ] operations = [ migrations.AlterField( model_name='book', name='cover', ...
etype'), ), migrations.AlterField( model_name='book', name='pages', field=models.FileField(blank=True, null=True, upload_to='model_filefields_example.BookPages/bytes/filename/m
imetype'), ), migrations.AlterField( model_name='sounddevice', name='instruction_manual', field=models.FileField(blank=True, null=True, upload_to='model_filefields_example.SoundDeviceInstructionManual/bytes/filename/mimetype'), ), ]
isudox/leetcode-solution
python-algorithm/leetcode/problem_962.py
Python
mit
1,140
0
"""962. Maximum Width Ramp https://leetcode.com/problems/maximum-width-ramp/ Given an array A of integers, a ramp is a tuple (i, j) for which i < j and A[i] <= A[j]. The width of suc
h a ramp is j - i. Find the maximum width of a ramp in A. If one doesn't exist, return 0. Example 1: Input: [6,0,8,2,1,5] Output: 4 Explanation: The maximum width ramp is achieved at (i, j) = (1, 5): A[1] = 0 and A[5] = 5. Example 2: Input: [9,8,1,0,1,9,4,0,4,1] Output: 7 Explanation: The maximum width ramp is ...
): A[2] = 1 and A[9] = 1. Note: 2 <= A.length <= 50000 0 <= A[i] <= 50000 """ import bisect from typing import List class Solution: def max_width_ramp(self, a: List[int]) -> int: ramp, size = 0, len(a) candidates = [(a[size - 1], size - 1)] # candidates: i's decreasing, by increasing val...
TAMU-CPT/galaxy-tools
tools/fasta/fasta_remove_id.py
Python
gpl-3.0
846
0.003546
#!/usr/bin/env python import sys import argparse import logging from Bio import SeqIO logging.basicConfig(level=logging.INFO) log = logging.getLogger() def drop_id(fasta_file=None): for rec in SeqIO.parse(fasta_file, "fasta"): rec.description = "" ind = str(rec.seq).find("##") if ( ...
h as from Apollo sequences) to be appended to the end of the previous sequence rec.seq = rec.seq[0:ind] yield rec if __name__ == "__main__": parser = argparse.ArgumentParser(description="Identify shine-dalgarno sequences") parser.add_argument("fasta_file", type=argparse.FileType("r"), help...
se_args() for rec in drop_id(**vars(args)): SeqIO.write([rec], sys.stdout, "fasta")
opesci/devito
devito/types/misc.py
Python
mit
1,443
0
from ctypes import c_int, c_double, c_void_p from devito.types import CompositeObject, LocalObject, Symbol __all__ = ['Timer', 'VoidPointer', 'VolatileInt', 'c_volatile_int', 'c_volatile_int_p'] class Timer(CompositeObject): def __init__(self, name, sections): super().__init__(name, 'profile...
_pic
kle_args = ['name'] class VolatileInt(Symbol): @property def _C_typedata(self): return 'volatile int' _C_typename = _C_typedata @property def _C_ctype(self): return c_volatile_int # ctypes subtypes class c_volatile_int(c_int): pass class c_volatile_int_p(c_void_p): ...
DynamicGravitySystems/DGP
dgp/gui/workspaces/project.py
Python
apache-2.0
517
0
# -*- coding: utf-8 -*- from PyQt5.QtCore import Qt from dgp.core.controllers.project_controllers import AirborneProjectController from .base import WorkspaceTab class ProjectTab(WorkspaceTab): def __init__(self, project: Airborne
ProjectController, parent=None): super().__init__(parent=parent, flags=Qt.Widget) self.project = project @property def title(self) -> str: return f'{self.project.get_attr("name")}' @property def uid(self): return self.project
.uid
foobarbazblarg/stayclean
stayclean-2017-february/display-during-signup.py
Python
mit
6,610
0.002874
#!/usr/bin/python from participantCollection import ParticipantCollection import string import re import datetime import pyperclip # Edit Me! # Remember, this is during signup, so current month is not June, it's May. currentMonthTotalDays = 31 currentMonthURL = "https://www.reddit.com/r/pornfree/comments/5lefq1/stay_c...
nswer) answer = re.sub('CURRENT_DAY_OF_MONTH_INDEX', str(currentDayOfMonthIndex), answer) answer = re.sub('CURRENT_DAY_OF_MONTH_NAME', currentDayOfMonthName, answer) answer = re.sub('CURRENT_DAY_OF_WEEK_NAME', currentDayOfWeekName, answer) answer = re.sub('UPPERCASE_MONTH'
, uppercaseMonth, answer) return answer outputString = stringToPrint() print "=============================================================" print outputString print "=============================================================" pyperclip.copy(outputString)
Merino/poc-cbb
vesper/apps.py
Python
bsd-3-clause
86
0.011628
from django.apps import A
ppConfig class VesperConfig(AppConfig): name = 'vesp
er'
bkudria/platformio
platformio/builder/scripts/atmelavr.py
Python
mit
3,837
0
# Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. """ Builder for Atmel AVR series of microcontrollers """ from os.path import join from time import sleep
from SCons.Script import (COMMAND_LINE_TARGETS, AlwaysBuild, Default, DefaultEnvironment, SConscript) from platformio.util import get_serial
ports def BeforeUpload(target, source, env): # pylint: disable=W0613,W0621 def _rpi_sysgpio(path, value): with open(path, "w") as f: f.write(str(value)) if "micronucleus" in env['UPLOADER']: print "Please unplug/plug device ..." upload_options = env.get("BOARD_OPTIONS", {})...
CartoDB/crankshaft
release/python/0.4.2/crankshaft/crankshaft/__init__.py
Python
bsd-3-clause
154
0
"""
Import all modules""" import crankshaft.random_seeds import crankshaft.clustering import crankshaft.space_time_dynamics import crankshaft.segmentation
red-hood/calendarserver
txdav/xml/parser_base.py
Python
apache-2.0
2,368
0.002956
## # Copyright (c) 2005-2015 Apple Inc. All rights reserved. # # 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...
return self.toxml() def __eq__(self, other): if isinstance(other,
AbstractWebDAVDocument): return self.root_element == other.root_element else: return NotImplemented def writeXML(self, output): raise NotImplementedError() def toxml(self): output = StringIO() self.writeXML(output) return output.getvalue()
wileeam/airflow
tests/executors/test_kubernetes_executor.py
Python
apache-2.0
12,298
0.002195
# 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 u...
_annotations'): '{ "iam.com/role" : "role-arn", "other/annotation" : "value" }' }) def test_kube_config_worker_annotations_properly_parsed(self): annotations = KubeConfig().kube_annotations self.assertEqual({'iam.com/role': 'role-arn', 'o
ther/annotation': 'value'}, annotations) @conf_vars({ ('kubernetes', 'git_ssh_known_hosts_configmap_name'): 'airflow-configmap', ('kubernetes', 'git_ssh_key_secret_name'): 'airflow-secrets' }) def test_kube_config_no_worker_annotations(self): annotations = KubeConfig().kube_annotati...
liloman/pomodoroTasks2
pomodorotasks/systray.py
Python
gpl-3.0
17,195
0.011573
#!/usr/bin/env python # from __future__ import print_function # from future import standard_library # standard_library.install_aliases() # from __future__ import absolute_import, division, print_function from builtins import str # For dbus import dbus import dbus.service import dbus.mainloop.glib import threading ...
m_file("images/iconStarted-0.png") self.status_icon.connect("popup-menu", self.right_click_event) self.status_icon.connect("activate", self.left_click_event) # systray daemon name =
dbus.service.BusName(self.bus_name, bus=dbus.SessionBus(),do_not_queue=True, replace_existing=False, allow_replacement=False ) dbus.service.Object.__init__(self, name, '/systray') # client for daemon bus = dbus.SessionBus(private = True) daemon_client = bus.get_object('org.liloman.pomod...
TheWylieStCoyote/gnuradio
gr-blocks/python/blocks/qa_repack_bits_bb.py
Python
gpl-3.0
5,600
0.005714
#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # SPDX-License-Identifier: GPL-3.0-or-later # # import random from gnuradio import gr, gr_unittest, blocks import pmt class qa_repack_bits_bb (gr_unittest.TestCase): def setUp (self): random.seed...
self.tb.connect(src, repack1, repack2, repack3, repack4, sink) self.tb.run () self.assertEqual(sink.data(), src_data) def test_004_three_with_tags (self): """ 8 -> 3 """ src_data = (0b11111101, 0b11111111) expected_data = (0b101,) + (0b111,)
* 4 + (0b001,) k = 8 l = 3 src = blocks.vector_source_b(src_data, False, 1) repack = blocks.repack_bits_bb(k, l, self.tsb_key) sink = blocks.tsb_vector_sink_b(tsb_key=self.tsb_key) self.tb.connect( src, blocks.stream_to_tagged_stream(gr.sizeof_char...
pescobar/easybuild-easyblocks
easybuild/easyblocks/d/db.py
Python
gpl-2.0
1,707
0.001172
## # Copyright 2013-2020 Ghent University # # This file is part of EasyBuild, # originally creat
ed by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of G
hent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Research Foundation (FWO) (http://www.fwo.be/en) # and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). # # https://github.com/easybuilders/easybuild # # EasyBu...
Statoil/libres
python/res/config/config_error.py
Python
gpl-3.0
1,517
0.002637
# Copyright (C) 2012 Equinor ASA, Norway. # # The file 'enkf_fs.py' is part of ERT - Ensemble based Reservoir Tool. # # ERT 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...
sPrototype("void config_error_free(config_error)") _count = ResPrototype("int config_error_count(config_error)") _iget = ResPrototype("char* config_error_iget(config_error, int)") def __init__(self): raise NotImplementedError("Class can not be instantiated directly!") def __getitem__(self, in...
raise IndexError("Index out of range: %d < %d" % (index, size)) return self._iget(index) def __len__(self): """ @rtype: int """ return self._count() def free(self): self._free()
Tithen-Firion/youtube-dl
youtube_dl/extractor/xnxx.py
Python
unlicense
1,596
0.000627
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor from ..compat import compat_urllib_parse_unquote class XNXXIE(InfoExtractor): _VALID_URL = r'https?://(?:video|www)\.xnxx\.com/video-?(?P<id>[0-9a-z]+)/' _TESTS = [{ 'url': 'http://www.xnxx.com/video-55awb78/sky...
_5_', 'only_matching': True, }, { 'url': 'http://www.xnxx.com/video-55awb78/', 'only_matching': True, }] def _real_extract(self, url): video_id = self._match_id(url) webpage = self._download_webpage(url, video_id) video_url = self._search_regex(r'flv_url=(.*...
&amp;', webpage, 'video URL') video_url = compat_urllib_parse_unquote(video_url) video_title = self._html_search_regex(r'<title>(.*?)\s+-\s+XNXX.COM', webpage, 'title') video_thumbnail = self._search_regex(r'u...
bountysource/www.gittip.com
tests/test_stats.py
Python
cc0-1.0
4,788
0
from datetime import datetime from decimal import Decimal from aspen.utils import utcnow from mock import patch from nose.tools import assert_equals from gittip import wireup from gittip.billing.payday import Payday from gittip.models import Tip from gittip.participant import Participant from gittip.testing import Ha...
', ctime=utcnow()) self.session.add(tip) self.session.commit() expected = ([[-1, 1, Decimal('5.37'), 1.0, Decimal('1')]],
1.0, Decimal('5.37')) actual = Participant(u'bob').get_tip_distribution() assert_equals(actual, expected) def test_get_tip_distribution_handles_no_tips(self): expected = ([], 0.0, Decimal('0.00')) actual = Participant(u'foo').get_tip_distribution() assert_equals(actual,...
googleapis/python-websecurityscanner
tests/unit/gapic/websecurityscanner_v1beta/test_web_security_scanner.py
Python
apache-2.0
194,786
0.001335
# -*- 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...
: factory.return_value = creds client = client_class.from_service_account_file("dummy/file/path.json") assert client.transport._credentials == creds
assert isinstance(client, client_class) client = client_class.from_service_account_json("dummy/file/path.json") assert client.transport._credentials == creds assert isinstance(client, client_class) assert client.transport._host == "websecurityscanner.googleapis.com:443" def test...
ScorpionResponse/freelancefinder
freelancefinder/freelancefinder/middleware/__init__.py
Python
bsd-3-clause
42
0
"""Middleware used by fr
eelancefind
er."""
MartinAltmayer/pokerserver
pokerserver/version.py
Python
gpl-3.0
126
0.007937
NAME = '
pokerserver' DESCRIPTION = 'Poker server for our Python workshop at TNG
Technology Consulting.' VERSION = '2017.3.10'
tszym/ansible
lib/ansible/modules/network/illumos/flowadm.py
Python
gpl-3.0
14,817
0.001012
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2016, Adam Števko <adam.stevko@gmail.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.0', ...
description: > - A flow is defined as a set of attributes based on Layer 3 and Layer 4 headers, which can be used to identify a protocol, service, or a zone. required: true aliases: [ 'flow' ] link: description: - Specifiies a link to confi
gure flow on. required: false local_ip: description: - Identifies a network flow by the local IP address. required: false remove_ip: description: - Identifies a network flow by the remote IP address. required: false transport: descripti...
Aloomaio/googleads-python-lib
examples/ad_manager/v201805/network_service/get_all_networks.py
Python
apache-2.0
1,350
0.006667
#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "Li
cense"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT ...
se. """This example gets all networks. """ # Import appropriate modules from the client library. from googleads import ad_manager def main(client): # Initialize appropriate service. network_service = client.GetService('NetworkService', version='v201805') networks = network_service.getAllNetworks() # Print ...
iandriver/RNA-sequence-tools
ballgown_make_sample_list.py
Python
mit
559
0.008945
import os import pandas as pd pats = ['/Volumes/Drobo/macs_all_+pnx'] sample_list = [] sample_folder = [] for path_to_file in pats: for root, dirnames, filenames in os.walk
(path_to_file): for f in filenames: if 'e_data.ctab' in f: sample_list.append(os.path.basename(root)) sample_folder.append(root.split('/')[-2]) sample_df = pd.DataFrame.from_dict({'run':sample_list, 'folder':sample_folder}) sample_df.to_csv(os.path.join(path_t
o_file,os.path.basename(path_to_file)+'_samples.txt'), sep='\t')
carlosefr/quicklook
components/connections.py
Python
gpl-2.0
6,270
0.002233
#!/usr/bin/env python # -*- coding: iso8859-1 -*- # # connections.py - network connections statistics # # Copyright (c) 2005-2007, Carlos Rodrigues <cefrodrigues@mail.telepac.pt> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License (version 2) ...
"--vertical-label", "connections", "--color", "BACK%s" % background, "--color", "SHADEA%s" % border, "--color", "SHADEB%s" % border, "DEF:proto_tcp=%s:proto_tcp:AVERAGE" % self.database, ...
to_other=%s:proto_other:AVERAGE" % self.database, "AREA:proto_tcp#a0df05:TCP ", "GPRINT:proto_tcp:LAST:\\: %6.0lf conn (now)", "GPRINT:proto_tcp:MAX:%6.0lf conn (max)", "GPRINT:proto_tcp:AVERAGE:%6.0lf conn (avg)\\n...
ESS-LLP/erpnext
erpnext/healthcare/doctype/triage/test_triage.py
Python
gpl-3.0
228
0.008772
# -*- coding: utf-8 -*- # Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and
Contributors # See license.txt from __future__ import unicode_literals # import frappe import unittest class TestTriage(unittest.T
estCase): pass
basirsedighi/LearingPython
01.Loops/FirstStepToBecomePropperEuropean.py
Python
mit
1,484
0.010782
while True: pass print('1. from Fahrenheit to Celsius') print('2. from Inches to Centimeter') print('3. from Feet to Meter') print('4. from Pounds to Kilogram') valg=int(input()) if (valg == 1): while True: print("Enter a temperature in Fahrenheit, enter q too quite : "...
if(Fahrenheit == ord('q')): break
Celsius =(Fahrenheit - 32)*(5.0/9) print ("Temperature:",Fahrenheit, " F=", Celsius, "Celsius ") elif (valg ==2): while True: print("Enter a mesure inches , enter q too quite : ") inches = float(input()) if(inches == ord('q')): bre...
chienlieu2017/it_management
odoo/odoo/addons/base/ir/ir_qweb/fields.py
Python
gpl-3.0
16,571
0.001931
# -*- coding: utf-8 -*- import re from collections import OrderedDict from odoo import api, fields, models, _ from PIL import Image from cStringIO import StringIO import babel from odoo.tools import html_escape as escape, posix_to_ldml, safe_eval, float_utils from .qweb import unicodifier import logging _logger = logg...
value and converts newlines to br. This is bullshit. """ return nl2br(html_escape(value, options)) if value else '' class SelectionConverter(models.AbstractModel): _name = 'ir.qweb.field.selection' _inherit = 'ir.qweb.field' @api.model def value_to_html(self, value, options): ...
(self, record, field_name, options): if 'selection' not in options: options = dict(options, selection=dict(record._fields[field_name].get_description(s
lcoandrade/DsgTools
gui/DatabaseTools/DbTools/BatchDbCreator/createBatchFromCsv.py
Python
gpl-2.0
7,059
0.005242
# -*- coding: utf-8 -*- """ /*************************************************************************** DsgTools A QGIS plugin Brazilian Army Cartographic Production Tools ------------------- begin : 2016-02-18 git sha ...
ngineer @ Brazilian Army email : borba.philipe@eb.mil.br ***************************************************************************/ /*************************************************************************** * * * Th...
ublished by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************...
nextgis/nextgisweb_compulink
nextgisweb_compulink/compulink_video_producer/command.py
Python
gpl-2.0
1,716
0.005828
# -*- coding: utf-8 -*- from datetime import datetime, timedelta from nextgisweb_compulink.compulink_video_producer.default_video_page import DefaultVideoPage, UNITS from nextgisweb_compulink.compulink_video_producer.model import VideoProduceTask from nextgisweb_compulink.compulink_video_producer.video_options import ...
_dt < datetime.now() - timedelta(days=days)) c = 0 for task in tasks:
remove_video_entry(task.id) c += 1 print('Video removed: ' + str(c)) @Command.registry.register class ProduceVideoCommand(): identity = 'compulink.produce_video' @classmethod def argparser_setup(cls, parser, env): parser.add_argument('--res-id', required=True, type=i...
sphaero/appie
appie/__init__.py
Python
gpl-3.0
104
0
__
all__ = ['appie.appie', 'appie.extensions'] from appie.appie import * from appie.extensions import *
8l/luz-cpu
luz_asm_sim/tests_full/testrun_utils.py
Python
unlicense
1,514
0.004624
# Some utilities for running full tests # # Eli Bendersky (C) 2008-2010 # import os, imp from lib.commonlib.portability import exec_function from lib.asmlib.assembler import Assembler from lib.asmlib.linker import Linker from lib.commonlib.luz_defs import ( USER_MEMORY_START, USER_MEMORY_SIZE) def s...
iven one (non-recursively). Full directory path names are returned. """
for dir in os.listdir(startdir): if not dir in excludes: fullpath = os.path.join(startdir, dir) if os.path.isdir(fullpath): yield fullpath def get_test_functions(testfile): """ Given the path of a testfile, extracts all the test_ functions from ...
deniszh/whisper
bin/whisper-update.py
Python
apache-2.0
1,129
0.009743
#!/usr/bin/env python import sys import time import signal import optparse try: import whisper except ImportError: raise SystemExit('[ERROR] Please make sure whisper is installed properly') # Ignore SIGPIPE signal.signal(signal.SIGPIPE, signal.SIG_DFL) now = int(time.time()) option_parser = optparse.OptionPars...
usage='''%prog [options] path [timestamp:value]* If no values are passed as arguments, they are read one-per-line from stdin.''') (options, args) = option_parser.parse_args() if not args: option_parser.print_help() sys.exit(1) path = args[0] if len(args) >= 2: datapoint_strings = args[1:] else: # no argv...
stdin datapoint_strings = sys.stdin datapoint_strings = [point.replace('N:', '%d:' % now) for point in datapoint_strings] datapoints = [tuple(point.split(':')) for point in datapoint_strings] try: if len(datapoints) == 1: timestamp, value = datapoints[0] whisper.update(path, value, ti...
zhujianjunscut/python_learning
netprogram/server.py
Python
mit
737
0.005427
import socket import time import threading def tcplink(sock, addr): print('Accept new connection from %s:%s...' % addr) sock.send(b'Welcome!') while True: data = sock.recv(1024) time.sleep(1) if not data or data.decode('utf-8') == 'exit': break sock.send(('Hello...
"waiting for connection....") while
True: sock,addr = s.accept() t = threading.Thread(target=tcplink, args=(sock,addr)) t.start() t.join() break print("server has exit")
electrumalt/electrum-doge
plugins/labels.py
Python
gpl-3.0
9,169
0.006762
from electrum_doge.util import print_error import httplib, urllib import socket import threading import hashlib import json from urlparse import urlparse, parse_qs try: import PyQt4 except Exception: sys.exit("Error: Could not import PyQt4 on Linux systems, you may try 'sudo apt-get install python-qt4'") from...
out.addWidget(decrypt_key_text, 1,1) layout.addWidget(QLabel("Decryption key: "),1,0) layout.addWidget(HelpButton("This key can be used on the LabElectrum website to decrypt your data in case you want to review it online."),1,2) self.upload = QPushButton("Force upload") self.upload.clic...
cked.connect(self.full_pull) layout.addWidget(self.download, 2,2) c = QPushButton(_("Cancel")) c.clicked.connect(d.reject) self.accept = QPushButton(_("Done")) self.accept.clicked.connect(d.accept) layout.addWidget(c,3,1) layout.addWidget(self.accept,3,2) ...
wmo-registers/code-manuals
initialUpload/bufrcommon.py
Python
cc0-1.0
3,434
0.004368
import os import cleanttl from ttlhead import ttlhead def main(): if not os.path.exists('ttl/def'): os.mkdir('ttl/def') with open('ttl/def/bulk_bufr4.ttl', 'w') as fhandle: fhandle.write(ttlhead) fhandle.write('<bufr4> a reg:Register, owl:Ontology, ldp:Container ;\n') fhandle....
ue of the BUFR Table B Element in WMO No. 306 Vol I.2 FM 94 BUFR."@en ; \n' '\trdfs:range xsd:integer ; \n' '\trdfs:isDefinedBy <bufr4>\n' '\t.\n\n') fhandle.write('<bufr4/referenceValue>a owl:ObjectProperty ;\n' '\trdfs:lab...
.2 FM 94 BUFR."@en ;\n' '\trdfs:range xsd:integer ;\n' '\trdfs:isDefinedBy <bufr4>\n' '\t.\n\n') fhandle.write('<bufr4/scale> a owl:ObjectProperty ;\n' '\trdfs:label "Scale"@en ;\n' '\trdfs:comment "Sca...
sametmax/Django--an-app-at-a-time
ignore_this_directory/django/core/paginator.py
Python
mit
6,204
0.000161
import collections.abc import inspect import warnings from math import ceil from django.utils.deprecation import RemovedInDjango31Warning from django.utils.functional import cached_property from django.utils.inspect import method_has_no_args from django.utils.translation import gettext_lazy as _ class UnorderedObjec...
d :cls:`Page` object. """ ret
urn Page(*args, **kwargs) @cached_property def count(self): """Return the total number of objects, across all pages.""" c = getattr(self.object_list, 'count', None) if callable(c) and not inspect.isbuiltin(c) and method_has_no_args(c): return c() return len(self.obje...
erjohnso/ansible
lib/ansible/plugins/action/ironware.py
Python
gpl-3.0
3,479
0.001725
# # (c) 2016 Red Hat Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is d...
pc.become = p
rovider['authorize'] or False pc.become_pass = provider['auth_pass'] display.vvv('using connection plugin %s' % pc.connection, pc.remote_addr) connection = self._shared_loader_obj.connection_loader.get('persistent', pc, sys.stdin) socket_path = connection.run() display.vvvv('s...
popravich/rdbtools3
docs/conf.py
Python
mit
8,613
0.005921
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # rdbtools3 documentation build configuration file, created by # sphinx-quickstart on Tue May 20 20:51:10 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # ...
n it is used: #today = '' # Else, today_fmt
is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_r...
elioth010/lugama
venv/lib/python2.7/site-packages/pymongo/settings.py
Python
gpl-2.0
3,353
0
# Copyright 2014-2015 MongoDB, 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 writi...
local_threshold_ms=LOCAL_THRESHOLD_MS, server_selection_timeout=SERVER_SELECTION_TIMEOUT): """Represent MongoClient's configuration. Take a list of (host, port) pairs and optional replica set name. """ self._s
eeds = seeds or [('localhost', 27017)] self._replica_set_name = replica_set_name self._pool_class = pool_class or pool.Pool self._pool_options = pool_options or PoolOptions() self._monitor_class = monitor_class or monitor.Monitor self._condition_class = condition_class or threadi...
libvirt/libvirt-test-API
libvirttestapi/repos/secret/setSecret.py
Python
gpl-2.0
2,012
0.000497
# Copyright (C) 2010-2012 Red Hat, Inc. # This work is licensed under the GNU GPLv2 or later. # Test secret series command, check the set secret value, get secret value import base64 from libvirttestapi.src import sharedmod from xml.dom import minidom from libvirt import libvirtError required_params = ('secretUUID',...
dmod.libvirtobj['conn'] secretobj = conn.secretLookupByUUIDString(secretUUID) private = minidom.parseString(secretobj.XMLDesc(0)).\ getElementsByTagName('secret')[0].getAttribute('private') secretobj.setValue(data, 0) """if private is no, the value of secret can be get; if th...
is %s" % (secretUUID, secretobj.value(0).decode())) ret = check_setSecret(value, secretobj, logger) return ret else: logger.info("the value of secret %s is %s" % (secretUUID, data)) logger.info("can not ch...
LighthouseHPC/lighthouse
src/lighthouseProject/lighthouse/models/lapack_routineInfo.py
Python
mit
305
0.022951
from django.db import models """ for routine information """ class lapack_RoutineInfo(models.Model): routine = models.CharField('Routine', max_length=
30) info = models.TextField('
Information', blank=True, null=True) def __unicode__(self): return self.info class Meta: app_label = 'lighthouse'
popego/neocortex-api-python
src/neocortex/client.py
Python
bsd-3-clause
3,380
0.00858
# -*- coding: utf-8 -*- __docformat__="restructuredtext" from rest import RestClient, Result, ResponseFormats from datetime import datetime class NeocortexRestClient(object): BASE_URL = "http://api.meaningtool.com/0.2/neocortex" __builder__ = None class Builder(RestClient): _functions = {...
_params = {} _input = None _format = None _tree_key = None def format(self, value): self._format = value return self def input(self, text): self._input = self._params["input"] = tex
t return self def categories(self, tree_key=None, additionals=None): params = dict(additionals or []) if tree_key is not None: params.update(dict(tree_key=tree_key)) self._functions["categories"] = params retur...
bjorncooley/rainforest_makers
spirit/models/topic_notification.py
Python
mit
4,847
0.002888
#-*- coding: utf-8 -*- from django.db import models from django.utils.translation import ugettext_lazy as _ from django.core.urlresolvers import reverse from django.conf import settings from django.utils import timezone from django.db import IntegrityError from spirit.signals.comment import comment_posted from spirit...
pass def topic_viewed_handler(sender, request, topic, **kwargs): if not request.user.is_authenticated(): return TopicNotification.objects.filter(user=request.user, topic=topic)\ .update(is_read=True) comment_posted.connect(comment_posted_handler, dispatch_uid=__name__)
topic_private_post_create.connect(topic_private_post_create_handler, dispatch_uid=__name__) topic_private_access_pre_create.connect(topic_private_access_pre_create_handler, dispatch_uid=__name__) topic_viewed.connect(topic_viewed_handler, dispatch_uid=__name__)
837468220/python-for-android
python3-alpha/python3-src/Lib/test/test_cfgparser.py
Python
apache-2.0
59,709
0.000737
import collections import configparser import io import os import sys import textwrap import unittest import warnings from test import support class SortedDict(collections.UserDict): def items(self): return sorted(self.data.items()) def keys(self): return sorted(self.data.keys()) def va...
nt', fallback=18), 18) eq(cf.getint('Types', 'no-such-int', fallback="18"), "18") # sic! with self.assertRaises(configparser.NoOptionError): cf.getint('Types', 'no-such-int') self.assertAlmostEqual(cf.getfloat('Types', 'float', fallback=0.0)...
oat('Types', 'no-such-float', fallback=0.0), 0.0) eq(cf.getfloat('Types', 'no-such-float', fallback="0.0"), "0.0") # sic! with self.assertRaises(configparser.NoOptionError): cf.getfloat('Types', 'no-such-float') eq(cf.getboolean('Types', 'bo...
wasit7/cs634
2016/lab6_calibration/jsonPorter.py
Python
bsd-2-clause
728
0.021978
# -*- coding: utf-8 -*- """ Created on Sat Sep 27 17:00:01 2014 @author: Wasit """ try: import json except ImportError: import simplejson as json import numpy as np import base64 def Base64Encode(ndarray): return json.dumps([str(ndarray.dtype),base
64.b64encode(ndarray),ndarray.shape]) def Base64Decode(jsonDump): loaded = json.loads(jsonDump) dtype = np.dtype(loaded[0]) arr = np.frombuffer(base64.decodestring(load
ed[1]),dtype) if len(loaded) > 2: return arr.reshape(loaded[2]) return arr a= np.random.random_sample((5, 7)) j1=json.dumps(Base64Encode(a)) f=open("data.json","w") f.write(j1) f.close() f=open("data.json","r") j2=json.loads(f.read()) f.close() b=Base64Decode(j2)
hellhovnd/dentexchange
dentexchange/apps/libs/mixins/views.py
Python
bsd-3-clause
1,114
0.001795
#
-*- coding:utf-8 -*- import urlparse from django.core.urlresolvers import reverse from django.shortcuts import redirect from django.http.response import HttpResponseBadRequest from .base import Mixin from .. import strings class SuccessURLAliasViewM
ixin(Mixin): def get_success_url(self): return reverse(self.success_url_alias) class HttpRefererViewMixin(Mixin): def get(self, request, referers=None, *args, **kwargs): from_referer = urlparse.urlsplit( request.META.get('HTTP_REFERER', '')).path if referers is not None \ ...