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
Sinar/popit_ng
popit/migrations/0016_auto_20151001_0131.py
Python
agpl-3.0
558
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migration
s class Migration(migrations.Migration): dependencies = [ ('popit', '0015_auto_20151001_0130'), ] operations = [ migrations.AlterField( model_name='contacts', name='valid_from', field=models.DateField(null=True), ), migrations.AlterFiel...
), ]
bsipocz/astropy
astropy/coordinates/builtin_frames/skyoffset.py
Python
bsd-3-clause
8,538
0.002342
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst from astropy import units as u from astropy.utils.compat import namedtuple_asdict from astropy.coordinates import representation as r from astropy.coordinates.transformations import DynamicMatrixTransform, FunctionTransform from ast...
ake_skyoffset_cls(framecls): """ Create a new class that is the sky offset frame for a specific class of origin frame. If such a class has already been created for this frame, the same class will be returned. The new class will always have component names for spherical coordinates of ``lon``/``...
frame class (i.e., subclass of `~astropy.coordinates.BaseCoordinateFrame`) The class to create the SkyOffsetFrame of. Returns ------- skyoffsetframecls : class The class for the new skyoffset frame. Notes ----- This function is necessary because Astropy's frame transformations...
telefonicaid/fiware-keystone-spassword
keystone_spassword/contrib/spassword/mailer.py
Python
apache-2.0
2,991
0.002675
# # Copyright 2018 Telefonica Investigacion y Desarrollo, S.A.U # # 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 unde...
server.starttls() # Use auth only if smtp_user and smtp_password not empty if CONF.spassword.smtp_user and CONF.spassword.smtp_password: try: server.login(CONF.spassword.smtp_user,
CONF.spassword.smtp_password) except smtplib.SMTPAuthenticationError: LOG.error('SMTP authentication error %s' % CONF.spassword.smtp_user) return False try: server.sendmail(CONF.spassword.smtp_from, dest, msg) except Exceptio...
GordonsBeard/frinkiac.py
Frinkiac/frinkiac.py
Python
mit
4,152
0.006021
import base64 import json import requests import textwrap FRINK_URL = 'https://frinkiac.com' FRINK_API_URL = '{0}/api/search'.format(FRINK_URL) FRINK_CAPTION_URL = '{0}/api/caption'.format(FRINK_URL) FRINK_RANDOM_URL = '{0}/api/random'.format(FRINK_URL) MORB_URL = 'https://morbotron.com' MORB_API_URL = '{0}/api/searc...
else: if len(caption) > 300: caption = caption[:300] caption = self._chop_captions(caption) return '{0}/meme/{1}/{2}.jpg?b64lines={3}'.format( SITE_URL, self.episode, self.timestamp, base64.urlsafe_b64encode(byt...
ink else MORB_CAPTION_URL cap_search = requests.get('{0}?e={1}&t={2}'.format(CAPTION_URL, self.episode, self.timestamp)) data = cap_search.json() # This controls how many captions you get. caption = " ".join([subtitle['Content'] for subtitle in data['Subtitles']]) self.caption =...
nwjs/chromium.src
third_party/protobuf/python/google/protobuf/internal/message_test.py
Python
bsd-3-clause
109,614
0.003431
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Protocol Buffers - Google's data interchange format # Copyright 2008 Google Inc. All rights reserved. # https://developers.google.com/protocol-buffers/ # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that t...
golden_message.SerializeToString(deterministic=False)) self.assertEqual(golden_data, golden_message.SerializeToString(deterministic=True)) class BadArgError(Exception): pass class BadArg(object): def __nonzero__(self): raise BadArgError() def __bool__...
le): golden_data = test_util.GoldenFileData('golden_message') golden_message = message_module.TestAllTypes() golden_message.ParseFromString(golden_data)
taotetek/cookbook
pyzmq/helloword/src/tests/server.py
Python
mit
1,799
0.004447
# -*- coding: utf-8 -*- # Copyright (c) the Contributors # # 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, modify...
s or sub
stantial 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 CLAI...
mattgreen/hython
test/operators/bitwise.py
Python
gpl-3.0
213
0.004695
print(~5) print(18 & 3) pr
int(83 | 7) print(22 ^ 5) print(2 << 4) print(16 >> 2) # multip
le print(~~19) print(197 & 92 & 345) print(197 | 92 | 345) print(197 ^ 92 ^ 345) print(1 << 2 << 3) print(256 >> 4 >> 3)
citp/BlockSci
blockscipy/setup.py
Python
gpl-3.0
2,879
0.004863
import os import re import sys import platform import subprocess from setuptools import setup, Extension, find_packages from setuptools.command.build_ext import build_ext from distutils.version import LooseVersion class CMakeExtension(Extension): def __init__(self, name, sourcedir=''): Extension.__init__...
e_args += ['-A', 'x64'] build_args += ['--', '/m'] else: cmake_args += ['-DCMAKE_BUILD_TYPE=' + cfg] build_args += ['--', '-j4'] env = os.environ.copy() env['CXXFLAGS'] = '{} -DVER
SION_INFO=\\"{}\\"'.format(env.get('CXXFLAGS', ''), self.distribution.get_version()) if not os.path.exists(self.build_temp): os.makedirs(self.build_temp) subprocess.check_call(['cmake', ext.sourcedir] + cmake_args, cwd=self.build_...
decebel/dataAtom_alpha
bin/plug/py/sources/weby/WikipediaDataCommand.py
Python
apache-2.0
2,608
0.036043
import os, sys basePlugPath = os.path.join("..", "..") sys.path.insert(0, os.path.join(basePlugPath, "api")) sys.path.insert(0, os.path.join(basePlugPath, "external")) # TODO - know difference between module import vs package import? import drawingboard from pattern.web import Wikipedia import pprint pp = pprint.Pr...
other things and as it does this, it will keep calling status message. ""
" print "loading " #self.set_icon("GUI/icons/blogger.png") # trying to figure out the icon to use based on display name self.set_display_name("blogger") self.set_initialized(True) #def start(self, **kwargs): def start(self, **kwargs): """Configures the command. - sets the display name of the command...
317070/kaggle-heart
generate_metadata_pkl.py
Python
mit
2,940
0.001701
import argparse import glob import re import cPickle as pickle from dicom.sequence import Sequence from log import print_to_file from paths import LOGS_PATH, TRAIN_DATA_PATH, TEST_DATA_PATH def read_slice(path): return pickle.load(open(path))['data'] def convert_to_number(value): value = str(value) tr...
arch(r'/(((4ch)|(2ch)|(sax))_\d+\.pkl)$', s).group(1) metadata = read_metadata(s) patient_data.append({'metadata': metadata,
'slice_id': slice_id}) print slice_id return patient_data, pid def get_metadata(data_path): patient_paths = sorted(glob.glob(data_path + '*/study')) metadata_dict = {} for p in patient_paths: patient_data, pid = get_patient_data(p) print "patient", pid metadata_dict...
chshibo/CosData_Tools
test_SqlReader.py
Python
gpl-3.0
316
0.018987
import SqlReader def main(): reader=SqlReader.SqlReader("SELECT p.objid,p.ra,p.dec,p.r,s.z as redshift FROM galaxy as p join specobj as s on s.bestobjid=p.objid WHERE p.ra BET
WEEN 194.138787 AND 195.548787 AND p.dec BETWEEN 27.259389 AND 28.709389") reader.dataCo
llect() if __name__ =="__main__": main()
lukemn/python-lzw
setup.py
Python
mit
2,823
0.008147
from distutils.core import setup, Command import unittest import doctest from unittest import defaultTestLoader, TextTestRunner import sys # BUG. At least we should support 3.0, which means getting # rid of a bunch of stupid byte-as-string stuff, which is kind # of awesome. (major_version, minor_version) = sys.versi...
d(lzw) utests = defaultTestLoader.loadTestsFromName(TEST_MODULE_NAME) urunner = TextTestRunner(verbosity=2) urunner.run(utests) if self.runslow: utests = defaultTes
tLoader.loadTestsFromName(SLOW_TEST_MODULE_NAME) urunner = TextTestRunner(verbosity=2) urunner.run(utests) class DocCommand(Command): """Generates package documentation using epydoc""" user_options = [] def initialize_options(self): pass def finalize_options(self): pass ...
uclmr/inferbeddings
inferbeddings/evaluation/metrics.py
Python
mit
5,197
0.003848
# -*- coding: utf-8 -*- import abc import numpy as np from sklearn import metrics from inferbeddings.evaluation.util import apk import logging logger = logging.getLogger(__name__) class BaseRanker(metaclass=abc.ABCMeta): def __call__(self, pos_triples, neg_triples=None): raise NotImplementedError c...
ascores = (ascores * (1e-7 / min_diff)).ast
ype(np.float64) aucroc_value = metrics.roc_auc_score(ays, ascores) precision, recall, thresholds = metrics.precision_recall_curve(ays, ascores, pos_label=1) aucpr_value = metrics.auc(recall, precision) return aucroc_value, aucpr_value
mattclay/ansible
test/lib/ansible_test/_internal/__init__.py
Python
gpl-3.0
2,387
0.001257
"""Test runner for all Ansible tests.""" from __future__ import annotations import os import sys import typing as t # This import should occur as early as possible. # It must occur before subprocess has been imported anywhere in the current process. from .init import ( CURRENT_RLIMIT_NOFILE, ) from .util import ...
target_names for use once we exit the exception handler target_names = ex.target_names except Delegate as ex:
# save delegation args for use once we exit the exception handler delegate_args = (ex.host_state, ex.exclude, ex.require) if delegate_args: delegate(config, *delegate_args) if target_names: for target_name in target_names: print(target_name) # inf...
iansprice/wagtail
wagtail/wagtailsites/wagtail_hooks.py
Python
bsd-3-clause
1,173
0.001705
from __futu
re__ import absolute_
import, unicode_literals from django.contrib.auth.models import Permission from django.core import urlresolvers from django.utils.translation import ugettext_lazy as _ from wagtail.wagtailadmin.menu import MenuItem from wagtail.wagtailcore import hooks from wagtail.wagtailcore.permissions import site_permission_polic...
mani-mishra/automateboringstuff
practice excercies/comma-code.py
Python
unlicense
721
0.019417
# Say you have a list value like this: # # # spam = ['apples', 'bananas', 'tofu', 'cats'] # Write a function that takes a list value as an argument and returns a string with all # the items separated by a comma and a space, with and inserted before the last item. # For example, passing the previous spam list to the fun...
unction should be able to work with any list value passed to it. def concat_list(input): first = ', '.join(map(str,input[0:-1])) last = str(input[-1]) print(first + ', and '+ last) concat_list(['apples', 'bananas', 'tofu', 'c
ats']) concat_list([22,33,112,92]) concat_list([2,3,'##',22]) concat_list([2.2,33,'fotu',42])
iadept/vim-gtranslate
plugin/gtranslate.py
Python
gpl-2.0
194
0.025773
import vim from translate i
mport Translator def main(): word = vim.eval("s:word") translator = Translator(to_lang="ru") print translator.translate(word) if __name__ == "
__main__": main()
rshk/ckan3-poc-experiments
ckan/catalog/api.py
Python
agpl-3.0
6,354
0.001731
import urllib from math import ceil from flask import request from flask.ext import restful from sqlalchemy.orm.exc import NoResultFound from .app import app from .models import db, Dataset, Distribution api = restful.Api(app, prefix='/api/1') class ModelResource(restful.Resource): """ Common methods for ...
) * page_size) return [self._serialize(o) for o in results], 200, headers pkg = self._get(obj_id) return self._serialize(pkg) def post(self): new = self.model() new.attributes = request.json db.session.add(new) db.session.commit() return self._se...
for key, value in request.json.iteritems(): obj.attributes[key] = value #obj.attributes.update(request.json) db.session.commit() def patch(self, obj_id): obj = self._get(obj_id) for key, value in request.json.iteritems(): if key.startswith('$'): ...
vapkarian/soccer-analyzer
src/parsers/flashscore.py
Python
mit
30,552
0.003666
import logging import os import re from datetime import datetime from typing import Tuple, Optional, List, Dict, Union, Any from urllib.error import URLError from bs4 import BeautifulSoup from bs4.element import Tag from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.we...
args: List[Any] = None): locators = { By.ID: id_, By.NAME: name, By.TAG_NAME: tag_name, By.CLASS_NAME: class_name, By.LINK_TEXT: link_text, By.PARTIAL_LINK_TEXT: partial_link_text, By.CSS_SELECTOR: css_selector, By...
cators = {locator: value for locator, value in locators.items() if value is not None} if len(locators) != 1: raise Exception( 'You have to provide one and only one value among `id_`, `name`, `tag_name`, ' '`class_name`, `link_text`, `partial_link_text`, `css_selector`...
pablodanielrey/python
gosa/changeOwnerDomain.py
Python
gpl-3.0
760
0.003947
# -*- coding: utf-8 -*- import os, sys, shutils if len(sys.argv) <= 1: print('debe llamar al sistema usando : ') print('python3 ' + sys.argv[0] + ' usuario dni') exit(1) usuario = sys.argv[1] dni = sys.argv[2] os.chdir('/home') os.rename(usuario,dni) os.chdir('/home/samba/profiles') os.rename(usuario,dni...
""" -- cambiar los permisos al directorio -- /home/dni /home/samba/profiles/dni """ for ruta, dirs, archivos in os.walk('/home/' + dni): shutil.chown(ruta, dni, 'root') for archivo in archivos: shutil.chown(archivo, dni, 'root') for ruta, dirs, archivos in os.walk('/home/samba/
profiles/' + dni): shutil.chown(ruta, dni, 'root') for archivo in archivos: shutil.chown(archivo, dni, 'root')
aspose-words/Aspose.Words-for-Java
Plugins/Aspose_Words_Java_for_Jython/asposewords/quickstart/HelloWorld.py
Python
mit
481
0.016632
from asposewords import Settings from com.aspose.words import Document from com.aspose.words import DocumentBuilder class HelloWorld: def __init__(self): dataDir = Settings.dataDir + 'quickstart/'
doc = Document()
builder = DocumentBuilder(doc) builder.writeln('Hello World!') doc.save(dataDir + 'HelloWorld.docx') print "Document saved." if __name__ == '__main__': HelloWorld()
vivek8943/GeoTweetSearch
main.py
Python
apache-2.0
14,290
0.006438
from api.core.utility import red
irectOutputToLogger redirectOutputToLogger() __author__ = 'Michael Pryor' if __name__ == '__main__': import ConfigParser import argparse import datetime import os import logging import sys from logging import config import bottle parser = argparse.ArgumentParser(description='Twitt...
t_default=argparse.SUPPRESS) parser.add_argument('--config', metavar='file', default='config.conf', help='Configuration file to use') parser.add_argument('--logging_config', metavar='file', d...
facebookexperimental/eden
eden/hg-server/edenscm/mercurial/progress.py
Python
gpl-2.0
26,512
0.000339
# Portions Copyright (c) Facebook, Inc. and its affiliates. # # This software may be used and distributed according to the terms of the # GNU General Public License version 2. # progress.py progress bars related code # # Copyright (C) 2010 Augie Fackler <durin42@gmail.com> # # This software may be used and distributed...
return " ".join(s for s in args if s) def shouldprint(ui): return not (ui.quiet or ui.plain("progress")) and ( ui._isatty(ui.ferr) or ui.configbool("progress", "assume-tty") ) def fmtremaining(seconds): """format a number of remaining seconds in human readable way This will properly di...
return "" if seconds < 60: # i18n: format XX seconds as "XXs" return _("%02ds") % seconds minutes = seconds // 60 if minutes < 60: seconds -= minutes * 60 # i18n: format X minutes and YY seconds as "XmYYs" return _("%dm%02ds") % (minutes, seconds) # we're goin...
Huawei/OpenStackClient_Auto-Scaling
asclient/common/utils.py
Python
apache-2.0
1,745
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # 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...
ning permissions and limitations # under the License. # from datetime import datetime def get_id(obj): """Get obj's uuid or object itself if no uuid Abstracts the common pattern of allowing both an object or an object's ID (UUID) as a parameter when dealing with relationships. """ try: ...
id'] except AttributeError: return obj def remove_empty_from_dict(original): """get a new dict which removes keys with empty values :param dict original: original dict, should not be None :return: a new dict which removes keys with empty values """ return dict((k, v) for k, v in origi...
exekias/droplet
droplet/web/wizards.py
Python
agpl-3.0
3,158
0
# -*- coding: utf-8 -*- # # droplet # Copyright (C) 2014 Carlos Pérez-Aradros Herce <exekias@gmail.com> # # This program 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 Lice...
.get_forms() return forms[step] class InstallWizard(Wizard): """ Wizard bounded to a module, it will install the module when done and redirect the user to moudles page """ #: Class of the module this wizard will
install module = None def __init__(self, *args, **kwargs): if not self.module or \ not issubclass(self.module, droplet.module.Module): raise ValueError('You should define module class to be installed') super(InstallWizard, self).__init__(*args, **kwargs) def finish(...
kthyng/tracpy
tracpy/tools.py
Python
mit
18,989
0.000369
""" Tools for dealing with drifter stuff. Functions include: * interpolate2d * interpolate3d * find_final * convert_indices * check_points * seed """ import numpy as np from scipy import ndimage import time import matplotlib.tri as mtri # from matplotlib.mlab import Path, find from matplotlib.path import Path def ...
d x, y, z. Can use the 3d version of this for transforming to lon/lat also if the xin/yin input are lon/lat arrays. * 'm_ij2ll' map_coordinates, from grid i, j to lon, lat xin: 3D array of x values that are mapped to the inp
ut x,y,z coordinates. This is only needed in the 3D mapping case. Normally, can just do this in 2D instead of 3D and get the same results. yin: 3D array of y values that are mapped to the input x,y,z coordinates. This is only needed in the 3D mapping case. Normally, can just ...
compgeog/cgl
cgl/tests/test_kdtrees.py
Python
gpl-3.0
1,003
0.031904
import sys sys.path.append('../..') from cgl.kdtree import * from cgl.point import Point data1 = [ (2,2), (0,5), (8,0), (9,8), (7,14), (13,12), (14,13) ] points = [Point(d[0], d[1]) for d in data1] t1 = kdtree(points, 'unbalanced') t2 = kdtree(points) print([t1.query_kdtree(p)[0] for p i
n points]) print([t2.query_kdtree(p)[0] for p in points]) print('Depth of t1:', t1.depth()) print('Depth of t2:', t2.depth()) data1 = [ (2,2), (0,5), (8,0), (9,8
), (7,14), (13,12), (14,13) ] points = [Point(d[0], d[1]) for d in data1] t1 = kdtree(points) rect = [ [1, 9], [2, 9] ] found = t1.range_query_orthogonal(rect) print('Orthogonal:', found) data1 = [ (2,2), (0,5), (8,0), (9,8), (7,14), (13,12), (14,13) ] points = [Point(d[0], d[1]) for d in data1] p = Point(5,5) t1 = kd...
DictGet/ecce-homo
setup.py
Python
mit
1,454
0.002751
# -*- coding: utf-8 -*- #! /usr/bin/env python import os import subprocess from setuptools import setup import six here = os.path.dirname(os.path.abspath(__file__)) README = open(os.path.join(here, 'README.md')).read() REQUIREMENTS = open(os.path.join(here, 'requirements/base.txt')).readlines() def get_version_from_...
( name='eccehomo', version=get_version_from_git_tag(), description='Micro application to serve images with customized cropping', long_description=README, author='DictGet Team', author_email='dictget@gmail.com', url="https://github.com/dictget/ecce-homo", download_url="https://github.com/...
homo/archive/{}.tar.gz".format( get_version_from_git_tag() ), packages=['eccehomo'], test_suite="eccehomo.tests", entry_points=scripts, install_requires=REQUIREMENTS, classifiers=[ 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Mo...
arthurljones/bikechurch-signin-python
src/controls/autowrapped_static_text.py
Python
bsd-3-clause
2,223
0.042285
# -*- coding: utf-8 -*- import wx from copy import copy sWhitespace = ' \t\n' def SplitAndKeep(string, splitchars = " \t\n"): substrs = [] i = 0 while len(string) > 0: if string[i] in splitchars: substrs.append(string[:i]) substrs.append(string[i]) string = string[i+1:] i = 0 else: i += 1 ...
tPieceCount = len(currentLine) if (currentPieceCount > 0 and newW
idth > maxWidth) or nextPiece == '\n': if currentPieceCount > 0 and currentLine[-1] in sWhitespace: currentLine = currentLine[:-1] if nextPiece in sWhitespace: pieces = pieces[1:] currentLine.append('\n') lines.extend(currentLine) currentLine = [nextPiece] currentString = n...
zielmicha/freeciv-android
lib/freeciv/client/actions.py
Python
gpl-2.0
10,344
0.004254
# Copyright (C) 2011 Michal Zielinski (michal@zielinscy.org.pl) # # 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, or (at your option) # any later version. # # This program is d...
freeciv.func.key_unit_transform() elif ident == ACTIVITY_FORTIFYING: freeciv.func.key_unit_fortify() elif ident == ACTIVITY_POLLUTION: freeciv.func.key_unit_pollution() elif ident == ACTIVITY_PARADROP: freeciv.func.key_unit
_paradrop() elif ident == ACTIVITY_FALLOUT: freeciv.func.key_unit_fallout() elif ident == ACTIVITY_SENTRY: freeciv.func.key_unit_sentry() elif ident == ACTIVITY_PILLAGE: freeciv.func.key_unit_pillage() #elif ident == ACTIVITY_: # freeciv.fun...
carlgao/lenga
images/lenny64-peon/usr/share/python-support/python-pygments/pygments/formatters/html.py
Python
mit
22,285
0.00193
# -*- coding: utf-8 -*- """ pygments.formatters.html ~~~~~~~~~~~~~~~~~~~~~~~~ Formatter for HTML output. :copyright: 2006-2007 by Georg Brandl, Armin Ronacher. :license: BSD, see LICENSE for more details. """ import sys, os import StringIO from pygments.formatter import Formatter from pygments.to...
from hashlib import sha1 as sha except ImportError: import sha sha = sha.new return sha('%s|%s' % (random(), time())).hexdigest() def _get_ttype_class(tty
pe): fname = STANDARD_TYPES.get(ttype) if fname: return fname aname = '' while fname is None: aname = '-' + ttype[-1] + aname ttype = ttype.parent fname = STANDARD_TYPES.get(ttype) return fname + aname CSSFILE_TEMPLATE = '''\ td.linenos { background-color: #f0f0f0; ...
espenak/enkel
testsuite/wansgli/apprunner.py
Python
gpl-2.0
5,360
0.021642
# This file is part of the Enkel web programming library. # # Copyright (C) 2007 Espen Angell Kristiansen (espen@wsgi.net) # # 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 # of...
BEFORE HTTP headers are sent to the browser and a traceback IS NOT supplied. This should produce an error, and the same will happen if start_response is called after HTTP headers are sent. """ start_response("200 OK", [("Content-type", "text/plain")]) start_response("500 ERROR", [("Content-type", "text/plain")]) ...
ser and a traceback is supplied. Should work. """ start_response("200 OK", [("Content-type", "text/plain")]) try: int("jeje") except ValueError: start_response("500 ERROR", [("Content-type", "text/plain")], exc_info()) return list() # return empty list class DoubleResponseErrInResponse(object): """ WSG...
teonlamont/mne-python
mne/io/array/tests/test_array.py
Python
bsd-3-clause
4,770
0
# Author: Eric Larson <larson.eric.d@gmail.com> # # License: BSD (3-clause) import os.path as op import matplotlib import numpy as np from numpy.testing import (assert_array_almost_equal, assert_allclose, assert_equal) import pytest from mne import find_events, Epochs, pick_types, channels...
nfo, _kind_dict from mne.utils import requires_
version, run_tests_if_main matplotlib.use('Agg') # for testing don't use X server base_dir = op.join(op.dirname(__file__), '..', '..', 'tests', 'data') fif_fname = op.join(base_dir, 'test_raw.fif') def test_long_names(): """Test long name support.""" info = create_info(['a' * 15 + 'b', 'a' * 16], 1000., ve...
c3nav/c3nav
src/c3nav/editor/urls.py
Python
apache-2.0
4,247
0.004238
from django.apps import apps from django.conf.urls import url from c3nav.editor.views.account import change_password_view, login_view, logout_view, register_view from c3nav.editor.views.changes import changeset_detail, changeset_edit, changeset_redirect from c3nav.editor.views.edit import edit, graph_edit, level_detai...
_detail, name='editor.users.detail'), url(r'^login$', login_view, name='editor.login'), url(r'^logout$', logout_view, name='editor.logout'), url(r'^register$', register_view, name='editor.register'), url(r'^change_password$', change_password_view, name='editor.change_password'), ] urlpatterns.extend(add...
atterns.extend(add_editor_urls('LocationGroup')) urlpatterns.extend(add_editor_urls('DynamicLocation')) urlpatterns.extend(add_editor_urls('WayType')) urlpatterns.extend(add_editor_urls('AccessRestriction')) urlpatterns.extend(add_editor_urls('AccessRestrictionGroup')) urlpatterns.extend(add_editor_urls('Source')) urlp...
Webcampak/v1.0
src/bin/wpakRtsp.py
Python
gpl-2.0
2,214
0.019422
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2010-2012 Infracom & Eurotechnia (sup
port@webcampak.com) # This file is part of the Webcampak project. # Webcampak 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.
# Webcampak 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 copy of the GNU General Public License along with ...
KSanthanam/rethinkdb
test/rdb_workloads/stress_workloads/x_stress_util.py
Python
agpl-3.0
3,021
0.004634
import math, random, datetime def perform_ignore_interrupt(f): while True: try: return f() except IOError as ex: if ex.errno != errno.EINTR: raise # end_date should be of the format YYYY-MM-DD - default is today # interval should be of the format NUMBER (day...
if self.interval_type == "day": start_date = self.end_date - datetime.timedelta(days=delta) end_date = start_date + datetime.timedelta(days=self.interval_length) elif self.interval_type == "month": #
Subtract the delta from the start date start_date = datetime.date(self.end_date.year, self.end_date.month, 1) while start_date.month < delta: delta -= 12 start_date = datetime.date(start_date.year - 1, start_date.month, start_date.day) start_date = dat...
fhs/pyhdf
pyhdf/HC.py
Python
mit
1,928
0.010892
# $Id: HC.py,v 1.2 2005-07-14 01:36:41 gosselin_a Exp $ # $Log: not supported by cvs2svn $ # Revision 1.1 2004/08/02 15:36:04 gosselin # Initial revision # from . import hdfext as _C class HC(object): """The HC class holds const
ants defining opening modes and data types. File opening modes (flags ORed together) CREATE 4 create file if it does not exist READ 1 read-only mode TRUNC 256 truncate if it exists WRITE 2 read-write mode Data types CHAR 4 8-bit char CHAR8 ...
-bit integer (0 to 255) UCHAR8 3 unsigned 8-bit integer (0 to 255) INT8 20 signed 8-bit integer (-128 to 127) UINT8 21 unsigned 8-bit integer (0 to 255) INT16 23 signed 16-bit integer UINT16 23 unsigned 16-bit integer INT32 24 signed 32-bit i...
g8os/core0
docs/_archive/examples/mongodb.py
Python
apache-2.0
3,162
0.004111
#!/bin/python from zeroos.core0.client import Client import sys import time """ This script expect you know the IP of the core0 and you can access it from the machine running this script. an easy way to do it is to build the initramfs with a customr zerotier network id (https://github.com/g8os/initramfs/tree/0.10.0#c...
print("[-] need at least one data disk available") return disks_by_name = {d['name']: d for d in disks} if disks_by_name['sda']['mountpoint'] is None: pri
nt("[+] mount disk") cl.disk.mount('/dev/sda', '/dev/mongodb_storage', ['']) try: print("[+] create container") container_id = cl.container.create('https://stor.jumpscale.org/stor2/flist/ubuntu-g8os-flist/mongodb-g8os.flist', mount={"/dev/mongodb_s...
jyapayne/PePy
__init__.py
Python
mit
36
0
__all__
= ['pe'] from .pe
import *
PeterRochford/SkillMetrics
skill_metrics/plot_pattern_diagram_markers.py
Python
gpl-3.0
4,916
0.015663
import matplotlib.pyplot as plt import matplotlib.colors as clr import matplotlib import warnings from skill_metrics import add_legend def plot_pattern_diagram_markers(X,Y,option): ''' Plots color markers on a pattern diagram. Plots color markers on a target diagram according their (X,Y) location...
markeredgecolor = marker[i][1], markeredgewidth = 2) hp += tuple(h) markerlabel.append(option['markerlabel'][i]) # Add legend if len(markerlabel) == 0: warnings.warn('No markers with
in axis limit ranges.') else: add_legend(markerlabel, option, rgba, markerSize, fontSize, hp) else: # Plot markers as dots of a single color with accompanying labels # and no legend # Plot markers at data points limit = option['axismax'] rgba = cl...
jordanemedlock/psychtruths
temboo/core/Library/eBay/Trading/GetSellerTransactions.py
Python
apache-2.0
7,981
0.007267
# -*- coding: utf-8 -*- ############################################################################### # # GetSellerTransactions # Retrieves order line item (transaction) information for the authenticated user only. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the Apache Licens...
IncludeContainingOrder(self, value): """ Set the value of the IncludeContainingOrder input for this Choreo. ((optional, boolean) When set to true, the ContainingOrder container is retu
rned in the response for each transaction node.) """ super(GetSellerTransactionsInputSet, self)._set_input('IncludeContainingOrder', value) def set_IncludeFinalValueFee(self, value): """ Set the value of the IncludeFinalValueFee input for this Choreo. ((optional, boolean) When set to...
vj-ug/gcloud-python
gcloud/bigquery/test_job.py
Python
apache-2.0
51,631
0.000019
# pylint: disable=C0302 # Copyright 2015 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless require...
resource['statistics']['startTime'] = self.WHEN_TS * 1000 if ended: resource['statistics']['endTime'] = (self.WHEN_TS + 1000) * 1000 return resource def _verif
yInitialReadonlyProperties(self, job): # root elements of resource self.assertEqual(job.etag, None) self.assertEqual(job.job_id, None) self.assertEqual(job.self_link, None) self.assertEqual(job.user_email, None) # derived from resource['statistics'] self.assertEq...
janezhango/BigDataMachineLearning
py/testdir_release/c5/test_c5_KMeans_sphere_26GB.py
Python
apache-2.0
6,833
0.010098
import unittest, time, sys, random, math, json sys.path.extend(['.','..','../..','py']) import h2o, h2o_cmd, h2o_kmeans, h2o_hosts, h2o_import as h2i, h2o_common import socket print "Assumes you ran ../build_for_clone.py in this directory" print "Using h2o-nodes.json. Also the sandbox dir" DO_KMEANS = True # assumes ...
ame = 'syn_sphere_gen.csv' totalBytes = 183538602156 if FROM_HDFS: importFolderPath = "datasets/kmeans_big" csvPathname = importFold
erPath + '/' + csvFilename else: importFolderPath = "/home3/0xdiag/datasets/kmeans_big" csvPathname = importFolderPath + '/' + csvFilename # FIX! put right values in # will there be different expected for random vs the other inits? expected = [ ([0.0,...
Razi91/BiblioTeKa
books/models.py
Python
gpl-2.0
3,611
0.003877
from django.db import models import uuid as uuid __author__ = 'jkonieczny' class Genre(models.Model): name = models.CharField(max_length=32) def __str__(self): return self.name class Publisher(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.nam...
.extra(select={ 'free_entities': "SELECT count(*) FROM books_bookentity " "WHERE books_bookentity.title_id = books_booktitle.id and bo
oks_bookentity.quality > 0" "and (SELECT count(*) FROM user_loan where book_id = books_bookentity.id) = 0", 'available_entities': "SELECT count(*) FROM books_bookentity " "WHERE books_bookentity.title_id = books_booktitle.id and book...
rmp91/jitd
java/stats.py
Python
apache-2.0
893
0.00224
import numpy as np file
= "/home/rishabh/IdeaProjects/jitd/java/benchmark_20151213_224704_freqWrites/ben
chmark_scatter_1024m.txt" # data = np.genfromtxt(file, dtype=(int, float, None), delimiter=',', names=['x', 'y', 'z'],) data = np.genfromtxt(file, dtype=None, delimiter=',', names=['x', 'y', 'z'], ) write = 0 read = 0 max_read = 0 max_write = 0 read_count = 0 write_count = 0 total_time = 0 for each in data: if eac...
addition-it-solutions/project-all
addons/point_of_sale/wizard/pos_session_opening.py
Python
agpl-3.0
5,032
0.006955
from open
erp.osv import osv, fields from openerp.tools.translate import _ from openerp.addons.point_of_sale.point_of_sale import p
os_session class pos_session_opening(osv.osv_memory): _name = 'pos.session.opening' _columns = { 'pos_config_id' : fields.many2one('pos.config', string='Point of Sale', required=True), 'pos_session_id' : fields.many2one('pos.session', string='PoS Session'), 'pos_state' : fields.relate...
eldarion/django-chunked-uploads
chunked_uploads/utils.py
Python
bsd-3-clause
531
0
from chunked_uploads.models import Upload, Chunk def handle_upload(uploaded_file, who): """ Expects to handle an individual file from request.FILES[name] Returns an Upload object """ u = Upload.objects.create( user=who, filename=
uploaded_file.name, filesize=uploaded_file.size ) Chunk.objects.create( upload=u, chunk=uploaded_file, chunk_size=uploaded_file.size ) u.state = Upload.STATE_COMPLETE u.save() u.sti
tch_chunks() return u
cysuncn/python
study/test/TestRe.py
Python
gpl-3.0
655
0
# -*- coding: utf-8 -*- import re test = '用户输入的字符串' if re.match(r'用户', test): print('ok') else: print('failed') print('a b c'.split(' ')) print(re.split(r'\s*'
, 'a b c')) print(re.split(r'[\s\,\;]+', 'a,b;; c d')) m = re.match(r'^(\d{3})-(\d{3,8})$', '010-12345') print(m.group(1)) m = re.match(r'^(\S+)@(\S+.com)$', 'cysuncn@126.com') print(m.group(2)) print(m.groups()) # <Tom Paris> tom@voyager .org re_mail = re.compile(r'<(\S+)\s+(\S+)>\s+(\S+)@(\S+.org)') print(re_mail...
.match(str).group())
google/cloud-berg
examples/mpi_helloworld.py
Python
apache-2.0
855
0.00117
#!/usr/bin/env python # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you
may not use this file except in complia
nce with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express o...
ging/fiware-chef_validator
doc/source/conf.py
Python
apache-2.0
9,737
0.000103
# -*- coding: utf-8 -*- # # fi-ware-chef_validator documentation build configuration file, created by # sphinx-quickstart on Wed Jul 15 12:28:39 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that no
t all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path...
on root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('../../')) sys.path.insert(0, os.path.abspath('../')) sys.path.insert(0, os.path.abspath('./')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphi...
jotes/pontoon
pontoon/sync/formats/__init__.py
Python
bsd-3-clause
2,225
0.000899
""" Parsing resource files. See base.py for the ParsedResource base class. """ import os.path from pontoon.sync.formats import ( compare_locales, ftl, json_extensions, lang, po, silme, xliff, ) # To add support for a new resource format, add an entry to this dict # where the key is the ex...
which describes information about currently processed locale. Some of the formats require information about things like e.g. plural form. """ root, extension = os.path.splitext(path) if extension in SUPPORTED_FORMAT_PARSERS: return SUPPORTED_FORMAT_PARSERS[extension]( path, sourc...
ranslation format {0} is not supported.".format(extension))
seatme/nucleon.amqp
tests/test_limits.py
Python
lgpl-3.0
726
0
import random from gevent.pool import Group from base import TestCase, declares_queues from nucleon.amqp import Connection from nucleon.amqp.spec import FrameQueueDeclareOk qname = 'test%s' % (random.random(),) queues = [qname + '.%s' % (i,) for i in xrange(100)] class TestLimits(TestCase): @declares_queues(*...
(queue=name) g = Group() res = g.map(declare, queues) assert len(res) == len(queues) assert all(isinstance(r, FrameQueueDeclareOk) for
r in res)
rmgorman/django-guardian
guardian/testapp/tests/test_tags.py
Python
bsd-2-clause
6,449
0.002636
from __future__ import unicode_literals from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.models import Group, AnonymousUser from django.contrib.contenttypes.models import ContentType from django.template import Template, Context, TemplateSyntaxError from django.t...
wrong_formats = ( '{% get_obj_perms user
for contenttype as obj_perms %}', # no quotes '{% get_obj_perms user for contenttype as \'obj_perms" %}', # wrong quotes '{% get_obj_perms user for contenttype as \'obj_perms" %}', # wrong quotes '{% get_obj_perms user for contenttype as obj_perms" %}', # wrong quotes ...
openbmc/openbmc-test-automation
lib/boot_data.py
Python
apache-2.0
15,236
0.003544
#!/usr/bin/env python3 r""" This module has functions to support various data structures such as the boot_table, valid_boot_list and boot_results_table. """ import os import tempfile import json import glob from tally_sheet import * from robot.libraries.BuiltIn import BuiltIn try: from robot.utils import DotDict...
wer On"). valid_boot_types A list of valid boot types such as that returned by create_valid_boot_list. """ for boot_name in boot_list: boot_name = boot_name.strip(" ") error_message = gv.valid_value(boot_name, ...
var_name="boot_name") if error_message != "": BuiltIn().fail(gp.sprint_error(error_message)) class boot_results: r""" This class defines a boot_results table. """ def __init__(self, boot_table, boot_pass=0, boot_fail=0, ...
j12y/predixpy
predix/data/eventhub/client.py
Python
bsd-3-clause
7,048
0.002838
import json import logging import os import threading import time import grpc import predix.config import predix.service from predix.data.eventhub import Health_pb2_grpc from predix.data.eventhub import Health_pb2 from predix.data.eventhub.publisher import PublisherConfig, Publisher from predix.data.eventhub.subscrib...
se def _grpc_tx_generator(self): """ the generator taking and messages added to the grpc_tx_queue and yield them to grpc :return: grpc messages """ while self._run_generator: while
len(self._grpc_tx_queue) != 0: yield self._grpc_tx_queue.pop(0) return
nextgis/dhi
general/download_modis_data.py
Python
mit
6,762
0.006655
#!/usr/bin/env python # -*- coding: utf-8 -*- #****************************************************************************** # # download_modis_data.py # --------------------------------------------------------- # Download MODIS data # More: http://github.com/nextgis/dhi # # Usage: # download_modis_data.py [-h]...
# python download_modis_data.py 2003 92 http://e4ftl01.cr.usgs.gov/MOTA/MCD15A3.005/ x:\MCD15A3\2003\ no # # Copyright (C) 2015 Maxim Dubinin (sim@gis-lab.info) # # This source is f
ree 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. # # This code is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY...
rogerthat-platform/rogerthat-gig-g8
src/gig/__init__.py
Python
bsd-2-clause
1,334
0.00075
# Copyright (c) 2016, Rogerthat # All rights reserved. # # Redistribution and use in
source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copy...
the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A ...
JuniorJPDJ/pyChomikBox
ChomikBox/PartFile.py
Python
lgpl-3.0
1,429
0.0014
import io import os def total_len(o): # Stolen from requests_toolbelt and modified if hasattr(o, '__len__'): return len(o) if hasattr(o, 'len'): return o.len if hasattr(o, 'fileno'): try: fileno = o.fileno() except io.UnsupportedOperation: pass...
hasattr(o, 'getvalue'): # e.g. BytesIO, cStringIO.StringIO return len(o.getvalue()) try: current_
pos = o.tell() length = o.seek(0, 2) o.seek(current_pos, 0) return length except IOError: pass class PartFile(io.IOBase): def __init__(self, file, start): assert hasattr(file, 'read') and hasattr(file, 'tell') and hasattr(file, 'seek') assert isinstance(start, i...
t-peters/meetup-doc
Running Scripts from Command Line/sys_arg.py
Python
mpl-2.0
26
0.038462
import
sys print sys.arg
v
globalwordnet/OMW
scripts/load-ili-kinds.py
Python
mit
1,029
0.006803
#!/usr/bin/python3 imp
ort sqlite3, sys # It takes one argument: the name of the new database if (len(sys.argv) < 1): sys.stderr.write('You need to give the name of the ILI DB\n') sys.exit(1) else: dbfile = sys.argv[1] ################################################################ # CONNECT TO DB ############################...
########## # USER ################################################################ u = "ili_load-kinds.py" ################################################################ # INSERT POS DATA (CODES AND NAMES) ################################################################ c.execute("""INSERT INTO kind (id, kind, u) ...
freedesktop-unofficial-mirror/libqmi
utils/qmidb/qmidb.py
Python
gpl-2.0
1,448
0.000691
#!/usr/bin/env python # -*- Mode: python; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- # # 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. # # This program is distributed ...
e Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright (C) 2011 - 2012 Red Hat, Inc. # import sys import Entities import Enums import Fields import Structs if len(sys.argv) > 2: print "Usage: qmi
db.py <path to Entity.txt>" sys.exit(1) path = "" if len(sys.argv) == 2: path = sys.argv[1] + "/" enums = Enums.Enums(path) entities = Entities.Entities(path) fields = Fields.Fields(path) structs = Structs.Structs(path) structs.validate(fields) entities.validate(structs) print '/* GENERATED CODE. DO NOT EDIT...
EdibleEd/vacbooru
VAB_massdownload.py
Python
bsd-2-clause
1,305
0.005364
import urllib2 import urllib import os, sys from bs4 import * argv = sys.argv[1:] begin = int(argv[0]) count = int(argv[1]
) for i in range(begin, begin+count): try: url = 'http://danbooru.donmai.us/posts/' + str(i) request = urllib2.Request(url) response = urllib2.urlopen(request) html = response.read() soup = BeautifulSoup(html) relURL = soup.select('#image')[0]['src'...
relURL = relURL.split('sample-')[1] newPath = 'http://danbooru.donmai.us/data/' + relURL newFile = 'C:\\programming\\vacbooru-master\\dbu\\' + relURL if not os.path.exists(newFile): r = urllib.urlopen(newPath).read() if len(r) > 400: f = open...
apmichaud/vitess-apm
test/keyspace_test.py
Python
bsd-3-clause
10,189
0.008931
#!/usr/bin/python # # Copyright 2013, Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can # be found in the LICENSE file. import base64 import logging import threading import struct import time import unittest from vtdb import keyrange_constants from vtdb import keys...
rtitions(master): -\n' + 'Partitions(rdonly): -\n' +
'Partitions(replica): -\n' + 'TabletTypes: master,rdonly,replica') ALL_DB_TYPES = ['master', 'replica', 'rdonly'] class TestKeyspace(unittest.TestCase): def _read_keyspace(self, keyspace_name): global vtgate_port vtgate_client = zkocc.ZkOccConnection("localhost:%u" ...
iandees/all-the-places
locations/spiders/pigglywiggly.py
Python
mit
4,159
0.004328
# -*- coding: utf-8 -*- import scrapy import json import re import logging from locations.items import GeojsonPointItem class PigglyWigglySpider(scrapy.Spider): ''' This spider scrapes from two different places, an api which has their stores in Wisconsin and Illinois, and a page which has all of their oth...
a0d4a6fad9ba3abc7fadef99ec': 'h3o7xcjnfcERSRrqJVh0soQdUI5IFIBDIQlytOZkhIU
', 'XSRF-TOKEN': 'eF2m10r8n51nsRgBSv1xSvhAGtCo8E84BExlmn54Vvc', 'has_js': 1, } yield scrapy.http.FormRequest( url=url, headers=headers, callback=self.parse_wi, cookies=cookies ) yield scrapy.Request( 'https://www.pigglywiggly.com/store-lo...
RyanSkraba/beam
sdks/python/apache_beam/transforms/external_test_py37.py
Python
apache-2.0
2,471
0.009308
# # 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...
estCase): def get_payload_from_typing_hints(self, values): @dataclasses.dataclass class DataclassTransform(beam.ExternalTransform): URN = 'beam:external:fakeurn:v1' integer_example: int boolean: bool string_example: str list_of_strings: typing.List[str] optional_kv: typi...
r]] = None return get_payload(DataclassTransform(**values)) def get_payload_from_beam_typehints(self, values): @dataclasses.dataclass class DataclassTransform(beam.ExternalTransform): URN = 'beam:external:fakeurn:v1' integer_example: int boolean: bool string_example: str ...
SkyTruth/vectortile
utils/tileinfo.py
Python
mit
2,468
0.000405
#!/usr/bin/env python """Print out a report about whats in a vectortile Usage: tileinfo.py [options] [SOURCE] Options: --srcformat=SRC_FORMAT Source file format: (tile | json) --indent=INT|None JSON indentation level. Defaults to 4. Use 'None' to disable. -h --help Show this screen. --vers...
'tile' if src_format == 'tile': header, data = Tile(f.read()).unpack() else: header = json.loads(f.read()) data = header.pop('data') # Generate the info report
report = info(data, header['cols']) # Merge report with other tile attributes out = {k: v for k, v in header.items() if k != 'data'} out['data'] = {} for field, vals in report.items(): out['data'][field + '_min'] = vals['min'] out['data'][field + '_max'] = vals['...
Tatsh-ansible/ansible
lib/ansible/modules/windows/win_share.py
Python
gpl-3.0
3,686
0.001628
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2015, Hans-Joachim Kliemeck <git@kliemeck.de> # # 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 ...
description: - Add, m
odify or remove Windows share and set share permissions. requirements: - As this module used newer cmdlets like New-SmbShare this can only run on Windows 8 / Windows 2012 or newer. - This is due to the reliance on the WMI provider MSFT_SmbShare U(https://msdn.microsoft.com/en-us/library/hh830471) which was ...
dasseclab/dasseclab
clones/routersploit/tests/exploits/routers/zyxel/test_d1000_rce.py
Python
gpl-2.0
735
0
from unittest import mock from flask import Response from routersploit.modules.exploits.routers.zyxel.d1000_rce import Exploit def apply_response(*args, **kwargs): resp = Response("TEST home_wan.ht
m TEST", status=404) return resp @mock.patch("routersploit.modules.exploits.routers.zyxel.d1000_rce.shell") def test_check_success(mocked_shell, target): """ Test scenario - successf
ul check """ route_mock = target.get_route_mock("/globe", methods=["GET"]) route_mock.side_effect = apply_response exploit = Exploit() assert exploit.target == "" assert exploit.port == 7547 exploit.target = target.host exploit.port = target.port assert exploit.check() assert ex...
chubbymaggie/amoco
tests/test_system_pe.py
Python
gpl-2.0
148
0.02027
import pytest from amoco.system.pe import PE def test_parser_PE(samples): for f in samples: if f
[-4:
]=='.exe': p = PE(f)
ActiveState/code
recipes/Python/577575_scale_rectangle_while_keeping_aspect/recipe-577575.py
Python
mit
175
0.011429
def scale(w, h, x, y, maximum=True): nw = y * w / h nh = x * h / w if maximum ^ (nw >= x):
retur
n nw or 1, y return x, nh or 1
germandiagogomez/meson
test cases/common/98 gen extra/srcgen.py
Python
apache-2.0
650
0.001538
#!/usr/bin/env python3 import sys import os import argparse parser = argparse.ArgumentParser() parser.add_argument('--input', dest='input', help='the input file') parser.add_argument('--output', dest='output', help='the output file') parser.add_argument('--upper', dest='upper',...
return 0; } ''' options = parser.parse_args(sys.argv[1:]) funcname = open(options.i
nput).readline().strip() if options.upper: funcname = funcname.upper() open(options.output, 'w').write(c_templ % funcname)
UNINETT/nav
tests/unittests/netmap/topology_layer2_testcase.py
Python
gpl-2.0
3,029
0.001651
from mock import patch import networkx as nx from nav.models.manage import SwPortVlan, Vlan from nav.netmap import topology from nav.topology import vlan from .topology_testcase import TopologyTestCase class TopologyLayer2TestCase(TopologyTestCase): def setUp(self): super(TopologyLayer2TestCase, self).se...
1], self.a2: [], self.b2:
[], self.a3: [], self.c3: [] }, { self.a: {201: a_vlan_between_a1_and_b1}, self.b: {201: a_vlan_between_a1_and_b1}, self.c: {} })) self.vlans.start() self.build_l2 = patch.object(vlan, '...
fako/datascope
src/sources/models/websites/kleding.py
Python
gpl-3.0
623
0.00321
from core.models.resources.http import HttpResource class KledingListing(HttpResource): URI_TEMPLATE = "https://www.kleding.nl{}" HEADERS = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel
Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36", } def next_parameters(self): mime_type, soup = self.content next_tag = soup.find(attrs={"rel":"next"}) if not next_tag: return {} next_link = next_tag["href"] next_pa...
page }
atty303/pyfilesystem
fs/tests/test_remote.py
Python
bsd-3-clause
11,134
0.005569
#!/usr/bin/env python # -*- coding: utf-8 -*- """ fs.tests.test_remote: testcases for FS remote support utilities """ from fs.tests import FSTestCases, ThreadingTestCases import unittest import threading import random import time import sys from fs.remote import * from fs import SEEK_END from fs.wrapfs import ...
of RemoteFileBuffer. When True, flush() should call setcontents and store to remote destination. When False, setcontents should be called only on close(). ''' self.fakeOn() f = self.fs.open('test.txt', 'wb', write_on_flush=True) f.write('Sample text') ...
'Second sample text') self.assertRaises(self.FakeException, f.close) f = self.fs.open('test.txt', 'wb', write_on_flush=False) f.write('Sample text') # FakeException is not raised, because setcontents is not called f.flush() f.write('Second sample text') s...
tebriel/dd-agent
checks.d/haproxy.py
Python
bsd-3-clause
19,440
0.001235
# (C) Datadog, Inc. 2012-2016 # All rights reserved # Licensed under Simplified BSD License (see LICENSE) # stdlib from collections import defaultdict import re import time # 3rd party import requests # project from checks import AgentCheck from config import _is_affirmative from util import headers STATS_URL = "/;...
data_dict = self._line_to_dict(fields, line) if self._is_aggregate(data_dict): back_or_front = data_dict['svname'] self._update_data_dict(data_dict, back_or_front) self._update_hosts_statuses_if_needed( collect_status_metrics, collect_status_metr...
# update status # Send the list of data to the metric and event callbacks self._process_metrics( data_dict, url, services_incl_filter=services_incl_filter, services_excl_filter=services_excl_filter ) ...
Dawny33/Code
HackerEarth/SuperProf Hiring/footy.py
Python
gpl-3.0
579
0.02418
T = input() while(T): T -= 1 buff = [] a,b = [int(i) for i in raw_input().split()] buff.append(b) pt = 0 while(a): a -= 1 c = [i for i in raw_input().split()] if len(c)==2: c[1] = int(c[1]) if c[0] == "P": buff.append(c[1]) ...
#print k print buff,
buff[k] print "Player " + str(buff[k])
openvenues/lieu
lib/lieu/address.py
Python
mit
8,181
0.000122
import six from collections import defaultdict, OrderedDict from lieu.coordinates import latlon_to_decimal from lieu.encoding import safe_decode class AddressComponents: NAME = 'house' HOUSE_NUMBER = 'house_number' HOUSE_NUMBER_BASE = 'house_number_base' STREET = 'road' BUILDING = 'building' F...
STRICT), ('is_in:city_district', AddressComponents.CITY_DISTRICT), ('quarter', AddressComponents.CITY_DISTRICT), ('addr:quarter', AddressCompo
nents.CITY_DISTRICT), ('is_in:quarter', AddressComponents.CITY_DISTRICT), ('county', AddressComponents.STATE_DISTRICT), ('addr:county', AddressComponents.STATE_DISTRICT), ('is_in:county', AddressComponents.STATE_DISTRICT), ('state_district', AddressComponents....
dotancohen/burton
configure_websites.py
Python
gpl-3.0
4,169
0.023987
import os import re import sys """ * Perform initial configuration to ensure that the server is set up to work with Burton's format sudo chown -R ubuntu:ubuntu /var/www mkdir -p /var/www/default/public_html mv /var/www/html/index.html /var/www/default/public_html # Ubuntu >=14.04 mv /var/www/index.html...
r -p /var/www/%s/logs/' % (site_name
,)) result = os.system('sudo chown -R %s:%s /var/www/%s/' % (current_user, current_user,)) result = os.system('sudo a2ensite %s.conf' % (site_name,)) restart_apache() return True def add_ssl(): global environment print("\nAdd SSL to website.\n") print("Please enter the URL of the website.\n") site_name =...
haje01/swak
tests/test_cli.py
Python
mit
6,911
0
"""This module implements core module test.""" from __future__ import absolute_import import os from subprocess import call import shutil import logging import pytest from swak.plugin import iter_plugins, get_plugins_dir,\ get_plugins_initpy_path, PREFIX from swak.util import which_exe from swak.const import PL...
pfile = os.path.join(plugin_dir, '{}_testfoo.py'.format(pr)) assert os.path.isfile(pfile) with open(pfile, 'rt') as f: code = f.read() assert "class TestFoo" in code readme_file = os.path.join(plugin_dir, 'README.md') assert os.path.isfile(readme_file) with open...
test_file = os.path.join(plugin_dir, 'test_testfoo.py') assert os.path.isfile(test_file) with open(test_file, 'rt') as f: code = f.read() assert 'test_testfoo' in code # enumerate external plugins plugin_infos = list(iter_plugins(False, _filter=plugin_filter_ext)) assert plugin_...
Administrate/surveymonkey
surveymonkey/tests/mocks/utils.py
Python
mit
3,642
0.001647
# -*- coding: utf-8 -*- from __future__ import absolute_import, division import math from datetime import datetime from random import randint from furl import furl from delorean import Delorean def create_quota_headers(qpd=None, qps=None, reset=datetime.now()): qpd_allotted, qpd_current = qpd if qpd else (10000...
urn per_page, current_page, pages def parse_url_with_folder(self, url): per_page, current_page, pages = self.parse_url(url) url = furl(url.geturl()) folder
_id = url.args.get("folder_id", None) return per_page, current_page, pages, folder_id def create_item(self): raise NotImplementedError("Implemented in subclass") def create_items(self, per_page, current_page, pages): items = [] remaining = self.calculate_number_remaining(per_pa...
odarbelaeze/dummy-project
firtFile.py
Python
mit
26
0.038462
# The scripts beg
in here
jlane9/selenium_data_attributes
sda/site.py
Python
mit
1,806
0.000554
# -*- coding: utf-8 -*- """sda.site .. codeauthor:: John Lane <jlane@fanthreesixty.com> """ from sda.element import SeleniumObject try: from urlparse import urljoin, urlparse except (ImportError, ModuleNotFoundError): from urllib.parse import urljoin, urlparse __all__ = ['Site'] class Site(SeleniumObjec...
it__(web_driver)
self.page_1 = Page1(web_driver) self.page_2 = Page2(web_driver) """ @property def domain(self): """Returns the domain for a website :return: domain :rtype: str """ return urlparse(self.url).netloc @property def path(self): ...
leedm777/asterisk
contrib/ast-db-manage/config/versions/45e3f47c6c44_add_pjsip_endpoint_identifier_order.py
Python
gpl-2.0
462
0.008658
"""add pjsip endpoint_identifier_order Revision ID: 45e3f47c6c44 Revises: 945b1098bdd Create Date: 2015-03-02 09:32:20.632015 """ # revision id
entifiers, used by Alembic. revision = '45e3f47c6c44' down_
revision = '945b1098bdd' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column('ps_globals', sa.Column('endpoint_identifier_order', sa.String(40))) def downgrade(): op.drop_column('ps_globals', 'endpoint_identifier_order')
Mirantis/tempest
tempest/api/compute/admin/test_quotas_negative.py
Python
apache-2.0
7,143
0
# Copyright 2014 NEC Corporation. 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 ...
ve', 'gate']) def test_create_server_when_cpu_quota_is_full(self): # Disallow server creation when tenant's vcpu quota is full resp, quota_set = self.
adm_client.get_quota_set(self.demo_tenant_id) default_vcpu_quota = quota_set['cores'] vcpu_quota = 0 # Set the quota to zero to conserve resources resp, quota_set = self.adm_client.update_quota_set(self.demo_tenant_id, force=True, ...
h4ck3rm1k3/github3.py
github3/gists/comment.py
Python
bsd-3-clause
961
0
# -*- coding: utf-8 -*- """ github3.gists.comment --------------------- Module containing the logic for a GistComment """ from __future__ import un
icode_literals from ..models import BaseComment from ..users import User class GistComment(BaseComment): """This object represents a comment on a gist. Two comment instances can be checked like so:: c1 == c2 c1 !=
c2 And is equivalent to:: c1.id == c2.id c1.id != c2.id See also: http://developer.github.com/v3/gists/comments/ """ def _update_attributes(self, comment): self._api = comment.get('url') #: :class:`User <github3.users.User>` who made the comment #: Unless it...
hailinzeng/zhuaxia
zhuaxia/i18n/msg_cn.py
Python
mit
7,738
0.01405
# -*- coding:utf-8 -*- head_xm = u'[虾]' head_163 = u'[易]' #summary fmt_summary_skip_title = u'增量下载忽略列表:' fmt_summary_skip_header = u'来源\t 最后下载时间 \t歌曲名\t保存路径' fmt_summary_success_title = u'成功下载列表:' fmt_summary_success_header = u'歌曲名\t保存路...
= u'开始初始化用户收藏[%s]' fmt_parse_song_url = u'解析歌曲链接[%s]' fmt_init_fav_ok = u'初始化用户收藏完毕[%s]' fmt_init_col
lect = u'开始初始化精选集[%s]' fmt_init_collect_ok = u'初始化精选集完毕[%s]' fmt_init_artist = u'初始化艺人TopSong[%s]' fmt_init_artist_ok = u'初始化艺人TopSong完毕[%s]' dl_128kbps_xm = u' 不登录虾米进行下载, 虾米资源质量为128kbps.' fmt_login_ok_xm = u'[Login] 用户: %s ...
david-ragazzi/nupic
nupic/research/monitor_mixin/plot.py
Python
gpl-3.0
4,761
0.004621
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2014-2015, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This p...
dded. The final digit specifies the nth grid location for the added subplot @param xlabel text to be displayed on the x-axis @param ylabel text to be display
ed on the y-axis @returns (matplotlib.Axes) Axes instance """ ax = self._fig.add_subplot(position) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) return ax
dcondrey/scrapy-spiders
dist/spiders/newenglandfilm.py
Python
mit
1,625
0.009231
#!/usr/bin/python # -*- coding: utf-8 -*- from scrapy.spider import Spider from scrapy.selector import Selector from my_settings import name_file, test_mode, difference_days from datetime import datetime, timedelta print "Run spider NewenglandFilm" file_output = open(name_file, 'a') email_current_sessio...
at(str(num_div))).re('(\d{1,2}\/\d{1,2}\/\d{4})')[0] email = sel.xpath('//*[@id="mainContent"]/div[{0}]/div/text()'.format(str(num_div))).re('(\w+@[a-zA-Z0-9_]+
?\.[a-zA-Z]{2,6})') if current_date == date: for address in email: if address + "\n" not in email_in_file and address not in email_current_session: file_output.write(address + "\n") email_current_session.append(address)...
LinkItONEDevGroup/LASS
LASS-Simulator/codes/ut.py
Python
mit
1,669
0.014979
#! /usr/bin/env python # -*- coding: utf-8 -*- # @file ut.py # @brief The main unit test program of whole project # README: organize the unit tests in the number range # refer UTGeneral functions # print the suggested procedure in the console # print th
e suggested check procedure in the console # support current supported important features # this unit test include in the release procedure # MODULE_ARCH: # CLASS_ARCH:
UTGeneral # GLOBAL USAGE: #standard import unittest #homemake import lib.globalclasses as gc from lib.const import * ##### Unit test section #### #the test ID provide the order of testes. class UTGeneral(unittest.TestCase): #local #ID:0-99 def test_01_setting_signature(self): print("\nThe expe...
frascoweb/frasco-menu
frasco_menu.py
Python
mit
2,929
0.002048
from frasco import Feature, action, hook, current_app, g, request, url_for class MenuMissingError(Exception): pass class Menu(object): def __init__(self, name=None, label=None, view=None, login_required=None, childs=None, separator=False, url=None, **options): self.name = name self.label = l...
urrent_menu", None) if current is None: return requ
est.endpoint == self.view return self.name == current def is_visible(self): if current_app.features.exists("users") and self.login_required is not None: if (self.login_required and not current_app.features.users.logged_in()) or \ (not self.login_required and current_app.f...
kajgan/e2
lib/python/Plugins/SystemPlugins/SkinSelector/plugin.py
Python
gpl-2.0
4,208
0.027329
# -*- coding: iso-8859-1 -*- # (c) 2006 Stephan Reichholf # This Software is Free, use it where you want, when you want for whatever you want and modify it if you want but don't remove my copyright! from Screens.Screen import Screen from Screens.Standby import TryQuitMainloop from Screens.MessageBox import MessageBox f...
elf.session.openWithCallback(self.restartGUI,MessageBox,_("GUI needs a restart to apply a new skin\nDo you want to restart the GUI now?"), MessageBox.TYPE_YESNO) restartbox.setTitle(_("Restart GUI now?")) def loadPreview(self): if self["SkinList"].getCurrent() == DEFAULTSKIN: pngpath = "." else: pngpath =...
elf.root, pngpath), "prev.png") if not os.path.exists(pngpath): pngpath = resolveFilename(SCOPE_PLUGINS, "SystemPlugins/SkinSelector/noprev.png") if self.previewPath != pngpath: self.previewPath = pngpath self["Preview"].instance.setPixmapFromFile(self.previewPath) def restartGUI(self, answer): if an...
GbalsaC/bitnamiP
venv/src/pystache-custom/pystache_custom/tests/examples/delimiters.py
Python
agpl-3.0
281
0.003559
""" TODO: add a docstring. """ class Delimiters(object): def first(self): return "It worked the first time." def second(self): return "And it worked the second time." def third(self): return "Then, surprisingly, it worked the third time.
"
bbchung/clighter
misc/clang/cindex.py
Python
gpl-3.0
107,742
0.001327
#===- cindex.py - Python Indexing Library Bindings -----------*- python -*--===# # # The LLVM Compiler Infrastructure # # This file is distributed under the University of Illinois Open Source # License. See LICENSE.TXT for details. # #===--------------------------------------------------------------...
mn %r>" % ( filename, self.line, self.column) class SourceRange(Structure): """ A SourceRange describes a range of source locations within the source code. """ _fields_ = [ ("ptr_data", c_void_p * 2), ("begin_int_data", c_uint), ("end_int_data",
c_uint)] # FIXME: Eliminate this and make normal constructor? Requires hiding ctypes # object. @staticmethod def from_locations(start, end): return conf.lib.clang_getRange(start, end) @property def start(self): """ Return a SourceLocation representing the first charact...
SekoiaLab/Fastir_Collector
health/windows10StateMachine.py
Python
gpl-3.0
4,814
0.004155
# -*- coding: utf-8 -*- from __future__ import unicode_literals from statemachine import _Statemachine class Windows10StateMachine(_Statemachine): def __init__(self, params): _Statemachine.__init__(self, params) def _list_share(self): return super(Windows10StateMachine, self)._list_...
ateMachine, self)._json_list_sockets_network(self._list_sockets_network()) def json_list_services(self): super(Windows10StateMachine, self)._json_list_services(self._list_services()) def json_list_kb(self): super(Windows10StateMachine, self)._json_li
st_kb(self._list_kb())
ptitjes/quodlibet
quodlibet/formats/_id3.py
Python
gpl-2.0
17,996
0.000111
# Copyright 2004-2013 Joe Wreschnig, Michael Urman, Niklas Janlert, # Steven Robertson, Nick Boultbee # # 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 of th...
_trackid"] = frame.data.decode("utf-8",
"replace") continue elif frame.FrameID == "POPM": rating = frame.rating / 255.0 if frame.email == const.EMAIL: try: self.setdefault("~#playcount", frame.count) except AttributeEr...
nesl/SCPI-Scripts
kei/ag-lib/power_measurement_suite_new.py
Python
bsd-3-clause
1,078
0.014842
import SCPI import time import numpy totalSamples = 10 sampleFreq = 100 #freq= SCPI.SCPI("172.17.5.121") dmm = SCP
I.SCPI("172.17.5.131") #setup freq gen #freq.setSquare() #freq.setVoltage(0,3) #freq.setFrequency(sampleFreq) #setup voltage meter #dmm.setVoltageDC("10V", "MAX") # set external trigger #dmm.setTriggerSource("INT") #dmm.setTriggerCount(str(totalSamples)) # wait for trigger dmm.setInitiate() dmm.setCurrentDC("500mA",...
unt(str(totalSamples)) dmm.setInitiate() time.sleep(1) #freq.setOutput(1) currentMeasurements = [] #voltageMeasurements = [] while 1: if len(currentMeasurements) < totalSamples: currentMeasurements += dmm.getMeasurements() if (len(currentMeasurements) >= totalSamples): break time.sleep...
ingadhoc/odoo-argentina
l10n_ar_ux/wizards/__init__.py
Python
agpl-3.0
400
0
############################
################################################## # For copyright and license notices, see __manifest__.py file in module root # directory ########################################
###################################### from . import res_config_settings from . import account_move_change_rate from . import account_payment_register from . import account_payment_add_checks
piskvorky/flann
test/test_nn_autotune.py
Python
bsd-3-clause
2,411
0.014517
#!/usr/bin/env python import sys from os.path import * import os from pyflann import * from copy import copy from numpy import * from numpy.random import * import unittest class Test_PyFLANN_nn(unittest.TestCase): def setUp(self): self.nn = FLANN(log_level="warning") #################################...
####
###################################################################################### # # Stress it should handle # def test_nn_stress_1d_1pt_kmeans_autotune(self): self.__nd_random_test_autotune(1, 1) def __ensure_list(self,arg): if type(arg)!=list: return [arg] ...
leesdolphin/rentme
rentme/raw/importer/models.py
Python
agpl-3.0
372
0
from django.db
import models class CachedResponse(models.Model): class Meta: unique_together = ( ('method', 'url', 'kwargs') ) method = models.CharField(max_length=10) url = models.TextField() kwargs = models.TextField() content = models.BinaryField() data = models.TextField()...
bruecksen/notifhain
notifhain/event/migrations/0010_auto_20180210_1256.py
Python
mit
821
0.002436
# Generated by Django 2.0.1 on 2018-02-10 11:56 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('event', '0009_auto_20180208_1452'), ] operations = [ migrations.AlterModelOptions( name
='dancefloorevent', options={'ordering': ['event_date'], 'verbose_name': 'Event', 'verbose_name_plural': 'Events'}, ), migrations.AlterModelOptions( name='danceflooreventdetails', options={'ordering': ['event_date'], 'verbose_name': 'Event Detail', 'verbose_name_plura...
=True, null=True), ), ]