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
mali/kdevelop
languages/qmljs/nodejsmodules/http.py
Python
gpl-2.0
3,792
0.001582
#!/usr/bin/python3 # -*- coding: utf-8 -*- # This file is part of qmljs, the QML/JS language support plugin for KDevelop # Copyright (c) 2014 Denis Steckelmacher <steckdenis@yahoo.fr> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # pub...
hostname', _string), ('backlog', _int), ('callback', _function)), F(_void, 'close', ('callback', _function)), Var(_int, 'maxHeadersCount'), F(_void, 'setTimeout', ('msecs', _int), ('callback', _function)), Var(_int, 'timeout'), ), Class('ServerResponse').prototype('event.EventEmi...
void, 'setTimeout', ('msecs', _int), ('callback', _function)), Var(_int, 'statusCode'), F(_void, 'setHeader', ('name', _string), ('value', _string)), Var(_bool, 'headersSent'), Var(_bool, 'sendDate'), F(_string, 'getHeader', ('name', _string)), F(_void, 'removeHeader', ('...
sanyaade-mobiledev/clusto
src/clusto/commands/attr.py
Python
bsd-3-clause
5,122
0.005076
#!/usr/bin/env python # -*- mode: python; sh-basic-offset: 4; indent-tabs-mode: nil; coding: utf-8 -*- # vim: tabstop=4 softtabstop=4 expandtab shiftwidth=4 fileencoding=utf-8 import argparse import sys import clusto from clusto import drivers from clusto import script_helper from pprint import pprint import sys impo...
] != None: opts[k] = kwargs[k] return (getattr(self, 'run_%s' % args.action[0])(opts)) def _add_arguments(self, parser): actions = ['add', 'show', 'set', 'delete'] choices = ['list', 'csv'] if JSON: choices.append('json') if YAML: choi...
'action', nargs=1, metavar='action', choices=actions, help='Action to execute (add, delete, set, show)') parser.add_argument('--format', choices=choices, default='list', help='What format to use to display the info, defaults to "list"') parser.add_argument('-k', '--key', help='At...
h4ck3rm1k3/states-2
sabnzbd/scripts/movie-mover.py
Python
bsd-3-clause
5,436
0.001472
#!/usr/bin/env python from __future__ import print_function import errno import json import os import re import shutil import string import sys import requests CONFIG_FILE = 'scripts.conf' EXTENSIONS = ['avi', 'm4v', 'mkv', 'mp4'] SUB_EXTENSIONS = ['idx', 'sub', 'srt'] PATTERN = re.compile('^(.*)(\d{4})\.(.*)', re.I...
mtree(job_dir) # try to remove the empty category directories parent_dirname = os.path.dirname(job_dir) parent_basename = os.path.basename(parent_dirname) if parent_basename.lower() == category.lower(): try
: os.rmdir(parent_dirname) print("Removed empty directory: %s" % parent_dirname) except OSError: print("Skipped non-empty directory: %s" % parent_dirname) pass if __name__ == '__main__': main(sys.argv[1], sys.argv[5])
dvoets/fibClock
fSequence.py
Python
gpl-2.0
980
0.003061
import collections class fSe
q: def __init__(self, fNumbers): self.fNumbers = fNumbers self.seq = self.fSequence() self.fDecom = self.fDecomposition() def fSequence(self): if self.fNumbers == 1: fSeq = [1] else: fSeq = [1, 1] if self.fNumbers > 2: ...
elf.fNumbers): fmt = '{0:0' + str(self.fNumbers) + 'b}' binToSubset = map(int, list(fmt.format(i))) property_asel = [val for is_good, val in zip(binToSubset, self.seq) if is_good] d.setdefault(sum(property_asel), []).append(binToSubset) return d def toon(self)...
jonathanslenders/libpymux
setup.py
Python
bsd-2-clause
617
0.003241
#!/usr/bin/env python try: from setuptools import setup except ImportError: from distutils.
core import setup requirements = [ 'pyte', 'docopt' ] try: import asyncio except ImportError: requirements.append('asyncio') setup( name='libpymux', author='Jonathan
Slenders', version='0.1', license='LICENSE.txt', url='https://github.com/jonathanslenders/libpymux', description='Python terminal multiplexer (Pure Python tmux clone)', long_description=open("README.rst").read(), packages=['libpymux'], install_requires=requiremen...
nebril/fuel-web
nailgun/nailgun/test/unit/test_attributes_plugin.py
Python
apache-2.0
10,481
0
# Copyright 2014 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re
quired by applicable law or agreed to in writing, software # distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import abc import os import mock import six import yaml from nailgun.db imp...
ktaneishi/deepchem
deepchem/molnet/load_function/lipo_datasets.py
Python
mit
2,563
0.012485
""" Lipophilicity dataset loader. """ from __future__ import division from __future__ import unicode_literals import os import logging import deepchem logger = logging.getLogger(__name__)
def load_lipo(featurizer='ECFP', split='index', reload=True, move_mean=True): """Load Lipophilicity datasets.""" # Featurize Lipophilicity dataset logger.info("About to featurize Lipophilicity dataset.") logger.info("About to load Lipophilicity dataset.") data_dir = deepchem.utils.get_data_dir() ...
dir_name = "lipo/" + featurizer + "_mean_unmoved/" + str(split) save_dir = os.path.join(data_dir, dir_name) dataset_file = os.path.join(data_dir, "Lipophilicity.csv") if not os.path.exists(dataset_file): deepchem.utils.download_url( 'http://deepchem.io.s3-website-us-west-1.amazonaws.com/da...
FriedrichK/volunteer_planner
shiftmailer/management/commands/mailer.py
Python
agpl-3.0
1,636
0.001834
# coding: utf-8 import datetime from django.core.management.base import BaseCommand # from django.template.loader import render_to_string from django.db.models import Count from scheduler.models import Need from shiftmailer.models import Mailer from shiftmailer.excelexport import GenerateExcelSheet DATE_FORMAT = '...
day().strftime(DATE_FORMAT), help='The date to generate scheduler for') def handle(self, *args, **options): mailer = Mailer.objects.all() t = datetime.datetime.strptime(options['print_date'], DATE_FORMAT) for mail in mailer: needs = Need.objects.filte...
n=mail.location).filter( ending_time__year=t.strftime("%Y"), ending_time__month=t.strftime("%m"), ending_time__day=t.strftime("%d")) \ .order_by('topic', 'ending_time') \ .annotate(volunteer_count=Count('registrationprofile')) \ ...
marcoesposito1988/easy_handeye
easy_handeye/scripts/robot.py
Python
lgpl-3.0
414
0.002415
#!/usr/bi
n/env python import rospy from easy_handeye.handeye_server_robot import HandeyeServerRobot def main(): rospy.init_node('easy_handeye_calibration_server_robot') while rospy.get_time() == 0.0: pass calibration_namespace=rospy.get_param('~calibration_namespace') cw = HandeyeServerRobot(namesp...
main()
steve-ord/daliuge
daliuge-engine/dlg/manager/composite_manager.py
Python
lgpl-2.1
19,989
0.002651
# # ICRAR - International Centre for Radio Astronomy Research # (c) UWA - The University of Western Australia, 2015 # Copyright by UWA (in the framework of the ICRAR) # All rights reserved # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser G...
rt `dmPort`. :param: dmPort The port at which the sub-DMs expose themselves :param: partitionAtt
r The attribute on each dropSpec that specifies the partitioning of the graph at this CompositeManager level. :param: subDmId The sub-DM ID. :param: dmHosts The list of hosts under which the sub-DMs should be found. :param: pkeyPath The path to the SSH private key to be used when...
FutureSharks/invokust
tests/test_loadtest.py
Python
mit
866
0
import os from unittest import TestCase from invokust.settings import create_settings from invokust import LocustLoadTest from locus
t import HttpUser, between, task class WebsiteUser(HttpUser): wait_time = between(1, 3) @task() def get_home_page(self): """ Gets / """ self.client.get("/") class TestLocustLoadTest(TestCase): def test_basic_load_test(self): settings = create_settings( ...
) loadtest = LocustLoadTest(settings) loadtest.run() stats = loadtest.stats() assert stats["num_requests"] > 10 assert stats["end_time"] > stats["start_time"] assert stats["requests"]["GET_/"]["total_rpm"] > 0
jackcht/pythonPractice
master/Homework3/hw3q3.py
Python
apache-2.0
573
0.019197
import collection
s import re import urllib2 url = 'http://shakespeare.mit.edu/hamlet/full.html' #url = 'https://courseworks.columbia.edu/access/content/group/COMSW3101_002_2015_3/week3/hamlet.html' req = urllib2.Request(url) response = urllib2.urlopen(req) page = response.read() #lines = page.split('\n') speech = re.findall(r'<b>(.+...
t = collections.defaultdict(int) #int will set all the values to 0 for name in speech: count[name] += 1 #my_dict = {name: speech.count(name) for name in speech} print [len(page.split('\n')), len(speech),count]
call-me-jimi/taskmanager
taskmanager/lib/hLog.py
Python
gpl-2.0
1,397
0.026485
import ConfigParser import os class hLog( object ): """! @brief raw implementation for configuring output of logger """ def __init__( self, logger ): self.logger = logger self.logCategories = {} # load config file
self.load() def load( self ): """! load config file about indication wether message of a particular category is passed to logger """ # get path to taskmanager. it is assumed that this fi
le is in the lib directory of # the taskmanager package. tmpath = os.path.normpath( os.path.join( os.path.dirname( os.path.realpath(__file__) ) + '/..') ) configFileName = '{tmpath}/etc/logger.cfg'.format(tmpath=tmpath) parser = ConfigParser.SafeConfigParser() if os.path.exists...
CIRCL/AIL-framework
var/www/modules/showpaste/Flask_showpaste.py
Python
agpl-3.0
19,911
0.006278
#!/usr/bin/env python3 # -*-coding:UTF-8 -* ''' Flask functions and routes for the trending modules page ''' import redis import json import os import sys import flask from flask import Flask, render_tem
plate, jsonify, request, Blueprint, make_response, Respon
se, send_from_directory, redirect, url_for, abort from Role_Manager import login_admin, login_analyst, login_read_only, no_cache from flask_login import login_required import difflib import ssdeep import Paste import requests sys.path.append(os.path.join(os.environ['AIL_BIN'], 'packages/')) import Tag import Item ...
globocom/database-as-a-service
dbaas/api/recreate_slave.py
Python
bsd-3-clause
770
0
# -*- coding: utf-8 -*- from __
future__ import absolute_import, unicode_literals from rest_framework import serializers from maintenance.models import RecreateSlave from api.maintenance_base import Mai
ntennanceBaseApi class RecreateSlaveSerializer(serializers.ModelSerializer): class Meta: model = RecreateSlave fields = ( 'id', 'current_step', 'status', 'can_do_retry', 'task', 'created_at', 'host', ) cl...
mgree/tmpl
www/backend/infer.py
Python
mit
3,314
0.016898
import sys, os import pickle import nltk import paths from utils import * def words_to_dict(words): return dict(zip(words, range(0, len(words)))) nltk.data.path.append(paths.nltk_data_path) use_wordnet = True if use_wordnet: stemmer = nltk.stem.wordnet.WordNetLemmatizer() stem = stemmer.lemmatize else...
dat_file,"w") out.write(str(len(bow))) out.write(' ') for term in bow: out.write(str(term)) out.write(':') out.write(str(bow[term])) out.write(' ') out.write('\n') out.close() log = base + ".log" os.system(paths.lda + " inf settings.txt %s %s %s >%s 2>&1" % (...
e + "-gamma.dat") gammas = read(model + ".gamma") papers = zip(read(docs), map(lambda s: map(float,s.split()), gammas)) tgt = ["INPUT PDF"] + map(lambda s: map(float,s.split()), inf) # XXX these are the topic values, if we want to visualize them # XXX be careful to not leak our filenames ...
jorgb/airs
gui/images/anim/make_images.py
Python
gpl-2.0
1,181
0.011854
#------------------------------------------------------------------------------- # $RCSfile: make_images.py $ # $Source: repos/minimal_app/src/images/make_images.py $ # $Revision: 1.3 $ # $Date: 18-sep-2007 16:35:29 $ #------------------------------------------------------------------------------- # Author: ...
st = src_f > dst_f # make when image is newer then python file if make_dst: print 'Converting', name, ' to ', root + '.py' i2p.img2py(n
ame, root + '.py')
CodeNameGhost/shiva
thirdparty/scapy/contrib/mqtt.py
Python
mit
8,943
0
# This file is part of Scapy # See http://www.secdev.org/projects/scapy for more informations # Copyright (C) Santiago Hernandez Ramos <shramos@protonmail.com> # This program is published under GPLv2 license from scapy.packet import Packet, bind_layers from scapy.fields import FieldLenField, BitEnumField, StrLenField...
e of the len field depends on the next layer, we need # to "cheat" with the length_of parameter and use adjust parameter to # calculate the value.
VariableFieldLenField("len", None, length_of="len", adjust=lambda pkt, x: len(pkt.payload),), ] class MQTTConnect(Packet): name = "MQTT connect" fields_desc = [ FieldLenField("length", None, length_of="protoname"), StrLenField("protoname", "", ...
scottkirkwood/wxoptparse
tests/rsync.py
Python
gpl-2.0
4,057
0.00986
import optparse if __name__ == "__main__": parser = optparse.OptionParser(add_help_option=False) parser.add_option('-v', '--verbose', action='store_true', help='increase verbosity') parser.add_option('-q', '--quiet', action='store_true',
help='decrease verbosity') parser.add_option('-c', '--checksum',action='store_true', help='always checksum') parser.add_option('-a', '--archive', action='store_true', help='archive mode, equivalent to -rlptgoD') parser.add_option('-r', '--recursive', action='store_true', help='r...
-relative', action='store_true', help='use relative path names') parser.add_option('--no-relative', action='store_true', help='turn off --relative') parser.add_option('--no-implied-dirs', action='store_true', help="don't send implied dirs with -R") parser.add_option('-b', '--backu...
ceb8/astroquery
astroquery/cadc/tests/test_cadctap.py
Python
bsd-3-clause
16,419
0.000731
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ ============= CadcClass TAP plus ============= """ from io import BytesIO from urllib.parse import urlsplit, parse_qs import os import sys from astropy.table import Table as AstroTable from astropy.io.fits.hdu.hdulist import HDUList from astropy.io.v...
es # To avoid this, use an anonymous session and replace it with an # auth session later cadc = Cadc(auth_session=requests.Session()) cadc.cadctap._session = authsession.AuthSession() user = 'user' password = 'password' cert = 'cert' with pytest.raises(AttributeError):
cadc.login(None, None, None) with pytest.raises(AttributeError): cadc.login(user=user) with pytest.raises(AttributeError): cadc.login(password=password) cadc.login(certificate_file=cert) assert cadc.cadctap._session.credentials.get( 'ivo://ivoa.net/sso#tls-with-certificate')....
OptoFidelity/cerbero
cerbero/commands/bootstrap.py
Python
lgpl-2.1
1,583
0.001263
# cerbero - a multi-platform build system for Open Source software # Copyright (C) 2012 Andoni Morales Alastruey <ylatuya@gmail.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; eit...
eral Public # License along with this library; if not, write to the # Free Software Foundation, Inc., 59 Temple Place - Suite 330, # Boston, MA 02111-1307, USA. from cerbero.commands import Command, register_command from cerbero.utils import N_, _, ArgparseArgument from cerbero.bootstrap.bootstrapper import Bootstrap...
args = [ ArgparseArgument('--build-tools-only', action='store_true', default=False, help=_('only bootstrap the build tools'))] Command.__init__(self, args) def run(self, config, args): bootstrappers = Bootstrapper(config, args.build_tools_only) for bootstrappe...
naruhodo-ryuichi/python-xPLpy
xPLpy/xPLConfig.py
Python
agpl-3.0
242
0.004132
# -*- coding: utf-8 -*- from __future__ impo
rt unicode_literals __author__ = "naruhodo-ryuichi" ###############GLOBAL CONFIGURATION # name of xpl host localVendor = "naruhodo-ryuichi" # size o
f receiving buffer in bytes bufferSize = 1500
lngauthier/LEAA.6
python/user_input.py
Python
gpl-2.0
707
0.015559
# # title : Interface # import os import time os.system('clear') print('#### ULTRA SECRET BOOT CAMP - NIS | ABC | NDSFLT | XEX | ####') time.sleep(1) print('Welcome to our organization, Agent 24') time.sleep(1) print('For our reccords, please answer truthfully
to the following questions') time.sleep(1) person = raw_input('Enter your name: ') weapon = raw_input('What is your favourite weapon: ') age = raw_input('How old are you: ') user = { "name":person, "weapon of choice":weapon, "age":age } os.system('clear') print("Do you confirm all of these informations?") print("Ple...
hat if you fail to comply, you could be prosecuted") for key, value in user.items(): print(key + " : " + value)
RedHatInsights/insights-core
insights/tests/datasources/test_cloud_init.py
Python
apache-2.0
3,823
0.001046
import json import pytest from mock.mock import Mock from insights.core import filters from insights.core.dr import SkipComponent from insights.core.spec_factory import DatasourceProvider from insights.specs import Specs from insights.specs.datasources.cloud_init import cloud_cfg, LocalSpecs CLOUD_CFG = """ users: ...
aises(SkipComponent) as e: cloud_cfg(broker) assert 'SkipComponent' in str(e) def test_cloud_cfg_bad(): cloud_init_file = Mock() cloud_init_file.content = CLOUD_CFG_BAD.splitlines() broker = {LocalSpecs.cloud_cfg_input: cloud_init_file} with pytest.raises(SkipComponent) as e: cloud...
broker = {LocalSpecs.cloud_cfg_input: cloud_init_file} with pytest.raises(SkipComponent) as e: cloud_cfg(broker) assert 'Unexpected exception' in str(e)
npyoung/python-neo
neo/core/analogsignalarray.py
Python
bsd-3-clause
11,882
0.000168
# -*- coding: utf-8 -*- ''' This module implements :class:`AnalogSignalArray`, an array of analog signals. :class:`AnalogSignalArray` derives from :class:`BaseAnalogSignal`, from :module:`neo.core.analogsignal`. :class:`BaseAnalogSignal` inherits from :class:`quantites.Quantity`, which inherits from :class:`numpy.arr...
nalogSignal obj = AnalogSignal(obj, sampling_rate=self.sampling_rate) if j.start: obj.t_start = (self.t_start + j.start * self.sampling_period) # return a Quantity (for some reason quantities does not ...
elif isinstance(j, int):
foursquare/pants
tests/python/pants_test/build_graph/test_build_file_aliases.py
Python
apache-2.0
5,509
0.00599
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import os import unittest from pants.build_graph.address import Address from pants.build...
iases(targets=targets, objects={}, context_aware_object_factories=factories), BuildFileAliases(targets=targets, context_aware_object_factories=factories)) self.assertEqual(BuildFil...
BuildFileAliases(objects=objects, context_aware_object_factories=factories)) self.assertEqual(BuildFileAliases(targets=targets, objects=objects, context_aware_object_factories=factori...
brianb/mdbtools
api_docx/pre_build.py
Python
gpl-2.0
969
0.004128
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os ROOT_PATH = os.path.abspath( os.path.join(os.path.dirname( __file__ ), "..")) files = os.listdir(os.path.join(ROOT_PATH, "doc")) index = [] for fname in sorted(files): if not fname.endswith(".txt"): continue cmd_name = fname[:-4] with ope...
cmd_name) with open(out_file, "w") as f: s = "# %s {#%s}\n\n```\n%s\n```\n" % (cmd_name, cmd_name, contents) f.write(s) f.close() index.append(cmd_name) print(" wrote %s" % out_file)
out_file = os.path.join(ROOT_PATH, "temp-man-pages", "index.md") s = "Man Pages {#man-pages}\n" s += "=========================\n\n" for page in index: s += "- @subpage %s\n" % page s += "\n" with open(out_file, "w") as f: f.write(s) f.close()
iglpdc/nipype
nipype/algorithms/tests/test_auto_CalculateNormalizedMoments.py
Python
bsd-3-clause
863
0.005794
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from ...testing import assert_equal from ..misc import Ca
lculateNormalizedMoments def test_CalculateNormalizedMoments_inputs(): input_map = dict(moment=dict(mandatory=True, ), timeseries_file=dict(mandatory=True, ), ) inputs = CalculateNormalizedMoments.input_spec() for key, metadata in list(input_map.items()): for metakey, value in lis...
(metadata.items()): yield assert_equal, getattr(inputs.traits()[key], metakey), value def test_CalculateNormalizedMoments_outputs(): output_map = dict(moments=dict(), ) outputs = CalculateNormalizedMoments.output_spec() for key, metadata in list(output_map.items()): for metakey, v...
Vagab0nd/SiCKRAGE
lib3/jwt/compat.py
Python
gpl-3.0
1,624
0
""" The `compat` module provides support for backwards compatibility with older versions of python, and compatibility wrappers around optional packages. """ # flake8: noqa import hmac import struct import sys PY3 = sys.version_info[0] == 3 if PY3: text_type = str binary_type = bytes else: text_type = un...
ning = remaining >> 8 byte_length += 1 return val.to_bytes(byte_length, 'big', signed=False) else: def bytes_from_int(val): buf = [] while val: val, remainder = divmod(val, 256) buf.append(remainder) buf.reverse() return st
ruct.pack('%sB' % len(buf), *buf)
nagyistoce/eutester
testcases/cloud_admin/4-2/euca9959.py
Python
bsd-2-clause
3,192
0.004386
''' Created on = '10/28/13" Author = 'mmunn' Unit test : EUCA-9959 MalformedPolicyDocument: Policy document should not specify a principal." Should Be Returned setUp : Install Credentials, test : create role with MalformedPolicyDocument and make sure an error message is returned ins...
elf.clc_ip + ':role-trust.json') # create user role self.runSysCmd("euare-rolecreate -r describe-instances -f role-trust.json --region " + self.account + "-
" + self.username) self.runSysCmd("euare-roleuploadpolicy -r describe-instances -p describe-instances-policy -f role-describe-instances-principle.json --region " + self.account + "-" + self.username) print self.STARTC + "Success " + str(self.out) + " ENABLED " + self.ENDC # Check to see that th...
Onager/plaso
plaso/engine/extractors.py
Python
apache-2.0
20,405
0.006273
# -*- coding: utf-8 -*- """The extractor class definitions. An extractor is a class used to extract information from "raw" data. """ import copy import pysigscan from dfvfs.helpers import file_system_searcher from dfvfs.lib import definitions as dfvfs_definitions from dfvfs.lib import errors as dfvfs_errors from df...
"""Determines if a parser can process a file entry. Args: file_entry (dfvfs.FileEntry): file entry. parser (BaseParser): parser. Returns: bool: True if the file entry can be processed by the parser object. """ for filter_object in parser.FILTERS: if filter_object.Match(fil...
hes one of the known signatures. Args: file_object (file): file-like object whose contents will be checked for known signatures. Returns: list[str]: parser names for which the contents of the file-like object matches their known signatures. """ parser_names = [] sca...
lorin/umdinst
test/testidentifysourcefiles.py
Python
bsd-3-clause
1,396
0.012178
import unittest import s
ys import os import errno import commands from xml.dom import minidom sys.path.append('bin') from umdinst import wrap from testsuccessfulcompiledata import getfield, timezonecheck, xmlifystring from testcapturecompile import programcheck def
createemptyfile(fname): """Creates an empty file. Throws an exception if the file alrady exists""" if os.access(fname,os.R_OK): raise ValueError,"File already exists" f = open(fname,'w') f.close() class TestIdentifySourcefiles(unittest.TestCase): def setUp(self): # Create some sour...
davidovitch/f90wrap
examples/example-arrays/tests.py
Python
gpl-2.0
1,524
0.002625
# -*- coding: utf-8 -*- """ Created on Tue Jul 28 15:19:03 2015 @author: David Verelst """ from __future__ import print_function import unittest import numpy as np import
ExampleArray as lib class TestExample(unittest.TestCase): def setUp(self): pass def do_array_stuff(self, ndata): x = np.arange(ndata) y = np.arange(ndata) br = np.zeros((ndata,), order='F') co = np.zeros((4, ndata), order='F') lib.library.do_array_stuff(n=nda...
:]) np.testing.assert_allclose(x/(y+1.0), br) def test_basic(self): self.do_array_stuff(1000) def test_verybig_array(self): self.do_array_stuff(1000000) def test_square(self): n = 100000 x = np.arange(n, dtype=float) y = np.arange(n, dtype=float) br...
Debian/dak
dak/check_overrides.py
Python
gpl-2.0
19,666
0.004271
#! /usr/bin/env python3 """ Cruft checker and hole filler for overrides @contact: Debian FTPMaster <ftpmaster@debian.org> @copyright: 2000, 2001, 2002, 2004, 2006 James Troup <james@nocrew.org> @opyright: 2005 Jeroen van Wolffelaar <jeroen@wolffelaar.nl> @copyright: 2011 Joerg Jaspert <joerg@debian.org> @license: ...
'component_id': component_id, 'type_id':
type_id}) # create source overrides based on binary overrides, as source # overrides not always get created q = session.execute("""SELECT package, priority, section, maintainer FROM override WHERE suite = :suite_id AND component = :component_id""", ...
antlarr/picard
picard/ui/searchdialog/__init__.py
Python
gpl-2.0
16,428
0.001278
# -*- coding: utf-8 -*- # # Picard, the next-generation MusicBrainz tagger # Copyright (C) 2016 Rahul Raturi # Copyright (C) 2018 Laurent Monin # # 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; ...
ccept_button.setEnabled(False) def setupUi(self): self.layout = QtWidgets.QVBoxLayout(self) self.search_row_widget = QtWidgets.QWidget(self) self.search_row_layout = QtWidgets.QHBoxLayout(self.search_row_widget) self.search_row_layout.setContentsMargins(1, 1, 1, 1) self.sear...
= QtWidgets.QLineEdit(self.search_row_widget) self.search_edit.setClearButtonEnabled(True) self.search_edit.returnPressed.connect(self.trigger_search_action) self.search_edit.textChanged.connect(self.enable_search) self.search_edit.setFocusPolicy(QtCore.Qt.StrongFocus) self.searc...
Microvellum/Fluid-Designer
win64-vc/2.78/python/lib/unittest/suite.py
Python
gpl-3.0
10,478
0.000477
"""TestSuite""" import sys from . import case from . import util __unittest = True def _call_if_exists(parent, attr): func = getattr(parent, attr, lambda: None) func() class BaseTestSuite(object): """A simple test suite that doesn't provide class or module shared fixtures. """ _cleanup = True...
"before passing them to addTest()") self._tests.append(test) def addTests(self, tests): if isinstance(tests, str): raise TypeError("tests must be an iterable of tests, not a string") for test in tests: self.addTest(test) def run(self, result): for ...
lt) if self._cleanup: self._removeTestAtIndex(index) return result def _removeTestAtIndex(self, index): """Stop holding a reference to the TestCase at index.""" try: test = self._tests[index] except TypeError: # support for suite i...
praekeltfoundation/mc2-freebasics
freebasics/migrations/0007_freebasicscontroller_postgres_db_url.py
Python
bsd-2-clause
442
0
# -*- coding: utf-8 -*- from __future__ import unicode_lit
erals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('freebasics', '0006_change_site_url_field_type'), ] operations = [ migrations.AddField( model_name='freebasicscontroller', name='postgres_db_url', ...
blank=True), ), ]
tchellomello/home-assistant
tests/components/nightscout/test_config_flow.py
Python
apache-2.0
3,995
0.000751
"""Test the Nightscout config flow.""" from aiohttp import ClientConnectionError from homeassistant import config_entries, data_entry_flow, setup from homeassistant.components.nightscout.const import DOMAIN from homeassistant.components.nightscout.utils import hash_from_url from homeassistant.const import CONF_URL fr...
://some.url:1234"}, ) assert result2["type"] == data_entry_flow.RESULT_TYPE_FORM assert result2["errors"] == {"base": "unknown"} async def test_user_form_duplicate(hass): """Test duplicate entries.""" with _patch_glucose_readings(), _pat
ch_server_status(): unique_id = hash_from_url(CONFIG[CONF_URL]) entry = MockConfigEntry(domain=DOMAIN, unique_id=unique_id) await hass.config_entries.async_add(entry) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOU...
mobarski/smash
test/test-parse2.py
Python
mit
600
0.06
in1 = """ [aaa] a = 123 456 789 b = 321 654 987 c = 135 24
6 999 """ in2 = """ [cmd]= ok [cmd] << 40+2 x << 123*2 [cmd] <<< x = 42 y = 123 print(x,y) ... print ok [data] = 1 2 3 4 5 6 7 8 9 [tsv] head = no cols = a b c out >> tab [insert] << tab table = mydata """ in2 = """ [aaa] <<< jest test x = 42 = x 123123 123123 123123554 [bbb] << x x = 42 [ccc...
rgs:',args(s)) print()
bernard357/shellbot
examples/todos.py
Python
apache-2.0
3,482
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional inf
ormation regarding copyright ownership. # The ASF licenses this file to You under the Apa
che License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distribute...
IsCoolEntertainment/pynba
src/iscool_e/pynba/globals.py
Python
mit
221
0
# -*- coding: utf-8 -*- """ IsCool-e Pynba ~~~~~~~~~~~~~~ :copyri
ght: (c) 2015 by IsCool Entertainment. :license: MIT, see LICENSE for more details. """ from pynba.wsgi import pynba _
_all__ = ['pynba']
jianajavier/pnc-cli
pnc_cli/swagger_client/models/user.py
Python
apache-2.0
6,614
0.000605
# coding: utf-8 """ Copyright 2015 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applica...
er. :param field_handler: The field_handler of this User. :type: FieldHandler """ self._field_handler = field_handler def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types)...
ist): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, datetime): result[attr] = str(va...
gunan/tensorflow
tensorflow/python/ops/nccl_ops.py
Python
apache-2.0
8,087
0.006059
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
of tensors, each with the sum of the input tensors, where tensor i has the same device as `tensors[i]`. """ return _apply_all_reduce('sum', tensors) @ops.RegisterGradient('NcclAllReduce') def _all_sum_grad(op, grad): """The gradients for `all_sum`. Args: op: The `all_
sum` `Operation` that we are differentiating. grad: Gradient with respect to the output of the `all_sum` op. Returns: The gradient with respect to the output of `all_sum`. Raises: LookupError: If `reduction` is not `sum`. """ if op.get_attr('reduction') != b'sum': raise LookupError('No gradien...
ampotty/fas
scripts/export-bugzilla.py
Python
gpl-2.0
5,752
0.00452
#!/usr/bin/python -t __requires__ = 'TurboGears' import pkg_resources pkg_resources.require('CherryPy >= 2.0, < 3.0alpha') import logging logging.basicConfig() import os import sys import getopt import xmlrpclib import smtplib from email.Message import Message import warnings # Ignore DeprecationWarnings. This allo...
g = Message() people = [] for person in no_bz_account: if person.person.status == 'Active':
people.append(' %(user)s -- %(name)s -- %(email)s' % {'name': person.person.human_name, 'email': person.email, 'user': person.person.username}) if people: people = '\n'.join(people) message = ''' The following people are in the pac...
esaezgil/aiohttp
aiohttp/client.py
Python
apache-2.0
26,142
0.000191
"""HTTP Client for asyncio.""" import asyncio import base64 import hashlib import os import sys import traceback import warnings from multidict import CIMultiDict, MultiDict, MultiDictProxy, istr from yarl import URL import aiohttp from . import hdrs, helpers from ._ws_impl import WS_KEY, WebSocketParser, WebSocket...
is
not None: self._cookie_jar.update_cookies(cookies) self._connector = connector self._default_auth = auth self._version = version # Convert to list of tuples if headers: headers = CIMultiDict(headers) else: headers = CIMultiDict() ...
dberc/tpzsimul.gems
jgraph/xact_mem.py
Python
gpl-2.0
140,056
0.019185
#!/s/std/bin/python import sys, string, os, glob, re, mfgraph #results_dir = "../results/isca07_final_version" #results_dir = "/p/multifacet/projects/logtm_eager_lazy/ISCA07_results/old/old-11-7/" results_dir = "../results/" #results_dir = "/p/multifacet/projects/shore/HPCA-filters-results/non-smt/" #results_dir = "/...
) line = string.split(grep_lines[0]) return int(line[6]) def get_average_stat(file, stat): grep_lines = mfgraph.grep(file, stat) if (grep_lines == []): return -1 line = string.split(grep_lines[0]) return float(line[8]) def make_microbench_line(jgraphs, name, runs, bw, protocol_ma...
5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31] #proc_values = [1, 2, 3, 4, 5, 6, 7] read_set = None data = [] for run in runs: #print run protocol = protocol_map[run[...
beiko-lab/gengis
bin/Lib/site-packages/numpy/f2py/setupscons.py
Python
gpl-3.0
4,305
0.009988
#!/usr/bin/env python """ setup.py for installing F2PY Usage: python setup.py install Copyright 2001-2005 Pearu Peterson all rights reserved, Pearu Peterson <pearu@cens.ioc.ee> Permission to use, modify, and distribute this software is given under the terms of the NumPy License. NO WARRANTY IS EXPRESS...
py.distutils.core import setup from numpy.distutils.misc_util import Configuration from __version__ import version def configuration(parent_package='',top_path=None): config = Configuration('f2py', parent_package, top_path) config.add_data_dir('docs') config.add_data_files('src/fortranobject.c...
) config.make_svn_version_py() def generate_f2py_py(build_dir): f2py_exe = 'f2py'+os.path.basename(sys.executable)[6:] if f2py_exe[-4:]=='.exe': f2py_exe = f2py_exe[:-4] + '.py' if 'bdist_wininst' in sys.argv and f2py_exe[-3:] != '.py': f2py_exe =...
EnTeQuAk/dotfiles
sublime-text-3/Packages/isort/pies/dbm/__init__.py
Python
unlicense
184
0
from
__future__ import absolute_import from dbm import * from ..version_info import PY2 if PY2: from . import dumb, gnu, ndbm from whichdb import * fr
om anydbm import *
markbenvenuto/buildbaron
analyzer/evg_log_file_analyzer.py
Python
apache-2.0
3,551
0.002534
#!/usr/bin/env python3 """ Analyze a evergreen task log page """ import argparse import json import os import sys if __name__ == "__main__" and __package__ is None: sys.path.append(os.path.dirname(os.path.abspath(os.path.realpath(__file__)))) print(sys.path) import faultinfo else: from . import faultin...
to read") args = parser.parse_args() for file in args.files: with open(file, "rb") as lfh: log_file_str = lfh.read().decode('utf-8') analyzer = EvgLogFileAnalyzer(log_file_str) analyzer.analyze() faults = analyzer.get_faults() if len(faults) == 0: ...
rint("===========================") print("Analysis failed for test: " + file) print("===========================") return for f in analyzer.get_faults(): print(f) print(analyzer.to_json()) f = json.loads(analyzer.to_json(), cls=faultinfo.Custom...
DorianDepriester/mtex2abaqus
MTEX2abaqus/AbaqusImport.py
Python
mit
2,602
0.04804
import string import csv import os from abaqusConstants import * from part import * from material import * from section import * from assembly import * from load import * from mesh import * from visualization import * def im
portEBSD(inpFileName): while True: fileName, file_extension = os.path.splitext(inpFileName) # Load grain properties try: file = open(fileName+'.csv', "r") reader = csv.DictReader(file,delimiter='\t',lineterminator='\n',quoting = csv.QUOTE_NONNUMERIC) phase=[];Xx=[];Xy=[];Xz=[];Yx=[];Yy=[];Yz=...
],) Yy.append(row['Yy'],) Yz.append(row['Yz'],) file.close() except IOError: print 'Error:',fileName+'.csv','not found.' break mdbName=os.path.basename(fileName) # Import INP file try: mdb.ModelFromInputFile(name=mdbName,inputFileName=inpFileName) pk=mdb.models[mdbName].parts...
pdgilbert/Vcourse
lib/GUIutils.py
Python
gpl-2.0
2,664
0.033408
import tkinter import logging ######################### Utility Functions ######################### def But(w, text='x', command='', side=tkinter.LEFT) : b = tkinter.Button(w, text=text, command=command) b.pack(side=side, padx=5, pady=5) return(b) def Drop(w, options=['zero', 'one', 'two'], defaul...
) b.pack(side=tkinter.LEFT
) #b.config(font=("Helvetica", 10)) does not reset, default on next call does the reset return v def ROW(t, text, width=30, ebg=None, pad=5): #ebg None means no entry field, otherwise color of entry field bg. row = tkinter.Frame(t) lab = tkinter.Label(row, width=width, text=text, anchor='w') if ebg i...
rmyers/trove-dashboard
setup.py
Python
apache-2.0
673
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in complian
ce with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from setuptools import setup setup( setup_requires=['pbr'], pbr=True, )
Exgibichi/statusquo
test/functional/zmq_test.py
Python
mit
4,305
0.002091
#!/usr/bin/env python3 # Copyright (c) 2015-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the ZMQ API.""" import configparser import os import struct from test_framework.test_framework im...
# Destroy the zmq context self.log.debug("Destroying zmq context") self.zmqContext.destroy(linger=None) def _zmq_test(self): genhashes = self.nodes[0].generate(1) self.sync_all() self.log.info("Wait for tx") msg = self.zmqSubSocket.recv_multipart()...
t_equal(msgSequence, 0) # must be sequence 0 on hashtx self.log.info("Wait for block") msg = self.zmqSubSocket.recv_multipart() topic = msg[0] body = msg[1] msgSequence = struct.unpack('<I', msg[-1])[-1] assert_equal(msgSequence, 0) # must be sequence 0 on hashblock ...
nijinashok/sos
sos/plugins/xfs.py
Python
gpl-2.0
1,029
0
# This file is part of the sos project: https://github.com/sosreport/sos # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # version 2 of the GNU General Public License. # # See the LICENSE file in the source distribution ...
plugin_name = 'xfs' profiles = ('storage',) def setup(self): mounts = '/proc/mounts' ext
_fs_regex = r"^(/dev/.+).+xfs\s+" for dev in zip(self.do_regex_find_all(ext_fs_regex, mounts)): for e in dev: parts = e.split(' ') self.add_cmd_output("xfs_info %s" % (parts[1])) self.add_cmd_output("xfs_admin -l -u %s" % (parts[1])) self.add_...
kjordahl/xray
xray/core/dataset.py
Python
apache-2.0
72,806
0.00011
import functools import warnings from collections import Mapping, Sequence from numbers import Number import numpy as np import pandas as pd from . import ops from . import utils from . import common from . import groupby from . import indexing from . import alignment from . import formatting from .. import conventio...
common_dims.update(zip(var.dims, var.shape)) variables[name] = existing_var.expand_dims(common_dims) new_coord_names.update(var.dims) def add_variable(name, var): var = _as_dataset_variable(name, var) i
f name not in variables: variables[name] = var new_coord_names.update(variables[name].dims) else: if not getattr(variables[name], compat)(var): raise ValueError('conflicting value for variable %s:\n' 'first value: %r\nsecond va...
durante987/nonogram_solver
tests/rules/test_init.py
Python
mit
3,997
0.001251
#!/usr/bin/env python3.8 import os import sys import unittest SCRIPT_DIR = os.path.dirname( os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__)))) sys.path.append( os.path.normpath(os.path.join(SCRIPT_DIR, os.path.pardir, os.path.pardir))) # pylint: disable=wrong-import-position from nono...
UNKNOWN, UNKNOWN, BLACK, UNKNOWN, WHITE, UNKNOWN, BLACK ]) expected = [ Block(start=0, end=0, length=1), Block(start=2, end=2, length=1), Block(start=7, end=7, length=1), Block(start=10, end=10, length=1), Block(start=14, end=14, length=1)...
UNKNOWN, BLACK, BLACK, WHITE, UNKNOWN, WHITE, UNKNOWN, UNKNOWN, BLACK, BLACK ]) expected = [ Block(start=1, end=2, length=2), Block(start=8, end=9, length=2) ] self.assertEqual(expected, rules._get_black_runs(mask)) mask = bytearray([BL...
DH-Box/dhbox
dhbox.py
Python
gpl-3.0
13,293
0.002558
import os, os.path, random, string, time, urllib2 from flask import Flask, flash, request, redirect, url_for, render_template, \ make_response, abort import ast from flask_sqlalchemy import SQLAlchemy from flask_security import Security, SQLAlchemyUserDatastore, login_user, logout_user, \ UserMixin, RoleMixin, ...
Column('role_id', db.Integer(), db.ForeignKey('role.id'))) class Role(db.Model, RoleMixin): id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(80), unique=True) description = db.Column(db.String(255)) class User(db.Model, UserMixi
n): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(255), unique=True) name = db.Column(db.String(255), unique=True) pwdhash = db.Column(db.String(160)) active = db.Column(db.Boolean()) dhbox_duration = db.Column(db.Integer) confirmed_at = db.Column(db.DateTime()) ...
kaflesudip/TweetStats
update_tweets.py
Python
apache-2.0
2,656
0.00113
from twython import Twython from models import Tweet import datetime import traceback # import time # first APP_KEY = '' APP_SECRET = '' OAUTH_TOKEN = '' OAUTH_TOKEN_SECRET = '' # second APP_KEY2 = '' APP_SECRET2 = '' OAUTH_TOKEN2 = '' OAUTH_TOKEN_SECRET2 = '' # third APP_KEY3 = '' APP_SECRET3 = '' OAUTH_TOKEN3 =...
otal_fetched=1, error_occured__ne=True) print("updating") i = 0 error_count = 0 for each_tweet in tweets: print("loop") data = update_given_tweet(each_tweet.tweet_id) if not data: error_count += 1 print("!!!!!!!!!error", error_count, "correct", i) ...
a['fetched_timestamp'] = datetime.datetime.now() data['fresh_tweet'] = False data['update_count'] = 2 each_tweet.total_fetched = 2 each_tweet.tweets.append(data) each_tweet.save() print(i, "errors=", error_count) i += 1 update_database()
omwdunkley/crazyflieROS
src/crazyflieROS/cflib/utils/callbacks.py
Python
gpl-2.0
1,843
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # # || ____ _ __ # +------+ / __ )(_) /_______________ _____ ___ # | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \ # +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/ # || || /_____/_/\__/\___/_/ \__,_/ /___/\___/ # # Copyright (C) 20...
GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. """ Callback objects
used in the Crazyflie library """ __author__ = 'Bitcraze AB' __all__ = ['Caller'] class Caller(): """ An object were callbacks can be registered and called """ def __init__(self): """ Create the object """ self.callbacks = [] def add_callback(self, cb): """ Register cb as a new ...
sigproc/robotic_surgery
src/ros/crustcrawler_smart_arm/smart_arm_kinematics/nodes/test_ik_service.py
Python
mit
3,443
0.004066
#!/usr/bin/env python # Copyright (c) 2010, Antons Rebguns. 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, t...
VICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING N
EGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # Author: Antons Rebguns import roslib; roslib.load_manifest('smart_arm_kinematics') import time import rospy from geometry_msgs.msg import PointStamped from smart_arm_kinematics.srv im...
pferreir/indico
indico/modules/events/surveys/views.py
Python
mit
1,351
0.00074
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from indico.modules.events.management.views import WPEventManagement from indico.modules.events.views impo...
e): template_prefix =
'events/surveys/' base_class = WPConferenceDisplayBase menu_entry_name = 'surveys' bundles = ('module_events.surveys.js', 'module_events.surveys.css') class WPDisplaySurveySimpleEvent(DisplaySurveyMixin, WPSimpleEventDisplayBase): template_prefix = 'events/surveys/' base_class = WPSimpleEventDisp...
nikolay-fedotov/tempest
tempest/api/compute/admin/test_fixed_ips_negative.py
Python
apache-2.0
3,516
0
# Copyright 2013 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 ...
dminTest): @classmethod def resource_setup(cls): super(FixedIPsNegativeTestJson, cls).resource_setup() if CONF.service_available.neutron: msg = ("%s skipped as neutron is available" % cls.__name__) raise cls.skipException(msg) cls.client = cls.os_adm.fixed_ips_cl...
CTIVE') resp, server = cls.servers_client.get_server(server['id']) for ip_set in server['addresses']: for ip in server['addresses'][ip_set]: if ip['OS-EXT-IPS:type'] == 'fixed': cls.ip = ip['addr'] break if cls.ip: ...
LIP-Computing/pelogw
src/epilw.py
Python
apache-2.0
950
0
#!/usr/bin/python ''' Epilog wrapper for docker images submission to batch systems Created on Oct 28, 2015 @author: mariojmdavid@gmail.com ''' import time import os import peUtils if __name__ == '__main__': print '===========================================' print '========================================...
al']['comp_stdout']] comp_stderr = os.environ[param['global']['comp_stderr']] sub_host = os.environ[param['global']['sub_host']] sub_workdir = os.environ[param['global']['sub_workdir']] print 'S
TDOUT: %s' % comp_stdout print 'STDERR: %s' % comp_stderr os.system('scp -r -q %s %s:%s' % (comp_stdout, sub_host, sub_workdir)) os.system('scp -r -q %s %s:%s' % (comp_stderr, sub_host, sub_workdir)) os.system('rm -f *') print '==========================================='
google/ctfscoreboard
scoreboard/mail.py
Python
apache-2.0
4,180
0
# Copyright 2018 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0
# # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the Li
cense. from email.mime import text import email.utils import smtplib import socket import mailjet_rest from scoreboard import main app = main.get_app() class MailFailure(Exception): """Inability to send mail.""" pass def send(message, subject, to, to_name=None, sender=None, sender_name=None): """Send...
dakiri/splunk-app-twitter
twitter2/bin/oauthlib/oauth2/rfc6749/parameters.py
Python
apache-2.0
12,583
0.000397
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals """ oauthlib.oauth2.rfc6749.parameters ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This module contains methods related to `Section 4`_ of the OAuth 2 RFC. .. _`Section 4`: http://tools.ietf.org/html/rfc6749#section-4 """ import json try: i...
in seconds of the access token.
For example, the value "3600" denotes that the access token will expire in one hour from the time the response was generated. If omitted, the authorization server SHOULD provide the expiration time via other means or document the default value. **scope** ...
ryfeus/lambda-packs
Keras_tensorflow_nightly/source2.7/tensorflow/tools/api/generator/api/keras/__init__.py
Python
mit
1,351
0.00074
"""Imports for Python API. This file is MACHINE GENERATED! Do not edit. Generated by: tensorflow/tools/api/generator/create_python_api.py script. """ from tensorflow.python.keras import Input from tensorflow.python.keras impo
rt Model from tensorflow.python.keras import Sequ
ential from tensorflow.tools.api.generator.api.keras import activations from tensorflow.tools.api.generator.api.keras import applications from tensorflow.tools.api.generator.api.keras import backend from tensorflow.tools.api.generator.api.keras import callbacks from tensorflow.tools.api.generator.api.keras import const...
vsajip/django
tests/regressiontests/generic_inline_admin/tests.py
Python
bsd-3-clause
17,051
0.002932
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.conf import settings from django.contrib import admin from django.contrib.admin.sites import AdminSite from django.contrib.contenttypes.generic import ( generic_inlineformset_factory, GenericTabularInline) from django.form...
url" value="http://example.com/logo.png" maxlength="200" /><input type="hidden" name="generic_inline_admin-media-content_type-objec
t_id-1-id" value="%s" id="id_generic_inline_admin-media-content_type-object_id-1-id" /></p>' % self.png_media_pk) self.assertHTMLEqual(formset.forms[2].as_p(), '<p><label for="id_generic_inline_admin-media-content_type-object_id-2-url">Url:</label> <input id="id_generic_inline_admin-media-content_type-object_id...
giliam/sharbrary
discussion/tests.py
Python
gpl-2.0
7,655
0.012021
# coding: utf-8 from django.test import TestCase from django.contrib.auth.models import User, Permission from django.utils import timezone from django.core.urlresolvers import reverse from django.contrib.auth.models import Group from utils.tests.common_test_case import CommonTestCase, with_login_user from discussion....
iscussion=self.discussion,message='Yoplait !',author=self.bob) response = self.client.post(reverse('message_delete',args=[message.id]),{}) # only moderators can delete messages self.assertEqual(response.status_code, 403) @with_login_user('bib') def test_update(self): message = M...
response = self.client.post(reverse('message_edit',args=[message.id]),data) self.assertEqual(response.status_code, 302) self.assertRedirects(response, reverse('discussion_list')) try: message = Message.objects.get(**data) except Message.DoesNotExist: ...
pair-code/lit
lit_nlp/lib/wsgi_serving.py
Python
apache-2.0
4,652
0.004944
# Copyright 2020 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 agreed to in writing, s...
werkzeug_serving class BasicDevServer(object): """Basic development server; not recommended for deployment.""" def __init__(self, wsgi_app, port: int = 4321, host: Text = '127.0.0.1', **unused_kw): self._port = port self._host = host self._app = wsgi_app self.can_act_as_model_serv...
def serve(self): """Start serving.""" logging.info(('\n\nStarting Server on port %d' '\nYou can navigate to %s:%d\n\n'), self._port, self._host, self._port) werkzeug_serving.run_simple( self._host, self._port, self._app, use_debugger=False,...
ygol/odoo
addons/hr_holidays/tests/__init__.py
Python
agpl-3.0
460
0
# -*- c
oding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from . import test_access_rights from . import test_automatic_leave_dates from . import test_allocation_access_rights from . import test_holidays_flow from . import test_hr_leave_type from . import test_accrual_allocations from...
eave
tfeldmann/tryagain
tasks.py
Python
mit
450
0
import os from invoke
import task @task def test(): os.system('coverage run --source tryagain -m py.test') os.system('coverage report') @task def register(production=False): target = 'pypi' if production else 'pypitest' os.system('python3 setup.py register -r %s' % target) @task def upload(production=False): targe...
y bdist_wheel upload -r %s' % target)
mancoast/CPythonPyc_test
fail/314_test_zlib.py
Python
gpl-3.0
23,273
0.001891
import unittest from test import support import binascii import random import sys from test.support import precisionbigmemtest, _1G, _4G zlib = support.import_module('zlib') try: import mmap except ImportError: mmap = None class ChecksumTestCase(unittest.TestCase): # checksum test cases def test_crc...
", 1)) self.assertTrue(zlib.adler32(b"abc", 0xffffffff)) def test_adler32empty(self): self.assertEqual(zlib.adler32(b"", 0), 0) self.assertEqual(zlib.adler32(b"", 1), 1)
self.assertEqual(zlib.adler32(b"", 432), 432) def assertEqual32(self, seen, expected): # 32-bit values masked -- checksums on 32- vs 64- bit machines # This is important if bit 31 (0x08000000L) is set. self.assertEqual(seen & 0x0FFFFFFFF, expected & 0x0FFFFFFFF) def test_penguins...
metabrainz/picard
test/test_api_helpers.py
Python
gpl-2.0
11,729
0.001108
# -*- coding: utf-8 -*- # # Picard, the next-generation MusicBrainz tagger # # Copyright (C) 2017 Sambhav Kothari # Copyright (C) 2018 Wieland Hoffmann # Copyright (C) 2018, 2020-2021 Laurent Monin # Copyright (C) 2019-2022 Philipp Wolfer # # This program is free software; you can redistribute it and/or # modify it und...
# along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. from unittest.mock import MagicMock from test.p
icardtestcase import PicardTestCase from picard.acoustid.manager import Submission from picard.metadata import Metadata from picard.webservice import WebService from picard.webservice.api_helpers import ( AcoustIdAPIHelper, APIHelper, MBAPIHelper, ) class APITest(PicardTestCase): def setUp(self): ...
laisrael/Game-Tools-NPC-Generator
classgen.py
Python
mit
1,109
0.002705
import random classes = [ ('Bar
barian', ['STR', 'CON', 'DEX', 'WIS', 'CHA', 'INT']), ('Bard', ['CHA', 'CON', 'STR', 'DEX', 'WIS', 'INT']), ('Cleric', ['WIS', 'CHA', 'CON', 'DEX', 'INT', 'STR']), ('Druid', ['WIS', 'CON', 'STR', 'DEX', 'INT', 'CHA']), ('Fighter', ['STR', 'CON', 'DEX', 'WIS', 'INT'
, 'CHA']), ('Monk', ['STR', 'WIS', 'CON', 'DEX', 'INT', 'CHA']), ('Paladin', ['CHA', 'WIS', 'STR', 'CON', 'DEX', 'INT']), ('Ranger', ['STR', 'DEX', 'WIS', 'CHA', 'CON', 'INT']), ('Rogue', ['DEX', 'CHA', 'CON', 'WIS', 'INT', 'STR']), ('Sorcerer', ['CHA', 'DEX', 'CON', 'WIS', 'INT', 'STR']), ('Wiz...
cython-testbed/pandas
pandas/tests/plotting/test_deprecated.py
Python
bsd-3-clause
1,513
0
# coding: utf-8 import string import pandas as pd import pandas.util.testing as tm import pandas.util._test_decorators as td import pytest from numpy.random import randn import pandas.tools.plotting as plotting from pandas.tests.plotting.common import TestPlotBase """ Test cases for plot functions imported from ...
by='indic') @pytest.mark.slow def test_radviz_deprecated(self, iris): with tm.assert_produces_warning(FutureWarning): plotting.radviz(frame=iris, class_column='Name') @pytest.mark.slow def test_plot_params(self): with tm.assert_produces_warning(F...
s.compat'] = True
armab/st2contrib
packs/dimensiondata/actions/create_vlan.py
Python
apache-2.0
826
0
from lib import actions __all__ = [ 'CreateVlanAction', ] class CreateVlanAction(actions.BaseAction): def run(self, **kwargs)
: action = kwargs['action'] del kwargs['action'] region = kwargs['region'] del kwargs['region'] network_domain_id = kwargs['network_domain_id'] del kwargs['network_domain_id'] driver = self._get
_compute_driver(region) network_domain = driver.ex_get_network_domain(network_domain_id) kwargs['network_domain'] = network_domain result = self._do_function(driver, action, **kwargs) # Wait to complete driver.ex_wait_for_state('NORMAL', driver.ex_get_vlan, ...
dwfreed/mitmproxy
examples/complex/tcp_message.py
Python
mit
917
0.001091
""" tcp_message Inline Script Hook API Demonstration ------------------------------------------------ * modifies packets containing "foo" to "bar" * prints various details for each packet. example cmdline invocation: mitmdump -T --host --tcp ".*" -q -s examples/tcp_message.py """ from mitmproxy.utils import strutils ...
lse if modified_msg == tcp_msg.message else True tcp_msg.message = modified_msg print( "[tcp_message{}] from {} {} to {} {}:\r\n{}".format( " (modified)" if is_modified else "", "client" if tcp_msg.sender == tcp_msg.client_conn else "server", tcp_msg.sender.address, ...
tils.bytes_to_escaped_str(tcp_msg.message)) )
richardbeare/SimpleITK
Examples/Python/CannyEdge.py
Python
apache-2.0
1,302
0
#!/usr/bin/env python # ========================================================================= # # Copyright NumFOCUS # # 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.txt #
# Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License...
pndurette/gTTS
gtts/__init__.py
Python
mit
137
0
# -*- coding: utf-8 -*- from .version import __version__ # no
qa: F401 from .tts import gTTS, gTTSError __all__ = ['gTTS', 'gTTSE
rror']
guozengxin/codeeval
easy/fizzBuzz.py
Python
mit
537
0.001862
#!/usr/bin/env python # https://
www.codeeval.com/open_challenges/1/ import sys def solve(X, Y, N): r = [] for i in range(1, N + 1):
if i % X == 0 and i % Y == 0: r.append('FB') elif i % X == 0: r.append('F') elif i % Y == 0: r.append('B') else: r.append(str(i)) print ' '.join(r) def main(): for line in sys.stdin: (X, Y, N) = line.strip().split(' ') ...
nickbjohnson4224/greyhat-crypto-ctf-2014
frontend/services.py
Python
mit
4,564
0.004163
import time import json import tornado.httpclient http_client = tornado.httpclient.HTTPClient() class HTTPServiceProxy(object): def __init__(self, host='localhost', port=6999, cache_timeout=5.0): self._host = host self._port = port self._cache_timeout = cache_timeout self._cache...
f __init__(self): super(MonitorProxy, self).__init__(host='localhost', port=6999, cache_timeout=0.0) @property def challenges(self): return json.loads(self.get('list')) @prope
rty def visible_challenges(self): return json.loads(self.get('list_visible')) def status(self, challenge): try: return json.loads(self.get('status')).get(challenge, None) except TypeError: return None def show(self, challenge): self.post('show', chal...
frol/django-mysql-fix
django_mysql_fix/backends/mysql/compiler.py
Python
mit
5,170
0.002901
from django.db.backends.mysql.compiler import SQLCompiler as BaseSQLCompiler from django.db.backends.mysql.compiler import SQLInsertCompiler, \ SQLDeleteCompiler, SQLUpdateCompiler, SQLAggregateCompiler, \ SQLDateCompiler, SQLDateTimeCompiler class SQLCompiler(BaseSQLCompiler): STRAIGHT_INNER = 'STRAIGHT_...
ld=_ordering_join_info.join_field, lhs_alias=ordering_table ) _query_alias_map[ordering_table] = _ordering_join_info._replace( join_type=None, join_cols=((None, None), ), join_field=No...
ace INNER joins with STRAIGHT joins # XXX: It's unsufficient, it recreates objects. for table in _query_tables[1:]: _query_alias_map[table] = _query_alias_map[table]\ ._replace(join_type=self.STRAIGHT_INNER) # Patch query ...
Inboxen/Inboxen
inboxen/search/migrations/0001_initial.py
Python
agpl-3.0
2,198
0.002275
# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-03-03 15:23 from __future__ import unicode_literals from django.conf import settings from django.contrib.postgres.search import SearchVector from django.db import migrations, models from django.db.models.expressions import Value def unicode_damnit(data, c...
.objects.filter( header__part__parent__isnull=True, header__name__name=header_name, header__part__email__id=email_id, ).first() return unicode_damnit(header.data) except AttributeError: return "" def populate_search_index(apps, schema_editor): Inbox...
.get_model("inboxen", "HeaderData") for inbox in Inbox.objects.all().select_related("domain").iterator(): inbox.search_tsv = combine_index(inbox.description, "{}@{}".format(inbox.inbox, inbox.domain.domain)) inbox.save(update_fields=["search_tsv"]) for email in Email.objects.all().iterator(): ...
gamechanger/deferrable
deferrable/queue/dockets.py
Python
mit
5,390
0.002226
from __future__ import absolute_import import logging from uuid import uuid1 import dockets.queue import dockets.error_queue from .base import Queue class DocketsQueue(Queue): def __init__(self, redis_client, queue_name, wait_time, timeout): self.queue = dockets.queue.Queue(redis_client, ...
timeout=timeout) def make_error_queue(self): return DocketsErro
rQueue(self.queue) def _push(self, item): push_kwargs = {} if 'delay' in item: push_kwargs['delay'] = item['delay'] or None return self.queue.push(item, **push_kwargs) def _push_batch(self, items): result = [] for item in items: try: ...
bkerster/utilities
cy_af2d/setup.py
Python
gpl-2.0
171
0.011696
from dis
tutils.core import setup from Cython.Build import cythonize import numpy setup( ext_modules = cythonize("af2d.pyx"), include_dirs=[numpy.get_in
clude()] )
akshaykamath/StateReviewTrendAnalysisYelp
StateReviewTrendsPOC.py
Python
mit
4,899
0.002654
__author__ = 'Akshay' """ File contains code to Mine reviews and stars from a state reviews. This is just an additional POC that we had done on YELP for visualising number of 5 star reviews per state on a map. For each business per state, 5 reviews are taken and the count of the review is kept in the dictionary for e...
ct[state] = 0 if state not in state_3_star_dict: state_3_star_dict[state] = 0 if
state not in state_2_star_dict: state_2_star_dict[state] = 0 if state not in state_1_star_dict: state_1_star_dict[state] = 0 if star_rating == 5: state_5_star_dict[state] += 1 if star_rating == 4: state_4_star_dict[st...
FrontSide/Sizun
sizun/controllers/syntaxhandler.py
Python
mit
1,697
0.000589
""" Sizun MIT License (C) 2015 David Rieger """ from flask import current_app as app from .confighandler import ConfigHandler class SyntaxHandler: SYNTAXFILES_FOLDER = "config/syntax/" SYNTAXFILES_APPDX = ".syn" ELEMENTS_SECTION = "ELEMENTS"
def __init__(self, _settings): # Instantiate a Configuration Handler fot the according syntax file self.language = _settings.get_language() self.app_path = _settings.get_
apppath() self.confighandler = ConfigHandler("{}/{}{}{}".format( self.app_path, self.SYNTAXFILES_FOLDER, self.language, self.SYNTAXFILES_APPDX)) def get_flowpath_regex(self): """ Returns the regex by which if st...
tensorflow/graphics
tensorflow_graphics/projects/points_to_3Dobjects/transforms/transforms.py
Python
apache-2.0
12,632
0.00855
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
ting(image) return image def subtract_mean_and_normalize(image, means, std, random=False): if len(m
eans) != len(std): raise ValueError('len(means) and len(std) must match') image = image / 255 if random: image = color_augmentations(image) image = (image - tf.constant(means)) / tf.constant(std) return image def _get_image_border(border, size): i = tf.constant(1) cond = lambda i: tf.math.less_equ...
sajuptpm/neutron-ipam
neutron/tests/unit/_test_extension_portbindings.py
Python
apache-2.0
17,806
0.000168
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 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...
eutron.manager import NeutronManager from neutron.tests.unit import test_db_plugin class PortBindingsTestC
ase(test_db_plugin.NeutronDbPluginV2TestCase): # VIF_TYPE must be overridden according to plugin vif_type VIF_TYPE = portbindings.VIF_TYPE_OTHER # VIF_DETAILS must be overridden according to plugin vif_details VIF_DETAILS = None def _check_response_portbindings(self, port): self.assertEqua...
aplicatii-romanesti/allinclusive-kodi-pi
.kodi/addons/plugin.video.kidsplace/brightcovePlayer.py
Python
apache-2.0
1,587
0.010082
import httplib from pyamf import AMF0, AMF3 from pyamf import remoting from pyamf.remoting.client import RemotingService height = 1080 def build_amf_request(const, playerID, videoPlayer, publisherID): env = remoting.Envelope(amfVersion=3) env.bodies.append( ( "/1", remotin...
erKey): rtmpdata = get_clip_info(const, playerID, videoPlayer
, publisherID, playerKey) streamName = "" streamUrl = rtmpdata['FLVFullLengthURL']; for item in sorted(rtmpdata['renditions'], key=lambda item:item['frameHeight'], reverse=False): streamHeight = item['frameHeight'] if streamHeight <= height: streamUrl = item['defaul...
idurkan/mtg-piper
get_land_ids.py
Python
mit
361
0.024931
import re import s
ys import pprint def main(args): text_path = args[0] file_content = open(text_path, 'r').read() link_id_expr = re.compile(r"multiverseid=(\d+)") matches = link_id_expr.findall(file_content) print "There were {0} matches in {1}".format(len(matches), text_path) pprint.pprint(matches) if __name__ == '__main__
': main(sys.argv[1:])
JavierGarciaD/athena
mneme/db_updater.py
Python
gpl-3.0
8,366
0.000478
#!/usr/bin/python # -*- coding: utf-8 -*- ''' @since: 2014-11-28 @author: Javier Garcia @contact: javier.garcia@bskapital.com @summary: Update from websources and csv the Master Securities SQLITE database. ''' # General imports import pandas.io.data as web import pandas as pd import numpy as ...
s['volume'] = vendor_results['volume'].astype(float) output = vendor_results.itertuples(index=False) data = list(output) return data except: print('Error pre
pare_list_for_loading()') raise def query_to_dictionary(query_result): """ helper creates a dictionary from the database query to the format needed for the update function. :param query_result: dict(symbol: (last_update_eod)) """ # print('query_result', query_result) ans...
qutip/qutip
qutip/topology.py
Python
bsd-3-clause
2,853
0.000701
__all__ = ['berry_curvature', 'plot_berry_curvature'] from qutip import (Qobj, tensor, basis, qeye, isherm, sigmax, sigmay, sigmaz) import numpy as np try: import matplotlib.pyplot as plt except: pass def berry_curvature(eigfs): """Computes the discretized Berry curvature on the two dimensional grid ...
he eigfs. """ nparam0 = eigfs.shape[0] nparam1 = eigfs.shape[1] nocc = eigfs.shape[2] b_curv = np.zeros((nparam0-1, nparam1-1), dtype=float) for i in range(nparam0-1): for j in range(nparam1-1): rect_prd = np.identity(nocc, dtype=complex) innP0 = np.zeros([nocc, ...
innP1 = np.zeros([nocc, nocc], dtype=complex) innP2 = np.zeros([nocc, nocc], dtype=complex) innP3 = np.zeros([nocc, nocc], dtype=complex) for k in range(nocc): for l in range(nocc): wf0 = eigfs[i, j, k, :] wf1 = eigfs[i+1, j,...
BartMassey/nb-misc
arrayqueue.py
Python
mit
1,163
0.000861
# Array-based circular queue implementation. # Copyright © 2014 Bart Massey # [This program is licensed under the "MIT License"] # Please see the file COPYING in the source # distribution of this software for license terms. class Queue(object): def __init__(self, max_size): self.queue = [None] * (max_size ...
v): assert not self.is_full() self.queue[self.enq] = v self.enq = self.increase(self.enq) self.n += 1 def dequeue(self): assert not self.is_empty() v = self.queue[self.deq] self.deq = self.increase(self.deq) self.n -= 1 return v def is_em...
self.increase(self.enq) == self.deq def size(self): return self.n if __name__ == "__main__": from queuetest import arrayqueuetest arrayqueuetest(Queue)
n4xh4ck5/wh01p
modules/getip/getip.py
Python
gpl-3.0
636
0.044025
#!/usr/bin/env python #-*- coding:utf-8 -*- import socket import requests def GetIP(tar
get): timeout = 8 ip="" valid_responses = ['200', '401', '403', '404', '301', '302'] try: if str(requests.get('http://' + target,timeout = timeout).status_code) not in valid_responses: if str(requests.get('https://' + target, timeout= timeout).status_code) in valid_responses: ip = socket.ge...
exit(0) else: ip = socket.gethostbyname(target) except Exception as e: print e pass return ip
tejasnikumbh/Algorithms
Warmup/AlternatingCharacgters.py
Python
bsd-2-clause
1,034
0.011605
# Importing Libraries import sys ''' Function that generates the results for all the test cases. Iterates through the test cases and delegates the work ot getCount ''' def genResults(cases): results = [] for case in cases: results.append(getCount(case)) return results ''' Function that...
= list(strCase) markList = [0]*len(strChars) prev = strChars[0] for i in range(1,len(strChars)): if(strChars[i] == prev): markList[i] = 1 else: prev = strChars[i] return sum(markList) ''' Main Function for the program ''' if __name__ == "__main__": #...
ases) # Printing out results for i in results: print i
antonyr/django-haystack
test_haystack/whoosh_tests/test_whoosh_backend.py
Python
bsd-3-clause
45,377
0.002402
# encoding: utf-8 from __future__ import absolute_import, division, print_function, unicode_literals import os import unittest from datetime import timedelta from decimal import Decimal from django.conf import settings from django.test import TestCase from django.test.utils import override_settings from django.utils...
, use_template=True) name = indexes.CharField(model_attr='author') pub_date = indexes.DateTimeField(model_attr='pub_date') def get_model(self): return MockModel class WhooshMockSearchIndexWithSkipDocument(WhooshMockSearchIndex): def prepare_text(self, obj): if obj.author == 'daniel3'...
dexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True) name = indexes.CharField(model_attr='author') pub_date = indexes.DateTimeField(model_attr='pub_date') def get_model(self): return AnotherMockModel def prepare_text(self, obj): return obj.author class A...
kobotoolbox/kpi
kpi/views/environment.py
Python
agpl-3.0
1,307
0.000765
# coding: utf-8 import constance from django.conf import settings from rest_framework.response import Response from rest_framework.views import APIView from kobo.static_lists import COUNTRIES, LANGUAGES, SECTORS from kobo
.apps.hook.constants import SUBMISSION_PLACEHOLDER class EnvironmentV
iew(APIView): """ GET-only view for certain server-provided configuration data """ CONFIGS_TO_EXPOSE = [ 'TERMS_OF_SERVICE_URL', 'PRIVACY_POLICY_URL', 'SOURCE_CODE_URL', 'SUPPORT_EMAIL', 'SUPPORT_URL', 'COMMUNITY_URL', ] def get(self, request, *a...
xzackli/isocurvature_2017
analysis/plot_isocurvature_spectra_effects/deriv_iso.py
Python
mit
3,825
0.019869
# must use python 2 from classy import Class import matplotlib.pyplot as plt import numpy as np import math max_l = 5000 max_scalars = '5000' ell = np.array( range(1, max_l+1) ) def getDl( pii1=0.5e-10, pii2=1e-9, pri1=1e-13 ): # Define your cosmology (what is not specified will be set to CLASS default para...
dpri1 )
# plot something with matplotlib... plt.plot( (pii1_tt2 - pii1_tt1)/(2 * dpii1), label='$P_{II}^1$', markersize=0 ) plt.plot( (pii2_tt2 - pii2_tt1)/(2 * dpii2), label='$P_{II}^2$', markersize=0 ) # plt.plot( (pri1_tt2 - pri1_tt1)/(2 * dpri1), label='$P_{RI}^1$', markersize=0 ) plt.title('TT Derivatives') plt.ylabel(...
kbarbary/cubefit
cubefit/__init__.py
Python
mit
158
0
from .fitting import * from .io import * from .
main import * from .plotting import * from .psf import * f
rom .utils import * from .version import __version__