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
leonardbinet/navitia_client
test/test_departures.py
Python
mit
529
0
"""Tests for the object departures module.""" import responses # initialize package, and does not mix up names import test as _test import navitia_client import requests class DeparturesTest(_test.Tes
tCase): def setUp(self): self.user = 'leo' self.core_url = "https://api.navitia.io/v1/" self.client = navitia_client.Client(self.user) self.coords = '2.333333;48.866667' def test_no_region_nor_coords(self):
# Should raise error if no region nor coords specified pass
mtik00/pyclimenu
docs/conf.py
Python
mit
4,835
0.000207
# -*- coding: utf-8 -*- # # climenu documentation build configuration file, created by # sphinx-quickstart on Tue Apr 11 09:13:31 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # A...
c = 'index' # General information about the project. project = u'climenu' copyrig
ht = u'2017, Timothy McFadden' author = u'Timothy McFadden' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = u'1.8.0' # The full version, including alpha/bet...
dasheq/lab11
list-aws-queues.py
Python
mit
901
0.011099
# This script created a queue # # Author - Paul Doyle + Damian Szczepny # # import boto.sqs import boto.sqs.queue from bo
to.sqs.message import Message from boto.sqs.connection import SQSConnection from boto.exception import SQSError import sys import urllib2 # Get the keys from a specific url and then use
them to connect to AWS Service response = urllib2.urlopen('http://ec2-52-30-7-5.eu-west-1.compute.amazonaws.com:81/key') html=response.read() result = html.split(':') #print (result[0]) #print (result[1]) access_key_id = result[0] secret_access_key = result[1] #print (access_key_id,secret_access_key) # Set up a...
rkk09c/Broadcast
app/mod_sms/custom_errors.py
Python
apache-2.0
437
0.01373
class Dupli
cateUserGroupException(Exception): def __init___(self): Exception.__init__(self,"Dupli
cate User group already created and active") class DuplicateUserException(Exception): def __init___(self): Exception.__init__(self,"Duplicate User already created and active") class DuplicateMessageException(Exception): def __init___(self): Exception.__init__(self,"Duplicate Message already cr...
DanielOaks/goshu
modules/commands.py
Python
isc
1,851
0
#!/usr/bin/env python3 # Goshu IRC Bot # written by Daniel Oaks <daniel@danieloaks.net> # licensed under the ISC license from gbot.modules import Module from gbot.libs.helper import split_num class commands(Module): """Provides general IRC commands such as msg, me, join, part.""" core = True # irc d...
msg_target, msg_msg) def acmd_notice(self, event, command, usercommand): """Send a /notice
@global @usage <target> <message> """ msg_target, msg_msg = split_num(usercommand.arguments) event['server'].notice(msg_target, msg_msg) def acmd_join(self, event, command, usercommand): """Join a channel @global @usage <channel> """ ...
BlueBrain/NeuroM
examples/plot_somas.py
Python
bsd-3-clause
2,929
0.003073
#!/usr/bin/env python # Copyright (c) 2015, Ecole Polytechnique Federale de Lausanne, Blue Brain Project # All rights reserved. # # This file is part of NeuroM <https://github.com/BlueBrain/NeuroM> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the fol...
in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of the copyright holder nor the names of # i
ts contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # 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 ME...
defunSM/code
pyth/randomword.py
Python
mit
348
0.045977
#!/usr/bin/env python import subprocess, random, sys, os def randomrange(): try: value1 = int(sys.argv[1]) value2 = int(sys.argv[2]) randvalue = random.randint(v
alue
1, value2) return randvalue except IndexError: randvalue = random.randint(0,10000000) return randvalue def main(): value = randomrange() print(value) main()
inkleby/inklebyrobots
robots/amendments.py
Python
mit
4,057
0.016761
''' US Amendments - tweets proposed ammendments to us constitution from: http://www.archives.gov/open/dataset-amendments.html ''' if __name__ == "__main__": import sys sys.path.append("..") import credentials from robot_core import Robot from funcs.ql import QuickList import os import time class ...
n: "%d%s" % (n,"ts
nrhtdd"[(n/10%10!=1)*(n%10<4)*n%10::4]) #adds ordinal stuff url = "https://www.congress.gov/bill/{0}-congress/{2}-joint-resolution/{1}" if row["joint_resolution_chamber"] == "House Joint Resolution": house = "house" else: house = "senate" ...
omar-AM/python-pgp
pgp/cipher/__init__.py
Python
gpl-3.0
1,228
0
# python-pgp A Python OpenPGP implementation # Copyright (C) 2014 Richard
Mitchell # # This program is free software: you c
an redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even t...
Tinkerforge/brickv
src/brickv/plugin_system/plugins/moisture/__init__.py
Python
gpl-2.0
909
0
# -*- coding: utf-8 -*- """ Moisture Plugin Copyright (C) 2013 Olaf Lüke <olaf@tinkerforge.com> __init__.py: package initialization 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 Founda
tion; either version 2 of the License, or (at your option) any later version. This program 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 sho...
alex/django-vcs
django_vcs/views.py
Python
bsd-3-clause
2,180
0.004128
import os from django.http import Http404 from django.shortcuts import get_object_or_404, render_to_response from django.template import RequestContext from django_vcs.models import CodeRepository def repo_list(request): repos = CodeRepository.objects.all() return render_to_response('django_vcs/repo_list.htm...
der_contents is None:
raise Http404 context['files'], context['folders'] = folder_contents context['files'] = [(os.path.join(path, o), o) for o in context['files']] context['folders'] = [(os.path.join(path, o), o) for o in context['folders']] return render_to_response([ 'django_vcs/%s/folder_con...
tricoder42/django-forme
tests/test_styles.py
Python
mit
787
0
# coding: utf-8 from __future__ import unicode_literals import pytest from django import template from forme import styles def test_indexing(): style = styles.Style() style['forme'] = 'Foo' style['forme', 'test'
] = 'Bar' assert style['forme', styles.Default] == style['forme'] assert style['forme', 'invalid key'] == style['for
me'] assert style['forme'] != ['forme', 'test'] with pytest.raises(KeyError): assert style['invalid tag'] def test_ellipsis(): style = styles.Style() style['forme'] = 'Foo' style['forme', 'test'] = 'Bar' style['forme', 'py'] = 'Fubar' assert len(style['forme', :]) == 3 del st...
igor-toga/local-snat
neutron/tests/unit/scheduler/test_l3_agent_scheduler.py
Python
apache-2.0
92,873
0.000118
# Copyright (c) 2013 OpenStack Foundation # 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 ...
ssertEqual(expected_routers,
unscheduled_routers) def test__get_routers_to_schedule_excludes_unsupported(self): routers = [ {'id': 'router_1'}, {'id': 'router_2'}, {'id': 'router_3'} ] expected_routers = [{'id': 'router_2'}] # exclude everything e
9thSenseRobotics/bosh_server
nbxmpp-0.1/nbxmpp/roster_nb.py
Python
gpl-3.0
13,001
0.00723
## roster_nb.py ## based on roster.py ## ## Copyright (C) 2003-2005 Alexey "Snake" Nezhdanov ## modified by Dimitur Kirov <dkirov@gmail.com> ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the...
ery') if query: self.received_from_server = True self.version = stanza.getTagAttr('query', 'ver') if self.version is None: self.version = '' for item in query.getTags('item'): jid=item.getAttr('jid')
if item.getAttr('subscription')=='remove': if self._data.has_key(jid): del self._data[jid] # Looks like we have a workaround # raise NodeProcessed # a MUST log.info('Setting roster item %s...' % jid) if not self._data....
spencerkclark/aospy
aospy/var.py
Python
apache-2.0
5,451
0
"""Funcionality for representing a physical variable in aospy.""" import numpy as np class Var(object): """An object representing a physical quantity to be computed. Attributes ---------- name : str The variable's name alt_names : tuple of strings All other names that the variable...
rface temperature. colormap : str (Currently not used by aospy) The name of the default colormap to be used in plots of this variable. valid_range : length-2 tuple The range of values outside which to flag as
unphysical/erroneous """ # noqa: W605 self.name = name if alt_names is None: self.names = tuple([name]) else: self.alt_names = alt_names self.names = tuple([name] + list(alt_names)) if func is None: self.func = lambda x: x ...
celery/kombu
kombu/transport/sqlalchemy/__init__.py
Python
bsd-3-clause
7,389
0.000406
"""SQLAlchemy Transport module for kombu. Kombu transport using SQL Database as the message store. Features ======== * Type: Virtual * Supports Direct: yes * Supports Topic: yes * Supports Fanout: no * Supports Priority: no * Supports TTL: no Connection String ================= .. code-block:: sqla+SQL_ALCHEMY...
about ``SQL_ALCHEMY_CONNECTION_STRING`` see SQLAlchemy Engine Configuration documentation. Examples: .. code-block:: # PostgreSQL with default driver sqla+postgresql://scott:tiger@localhost/mydatabase # PostgreSQL with psycopg2 driver sqla+postgresql+psycopg2://scott:tiger@localhost/mydatabase ...
esql+pg8000://scott:tiger@localhost/mydatabase # MySQL with default driver sqla+mysql://scott:tiger@localhost/foo # MySQL with mysqlclient driver (a maintained fork of MySQL-Python) sqla+mysql+mysqldb://scott:tiger@localhost/foo # MySQL with PyMySQL driver sqla+mysql+pymysql://scott:tiger@loc...
jamesbeebop/evennia
evennia/utils/tests/test_validatorfuncs.py
Python
bsd-3-clause
6,369
0.001256
"""Tests for validatorfuncs """ from django.test import TestCase from evennia.utils import validatorfuncs import mock import datetime import pytz class TestValidatorFuncs(TestCase): def test_text_ok(self): for val in [None, -123, "abc", 1.234, {1: True, 2: False}, ["a", 1]]: self.assertEqual(...
"Jan 2 12:00 {year-1}
", f"Dec 31 00:00 {year-1}"]: with self.assertRaises(ValueError): validatorfuncs.future(f, from_tz=pytz.UTC) def test_signed_integer_ok(self): for si in ["123", "4567890", "001", "-123", "-45", "0"]: self.assertEqual(int(si), validatorfuncs.signed_integer(si)) @...
shadowmint/nwidget
samples/snake/views/game_view.py
Python
apache-2.0
5,269
0.010249
# Copyright 2013 Douglas Linder # 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...
E_RESTART",
self.on_restart) nwidget.listen("GAME_GOTO_MENU", self.on_menu) # Background bg = model.Background(assets) self.add(bg.node) # Add path and snake self.snake = model.Snake(assets) self.path = model.Path() width, height = cocos.director.director.get_window_size() x = width / 2 y ...
amoya-dx/runbot-addons
runbot_build_instructions/runbot_repo.py
Python
agpl-3.0
2,056
0
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # This module copyright (C) 2010 - 2014 Savoir-faire Linux # (<http://www.savoirfairelinux.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 # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, ...
R A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # #########################################################################...
openstack/glance
glance/db/sqlalchemy/metadata.py
Python
apache-2.0
17,923
0
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2013 OpenStack Foundation # Copyright 2013 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not ...
e(meta): return sqlalchemy.Table('metadef_objects', meta, autoload=T
rue) def get_metadef_tags_table(meta): return sqlalchemy.Table('metadef_tags', meta, autoload=True) def _get_resource_type_id(meta, name): rt_table = get_metadef_resource_types_table(meta) resource_type = ( select([rt_table.c.id]). where(rt_table.c.name == name). select_from(rt_t...
jcass77/mopidy
mopidy/models/immutable.py
Python
apache-2.0
7,076
0
import copy import itertools import weakref from mopidy.models.fields import Field # Registered models for automatic deserialization _models = {} class ImmutableObject: """ Superclass for immutable objects whose fields can only be modified via the constructor. This version of this class has been re...
tr__(self, name) else: raise AttributeError("Object is immutable.") def _is_valid_field(self, name): return hasattr(self, name) and not callable(getattr(self, name)) def _set_field(self, name, value): if value == getattr(self.__class__, name): self.__dict__.
pop(name, None) else: self.__dict__[name] = value def _items(self): return self.__dict__.items() def __repr__(self): kwarg_pairs = [] for key, value in sorted(self._items()): if isinstance(value, (frozenset, tuple)): if not value: ...
ovresko/erpnext
erpnext/crm/doctype/sales_stage/sales_stage.py
Python
gpl-3.0
276
0.007246
# -*- coding: utf-8 -*- # Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contr
ibutors # For license information, please see license.txt from __future__ import
unicode_literals import frappe from frappe.model.document import Document class SalesStage(Document): pass
az7arul/ansible-modules-core
cloud/openstack/os_subnet.py
Python
gpl-3.0
8,648
0.000347
#!/usr/bin/python #coding: utf-8 -*- # (c) 2013, Benno Joy <benno@ansible.com> # # This module 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 ...
dule, subnet): state = module.params['state'] if state == 'present':
if not subnet: return True return _needs_update(subnet, module) if state == 'absent' and subnet: return True return False def main(): argument_spec = openstack_full_argument_spec( name=dict(required=True), network_name=dict(default=None), cidr=dict(defa...
zhs007/movieSpider
moviespider/moviespider/spiders/cili006all_spider.py
Python
mit
1,758
0.003413
# -*- coding: utf-8 -*- from scrapy.spider import Spider from scrapy.selector import Selector from moviespider.items import Cili006Item from moviespider.moviedb import MovieDB import scrapy class Cili006AllSpider(Spider): moviedb = MovieDB() name = "cili006all" allowed_domains = ["cili09.com"] maxid...
for cur in range(31, self.maxid + 1)[::-1]: if not self.moviedb.hasMovie_cili006(cur): req = scrapy.FormRequest
("http://cili09.com/%d.html" % (cur), callback=self.parse) req.__setattr__('cili006searchid', cur) lstreq.append(req) return lstreq def parse(self, response): print "%d" % (response.request.cili006searchid) sel = Selector(response) item = Cili006Ite...
sinhrks/pandas-ml
pandas_ml/xgboost/test/test_base.py
Python
bsd-3-clause
4,415
0.000906
#!/usr/bin/env python import matplotlib matplotlib.use('Agg') import numpy as np # noqa import pandas as pd # noqa import pandas_ml as pdml # noqa import pandas_ml.util.testing as tm # noqa import sklearn.datasets as data...
om.rand(X.shape[0] // 5)) df = pdml.ModelFrame(data=X, target=y) models = ['XGBRegressor'] for model in models: mod1 = getattr(df.xgboost, model)() mod2 = getattr(xgb, model)() df.fit(mod1) mod2.fit(X, y) result = df.pre...
ted) self.assertIsInstance(df.predicted, pdml.ModelSeries) self.assert_numpy_array_almost_equal(df.predicted.values, expected) def test_grid_search(self): tuned_parameters = [{'max_depth': [3, 4], 'n_estimators': [50, 100]}] df = pdml....
francispotter/pythopoly
card_deck.py
Python
mit
326
0.006135
from ra
ndom import shuffle class CardDeck: def __init__(self): self.shuffle_deck() def shuffle_deck(self): self.deck = [card for card in self.cards] shuffle(self.deck) def next_card(self): if len(self.deck) == 0: self.shuffle_deck()
return self.deck.pop()
proyectos-analizo-info/pybossa-analizo-info
pybossa/auth/__init__.py
Python
agpl-3.0
1,618
0.001854
# -*- coding: utf8 -*- # This file is part of PyBossa. # # Copyright (C) 2013 SF Isle of Man Limited # # PyBossa is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at...
ed def __getattr__(self, attr): real = getattr(self.wrapped, attr) return Requirement(real) def __call__(self, *args, **kwargs): fc = self.wrap
ped(*args, **kwargs) if fc is False: if current_user.is_anonymous(): raise abort(401) else: raise abort(403) return fc @classmethod def here(cls): module = inspect.getmodule(cls) return cls(module) require = Requirement.he...
vileopratama/vitech
src/openerp/addons/base/tests/test_orm.py
Python
mit
18,738
0.002562
from collections import defaultdict from openerp.tools import mute_logger from openerp.tests import common UID = common.ADMIN_USER_ID class TestORM(common.TransactionCase): """ test special behaviors of ORM CRUD functions TODO: use real Exceptions types instead of Exception """ def setUp(self):...
with self.assertRaises(Exception):
self.partner.unlink(cr, uid2, [p1,p2]) def test_multi_read(self): record_id = self.partner.create(self.cr, UID, {'name': 'MyPartner1'}) records = self.partner.read(self.cr, UID, [record_id]) self.assertIsInstance(records, list) def test_one_read(self): record_id = se...
nicproulx/mne-python
mne/io/tests/test_raw.py
Python
bsd-3-clause
5,337
0
# Generic tests that all raw classes should run from os import path as op import math import numpy as np from numpy.testing import assert_allclose, assert_array_almost_equal from nose.tools import assert_equal, assert_true from mne import concatenate_raws from mne.datasets import testing from mne.io import read_raw_f...
data = raw1[:, :][0] assert_allclose(data, raw1[:, :][0]) for first_preload in (True, False): raw = reader(*args, preload=first_preload) data = raw[:, :][0] for preloads in ((True, True), (True, False), (False, False)): for last_preload in (True, False):
t_crops = raw.times[np.argmin(np.abs(raw.times - 0.5)) + [0, 1]] raw1 = raw.copy().crop(0, t_crops[0]) if preloads[0]: raw1.load_data() raw2 = raw.copy().crop(t_crops[1], None) if preloads[1]: ...
innotechsoftware/Quantum-GIS
python/plugins/sextante/saga/SagaAlgorithm.py
Python
gpl-2.0
19,220
0.006139
# -*- coding: utf-8 -*- """ *************************************************************************** SagaAlgorithm.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com *************************...
ater version.
* * * *************************************************************************** """ __author__ = 'Victor Olaya' __date__ = 'August 2012' __copyright__ = '(C) 2012, Victor Olaya' # This will get replaced with a git SHA1 when you do...
kawamon/hue
desktop/libs/azure/src/azure/tests.py
Python
apache-2.0
10,158
0.013487
# Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file ex...
oken': 'access_token', 'token_type': '', 'expires_on': None} get_conf.return_value = {} core_site_get_conf.return_value = {'fs.azure.account.oauth2.client.id': 'client_id', 'fs.azure.account.oauth2.client.secret': 'client_secret', 'fs.azure.accou
nt.oauth2.client.endpoint': 'refresh_url'} client1 = get_client(name='default', fs='abfs') client2 = get_client(name='default', fs='abfs', user='test') provider = get_credential_provider('default', 'hue') assert_equal(provider.get_credentials().get('access_token'...
henrysher/aws-cloudinit
cloudinit/config/cc_salt_minion.py
Python
gpl-3.0
2,541
0
# vi: ts=4 expandtab # # Copyright (C) 2014 Amazon.com, Inc. or its affiliates. # # Author: Jeff Bauer <jbauer@rubic.com> # Author: Andrew Jorgensen <ajorgens@amazon.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License versio...
h.join(pki_dir, 'minion.pem') util.write_file(pub_name, salt_cfg['public_key']) util.write_file(pem_name, salt_cfg['priva
te_key']) # start / restart salt-minion. if it was started, it needs to be restarted # for config change. if cloud.distro.service_running('salt-minion'): cloud.distro.service_control('salt-minion', 'restart', capture=False) else: cloud.distro.service_control('salt-minion', 'start', capt...
kyasabu/Telethon
telethon_tests/tl_test.py
Python
mit
85
0
import unittest class
TLTests(unittest.TestCase): ""
"There are no tests yet"""
acsone/mozaik
mozaik_membership/migrations/1.0.1/post-migration.py
Python
agpl-3.0
511
0
# -*- encoding: utf-8 -*- __name__ = "Remove useless IDENTIFIER column in table MEMBERSHIP_REQUEST" def migrate(cr, version): if not version: return cr.execute('SELECT 1 ' 'FROM pg_class c,pg_attribute a
' 'WHERE c.relname=%s ' 'AND c.oid=a.attrelid ' 'AND a.attname = %s', ('membership_request', 'identifier')) if cr.fetchone(): cr.execute("ALTER T
ABLE membership_request " "DROP COLUMN identifier")
inguma/bokken
ui/console_textview.py
Python
gpl-2.0
4,916
0.002848
# console_textview.py # # Copyright 2015 Hugo Teso <hugo.teso@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the Lic...
self.buffer = GtkSource.Buffer() self.buffer.create_tag("green-background", background="green", foreground="black") self.view = GtkSource.View.new_with_buffer(self.buffer) # FIXME options must be u
ser-selectable (statusbar) self.view.set_editable(False) #self.view.set_highlight_current_line(True) # posible values: Gtk.WrapMode.NONE, Gtk.WrapMode.CHAR, Gtk.WrapMode.WORD... self.view.set_wrap_mode(Gtk.WrapMode.NONE) self.view.connect("populate-popup", self._populate_menu) ...
ciprian-radu/unimap.ns-3noc
bindings/python/apidefs/gcc-ILP32/ns3_module_dot11s.py
Python
gpl-2.0
49,784
0.015306
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers def register_types(module): root_module = module.get_root() ## simple-ref-count.h: ns3::SimpleRefCount<ns3::dot11s::IeBeaconTimingUnit, ns3::empty, ns3::DefaultDeleter<ns3::dot11s::IeBeaconTimingUnit> > [class] module.ad...
HwmpProtocol']) ## ie-dot11s-beacon-timing.h: ns3::dot11s::IeBeaconTiming [class] module.add_class('IeBeaconTiming', parent=root_module['ns3::WifiInformationElement']) ## ie-dot11s-beacon-timing.h: ns3::dot11s::IeBeaconTimingUn
it [class] module.add_class('IeBeaconTimingUnit', parent=root_module['ns3::SimpleRefCount< ns3::dot11s::IeBeaconTimingUnit, ns3::empty, ns3::DefaultDeleter<ns3::dot11s::IeBeaconTimingUnit> >']) ## ie-dot11s-configuration.h: ns3::dot11s::IeConfiguration [class] module.add_class('IeConfiguration', parent=root...
rackerlabs/django-DefectDojo
dojo/db_migrations/0055_notifications_jira_update_verbose_name.py
Python
bsd-3-clause
669
0.001495
from django.db import migrations import multiselectfield.db.fields class Migrat
ion(migrations.Migration): dependencies = [ ('dojo', '0054_dojometa_finding'), ] operations = [ migrations.AlterField( model_name='notifications', name='jira_update', field=multiselectfield.db.fields.MultiSelectField(blank=True, choices=[('slack', 'slack...
lert', help_text='JIRA sync happens in the background, errors will be shown as notifications/alerts so make sure to subscribe', max_length=24, verbose_name='JIRA problems'), ), ]
zionist/mon
mon/apps/payment/migrations/0004_auto__add_field_payment_payment_state.py
Python
bsd-3-clause
20,627
0.008193
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Payment.payment_state' db.add_column(u'payment_payment', 'payment_state', ...
{'null': 'True', 'blank': 'True'}), 'area_cmp':
('django.db.models.fields.IntegerField', [], {'default': '1', 'null': 'True', 'blank': 'True'}), 'budget': ('django.db.models.fields.SmallIntegerField', [], {'null': 'True'}), 'clinic': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'creation_form':...
mitodl/xanalytics
logger.py
Python
mit
498
0.008032
from google.appengine.ext import ndb from models import LogLine def LogAccess(username, request, course_id=None): ''' Write a log entry lin
e ''' ll = LogLine(username=username, course_id=course_id,
url=request.url, ipaddr=request.remote_addr) ll.put() def GetRecentLogLines(nlast=10): ''' Return last nlast entries in access log ''' ret = LogLine.query().order(-LogLine.created).fetch(nlast) return ret
ifduyue/sentry
tests/sentry/api/endpoints/test_group_hashes.py
Python
bsd-3-clause
1,432
0
from __future__ import absolute_import from six.moves.urllib.parse import urlencode from sentry.models import GroupHash from sentry.testutils import APITestCase class GroupHashesTest(APITestCase): def test_simple(self): self.login_as(user=self.user) group = self.create_group() GroupHash...
roup=group, hash='b' * 32) url = '/api/0/issues/{}/hashes/'.format(group.id) response = self.client.get(url, format='json') assert response.status_code == 200, response.content assert len(response.data) == 2 assert sorted(map(lambda x: x['id'], response.data)) == sorted
([ 'a' * 32, 'b' * 32, ]) def test_unmerge(self): self.login_as(user=self.user) group = self.create_group() hashes = [ GroupHash.objects.create( project=group.project, group=group, hash=hash, ...
zatricion/Streams
ExamplesWindowOperations/ExamplesWindowSplitNoState.py
Python
mit
1,672
0.007177
if __name__ == '__main__': if __package__ is None: import sys from os import path sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) ) from Agent import * from Stream import * from WindowOperators import window_split from PrintFunctions import print_streams_recent def ...
tep_size=2) y.set_name('y') z.set_name('z') x.extend([5, 11, 3, 8, 5, 5, 2, 3, 9, 21, 7]) # The windows are [5, 11], [3, 8], [5, 5], [2, 3], [9, 21] # with sums 16, 11, 10, 5, 30 and the even numbers are 16, 10, 30 # and so the y stream is [16, 0, 10, 0, 30] and # the x stream is [0, 11...
.extend([8, 15, 18, 8, 20]) print_streams_recent([x, y, z]) def main(): example_1() if __name__ == '__main__': main()
denniswjackson/embedded-tools
apollo/bin/stubFactory/stub_systemMessages.py
Python
mit
13,464
0.044415
import sys from genStubs import * stub = Stubs( "systemMessages", sys.argv[1], sys.argv[2] ) stub.include( "nanopb/IMessage.h" ) stub.include( "systemMessages/AGLMsg.pb.h" ) stub.include( "systemMessages/AGLOffsetMsg.pb.h" ) stub.include( "systemMessages/AGLRawMsg.pb.h" ) stub.include( "systemMessages/AbortLaunchMsg....
ssages/MissionList.pb.h" ) stub.include( "systemMessages/MissionStatus.pb.h" ) stub.include( "systemMessages/ModemConf
ig.pb.h" ) stub.include( "systemMessages/ModemGetRadioType.pb.h" ) stub.include( "systemMessages/ModemLinkStatus.pb.h" ) stub.include( "systemMessages/ModemPower.pb.h" ) stub.include( "systemMessages/NakMsg.pb.h" ) stub.include( "systemMessages/OperatorModuleConfig.pb.h" ) stub.include( "systemMessages/PWMRateMsg.pb.h"...
matted/bracketbot
pyrsvd/pyrsvd_orig/rsvd/__init__.py
Python
mit
1,640
0.009146
""" PyRSVD ------ This package provides a regularized singular value decomposition (RSVD) solver used to compute low-rank approximations of a large partial matrices (i.e. a matrices with lots of missing valus). R ~ U*V' where R: MxC, U: MxK and V: CxK. M is the number of movies, C is the number of clients This kind o...
_.split('.')))\ < _numpy_version: print "Numpy version %s is required for PyRSVD (%d detected)." % ('.'.join(_numpy_version),np.__version__) sys.exit(-1) except ImportError,e: print "PyRSVD requieres Numpy %s.
" % '.'.join(_numpy_version) sys.exit(-1) from rsvd import RSVD,rating_t from dataset import MovieLensDataset,NetflixDataset
nlesc-sherlock/analyzing-corpora
scripts/corpus_to_sparse.py
Python
apache-2.0
1,290
0
#!/usr/bin/env python # # Copyright 2015 Netherlands eScience Center <info@esciencecenter.nl> # # 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....
se corpus") parser.add_argument( 'corpus', help="python pickle file, containing tokens and metadata") parser.add_argument('matrix') parser.add_argument('-d', '--dictionary', default=None) args = parser.parse_args() print("loading corpus") corpus = load_sparse_corp
us( documents_file=args.corpus, dictionary_file=args.dictionary) print("writing matrix to file") corpus.save(sparse_matrix_file=args.matrix)
translate/translate
translate/convert/test_oo2po.py
Python
gpl-2.0
13,354
0.002771
import os from io import BytesIO from urllib import parse from translate.convert import oo2po, po2oo, test_convert from translate.storage import oo, po from translate.storage.poheader import poheader class TestOO2PO: target_filetype = po.pofile conversion_module = oo2po conversion_class = oo2po.oo2po ...
02:02:02" oosource = (ootemplate % (filename, entitystring)).encode("utf-8") ooinputfile = BytesIO(oosource) ootemplatefile = BytesIO(oosource) pooutputfile = BytesIO() self.conversion_module.convertoo( ooinputfile, pooutputfile, ootemplatefile, targetlanguage="en-U...
posource = pooutputfile.getvalue() poinputfile = BytesIO(posource) ootemplatefile = BytesIO(oosource) oooutputfile = BytesIO() po2oo.convertoo( poinputfile, oooutputfile, ootemplatefile, targetlanguage="en-US" ) ooresult = oooutputfile.getvalue().decode("utf-...
ajrichards/bayesian-examples
statistics/gamma-distn.py
Python
bsd-3-clause
1,524
0.023684
#!/usr/bin/env python """ The Gamma is a probability distribution over a positive random variable τ > 0 It is governed by parameters a and b that are subject to the constraints a > 0 and b > 0 The constraints exist to ens
ure that the distribution can be normalized. Special case of a = 1 is known as the exponential distribution. scipy.stats With a shape parameter α = k and an inverse scale parameter β = 1/θ, called a rate parameter. """ import sys,os import numpy as np import matplotl
ib.pyplot as plt import scipy.stats as scs ## declare variables font_size = 11 font_name = 'sans-serif' n = 10000 fig = plt.figure(figsize=(10,6)) splot = 0 ## loop through parameterizations of the beta for a,b in [(1.0,1.0),(3.0,1.0),(5.0,1.0)]: b = 1/b splot += 1 ax = fig.add_subplot(1,3,splot) ...
jjkoletar/panda3d
contrib/src/panda3dtoolsgui/Panda3DToolsGUI.py
Python
bsd-3-clause
166,069
0.00849
import wx import wx.html from wx.lib.filebrowsebutton import FileBrowseButton import wx.lib.agw.pycollapsiblepane as PCP import xml.dom.minidom from xml.dom.minidom import Node, Document, Element import time import sys import os import subprocess ID_CHOOSEPANDA = wx.NewId() ID_CLEAROUTPUT = wx.NewId() ID_LOADPREFS = w...
do_layout(self): # begin wxGlade: OutputDialog.__do_layout self.dlg_static_sizer_staticbox.Lower() dlg_static_sizer = wx.StaticBoxSizer(self.dlg_static_sizer_staticbox, wx.HORIZONTAL) dlg_main_flex
_sizer = wx.FlexGridSizer(3, 1, 0, 0) dlg_button_sizer = wx.GridSizer(1, 2, 0, 0) dlg_main_flex_sizer.Add(self.dlgOutText, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 2) dlg_button_sizer.Add(self.dlgClearOutBTN, 0, wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL,...
rcbops/nova-buildpackage
nova/tests/api/openstack/compute/contrib/test_users.py
Python
apache-2.0
5,843
0
# Copyright 2010 OpenStack 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 b...
lf.assertTrue('id1' not in [u.id for u i
n fakes.FakeAuthManager.auth_data]) def test_user_create(self): secret = utils.generate_password() body = dict(user=dict(name='test_guy', access='acc3', secret=secret, admin=True)) ...
antoinecarme/pyaf
tests/artificial/transf_Anscombe/trend_LinearTrend/cycle_5/ar_12/test_artificial_1024_Anscombe_LinearTrend_5_12_20.py
Python
bsd-3-clause
267
0.086142
imp
ort pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.proce
ss_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "LinearTrend", cycle_length = 5, transform = "Anscombe", sigma = 0.0, exog_count = 20, ar_order = 12);
jkyeung/XlsxWriter
xlsxwriter/test/comparison/test_image33.py
Python
bsd-2-clause
1,284
0.000779
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2016, John McNamara, jmcnamara@cpan.org # from ..excel_comparsion_test import ExcelComparisonTest from ...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest): """...
created by XlsxWriter against a file created by Excel. """ def setUp(self): self.maxDiff = None filename = 'image33.xlsx' test_dir = 'xlsxwriter/test/comparison/' self.image_dir = test_dir + 'images/' self.got_filename = test_dir + '_test_' + filename self.ex...
self.ignore_elements = {} def test_create_file(self): """Test the creation of a simple XlsxWriter file with image(s).""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() worksheet.set_column('D:D', 3.86) worksheet.set_column('E:E', 1.43...
mementum/backtrader
samples/signals-strategy/signals-strategy.py
Python
gpl-3.0
5,158
0
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2020 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
lines = ('signal',) params = (('p1', 5), ('p2', 30),) def __init__(self): sma1 = bt.indicators.SMA(period=self.p.p1) sma2 = bt.indicators.SMA(period=self.p.p2) self.lines.signal = sma1 - sma2 def runstrat(args=None): args = parse_args(args) cerebro = bt.Cerebro() cerebr...
['fromdate'] = fromdate if args.todate is not None: todate = datetime.datetime.strptime(args.todate, '%Y-%m-%d') dkwargs['todate'] = todate # if dataset is None, args.data has been given data = bt.feeds.BacktraderCSVData(dataname=args.data, **dkwargs) cerebro.adddata(data) cerebro...
bourneagain/pythonBytes
selectionSort.py
Python
mit
444
0.036036
# idea is to scan the elments from left to right # partition the list into two lists # one with emtpy [ where we shall
keep things sorted ] and the other the given list # scan and swap elments in two lists def ss(a): for i in range(0,len(a)-1): smallest=i; for j in range(i,len(a)): if a[j]
<a[smallest]: smallest=j a[i],a[smallest]=a[smallest],a[i] print a a=[3,4,3,5,-1] ss(a)
pshc/archipelago
tests/list_match.py
Python
mit
357
0.005602
from bedrock import * @annot('void -> List(int)') def test(): kept = Cons(0, Cons(1, Nil())) a = Cons(1, Con
s(2, Cons(3, Nil()))) b = match(a, ("Cons(_, Cons(two, Cons(_, Nil())))", identity), ("_", lambda: 4)) assert b == 2, "List pattern match"
return kept def main(): kept = test() nil = Nil() return 0
asnorkin/sentiment_analysis
site/lib/python2.7/site-packages/sklearn/utils/tests/test_extmath.py
Python
mit
24,372
0
# Authors: Olivier Grisel <olivier.grisel@ensta.org> # Mathieu Blondel <mathieu@mblondel.org> # Denis Engemann <d.engemann@fz-juelich.de> # # License: BSD 3 clause import numpy as np from scipy import sparse from scipy import linalg from scipy import stats from sklearn.utils.testing import assert_eq...
)) # compute the singular
values of X using the slow exact method U, s, V = linalg.svd(X, full_matrices=False) for normalizer in ['auto', 'LU', 'QR']: # 'none' would not be stable # compute the singular values of X using the fast approximate method Ua, sa, Va = \ randomized_svd(X, k, power_iteration_normal...
31415us/linda-lidar-rangefinder-playground
linda/Vec2D.py
Python
mit
2,599
0.001539
"basic 2D vector geometry" from math import acos, sqrt, sin, cos, pi class Vec2D(object): " Simple 2D vector class for euclidean geometry " EPSILON = 0.0001 def __init__(self, x=0.0, y=0.0): self.pos_x = x self.pos_y = y def dot(self, other): "dot product" return sel...
alized() vec2 = other.normalized() cross_prod = vec1.cross(vec2) # sin(angle) dot_prod = vec1.dot(vec2) # cos(angle) if dot_prod < -1.0: dot_prod = -1.0 if dot_prod > 1.0: dot_prod = 1.0 if cross_prod > 0: angle = acos(dot_prod) ...
angle = -acos(dot_prod) if angle < 0: angle = angle + 2 * pi return angle def __neg__(self): return Vec2D(-self.pos_x, -self.pos_y) def __add__(self, other): return Vec2D(self.pos_x + other.pos_x, self.pos_y + other.pos_y) def __sub__(self, othe...
KathleenLabrie/KLpyastro
klpyastro/__init__.py
Python
isc
86
0
""
" Collection of astronomy-related functions and ut
ilities """ __version__ = '0.1.1'
absalon-james/usage
usage/args/summary.py
Python
apache-2.0
1,374
0
""" Module for parsing arguments from the command line. Import parser from this module. """ import argparse from usage import meta description = ( 'Python tool for aggregating a usage report by domain' ' and some user defined field.' ) parser = argparse.ArgumentParser(description=descr
iption) # Configuration file parser.add_argument( '--config-file', type=str, help="Configuration file location", default='/etc/usage/usage.yaml' ) # Version parser.add_argument( '--version', actio
n='version', version='%(prog)s ' + str(meta.version) ) # Set the log level. parser.add_argument( '--log-level', help="Log level", choices=['debug', 'info'], default='info' ) # Input file location parser.add_argument('csv_file', help="Location of report csv file.", type=str) # Field in report to group by ...
jorisvandenbossche/pandas
pandas/tests/indexing/test_iloc.py
Python
bsd-3-clause
47,159
0.001081
""" test positional based indexing with iloc """ from datetime import datetime import re from warnings import ( catch_warnings, simplefilter, ) import numpy as np import pytest import pandas.util._test_decorators as td from pandas import ( NA, Categorical, CategoricalDtype, DataFrame, In...
2],
dtype=object), 1: range(3)}) df = frame.copy() orig_vals = df.values indexer(df)[key, 0] = cat expected = DataFrame({0: cat, 1: range(3)}) tm.assert_frame_equal(df, expected) # TODO(ArrayManager) does not yet update parent @td.skip_array_manager_not_yet_implemented ...
raildo/python-keystoneclient
python-keystoneclient-0.4.1.7.gdca1d42/keystoneclient/tests/test_shell.py
Python
apache-2.0
22,938
0.000131
# 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 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...
def _tolerant_shell(self, cmd): t_shell = openstack_shell.OpenStackIdentityShell(NoExitArgumentParser) t_shell.main(cmd.split()) # Patch os.environ to avoid required auth info. def setUp(self): super(ShellTest, self).setUp() for var
in self.FAKE_ENV: self.useFixture(fixtures.EnvironmentVariable(var, self.FAKE_ENV[var])) # Make a fake shell object, a helping wrapper to call it, and a quick # way of asserting that certain API calls were made. global shell, _shell, assert_called, asser...
wanyuac/BINF_toolkit
parse_ENA_sampleInfo_XML.py
Python
gpl-3.0
2,321
0.019819
""" This script parses an ENA metadata file in XML format and prints a subset of information. Usage: python parse_ENA_sampleInfo_XML.py ERP000909.xml > samples.txt Input: an XML file exported for a list of ERS accession numbers from ENA using the REST URLs API. For example, one can download an XML file for sample...
strain, host, place, year] def main(): file = sys.argv[1] xml = xmlTree.parse(file).getroot() # parse an XML into a tree of elements # print the header line print "\t".join(["study_accession", "samp
le_accession", "secondary_sample_accession", "experiment_accession", "run_accession", "Isolate_ID", "Strain", "Host", "Place_of_isolation", "Year_of_isolation"]) for sample in xml: print "\t".join(get_domains(sample)) return if __name__ == '__main__': main()
ben-ng/swift
utils/SwiftIntTypes.py
Python
apache-2.0
3,751
0
# ===--- SwiftIntTypes.py ----------------------------*- coding: utf-8 -*-===// # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See https://swift.org/LICENSE.t...
ed) def __eq__(self, other): return self.is_word == other.is_word and \ self.bits == other.bits and \ self.is_signed == other.is_signed def __ne__(self, other): return not self.__eq__(other) def all_integer_types(word_bits): for bitwidth in _all_
integer_type_bitwidths: for is_signed in [False, True]: yield SwiftIntegerType( is_word=False, bits=bitwidth, is_signed=is_signed) for is_signed in [False, True]: yield SwiftIntegerType( is_word=True, bits=word_bits, is_signed=is_s...
ifcharming/original2.0
tests/scripts/examples/sql_coverage/normalizer.py
Python
gpl-3.0
4,812
0.002286
#!/usr/bin/env python # This file is part of VoltDB. # Copyright (C) 2008-2011 VoltDB Inc. # # 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 limitati...
ermit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY
OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF O...
paninetworks/neutron
neutron/plugins/ml2/drivers/type_gre.py
Python
apache-2.0
3,250
0
# Copyright (c) 2013 OpenStack Foundation # 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 ...
"Service terminated!")) raise SystemExit() def get_endpoints(self): """Get every gre endpoints from database.""" gre_endpoints = self._get_endpoints() return [{'ip_address': gre_endpoint.ip_address, 'host': gre_endpoint.host} for gr...
mtu(self, physical_network=None): mtu = super(GreTypeDriver, self).get_mtu(physical_network) return mtu - p_const.GRE_ENCAP_OVERHEAD if mtu else 0
htwenhe/DJOA
whoa/urls.py
Python
mit
1,112
0.003597
"""whoa URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based...
f 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import patterns,include, url from django.
contrib import admin from django.conf import settings from django.conf.urls.static import static from xadmin.plugins import xversion import xadmin import demo urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'xadmin/', include(xadmin.site.urls)), url(r'demo/', include('demo.urls')), url(r'oa/',...
J216/gimp_be
gimp_be/draw/__init__.py
Python
mit
61
0
f
rom draw import * from effects import *
from chart import *
tlecomte/friture
friture/octavefilters.py
Python
gpl-3.0
4,411
0.003627
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2009 Timoth?Lecomte # This file is part of Friture. # # Friture is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as published by # the Free Software Foundation. # # Friture is distribu...
g10(Rc) self.B = 0.17 + 20. * log10(Rb) self.A = 2.0 + 20. * log10(Ra) self.zfs = octave_filter_bank_decimation_filtic(self.bdec, self.adec, self.boct, self.aoct) if bandsperoctave == 1: # with 1 band per octave, we would need the "R3.33" Renard series, but it does not exist...
ce the numbers simply round up. self.f_nominal = ["%.1fk" % (f/1000) if f >= 10000 else "%.2fk" % (f/1000) if f >= 1000 else "%d" % (f) for f in self.fi] else: # with more than 1 band per octave, us...
dimagi/commcare-hq
corehq/ex-submodules/pillowtop/tests/test_elasticsearch.py
Python
bsd-3-clause
14,655
0.002661
import functools from unittest import mock import uuid from django.conf import settings from django.test import SimpleTestCase from corehq.util.es.elasticsearch import ConnectionError, RequestError from corehq.apps.es.tests.utils import es_test from corehq.apps.hqadmin.views.data import lookup_doc_in_es from corehq...
tings'] self._compare_es_dicts(INDEX_STANDARD_SETTINGS, index_settings_back) def _compare_es_dicts(self, expected, returned):
sub_returned = returned['index'] should_not_exist = disallowed_settings_by_es_version[settings.ELASTICSEARCH_MAJOR_VERSION] for key, value in expected['index'].items(): if key in should_not_exist: continue split_key = key.split('.') returned_value =...
ssanderson/numpy
numpy/lib/arraysetops.py
Python
bsd-3-clause
16,818
0.000476
""" Set operations for 1D numeric arrays based
on sorting. :Contains: ediff1d, unique, intersect1d, setxor1d, in1d, uni
on1d, setdiff1d :Notes: For floating point arrays, inaccurate results may appear due to usual round-off and floating point comparison issues. Speed could be gained in some operations by an implementation of sort(), that can provide directly the permutation vectors, avoiding thus calls to argsort(). To do: Optiona...
georgemarshall/django
tests/gis_tests/gis_migrations/test_operations.py
Python
bsd-3-clause
9,026
0.002437
from unittest import skipIf from django.contrib.gis.db.models import fields from django.contrib.gis.geos import MultiPolygon, Polygon from django.core.exceptions import ImproperlyConfigured from django.db import connection, migrations, models from django.db.migrations.migration import Migration from django.db.migratio...
.apply_operations('gis', self.current_state, [migrations.DeleteModel('Neighborhood')]) super().tearDown() @property def has_spatial_indexes(self): i
f mysql: with connection.cursor() as cursor: return connection.introspection.supports_spatial_index(cursor, 'gis_neighborhood') return True def get_table_description(self, table): with connection.cursor() as cursor: return connection.introspection.get_table_d...
knuu/competitive-programming
atcoder/corp/codethxfes2014a_b.py
Python
mit
223
0
n = int(input()) m = [int(
input()) for _ in range(3)] cnt = int(n / sum(m)) * 3 n %= sum(m) m.sort() if n
== 0: print(cnt) elif n <= m[2]: print(cnt+1) elif n <= m[1] + m[2]: print(cnt+2) else: print(cnt+3)
LockScreen/Backend
venv/lib/python2.7/site-packages/requests/__init__.py
Python
mit
1,861
0
# -*- coding: utf-8 -*- # __ # /__) _ _ _ _ _/ _ # / ( (- (/ (/ (- _) / _) # / """ Requests HTTP library ~~~~~~~~~~~~~~~~~~~~~ Requests is an HTTP library, written in Python, for human beings. Basic GET usage: >>> import requests >>> r = requests.get('https://www.python.org') >>> ...
__version__ = '2.8.1' __build__ = 0x020801 __author__ = 'Kenneth Reitz' __license__ = 'Apache 2.0' __copyright__ = 'Copyright 2015 Kenneth Reitz' # Attempt to enable urllib3's SNI support, if possible try: from .packages.urllib3.
contrib import pyopenssl pyopenssl.inject_into_urllib3() except ImportError: pass from . import utils from .models import Request, Response, PreparedRequest from .api import request, get, head, post, patch, put, delete, options from .sessions import session, Session from .status_codes import codes from .except...
mozilla/FlightDeck
apps/tutorial/urls.py
Python
bsd-3-clause
141
0.007092
from d
jango.conf.urls.defaults import url, patterns urlpatterns = patterns('tutorial.views', url(r'^$', 'tutorial', name='tutorial'),
)
julzhk/codekata
InfixtoPostfixConverter.py
Python
mit
2,483
0.007652
import string from operator import ge as greater_than_or_equal, gt as greater_than from collections import deque OPERATOR_PRECEDENCE = { '(':0, '+':1, '-':1, '*':2, '/':2, '^':3, } RIGHT_ASSOCIATIVE_OPERATORS = '^' LEFT_ASSOCIATIVE_OPERATORS = '+-/*' def pop_operator_queue(operators, output,...
st.assert_equals("562-9*+", to_postfix("5+(6-2)*9")) Test.assert_equals("562-9*+36^+", to_postfix("5+(6-2)*9+3^6")) Test.assert_equals("562-9*+371-^+", to_postfix
("5+(6-2)*9+3^(7-1)")) Test.assert_equals(to_postfix("(5-4-1)+9/5/2-7/1/7"), "54-1-95/2/+71/7/-")
megaserg/pants
src/python/pants/backend/jvm/tasks/jvm_compile/zinc/zinc_compile.py
Python
apache-2.0
15,198
0.00783
# 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, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re ...
Shader.exclude_package('scala', recursive=True), Shader.exclude_package('xsbt', recursive=True), Shader.exclude_package('xsbti', recursive=True), ]) def sbt_jar(name, **kwargs): return JarDependency(org='com.typesafe.sbt', ...
gister_jvm_tool(register, 'compiler-interface', classpath=[ sbt_jar(name='compiler-interface', classifier='sources', # We just want the single compiler-interface jar an...
piyush82/icclab-rcb-web
virtualenv/lib/python2.7/site-packages/pip/vendor/distlib/util.py
Python
apache-2.0
42,456
0.001272
# # Copyright (C) 2012-2013 The Python Software Foundation. # See LICENSE.txt and CONTRIBUTORS.txt. # import codecs from collections import deque import contextlib import csv from glob import iglob as std_iglob import io import json import logging import os import py_compile import re import shutil import socket import...
ef __init__(self, dry_run=False): self.dry_run = dry_run self.ensured = set() self._init_record() def _init_record(self): self.record = False self.files_written = set() self.dirs_created = set() def record_as_written(self, path): if self.record: ...
ecently modified than 'target', or if 'source' exists and 'target' doesn't. Returns false if both exist and 'target' is the same age or younger than 'source'. Raise PackagingFileError if 'source' does not exist. Note that this test is not very accurate: files created in the same ...
brython-dev/brython
www/src/Lib/test/test_sunau.py
Python
bsd-3-clause
6,125
0.000327
import unittest from test import audiotests from audioop import byteswap import io import struct import sys import sunau class SunauTest(audiotests.AudioWriteTests, audiotests.AudioTestsWithSourceFile): module = sunau class SunauPCM8Test(SunauTest, unittest.TestCase): sndfilename = 'pluck-pc...
pname = 'not compressed' frames = bytes.fromhex("""\ 022EFFEA 4B5C00F9 311404EF 80DB0844 CBE006B0 48AB03F3 BFE601B5 0367FE80 \ B853FA42 B4AFF351 2997EBCD 1A5AE6DC EDF9E492 C627E277 0E06E0B7 EF29E029 \ 5759E271 FB34E83F 1377EF85 D82CF727 978EFB79 F5F7FC12 0864FB9E DF30FB40 \ 1183FA30 3EEAFB59...
0EB7 52B40DC1 EFAD0F65 CE3A0FBE \ E4B70CE6 63490A57 08CC0A1D 2BBC0B09 51480E46 8BCB113C B6F60EE9 44150A5A \ """) class SunauPCM24Test(SunauTest, unittest.TestCase): sndfilename = 'pluck-pcm24.au' sndfilenframes = 3307 nchannels = 2 sampwidth = 3 framerate = 11025 nframes = 48 c...
sean-smith/website_status
inemail.py
Python
mit
782
0.002558
__author__ = 'bernardo' import csv import mechanize import re import time import BeautifulSoup import sm
tplib def sendEmail(result, sfrom, pwd, sto): SMTP_SERVER = 'smtp.live.com' SMTP_PORT = 587 sender = 'sfrom' recipient = 'sto' subject = 'Promocoes' body = result body = "<b>" + body + "<b>" headers = ["From: " + sender, "Subject: " + subject, "To: " + r...
SERVER , SMTP_PORT) session.ehlo() session.starttls() session.ehlo session.login(sender, pwd) session.sendmail(sender, recipient, headers + "\r\n\r\n" + body) session.quit()
gonzalocasas/ttn-coverage-tracker
features.py
Python
mit
1,967
0.000508
import parser import geojson import os.path gateway_marker_symbols = {} def build(data_point): coords = parser.get_coords(data_point) if coords is None: raise ValueError("No GPS data") point = geojson.Point(coords) props = dict(hash=data_point['hash'], time=data_point['time'], ...
s) def build_gateway(status_packet): coords = (status_packet["longitude"], status_packet["latitude"]) point = geojson.Point(coords) props = dict(hash=status_packet['eui'], eui=status_packet['eui']) # Add styling features props['marker-symbol'] = 'rocket' props['marker-color'] = '#990000' ...
rties=props) def build_collection(features): return geojson.FeatureCollection(features) def get_marker_color(data_point): color = '#7d8182' # default to grey try: rssi = float(data_point['rssi']) except: return color if rssi < 0 and rssi >= -70: color = '#005a32' i...
jGaboardi/LP_MIP
Gurobi_Primal_Standard.py
Python
lgpl-3.0
3,759
0.011173
''' GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. ''' # Building a Standard Primal Linear Progr...
###' print ' < ISSUE : ', e, ' >' print ' ################################################################' # Write LP file mPrimal_Standard_GUROBI.write('LP.lp') print '\n*************************************************************************' print ' | Decision Variab...
***************************************' val = mPrimal_Standard_GUROBI.objVal print ' | Objective Value ------------------ ', val print ' | Aij Sum -------------------------- ', AijSum print ' | Cj Sum --------------------------- ', CjSum print ' | Bi Sum ------------------------...
gillett-hernandez/project-euler
Python/problem_17.py
Python
mit
2,193
0.033744
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Author: Gillett Hernandez # @Date: 2016-06-24 18:59:07 # @Last Modified by: Gillett Hernandez # @Last Modified time: 2017-08-10 12:37:57 from euler_funcs import timed numberDict={} numberDict[1]='one' numberDict[2]='two' numberDict[3]='three' numberDict[4]='four'...
,''))-1 if number<0: number=-number ne=-1 else: ne=1 number=str(number) numbers=[] for x in range(order+1): numbers.append(ne*int(number[x])*10**(order-x)) r
eturn numbers def countLetters(string): st=string[:] st=st.replace('-','') st=st.replace(' ','') st=st.replace('\n','') return len(st) @timed def main(): bigString="""""" for k in range(1,1001): de=decompose(k) for digit in de: if digit==10 and de[-1]>0: ...
goerz/clusterjob
tests/test_workflow.py
Python
mit
4,046
0.001236
from __future__ import print_function import os import logging from clusterjob import JobScript, AsyncResult from clusterjob.utils import _wrap_run_cmd from clusterjob.cli import _run_testing_workflow import pytest try: # Python 2 compatiblity input = raw_input except NameError: pass # builtin fixtures: tmp...
staticmethod(JobScript._run_cmd)) monkeypatch.setattr(AsyncResult, '_min_sleep_interval', 0) # configure job script with open(bodyfile) as in_fh: body =
in_fh.read() jobname = 'test_clj' for key in JOB_NAMES: if ini_file.endswith(key): jobname = JOB_NAMES[key] break job = JobScript(body, jobname=jobname) job.read_settings(ini_file) stdout = 'clusterjob_test.out' job.resources['stdout'] = stdout if len(job.prol...
tcstewar/nengo_assignments
groningen_2018/addition.py
Python
gpl-3.0
422
0.021327
import nengo mo
del = nengo.Network() with model: a = nengo.Ensemble(n_neurons=100, dimensions=1) stim_a = nengo.Node([0]) nengo.Connection(stim_a, a) b = nengo.Ensemble(n_neurons=100, dimensions=1) stim_b =
nengo.Node([0]) nengo.Connection(stim_b, b) c = nengo.Ensemble(n_neurons=100, dimensions=1) nengo.Connection(a, c) nengo.Connection(b, c)
pycontw/pycontw2016
src/proposals/migrations/0027_auto_20160426_1137.py
Python
mit
659
0.003035
# -*- coding: utf-8 -*- # Generated by Django 1.9.3 on 2016-04-26 11:37 from __future__ import unicode_literals from django.db import migrations class M
igration(migrations.Migration): dependencies = [ ('proposals', '0026_auto_20160425_1501'), ] operations = [ migrations.AlterModelOptions( name='talkproposal', options={'verbose_name': 'talk proposal', 'verbose_name_plural': 'talk proposals'}, ), migr...
'tutorial proposal', 'verbose_name_plural': 'tutorial proposals'}, ), ]
Gebesa-Dev/Addons-gebesa
account_invoice_refund_mode/models/__init__.py
Python
agpl-3.0
187
0
# -*- coding: utf-8 -*- # © <YEAR(S)> <AUTHOR(S)> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from . import account_invoi
ce from . import
account_invoice_refund
chrislit/abydos
abydos/distance/_strcmp95.py
Python
gpl-3.0
8,223
0
# Copyright 2014-2020 by Christopher C. Little. # This file is part of Abydos. # # Abydos 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 versio...
('X', 'S'), ('Q', 'C'), ('U', 'V'), ('M', 'N'), ('L', 'I'), ('Q', 'O'), ('P', 'R'), ('
I', 'J'), ('2', 'Z'), ('5', 'S'), ('8', 'B'), ('1', 'I'), ('1', 'L'), ('0', 'O'), ('0', 'Q'), ('C', 'K'), ('G', 'J'), ) def __init__(self, long_strings: bool = False, **kwargs: Any) -> None: """Initialize Strcmp95 instance. ...
EuropeanSocialInnovationDatabase/ESID-main
TextMining/Classifiers/Trainers/NaiveBayesInnovativeness.py
Python
gpl-3.0
16,369
0.002505
from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.naive_bayes import MultinomialNB from sklearn import metrics from sklearn.pipeline import Pipeline import numpy as np import pandas as pd import re from os import listdir from os.path im...
() l.StartSpan = line_index l.EndSpan = line_index + len(line) l.Text = line line_index = line_index + len(line) + 1 sentences.append(line)
doc.Lines.append(l) an = open(data_folder + "/" + ann + '/' + file.replace(".txt", ".ann"), 'r') annotations = an.readlines() for a in annotations: a = re.sub(r'\d+;\d+', '', a).replace(' ', ' ') split_ann = a.split('\t') if (split_ann[0].startswith("T")):...
sumedh123/debatify
venv/lib/python2.7/site-packages/sqlalchemy/sql/type_api.py
Python
mit
42,846
0
# sql/types_api.py # Copyright (C) 2005-2016 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """Base types API. """ from .. import exc, util from . import operators from .vi...
r self.type = expr.type @util.dependencies('sqlalchemy.sql.default_comparator') def operate(self, default_comparator, op, *other, *
*kwargs): o = default_comparator.operator_lookup[op.__name__] return o[0](self.expr, op, *(other + o[1:]), **kwargs) @util.dependencies('sqlalchemy.sql.default_comparator') def reverse_operate(self, default_comparator, op, other, **kwargs): o = default_comparator.ope...
atiqueahmedziad/addons-server
src/olympia/files/tests/test_file_viewer.py
Python
bsd-3-clause
17,440
0
# -*- coding: utf-8 -*- import mimetypes import os import shutil import zipfile from django import forms from django.conf import settings from django.core.cache import cache from django.core.files.storage import default_storage as storage import flufl.lock import pytest from freezegun import freeze_time from mock im...
self.viewer.extract() assert self.viewer.is_extracted() def test_recurse_contents(self): self.viewer.src = get_file('recurse.xpi') self.viewer.extract() files = self.viewer.get_files() # We do not extract nested .zip or .xpi files anymore assert files.keys() == [...
u'recurse/chrome/test.jar', u'recurse/notazip.jar', u'recurse/recurse.xpi', u'recurse/somejar.jar'] def test_locked(self): self.viewer.src = get_file('dictionary-test.xpi') # Lock was successfully attained assert self.viewer.extract() l...
nberliner/delveData
lib/countryMentionNYT.py
Python
gpl-2.0
3,856
0.008039
# -*- coding: utf-8 -*- """ Estimate the international "visibility" of countries by retrieving the average number of articles the New York Times returns in its search query. For each year and each country, a query is send to the NYT api and the number of returned hits (i.e. articles) is taken as estimate for the inter...
deMapper from utils import Country, CountryContainer from nytimesa
rticles import articleAPI, DeveloperOverRate api = articleAPI('/* Your API access key here */') # Use tmp folder to keep intermediate results. Final output will be placed there as well tmpFolder = "../data/newspaper/raw/" ## Read the temporary folder content done = [ int(fname[8:-2]) for fname in os.listdir(tmpFold...
NitishT/minio-py
tests/functional/tests.py
Python
apache-2.0
79,042
0.003796
#!/usr/bin/env python # -*- coding: utf-8 -*- # Minio Python Library for Amazon S3 Compatible Cloud Storage, # (C) 2015, 2016, 2017, 2018 Minio, 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 Lice...
m from string import ascii_lowercase import time import traceback from datetime import datetime, timedelta import urllib3 import certifi import hashlib from threading import Thread from minio import Minio, PostPolicy, CopyConditions from minio.error import (APINotImp
lemented, NoSuchBucketPolicy, ResponseError, PreconditionFailed, BucketAlreadyOwnedByYou, BucketAlreadyExists, InvalidBucketError) class LimitedRandomReader(object): """ LimitedRandomReader returns a Reader that upon read returns random data, but stops with...
peterjoel/servo
tests/wpt/update.py
Python
mpl-2.0
1,083
0.00277
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at https://mozilla.org/MPL/2.0/.
import os import sys from wptrunner import wptcommandline here = os.path.split(__file__)[0] def wpt_path(*args): return os.path.join(here, *args) # Imports from update import updatecommandline def update_tests(**kwargs): import update set_defaults(kwargs) logger = update.setup_logging(kwargs, {...
out}) rv = update.run_update(logger, **kwargs) return 1 if rv is update.exit_unclean else 0 def set_defaults(kwargs): if kwargs["product"] is None: kwargs["product"] = "servo" if kwargs["config"] is None: kwargs["config"] = wpt_path('config.ini') kwargs["store_state"] = False ...
hnu2013wwj/DH-AutoAC
Python/hdu.py
Python
gpl-2.0
2,371
0.000422
import time import requests import answer min_question_id = 1000 max_question_id = 5604 sleep_time = 10 submit_url = 'http://acm.hdu.edu.cn/submit.php?action=submit' login_url = 'http://acm.hdu.edu.cn/userloginex.php?action=login' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/53...
# print(res.tex
t.encode('UTF-8')) if res.status_code == 200: self.is_login = True return True return False def submit(self, problem, code): data = { "check": "0", "problemid": str(problem), "usercode": code, "language": "0" } ...
luisibanez/SahanaEden
controllers/bulk_gis.py
Python
mit
8,554
0.005962
#!/usr/bin/python """ Bulk Uploader - Controllers A simple loader for GIS files in CSV format. Developed primarily for loading Administrative Areas for Haiti. LICENSE: This
source file is subject to LGPL license that is available through the world-wide-web at the following URI: http://www.gnu.org/copyleft/lesser.html @author: Timothy Caro-Bruce <tcarobruce@gmail.com> @package: Sahana - http://sahana.lk/ @module: bulk_gis @copyright: Lanka Software Foundation - ht...
y.wkt import loads as wkt_loads # CONSTANTS ADMIN_FEATURE_CLASS_NAME = "Administrative Area" BASEDIR = os.path.join(request.folder, 'private') FILES = { 'Departments': 'Haiti_departementes_edited_01132010.csv', 'Communes': 'Haiti_communes_edited_01132010.csv', 'Sections': 'Haiti_Sections_Final_WGS84.csv' ...
SpreadBand/SpreadBand
apps/venue/urls.py
Python
agpl-3.0
2,471
0.00688
from django.conf.urls.defaults import patterns, url from django.conf import settings import views urlpatterns = patterns('', # CRUD url(r'^new$', views.new, name='create'), # Search url(r'^search$', views.search, name='search'), url(r'^search/cantfind$', views.search_cantfi...
# pictures url(r'^(?P<venue_slug>[-\w]+)/pictures$', views.picture_list, name='venue-pictures'), url(r'^(?P<venue_slug>[-\w]+)/pictures/new$', views.picture_new, name='venue-pict
ure-new'), url(r'^(?P<venue_slug>[-\w]+)/pictures/delete/(?P<picture_id>\d+)$', views.picture_delete, name='venue-picture-delete'), # membership # url(r'^(?P<venue_slug>[-\w]+)/members/request$', views.members.membership_request, name='membership-request'), url(r'^(?P<venue_slug>[-\w]+)/members/(?P<me...
eharney/cinder
cinder/volume/drivers/infortrend/raidcmd_cli/cli_factory.py
Python
apache-2.0
18,508
0
# Copyright (c) 2015 Infortrend Technology, 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 # # ...
ract class.""" def __init__(self): super(BaseCommand, self).__init__() @abc.abstractmethod def execute(self, *args, **kwargs): pass class ExecuteCommand(BaseCommand): """The Common ExecuteCommand.""" def __init__(self, cli_conf): super(ExecuteCom
mand, self).__init__() self.cli_retry_time = cli_conf.get('cli_retry_time') @retry_cli def execute(self, *args, **kwargs): result = None rc = 0 try: result, err = utils.execute(*args, **kwargs) except processutils.ProcessExecutionError as pe: rc =...
telminov/raspberry-car
frontend/ui.py
Python
mit
229
0.004367
# coding: utf-8 import http.server import socketserver PORT = 8000 Handler = htt
p.server.SimpleHTTPRequestHandler httpd = socketserver.TCPServer(("0.0.0.0", PORT), Hand
ler) print("serving at port", PORT) httpd.serve_forever()
obi-two/Rebelion
data/scripts/templates/object/mobile/shared_dressed_izaryx.py
Python
mit
430
0.048837
#
### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Creature() result.template = "object/mobile/shared_dressed_izaryx.iff" result.attribute_template_id = 9 result.st...
MODIFICATIONS #### return result
Elastica/kombu
kombu/transport/zmq.py
Python
bsd-3-clause
8,476
0.000118
""" kombu.transport.zmq =================== ZeroMQ transport. """ from __future__ import absolute_import, unicode_literals import errno import os import socket try: import zmq from zmq import ZMQError except ImportError: zmq = ZMQError = None # noqa from kombu.five import Empty from kombu.log import g...
ink=True, context=None): try:
scheme, parts = uri.split('://') except ValueError: scheme = 'tcp' parts = uri endpoints = parts.split(';') self.port = port if scheme != 'tcp': raise NotImplementedError('Currently only TCP can be used') self.context = context or zmq.Co...
volpino/Yeps-EURAC
tools/new_operations/flanking_features.py
Python
mit
8,583
0.014214
#!/usr/bin/env python #By: Guruprasad Ananda """ Fetch closest up/downstream interval from features corresponding to every interval in primary usage: %prog primary_file features_file out_file direction -1, --cols1=N,N,N,N: Columns for start, end, strand in first file -2, --cols2=N,N,N,N: Columns for start, end...
for n in result_up: ends.append(n.end) res_ind = ends.index(max(ends)) #fetch the index of the closest interval i.e. the interval with the max end from the results_up list else: res_ind = 0
if not(either): map(outfields.append, result_up[res_ind].other) yield outfields if result_down: outfields = list(interval) if not(either): map(outfields.appen...
dimagi/commcare-android
images/utils.py
Python
apache-2.0
198
0
import os def
ensure_dir(directory): """Ensures that the path specified is an existing directory. If not, create it""" if not os.path.exists(director
y): os.makedirs(directory)