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
gfyoung/pandas
pandas/tests/frame/methods/test_sample.py
Python
bsd-3-clause
12,586
0.001827
import numpy as np import pytest from pandas import ( DataFrame, Index, Series, ) import pandas._testing as tm import pandas.core.common as com class TestSample: @pytest.fixture(params=[Series, DataFrame]) def obj(self, request): klass = request.param if klass is Series: ...
result2 = obj.sample(n=50, random_
state=np.random.default_rng(11)) tm.assert_equal(result1, result2) def test_sample_upsampling_without_replacement(self, frame_or_series): # GH#27451 obj = DataFrame({"A": list("abc")}) if frame_or_series is Series: obj = obj["A"] msg = ( "Replace ha...
codetojoy/gists
python/module_jun_2020/eg_2/tests/test_location.py
Python
apache-2.0
253
0.007905
from location import build_location
def test_build_location_simple(): # test Location = build_location()
location = Location("Canada", "Charlottetown") assert location.country == "Canada" assert location.city == "Charlottetown"
SiLab-Bonn/pyBAR
pybar/analysis/analyze_raw_data.py
Python
bsd-3-clause
88,134
0.004039
''' Script to convert the raw data and to plot all histograms''' from __future__ import division import logging import warnings import os import multiprocessing as mp from functools import partial from matplotlib.backends.backend_pdf import PdfPages import tables as tb from tables import dtype_from_descr, Col import ...
self._analyzed_data_file = None # create a scan parameter table from all raw data files if raw_data_files is not None: self.files_dict = analysis_utils.get_parameter_from_files(raw_data_files, parameters=scan_parameter_name) if not analysis_utils.check_parameter...
self.scan_parameters = analysis_utils.create_parameter_table(self.files_dict) scan_parameter_names = analysis_utils.get_scan_parameter_names(self.scan_parameters) logging.info('Scan parameter(s) from raw data file(s): %s', (', ').join(scan_parameter_names) if scan_parameter_names els...
vportascarta/UQAC-8INF844-SPHERO
agents/Destructor.py
Python
gpl-3.0
35
0
#
TODO : Faire l'agen
t destructeur
vicky2135/lucious
tests/integration/offer/test_priority_offers.py
Python
bsd-3-clause
1,700
0
import mock import datetime from django.test import TestCase from django.utils import timezone from oscar.core.loading import get_model from oscar.apps.offer import utils from oscar.test import factories Voucher = get_model('voucher', 'Voucher') class TestPriorityOffers(TestCase): def test_site_offers_are_orde...
one.now(), end_datetime=timezone.now() + datetime.timedelta(days=12)) voucher.offers = [ factories.create_offer(name="A", priority=0), factories.create_offer(name="B", priority=7), factories.create_offer(name="C", priority=5), factories.create_offer(n...
factories.create_offer(name="E", priority=1), ] basket = factories.create_basket() user = mock.Mock() # Apply voucher to basket basket.vouchers.add(voucher) offers = utils.Applicator().get_basket_offers(basket, user) ordered_names = [offer.name for ...
suzannerohrback/somaticCNVpipeline
bin/arguments.py
Python
mit
9,538
0.040784
#!/usr/bin/python import argparse ###basic parser for parent help statement### def parentArgs(): parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description='''\ Suzanne's pipeline to identify somatic CNVs from single-cell whole-genome sequencing data =============...
help = 'The path to the folder to save output files') parser.add_argument('species', choices=['hg38', 'mm10'], help = 'The genome build of the species being assessed') #optional arguments# parser.add_argument('-f', '--nofilter', action='store_true', help = 'Set this flag if you do not want to perform FUnC f...
g of low-quality CNV calls (UNTESTED)') # parser.add_argument('-i', '--infofile', metavar='/path/to/sample.info.txt', default=False, # help='Path to a .txt file containing information about the samples to be processed (unique name, number of cells, group)\n\tIf not all are identical. This file should not have a header...
nskinkel/oppy
oppy/tests/unit/circuit/test_circuitmanager.py
Python
bsd-3-clause
19,440
0.000463
import mock from twisted.trial import unittest from oppy.circuit.circuitmanager import CircuitManager from oppy.circuit.definitions import ( CircuitType, DEFAULT_OPEN_IPv4, DEFAULT_OPEN_IPv6, ) from oppy.path.path import Path ID = 0 class CircuitManagerTest(unittest.TestCase): @mock.patch('oppy.c...
tEqual(len(self.cm._pending_stream_list), 1) # TODO: test _buildCircuit is called with correct args # test specific correct stream added to pending streams @mock.patch('oppy.stream.stream.Stream', autospec=True) def test_getOpenCircuit_no_
circuit(self, mock_stream): r = mock.Mock() mock_stream.request = r self.cm._getOpenCandidates = mock.Mock() self.cm._getOpenCandidates.return_value = [] self.cm._getPendingCandidates = mock.Mock() self.cm._getPendingCandidates.return_value = [] self.cm._buildCirc...
google-research/pyreach
pyreach/mock/client_annotation_mock_test.py
Python
apache-2.0
1,275
0.002353
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
h import client_annotation from pyreach.mock import client_annotation_mock class TestClientAnnotationMock(unittest.TestCase): """Test the TextInstructionsMock.""" def test_logger(self) -> None: """Test the MockLogger.""" mock_client_annotation: client_annotation_mock.ClientAnnotationMock mock_client_...
client_annotation_mock.ClientAnnotationMock) assert isinstance(mock_client_annotation, client_annotation.ClientAnnotation) if __name__ == "__main__": unittest.main()
pombreda/pydbgr
trepan/bwprocessor/__init__.py
Python
gpl-3.0
785
0
# This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This progra
m is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with thi...
s/>. """ Copyright (C) 2013 Rocky Bernstein <rocky@gnu.org> """ __import__('pkg_resources').declare_namespace(__name__) __all__ = ['main', 'msg']
FabriceSalvaire/PySpice
examples/basic-usages/subcircuit.py
Python
gpl-3.0
1,938
0.013982
#r# ======================= #r# How to Use SubCircuit #r# ======================= #r# This example shows how to use subcircuits. ####################################
################################################################ import PySpice.Logging.Logging as Logging logger = Logging.setup_logging() #####################################################
############################################### from PySpice.Spice.Netlist import Circuit, SubCircuit, SubCircuitFactory from PySpice.Unit import * #################################################################################################### #r# There is two ways to define subcircuit with PySpice, either usin...
konstantinoskostis/sqlalchemy-utils
tests/functions/test_get_columns.py
Python
bsd-3-clause
1,840
0
import pytest import sqlalchemy as sa from sqlalchemy_utils import get_columns @pytest.fixture def Building(Base): class Building(Base): __tablename__ = 'building' id = sa.Column('_id', sa.Integer, primary_key=True) name = sa.Column('_name', sa.Unicode(255)) return Building class Te...
get_columns(Building()), sa.util._collection
s.OrderedProperties ) def test_mapper(self, Building): assert isinstance( get_columns(Building.__mapper__), sa.util._collections.OrderedProperties ) def test_class_alias(self, Building): assert isinstance( get_columns(sa.orm.aliased(Building)...
lcoandrade/DsgTools
core/DSGToolsProcessingAlgs/Algs/LayerManagementAlgs/assignFilterToLayersAlgorithm.py
Python
gpl-2.0
7,059
0.001275
# -*- coding: utf-8 -*- """ /*************************************************************************** DsgTools A QGIS plugin Brazilian Army Cartographic Production Tools ------------------- begin : 2019-04-26 git sha ...
anslated algorithm name, which should be used for any use
r-visible display of the algorithm name. """ return self.tr('Assign Filter to Layers') def group(self): """ Returns the name of the group this algorithm belongs to. This string should be localised. """ return self.tr('Layer Management Algorithms') def gr...
xolox/python-linux-utils
linux_utils/atomic.py
Python
mit
7,481
0.000668
# linux-utils: Linux system administration tools for Python. # # Author: Peter Odding <peter@peterodding.com> # Last Change: June 24, 2017 # URL: https://linux-utils.readthedocs.io """ Atomic filesystem operations for Linux in Python. The most useful functions in this module are :func:`make_dirs()`, :func:`touch()`, ...
(basename, os.getpid())) def make_dirs(directory, mode=0o777): """ Create a directory if it doesn't alre
ady exist (keeping concurrency in mind). :param directory: The pathname of a directory (a string). :returns: :data:`True` if the directory was created, :data:`False` if it already existed. :raises: Any exceptions raised by :func:`os.makedirs()`. This function is a wrapper for :func:`os.m...
krattai/noo-ebs
docs/zeroMQ-guide2/examples/Python/clonesrv4.py
Python
bsd-2-clause
2,618
0.004202
""" Clone server Model Four Author: Min RK <benjaminrk@gmail.com """ import zmq from kvsimple import KVMsg # simple struct for routing information for a key-value snapshot class Route: def __init__(self, socket, identity, subtree): self.socket = socket # ROUTER socket to send to self.iden...
isher) kvmsg.store(kvmap) print "I: publishing update %5d" % sequence # Exec
ute state snapshot request if snapshot in items: msg = snapshot.recv_multipart() identity, request, subtree = msg if request == "ICANHAZ?": pass else: print "E: bad request, aborting\n", break ...
why2pac/dp-tornado
example/controller/tests/helper/datetime/timestamp.py
Python
mit
3,271
0.006114
# -*- coding: utf-8 -*- from dp_tornado.engine.controller import Controller class TimestampController(Controller): def get(self): backup_zone = self.model.tests.helper_test.datetime.switch_timezone('Asia/Seoul') assert_tuple = self.model.tests.assert_tuple tzx_seoul = 'Asia/Seoul' ...
lper.datetime.timestamp.yesterday(timestamp=epoch) epoch_ms_tomorrow = self.helper.datetime.timestamp.tommorow(timestamp=epoch_ms, ms=True) dt_yesterday = self.helper.datetime.from_timestamp(timestamp=epoch_yesterday) dt_tomorrow = self.helper.datetime.from_timestamp(timestamp=epoch_ms_tomorrow...
.convert(timestamp=ts_conv, timezone=tz_seoul, ms=True) dt_b = self.helper.datetime.convert(timestamp=ts_conv, timezone=tz_shanghai, ms=True) assert_tuple(self.helper.datetime.tuple(datetime=dt_a), [1989, 2, 2, 9, 20, 30, 'Asia/Seoul']) assert_tuple(self.helper.datetime.tuple(datetime=dt_b), [1...
shs96c/buck
scripts/migrations/include_def_test.py
Python
apache-2.0
1,032
0.000969
import ast import unittest import include_def import repository class IncludeDefTest(unittest.TestCase): def test_can_get_location_from_ast_call(self): include = self._parse_include_def('include_defs("//foo/DEFS")') self.assertEqual("//foo/DEFS", include.get_location()) def test_can_get_incl...
t_include_path(repo)) def test_handles_dash_in_path(self): repo = repository.Repository("/repo", {}) inc
lude = self._parse_include_def('include_defs("//third-party/DEFS")') self.assertEqual("//third-party/DEFS", include.get_location()) self.assertEqual("/repo/third-party/DEFS", include.get_include_path(repo)) def _parse_include_def(self, code: str) -> include_def.IncludeDef: return include_de...
JamesJGarner/cms
src/cms/project_template/project_name/apps/site/__init__.py
Python
bsd-3-clause
51
0.019608
""
"Site-specific content, templatetags and such."""
BaileySN/Support-Client
bin/update.py
Python
gpl-3.0
6,233
0.006257
#!/usr/bin/python # -*- coding: utf-8 -*- ############################################################################################################################## # Support-Client <http://wiki.pratznschutz.com/index.php/Support-Client>. # # Copyright (C) [2015] ...
, self.fna
me) showinfo(ltrans.programm_name, ltrans.label_update_finish) except IOError: print("cant run") else: showerror(ltrans.programm_name, ltrans.label_update_error) def dlprogram(self): import urllib2 if not os.path.exists(self.dldir): ...
DarthMaulware/EquationGroupLeaks
Leak #5 - Lost In Translation/windows/Resources/DeMi/PyScripts/Lib/demi/mcf/cmd/diba/tasking.py
Python
unlicense
537
0.003724
# uncompyle6 version 2.9.10 # Python bytecode 2.7 (62211) # Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10) # [GCC 6.2.0 20161005] # Embedded file name: tasking.py import mcl_platform.tasking from tasking_dsz import * _fw = mcl_platform.tasking.GetFramework() if _fw == 'dsz': RP
C_INFO_INSTALL = d
sz.RPC_INFO_INSTALL RPC_INFO_UNINSTALL = dsz.RPC_INFO_UNINSTALL RPC_INFO_SURVEY = dsz.RPC_INFO_SURVEY RPC_INFO_UPGRADE = dsz.RPC_INFO_UPGRADE else: raise RuntimeError('Unsupported framework (%s)' % _fw)
statsmodels/statsmodels
statsmodels/tsa/ardl/tests/test_ardl.py
Python
bsd-3-clause
24,282
0
from typing import NamedTuple import numpy as np from numpy.testing import assert_allclose import pandas as pd from pandas.testing import assert_index_equal import pytest from statsmodels.datasets import danish_data from statsmodels.iolib.summary import Summary from statsmodels.tools.sm_exceptions import Specificatio...
ning, match="exog contains variables that" ): ARDL(data.y, 2, data.x, {"lry": [1, 2]}, causal=False) def test_ardl_deterministic_exceptions(data): with pytest.raises(TypeError):
ARDL(data.y, 2, data.x, 2, deterministic="seasonal") with pytest.warns( SpecificationWarning, match="When using deterministic, trend" ): deterministic = DeterministicProcess( data.y.index, constant=True, order=1 ) ARDL(data.y, 2, data.x, 2, deterministic=determini...
jrkerns/pylinac
tests_basic/__init__.py
Python
mit
604
0.003311
import os import os.path as osp import unittest import matplotlib TEST_FILES_DIR = osp.abspath(osp.join(osp.dirname(__file
__), 'test_files')) TEST_BANK_DIR = osp.abspath(osp.join(osp.dirname(__file__), '..', '..', 'pylinac test files')) matplotlib.use('Agg') DELETE_FI
LES = bool(os.environ.get("DELETE_FILES", default=False)) def run_tests(directory, pattern='test*.py'): # import a runner to run tests_basic runner = unittest.TextTestRunner() # run test discovery test_suite = unittest.defaultTestLoader.discover(directory, pattern) # run test runner runner.run(...
Cube777/dotgit
tests/test_git.py
Python
gpl-2.0
5,561
0.006474
import os import subprocess import pytest from dotgit.git import Git, FileState class TestGit: def touch(self, folder, fname): open(os.path.join(folder, fname), 'w').close() def test_init(self, tmp_path): path = os.path.join(tmp_path, 'nonexistent') # check that using a non-existent ...
tmp_path): git, repo = self.setup_git(tmp_path) self.touch(repo, 'file') self.touch(repo, 'file2') assert git.status()==[(FileState.UNTRACKED,f) for f in ['file','file2']] git.add() assert git.status()==[(FileState.ADDED,f) for f in ['file','file2']] def test_add_fi...
file') self.touch(repo, 'file2') assert git.status()==[(FileState.UNTRACKED,f) for f in ['file','file2']] git.add('file') assert git.status()==[(FileState.ADDED, 'file'), (FileState.UNTRACKED, 'file2')] def test_commit_msg(self, tmp_path): git, repo = self.setup_...
Sarthak30/Codeforces
present_from_lena.py
Python
gpl-2.0
302
0.016556
inp = int(raw_input()) k = inp - 1 def generate(n): return [' ' for i in range(inp - n + 1)] \ + [str(i) for i in range(n)] + [
str(i) for i in range(n-1)][::-1] for i in range(inp + 1): print " ".join(generate(i + 1)) while(k >= 0): print " ".join(generate(k + 1))
k -= 1
Arduino-IoT/libraries
StepperModel/Utils/gcodeManage.py
Python
gpl-2.0
1,210
0.018182
#!/usr/bin/python # Some usfull gcode info - manipulation functions # # prerequisite: http://pyserial.sourceforge.net # Installation on Ubuntu: sudo aptitude install python-serial # Configure: # End configuration import sys import re import serial class Range: def __init__(self): self.min = 9...
ileToFeed, "r") xRange = Range() yRange = Range() pattern = re.compile('([(!;].*|\s+|[a-zA-Z0-9_:](?:[+-])?\d*(?:\.\d*)?|\w\#\d+|\(.*?\)|\#\d+\=(?:[+-])?\d*(?:\.\d*)?)') lines = gcode.readlines() for line in lines: line = line.lower() words = pattern.findall(line) for word in words: if word[0] ==...
l(word[1:]) xRange.adjust(x) if word[0] == 'y': y = eval(word[1:]) yRange.adjust(y) print "x=", xRange, " y=",yRange
tigercomputing/nagios-mass-scheduler
app.py
Python
gpl-3.0
3,456
0
#!/usr/bin/env python3 """ This file is part of mass-scheduler. mass-scheduler is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as pu
blished by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. mass-scheduler is distributed in the hope that i
t will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with mass-scheduler. If not, see <http://www.gnu.org/licen...
mvx24/fabric-shuttle
shuttle/services/postgis.py
Python
mit
2,444
0.001637
from fabric.api import run, sudo, cd from shuttle.shared import apt_get_install, get_django_setting _GEOS_URL = 'http://archive.ubuntu.com/ubuntu/pool/universe/g/geos/geos_3.3.3.orig.tar.gz' _GEOS_DIR = 'geos-3.3.3' _
PROJ4_URL = 'http://download.osgeo.org/proj/proj-4.8.0.tar.gz' _PROJ4_DIR = 'proj-4.8.0/nad' _PROJ4_DATUM_URL = 'http://download.osgeo.org/proj/proj-datumgrid-1.5.tar.gz' _G
DAL_URL = 'http://download.osgeo.org/gdal/gdal-1.9.2.tar.gz' _GDAL_DIR = 'gdal-1.9.2' _POSTGIS_URL = 'http://download.osgeo.org/postgis/source/postgis-2.0.3.tar.gz' _POSTGIS_DIR = 'postgis-2.0.3' def install_postgis(): apt_get_install('postgresql-server-dev-all', 'libpq-dev', 'libxml2', 'libxml2-dev') # Inst...
aronsky/home-assistant
homeassistant/components/synology_chat/notify.py
Python
apache-2.0
1,900
0
"""SynologyChat platform for notify component.""" from http import HTTPStatus import json import logging import requests import voluptuous as vol
from homeassistant.components.notify import ( ATTR_DATA, PLATFORM_SCHEMA, BaseNotificationService, ) from homeassistant.const import CONF_RESOURCE, CONF_VERIFY_SSL import homeassistant.helpers.config_validation as cv ATTR_FILE_URL = "file_url" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol....
er(__name__) def get_service(hass, config, discovery_info=None): """Get the Synology Chat notification service.""" resource = config.get(CONF_RESOURCE) verify_ssl = config.get(CONF_VERIFY_SSL) return SynologyChatNotificationService(resource, verify_ssl) class SynologyChatNotificationService(BaseNot...
alekz112/xlwings
examples/simulation/build_standalone.py
Python
apache-2.0
704
0.004261
import os import shutil from subprocess import call def main(): # Clean the build directory if os.path.isdir('./build'): shutil.rmtree('./build') # Freeze it call('python setup.py bu
ild') # Zip it up - 7-zip provides better compression than the
zipfile module # Make sure the 7-zip folder is on your path file_name = 'simulation_standalone' if os.path.isfile('{}.zip'.format(file_name)): os.remove('{}.zip'.format(file_name)) call('7z a -tzip {}.zip simulation.xlsm'.format(file_name, file_name)) call('7z a -tzip {}.zip LICENSE.txt'.for...
Yogesh3/Data-Reduction
Exoplanet/lightcurve.py
Python
mit
4,335
0.018916
import pdb import numpy as np import math as m import sys import matplotlib.pyplot as plt #Calculate average and its error for a given data set def Average(values, error= None): #No error in the values if (error is None): #Calculate the average mu = np.sum(values)/values.shape[0] ...
0) and (denom == 0): #in case series of outliers mu = 0 sigma = 0 elif denom == 0: #in case no error mu = num/denom
sigma == 0 else: #if normal mu = num/denom sigma = m.sqrt(1.0/denom) return (mu, sigma) #Gives limits (indices) of exposures used for baseline flux def getLim(images, lowexp, upexp): l = np.array(np.where(images > lowexp)) ...
ntucker/django-aloha-edit
setup.py
Python
bsd-2-clause
1,190
0.001681
from __future__ import unicode_literals import os.path from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='django-aloha-edit', version='0.4.0', description='Django Aloha Edit', au
thor='Nathaniel Tucker', author_email='me@ntucker.me', url='https://github.com/ntucker/django-aloha-edit', packages=find_packages(), include_package_data=True, install_requires=['django>=1.6', 'blea
ch>=1.4', 'lxml>=2.3', 'Pillow>=2.9.0', 'tinycss>=0.3'], long_description=read('README.rst'), license="BSD", classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'Li...
magic0704/oslo.messaging
oslo_messaging/_drivers/zmq_driver/server/zmq_incoming_message.py
Python
apache-2.0
2,020
0
# Copyright 2015 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
q_async from oslo_messaging._drivers.zmq_driver import zmq_names LOG = logging.getLogger(__name__) zmq = zmq_async.import_zmq() class ZmqIncomingRequest(base.IncomingMessage): def __init__(self, listener, context, message, socket, rep_id, poller): super(ZmqIncomingRequest, self).__init__(listener, con...
ne self.poller = poller def reply(self, reply=None, failure=None, log_failure=True): if failure is not None: failure = rpc_common.serialize_remote_exception(failure, log_failure) message_reply = {zmq_names.FIELD_REPLY: ...
edx/edx-platform
openedx/core/djangoapps/discussions/tests/test_handlers.py
Python
agpl-3.0
6,691
0.001943
""" Tests for discussions signal handlers """ from unittest.mock import patch from uuid import uuid4 import ddt from django.test import TestCase from opaque_keys.edx.keys import CourseKey from openedx.core.djangoapps.discussions.data import CourseDiscussionConfigurationData, DiscussionTopicContext from openedx.core.d...
.external_id == str(existing_external_id) assert existing_topic_link.enabled_in_context @patch.dict( "openedx.core.djangoapps.discussions.models.AVAILABLE_PROVIDER_MAP"
, {"test": {"supports_in_context_discussions": True}}, ) def test_provider_change(self): """ Test that changing providers creates new links, and doesn't update existing ones. """ contexts = list(self.create_contexts(general=2, unit=3)) config_data = CourseDiscussi...
doublereedkurt/boltons
boltons/iterutils.py
Python
bsd-3-clause
32,952
0.000364
# -*- coding: utf-8 -*- """:mod:`itertools` is full of great examples of Python generator usage. However, there are still some critical gaps. ``iterutils`` fills many of those gaps with featureful, tested, and Pythonic solutions. Many of the functions below have two versions, one which returns an iterator (denoted by ...
ite of :func:`is_scalar`. Returns ``True`` if an object is an iterable other than a string. >>> is_collection(object()) False >>> is_collection(range(10)) True >>> is_collection('hello') False """ return is_iterable(obj) and not isinstance(obj, basestring) def split(src, sep=None...
"""Splits an iterable based on a separator. Like :meth:`str.split`, but for all iterables. Returns a list of lists. >>> split(['hi', 'hello', None, None, 'sup', None, 'soap', None]) [['hi', 'hello'], ['sup'], ['soap']] See :func:`split_iter` docs for more info. """ return list(split_iter(src, ...
frustreated/VDiscover
vdiscover/Mutation.py
Python
gpl-3.0
5,605
0.019982
""" This file is part of VDISCOVER. VDISCOVER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. VDISCOVER is distributed in the hope that it ...
filename = mfile.filename #print "checking",filename if 'open("'+filename in output[1]: return True return False #print output def fuzz_cmd(prepared_inputs, fuzzer_cmd, seed): p = Popen(fuzzer_cmd.split(" ")+[str(seed)], stdout=PIP
E, stdin=PIPE, stderr=PIPE) mutated_input = p.communicate(input=prepared_inputs)[0] return mutated_input.replace("\0","")[:32767] class DeltaMutation(object): def __init__(self, inp, atts): self.inp_type = str(inp.GetType()) #self.mut_type = str(typ) self.atts = copy.copy(atts) def __str__(self)...
huntxu/python-neutronclient
neutronclient/osc/v2/sfc/sfc_port_chain.py
Python
apache-2.0
14,745
0
# Copyright (c) 2017 Huawei Technologies India Pvt.Limited. # 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-...
nclient._i18n import _ from neutronclient.osc import utils as nc_osc_utils LOG = logging.getLogger(__name__) resource = 'port_chain' _attr_map = ( ('id', 'ID', nc_osc_utils.LIST_BOTH), ('name', 'Name', nc_osc_utils.LIST_BOTH), ('port_pair_groups', 'Port Pair Groups', nc_osc_utils.LIST_BOTH), ('flow_c...
, nc_osc_utils.LIST_BOTH), ('chain_parameters', 'Chain Parameters', nc_osc_utils.LIST_BOTH), ('description', 'Description', nc_osc_utils.LIST_LONG_ONLY), ('chain_id', 'Chain ID', nc_osc_utils.LIST_BOTH), ('project_id', 'Project', nc_osc_utils.LIST_LONG_ONLY), ) class CreateSfcPortChain(comm...
pythonpatterns/patterns
p0141.py
Python
unlicense
122
0
impo
rt numpy as np v1 = np.array([1, 2, 3]) v2 = np.array([4, 5, 6]) p = np.cross(v1, v2) print(p) """< [ 1 70 96]
>"""
younglim/hats-ci
robot_automation/src/logs.py
Python
gpl-3.0
3,513
0.011386
import commandRunner as cr import subprocess import glob, os, platform, shutil, adb from pathlib import Path def combine_browsers_logs(udid): cmd = 'rebot -N Combined --outputdir browserlogs/ ' for idx, device in enumerate(udid): #Get all the output.xml files for the devices if platform.s...
= "Compress-Archive browserlogs browserlogs-$(date +%Y-%m-%d-%H%M).zip" subprocess.cal
l(["powershell.exe", cmd]) elif platform.system() == "Linux" or platform.system() == "Darwin": cmd = "zip -vr browserlogs-$(date +%Y-%m-%d-%H%M).zip" + " browserlogs/" cr.run_command(cmd) def delete_previous_logs(): cmd = 'rm -rf logs/*' cr.run_command(cmd) def delete_previous_logs_...
lvh/txyoga
txyoga/test/test_serialization.py
Python
isc
2,471
0.002428
# -*- coding: utf-8 -*- # Copyright (c), 2011, the txyoga authors. See the LICENSE file for details. """ Tests for basic class serialization and deserialization. """ from twisted.trial.unittest import TestCase from txyoga.base import Collection, Element from txyoga.serializers import jsonEncode class Screwdriver(Ele...
""" exposedAttributes = "head", "size" identifyingAttribute = "size" def __init__(self, head, size): self.head = head self.size = size class Toolbox(Collection): """ A toolbox. """ defaultElementClass = Screwdriver class SerializationTest(TestCase): """ Test...
= Screwdriver("philips", "m3") state = screwdriver.toState() self.assertEqual(state, {"head": "philips", "size": "m3"}) def test_partial(self): """ Test partial serialization of a screwdriver. """ screwdriver = Screwdriver("philips", "m3") state = screwdrive...
ppwwyyxx/tensorflow
tensorflow/python/eager/imperative_grad.py
Python
apache-2.0
3,071
0.001303
# Copyright 2017 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...
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. # ============================================================================== """Code for backpropagation using the tape utilities.""" from __future__ import absolute_import from __future__ import division from __future__ import print...
TornikeNatsvlishvili/skivri.ge
backend/backend/app.py
Python
mit
1,523
0
from flask import Flask, jsonify from backend import commands from backend.settings import ProdConfig from backend.api import api from backend.extensions import mongo, cors def create_app(config_object=ProdConfig): app = Flask(__name__) app.config.from_object(config_object) register_extensions(app) re...
'db': db, 'User': user.models.User} app.shell_context_processor(shell_context) def register_commands(ap
p): """Register Click commands.""" app.cli.add_command(commands.test) app.cli.add_command(commands.lint) app.cli.add_command(commands.clean) app.cli.add_command(commands.urls)
LeoCBS/scrapy-proxy
src/spiders/xroxy.py
Python
apache-2.0
476
0.012605
# -*- coding: utf-8 -*- import scrapy from src.items import SrcIte
m class XroxySpider(scrapy.Spider): name = "xroxy" allowed_domains = ["xrory.com"] start_urls = ( 'http://www.xroxy.com/proxylist.htm', ) def parse(self, response): table = response.xpath('/html/body/div[1]/div[2]/table[1]') self.log(table) fo
r tr in table: item = SrcItem() item['ip'] = tr.xpath('//table/tr/td[2]/a/text()').extract() yield item
gratefulfrog/lib
python/pymol/pymol_path/test/trim.py
Python
gpl-2.0
319
0.062696
import sys import string f = sys.stdin g = sys.stdout echo = 0 while 1: l = f.readline()
if not l: break ll=string.strip(l) if ll=='BEGIN-LOG': echo = 1 elif ll=='END-LOG': echo = 0 e
lif echo: l=string.replace(l,"-0.000"," 0.000") # squish annoying negative zeros g.write(l)
KarolBedkowski/alldb
alldb/configuration.py
Python
gpl-2.0
436
0
#!/usr/bin/python # -*- coding: utf-8 -*- ''' Standard paths ''' __author__ = "Karol Będkowski" __copyright__ = "Copyright (c) Karol Będkowski, 2009-2010" __version__ = "2010-05-03" LINUX_LOCALES_DIR = '/usr/
share/locale/' LINUX_INSTALL_DIR = '/usr/share/alldb/' LINUX_DOC_DIR = '/usr/share/doc/alldb/' LINUX_DATA_DIR = '/usr/share/doc/alldb/data/' LOCALES_DIR = './locale/' DATA_DIR = './da
ta/' # vim: encoding=utf8: ff=unix:
Cunqi/leetcode
PLeetcode/com/cx363/Permutations.py
Python
gpl-2.0
1,148
0.006969
''' Created on O
ct 7, 2014 @author: xiaocunqi ''' class Solution: # @param num, a list of integer # @return a list of lists of integers def permute
(self, num): if(len(num) == 1): return [num] result = [] self.perm(result, num, 0, len(num)) return result # @param a, a number waiting for swiping # @param b, a number waiting for swiping def swip(self, current, a, b): tmp = current[a] ...
Hakuba/youtube-dl
youtube_dl/extractor/tumblr.py
Python
unlicense
4,840
0.002274
# -*- coding: utf-8 -*- from _
_future__ import unicode_literals import re from .common import InfoExtractor from ..utils import int_or_none class TumblrIE(InfoExtractor): _VALID_URL = r'http://(?P<blog_name>.*?)\.tumblr\.com/(?:post|video)/(?P<id>[0-9]+)(?:$|[/?#])' _TEST
S = [{ 'url': 'http://tatianamaslanydaily.tumblr.com/post/54196191430/orphan-black-dvd-extra-behind-the-scenes', 'md5': '479bb068e5b16462f5176a6828829767', 'info_dict': { 'id': '54196191430', 'ext': 'mp4', 'title': 'tatiana maslany news, Orphan Black || DVD ex...
fengbeihong/tempest_automate_ironic
tempest/api/volume/test_volumes_get.py
Python
apache-2.0
6,313
0
# Copyright 2012 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 requ...
the # License for the specific language governing permissions and limitations # under the License. from tempest_lib.common.utils import data_utils from testtools import matchers from tempest.api.volume import base from tempest import
config from tempest import test CONF = config.CONF class VolumesV2GetTest(base.BaseVolumeTest): @classmethod def setup_clients(cls): super(VolumesV2GetTest, cls).setup_clients() cls.client = cls.volumes_client @classmethod def resource_setup(cls): super(VolumesV2GetTest, cls...
nohona/cron-crm
usr/local/certbot/certbot/display/dummy_readline.py
Python
gpl-3.0
570
0
"""A dummy module with no effect for use on systems without readline.""" def get_completer(): ""
"An empty implementation of readline.get_completer.""" def get_completer_delims(): """An empty implementatio
n of readline.get_completer_delims.""" def parse_and_bind(unused_command): """An empty implementation of readline.parse_and_bind.""" def set_completer(unused_function=None): """An empty implementation of readline.set_completer.""" def set_completer_delims(unused_delims): """An empty implementation of ...
tualatrix/ubuntu-tweak-old
src/common/config.py
Python
gpl-2.0
6,864
0.004662
#!/usr/bin/python # Ubuntu Tweak - PyGTK based desktop configure tool # # Copyright (C) 2007-2008 TualatriX <tualatrix@gmail.com> # # Ubuntu Tweak 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 versio...
('()').split(',') else: return (0, 0) def get_str
ing(self, key): if not key.startswith("/"): key = GconfKeys.keys[key] string = self.get_value(key) if string: return string else: return '0' def get_client(self): return self.__client class TweakSettings: '''Manage the settings of ...
Kriechi/mitmproxy
mitmproxy/tools/console/layoutwidget.py
Python
mit
1,022
0.001957
class LayoutWidget: """ All top-level layout widgets and all widgets that may be set in an overlay must comply with this API. """ # Title is only required for windows, not overlay components title = "" keyctx = "" def key_responder(self): """ Returns the obje...
ged(self): """ The view focus has changed. Layout object
s should implement the API rather than directly subscribing to events. """ pass def view_changed(self): """ The view list has changed. """ pass def layout_popping(self): """ We are just about to pop a window off the stack, or ...
CRImier/pyLCI
output/drivers/pfcad.py
Python
apache-2.0
2,181
0.005961
import pifacecad from time import sleep class Screen(): """ A driver for PiFace Control and Display Raspberry Pi shields. It has a simple 16x2 LCD on it, controlled by a MCP23S17 over SPI. Doesn't yet conform to HD44780 library specs, many functions are not transferred from the ``pifacecad`` library. TOD...
``rows`` (default=2): rows of the connected display * ``cols`` (default=16): columns of the connected display """ self.rows = rows self.cols = cols self.lcd = pifacecad.PiFaceCAD().lcd self.backlight = True
self.busy_flag = False def enable_backlight(self): """Enables backlight. Doesn't do it instantly, you'll have to wait until data is sent to the display.""" self.backlight = True def disable_backlight(self): """Disables backlight.""" self.backlight = False self.l...
squisher/stella
ipythoninit.py
Python
apache-2.0
261
0
from dis import dis import stella import llvmlite.ir as ll import llvmlite.binding as llvm import pdb from pdb import pm from wip import * # Now logg
ing is turned off by
default, but this is for debugging: stella.logLevel('DEBUG') # pylama:ignore=W0611,W0401
dmerejkowsky/qibuild
python/qidoc/test/projects/world/source/conf.py
Python
bsd-3-clause
214
0.014019
## Copyright (c) 2012-2015
Aldebaran Robotics. All rights reserved. ## Use of this source code
is governed by a BSD-style license that can be ## found in the COPYING file. project = 'prebuild' master_doc = 'index'
OCA/sale-workflow
sale_pricelist_from_commitment_date/models/sale_order.py
Python
agpl-3.0
1,711
0.000584
# Copyright 2021 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, models class SaleOrder(models.Model): _inherit = "sale.order" def _apply_pricelist_from_commitment_date(self): self.ensure_one() for line in self.order_line: # Pr...
id ): sale._apply_pricelist_from_commitment_date() return True
def update_prices(self): self.ensure_one() return super( SaleOrder, self.with_context(force_pricelist_date=self.commitment_date), ).update_prices()
Gebesa-Dev/Addons-gebesa
mrp_product_color/__openerp__.py
Python
agpl-3.0
716
0
# -*- coding: utf-8 -*- # © <YEAR(S)> <AUTHOR(S)> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "MRP product color", "summary": "MRP product color", "version": "9.0.1.0.0", "category": "Product", "website": "https://odoo-community.org/", "author": "<Samuel Barron...
"application": False, "installable": True, "external_dependencies": { "python": [], "bin": [], }, "depends
": [ "base", "product", "stock" ], "data": [ "views/mrp_product_color.xml", "security/ir.model.access.csv", ], "demo": [ ], "qweb": [ ] }
vedang/Rope
ropetest/pycoretest.py
Python
gpl-2.0
50,538
0.000633
import sys import unittest from rope.base import exceptions from rope.base.pycore import _TextChangeDetector from rope.base.pyobjects import get_base_type, AbstractFunction from ropetest import testutils class PyCoreTest(unittest.TestCase): def setUp(self): super(PyCoreTest, self).setUp() self.p...
' def __init__
(self):\n self.var = 20\n') mod_element = self.pycore.get_module('mod') sample_class = mod_element['C'].get_object() var = sample_class['var'] def test_class_attributes_set_in_init_overwriting_a_defined(self): mod = testutils.create_module(self.project, 'mod') code = ...
Bakterija/log_fruit
src/app_modules/widgets/find_bar.py
Python
unlicense
724
0
from kivy.uix.stacklayout import StackLayout from kivy.uix.behaviors import Dr
agBehavior from kivy.uix.modalview import ModalView from kivy.core.window import Window from kivy.uix.button import Button from kivy.uix.label import Label from kivy.lang import Builder from kivy.clock import Clock from kivy.uix.stencilvi
ew import StencilView Builder.load_string(''' <FindBar>: canvas.before: Color: rgba: col_dgrey Rectangle: size: self.size pos: self.pos TextInput: size_hint: 1, 0.5 TextInput: size_hint: 1, 0.5 ''') class FindBar(StackLayout, StencilVi...
jinnykoo/christmas
src/oscar/test/testcases.py
Python
bsd-3-clause
3,477
0
from django.utils.six.moves import http_client from django.core.urlresolvers import reverse from django.contrib.auth.models import Permission from django_webtest import WebTest from purl import URL from oscar.core.compat import get_user_model User = get_user_model() def add_permissions(user, permissions): """...
nse) location = response['Location'].replace('http://testserver', '') self.assertEqual(location, reverse(name, kwargs=kwargs)) def assertIsOk(self, response): self.assertEqual(http_client.OK, response.status_code) def assertContext(self, response): self.assertTrue(response.cont...
self.assertTrue(key in response.context, "Context should contain a variable '%s'" % key)
egnyte/gitlabform
tests/unit/test_non_empty_configs_provider.py
Python
mit
846
0.003546
import pytest from gitlabform import EXIT_INVALID_INPUT from gitlabform.configuration.projects_and_groups import ConfigurationProjectsAndGroups from gitlabform.filter import NonEmptyConfigsProvider def test_error_on_missing_key(): config_yaml = """ --- # no key at all """ with pytest.raises(Syst...
figuration, None, None) assert e.value.code == EXIT_INVALID_INPUT def test_error_on_empty_key(): config_yaml = """ --- projects_and_groups: """ with pytest.raises(SystemExit) as e: configuration = ConfigurationProjectsAndGroups(config_string=config_yaml)
NonEmptyConfigsProvider(configuration, None, None) assert e.value.code == EXIT_INVALID_INPUT
antoviaque/edx-platform
common/test/acceptance/pages/lms/index.py
Python
agpl-3.0
1,731
0.001155
# -*- coding: utf-8 -*- """ LMS index (home) page. """ from bok_choy.page_object import PageObject from
. import BASE_URL BANNER_SELECTOR = 'section.home header div.outer-wrapper div.title hgroup h1' INTRO_VIDEO_SELECTOR = 'div.play-intro' VIDEO_MODAL_SELECTOR = 'section#video-modal.modal.home-page-video-modal.video-modal' class IndexPage(PageObject): """ LMS index (home) page, the default
landing page for Open edX users when they are not logged in """ def __init__(self, browser): """Initialize the page. Arguments: browser (Browser): The browser instance. """ super(IndexPage, self).__init__(browser) url = "{base}/".format(base=BASE_URL) def ...
glwagner/py2Periodic
tests/twoLayerQG/testTwoLayerQG.py
Python
mit
1,366
0.025622
import time, sys import numpy as np import matplotlib.pyplot as plt sys.path.append('../../') from py2Periodic.physics import twoLayerQG from numpy impor
t pi params = { 'f0' : 1.0e-4, 'Lx' : 1.0e6, 'beta' : 1.5e-11, 'defRadius' : 1.5e4, 'H1' : 500.0, 'H2' : 2000.0, 'U1' : 2.5e-2, 'U2'
: 0.0, 'bottomDrag' : 1.0e-7, 'nx' : 128, 'dt' : 1.0e3, 'visc' : 2.0e8, 'viscOrder' : 4.0, 'timeStepper': 'AB3', 'nThreads' : 4, 'useFilter' : False, } # Create the two-layer model qg = twoLayerQG.model(**params) qg.describe_model() # Initial condit...
manoranjanp/django-twitter-api
twitter_api/admin.py
Python
bsd-3-clause
516
0
# -*- coding: utf-8 -*- from django.contrib import admin from models import Status, User class TwitterModelAdmin(admin.ModelAdmin): def get_readonly_fields(self, request, obj=None)
: if obj: return [field.name for field in obj._meta.fields] return [] class StatusAdmin(TwitterModelAdmin): list_display = ['id', 'author', 'text'] class UserAdmin(TwitterModelAdmin): exclude = ('followers',) admin.site.r
egister(Status, StatusAdmin) admin.site.register(User, UserAdmin)
openego/oeplatform
modelview/rdf/widget.py
Python
agpl-3.0
5,599
0.00125
from django.forms.widgets import TextInput, Widget, MultiWidget from django_better_admin_arrayfield.forms.widgets import DynamicArrayWidget from django import forms class FactoryWidget(MultiWidget): template_name = "modelview/widgets/multiwidget.html" def __init__(self, factory): self.factory = facto...
e(self, prefix): d = self.factory.build_template_structure(prefix) fac = self.factory()
d[prefix] = self.render("", fac, attrs={"id": "{prefix}"}) return d def get_context(self, name, value, attrs): context = super(MultiWidget, self).get_context(name, value, attrs) if self.is_localized: for widget in self.widgets: widget.is_localized = self.is_l...
antong/webut
examples/navi/demoplugins/foo.py
Python
mit
1,433
0.004187
from zope.interface import implements, classProvides from twisted.internet import address from nevow import inevow, rend, loaders, util, url from webut.navi import inavi from demoplugins import idemo class FooPage(rend.Page): implements(inavi.INavigationElement) t
itle = 'Foo!' docFactory = loaders.xmlfile(util.resource_filename('demoplugins', 'foo.html')) de
f render_navigation(self, ctx, data): return ctx.tag.clear()[idemo.IDemoNavigation(ctx)] def render_visible(self, ctx, data): u = url.URL.fromContext(ctx) netloc = u.netloc.split(':', 1) netloc[0] = '127.0.0.1' u.netloc = ':'.join(netloc) return u def render_inv...
hoangt/PoC
py/Base/Exceptions.py
Python
apache-2.0
2,252
0.022202
# EMACS settings: -*- tab-width: 2; indent-tabs-mode: t -*- # vim: tabstop=2:shiftwidth=2:noexpandtab # kate: tab-width 2; replace-tabs off; indent-width 2; # # ============================================================================== # Authors: Patrick Lehmann # # Python Class: TODO # # Description: # -...
red by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express o
r implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # entry point if __name__ != "__main__": # place library initialization code here pass else: from lib.Functions import Ex...
dqi2018/python-structure
setup.py
Python
apache-2.0
1,121
0
# -*- coding: utf-8 -*- from os.path import join, dirname import sys from setuptools import setup, find_packages VERSION = (0, 1, 0) __version__ = VERSION __versionstr__ = '.'.join(map(str, VERSION)) README_FILE = 'README.md' LICENSE_FILE = 'LICENSE' f = open(join(dirname(__file__), README_FILE)) long_description =...
s = [ 'pytest>=3.1.0', ] tests_require = [ 'nose', 'coverage', ] # use external unittest for 2.6 if sys.version_info[:2] == (2, 6): install_requires.append('unittest2') setup( name='pystructuresample', version='0.1.0', description='Python Project Structure Sample', long_description=lon...
se, packages=find_packages( where='.', exclude=('tests', 'docs') ), install_requires=install_requires, test_suite='tests.test_sample', tests_require=tests_require )
plotly/python-api
packages/python/plotly/plotly/matplotlylib/mplexporter/tests/__init__.py
Python
mit
72
0.013889
impo
rt matplotlib matplotlib.use('Agg') import matplotlib.py
plot as plt
pombredanne/invenio
modules/miscutil/lib/dateutils_tests.py
Python
gpl-2.0
8,759
0.003197
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either ve...
kday abbreviation""" limit = 'Tue'
day = datetime.date.today() now = datetime.time() while day.weekday() != calendar.TUESDAY: day -= datetime.timedelta(1) present_from = datetime.datetime.combine(day, now.replace(hour=0)) present_to = present_from + datetime.timedelta(days=1) future_from = present_fro...
skosukhin/spack
lib/spack/spack/cmd/blame.py
Python
lgpl-2.1
4,597
0
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
tartswith(spack.prefix): blame_file = path if not blame_file: pkg = spack.repo.get(args.package_name) blame_file = pkg.module.__file__.rstrip('c') # .pyc -> .py # get git blame for the package with working_dir(spack.prefix): if args.view == 'git': git('blam...
'--line-porcelain', blame_file, output=str) lines = output.split('\n') # Histogram authors counts = {} emails = {} last_mod = {} total_lines = 0 for line in lines: match = re.match(r'^author (.*)', line) if match: author = match.group(1) match =...
icio/github3.py
tests/unit/test_github.py
Python
bsd-3-clause
31,906
0
import pytest from github3 import AuthenticationFailed, GitHubError from github3.github import GitHub from .helper import UnitHelper, UnitIteratorHelper def url_for(path=''): """Simple function to generate URLs with the base GitHub URL.""" return 'https://api.github.com/' + path.strip('/') class TestGitHu...
) def test_is_starred_requires_an_owner(self): """Test that GitHub#is_starred requires an owner.""" self.instance.is_starred(None, 'repo') assert self.session.get.called is False def test_is_starred_req
uires_a_repo(self): """Test that GitHub#is_starred requires an repo.""" self.instance.is_starred('username', None) assert self.session.get.called is False def test_issue(self): """Test the request to retrieve a single issue.""" self.instance.issue('owner', 'repo', 1) ...
dmwyatt/disney.api
join.py
Python
mit
4,714
0.040305
import logging from typing import Sequence, Any, MutableMapping import requests logger = logging.getLogger(__name__) JOIN_URL = "https://joinjoaomgcd.appspot.com/_ah/api/messaging/v1/sendPush" class Join: VALID_GROUPS = ["group.all", "group.android", "group.chrome", ...
one self.title = None self.icon = None self.smallicon = None self.url = None self.clipboard = None self.file = None self.smsnumber = None self.smstext = None self.wallpaper = None self.find = None class PlainTextualNotification: def __init__(self, text: str, title: str=None, icon: str=None, small...
tle self.icon = icon self.smallicon = icon def get_params(self): params = {'text': self.text} if self.title: params['title'] = self.title if self.icon: params['icon'] = self.icon if self.smallicon: params['smallicon'] = self.smallicon return params
mabuchilab/NiceLib
tests/test_if.py
Python
gpl-3.0
3,236
0
import pytest from nicelib.process import Parser @pytest.mark.parametrize("num,result", [ (1, "20"), (2, "40"), (3, "60"), (0, "60"), ]) def test_if(num, result): parser = Parser(""" #define x {} #if x == 1 #define y 20 #elif x == 2 #define y 40 ...
lt): parser = Parser(""" #define x {} #define y 5 #if 0 #if x == 1 #define y 20 #elif x == 2 #define y 40 #else #define y 60 #endif #endif """.format(num)) parser
.parse() print(parser.get_any_macro('y').body_str()) assert parser.get_any_macro('y').body_str() == result @pytest.mark.parametrize("num,result", [ (1, "20"), (2, "40"), (3, "60"), (0, "60"), ]) def test_nested_if2(num, result): parser = Parser(""" #define x {} #define y 0 ...
wearespindle/flindt
backend/flindt/role/migrations/0006_auto_20160908_1705.py
Python
agpl-3.0
657
0.001522
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-09-08 15:05 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('role', '0005_auto_20160906_1029'), ] operations = [ ...
tions.AlterField( model_name='role', name='purpose', field=models.TextField(blank=True), ), migrations.AlterField( model_name='role', name='users', field=mo
dels.ManyToManyField(blank=True, to=settings.AUTH_USER_MODEL), ), ]
apierleoni/MyBioDb
languages/it.py
Python
bsd-3-clause
9,410
0.026705
# coding: utf-8 { '!=': '!=', '!langcode!': 'it', '!langname!': 'Italiano', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" è un\'espressione opzionale come "campo1=\'nuovo valore\'". Non si può fare "update" o "delete" dei risultati di un JO...
atch": "Password fields don't match", 'please input your password again': 'please input your password again', 'Plugins': 'Plugins', 'Powered by': 'Powered by', 'Preface': 'Preface', 'previous 100 rows': '100 righe precedenti', 'Profile': 'Profile', 'Python': 'Python', 'Query:': 'Richiesta (query):', 'Quick Examples'
: 'Quick Examples', 'RAM': 'RAM', 'RAM Cache Keys': 'RAM Cache Keys', 'Ram Cleared': 'Ram Cleared', 'Recipes': 'Recipes', 'Record': 'Record', 'record does not exist': 'il record non esiste', 'Record ID': 'Record ID', 'Record id': 'Record id', 'Register': 'Register', 'register': 'registrazione', 'Registration identifier...
chinmayhegde/retinopathy-detection
retinopathy/helpers.py
Python
mit
2,286
0.000437
import csv import os import random import svm_classifier def get_classifier_filename(classifier_name): dir_name = os.path.dirname(os.path.realpath(__file__)) return os.path.join(dir_name, 'classifiers', classifier_name + '.pkl') def get_image_split(csv_filename, image_folder): # Get image names and cla...
.extend(class_image_names) for image_name in class_image_names: image_classes[image_name] = image_class
random.shuffle(image_names) train_ratio = 0.8 train_num = int(train_ratio * len(image_names)) train_filenames = image_names[:train_num] test_filenames = image_names[train_num:] return train_filenames, test_filenames, image_classes def get_classifier(classifier_name): if classifier_name == 's...
JaroCamphuijsen/SVVR
Assignment 2/Assignment2.py
Python
gpl-2.0
3,968
0.010585
# -*- coding: utf-8 -*- """ Created on Wed Sep 16 14:27:37 2015 @author: Jaromir Camphuijsen (6042473) and Eva van Weel(10244743) """ #This code is based on code found at: http://www.vtk.org/gitweb?p=VTK.git; #a=blob;f
=Examples/Medical/Python/Medical3.py import Tkinter import vtk from vtk.tk.vtkTkRenderWidget import vtkTkRenderWidget # Create the renderer and the GUI root = Tkinter.Tk() aRenderer = vtk.vtkRenderer() aRenderer.TexturedBackgroundOn() renderWidget = vtkTkRenderWidget(root,width=800,height=600) renderWidget.pack(exp
and='true',fill='both') renWin = renderWidget.GetRenderWindow() renWin.AddRenderer(aRenderer) aRenderer.SetBackground(1, 1, 1) renWin.SetSize(600, 480) # Read the 2D images (CT scan slices). v16 = vtk.vtkVolume16Reader() v16.SetDataDimensions(256, 256) v16.SetDataByteOrderToLittleEndian() v16.SetFilePrefix(".\Data\sl...
morepath/more.jinja2
more/jinja2/tests/test_jinja2.py
Python
bsd-3-clause
1,589
0
from webtest import TestApp as Client from .fixtures import ( template, template_inheritance, override_template, override_template_inheritance, ) def test_template(): c = Client(template.App()) response = c.get("/persons/world") assert ( response.body == b"""\ <html> <body...
</html>""" ) c = Client(override_template.SubApp()) response = c.get("/persons/world") assert ( response.body == b"""\ <html> <body> <p>Hi world!</p> </body> </html>""" ) def test_template_inheritance(): c = Client(template_inheritance.App()) response = c.get("/persons/w...
"content"> <p>Hello world!</p> </div> </body> </html>""" ) def test_override_template_inheritance(): c = Client(override_template_inheritance.App()) response = c.get("/persons/world") assert ( response.body == b"""\ <html> <head> </head> <body> <div id="content"> <p>Hello world!</p> <...
eayunstack/ceilometer
ceilometer/tests/unit/hardware/pollsters/test_generic.py
Python
apache-2.0
6,766
0
# # Copyright 2015 Intel Corp. # # 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.ap
ache.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 KIN
D, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import mock import six import yaml from oslo_config import fixture as fixture_config from oslo_utils import fileutils from oslotest import mockpatch from ceilometer.hardware.inspector ...
detiber/lib_openshift
lib_openshift/models/v1_container_state_running.py
Python
apache-2.0
3,435
0.001164
# coding: utf-8 """ OpenAPI spec version: Generated by: https://github.com/swagger-api/swagger-codegen.git 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 ...
attr] = v
alue.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr...
Rapptz/discord.py
discord/mixins.py
Python
mit
1,594
0
""" The MIT License (MIT) Copyright (c) 2015-present Rapptz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merg...
al portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITH
OUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,...
awblocker/glm
lib/glm/glm.py
Python
bsd-3-clause
11,500
0.008522
import warnings import numpy as np from scipy import linalg import links import families # Function for fast WLS def wls(X, y, w, method='cholesky'): """ Computes WLS regression of y on X with weights w. Can use Cholesky or QR decomposition. The 'cholesky' method is extremely fast as it dire...
WLS z = eta + (y-mu)/family.link.deriv(eta) - offset # Run WLS with desired method fit = wls(X=X, y=z, w=weights_ls, method=ls_method) # Compute new values of eta and mu eta = (z - fit['resid']) + offset mu = family.link.inv(eta) # Upd...
ce dev = family.deviance(y=y, mu=mu, w=w) # Check for convergence criterion = np.abs(dev - dev_last) / (np.abs(dev_last) + 0.1) if (criterion < tol): converged = True dev_last = dev iteration += 1 # Start building return ...
Conedy/Conedy
testing/dynNetwork/evolve3.py
Python
gpl-2.0
241
0.020747
import conedy as co N
= co.network() newNodeNumber = N.addNode( co.roessler() ) N.observeTime("output/evolve3.py.series") N.observe(newNodeNumber, "output/
evolve3.py.series") N.evolve(0.0,3.0) N.evolve(5.0,13.0) N.evolve (-0.1, 0.0)
jylaxp/django
django/utils/log.py
Python
bsd-3-clause
5,244
0.001335
from __future__ import unicode_literals import logging import logging.config # needed when logging_config doesn't start with logging.config import sys import warnings from copy import copy from django.conf import settings from django.core import mail from django.core.mail import get_connection from django.utils.depr...
no_exc_record.exc_info = None no_exc_record.exc_text = None if record.exc_info: exc_info = record.exc_info else: exc_info = (None, record.getMessage(), None) reporter = ExceptionReporter(request, is_email=True, *exc_info) message = "%s\n\n%s" % (self....
rter.get_traceback_text()) html_message = reporter.get_traceback_html() if self.include_html else None self.send_mail(subject, message, fail_silently=True, html_message=html_message) def send_mail(self, subject, message, *args, **kwargs): mail.mail_admins(subject, message, *args, connection...
openstack/nomad
cyborg/accelerator/drivers/spdk/nvmf/nvmf.py
Python
apache-2.0
4,000
0
""" SPDK NVMFDRIVER module implementation. """ from cyborg.accelerator.drivers.spdk.util.pyspdk.nvmf_client import NvmfTgt from oslo_log import log as logging from cyborg.accelerator.common import exception from cyborg.accelerator.drivers.spdk.util import common_fun from cyborg.accelerator.drivers.spdk.spdk import SPD...
lerators(self): accelerators = [] for accelerator_i in range(len(self.servers)): accelerator = self.servers[accelerator_i] py_tmp = PySPDK(accelerator) if py_tmp.is_alive(): accelerators.append(self.get_one_acc
elerator()) return accelerators def update(self, driver_type, **kwargs): pass def attach_instance(self, instance_id): pass def detach_instance(self, instance_id): pass def delete_subsystem(self, nqn): """Delete a nvmf subsystem :param nqn: Target nqn(...
overdrive3000/skytools
tests/quoting/regtest.py
Python
isc
2,848
0.00316
#! /usr/bin/env python import sys, time import skytools.psycopgwrapper import skytools._cquoting, skytools._pyquoting from decimal import Decimal # create a DictCursor row class fake_cursor: index = {'id': 0, 'data': 1} description = ['x', 'x'] dbrow = skytools.psycopgwrapper._CompatRow(fake_cursor()) dbrow[0...
=qwe"], [{'a': '\000%&'}, "a=%00%25%26"], [dbrow, 'data=value&id=123'], [{'a': Decimal("1")}, "a=1"], ] regtest("db_urlencode/c", skytools._cquoting.db_urlencode, t_urlenc) regtest("db_urlencode/py", skytools._pyquoting.db_urlencode, t_urlenc) t_urldec = [ ["", {}], ["a=b&c", {'a': 'b', 'c': None}]...
decode, t_urldec) regtest("db_urldecode/py", skytools._pyquoting.db_urldecode, t_urldec) t_unesc = [ ["", ""], ["\\N", "N"], ["abc", "abc"], [u"abc", "abc"], [r"\0\000\001\01\1", "\0\000\001\001\001"], [r"a\001b\tc\r\n", "a\001b\tc\r\n"], ] regtest("unescape/c", skytools._cquoting.unescape, t_u...
TwilioDevEd/api-snippets
twiml/voice/connect/virtualagent-2/virtualagent-2.6.x.py
Python
mit
394
0.002538
from twilio.twiml.voice_response import Connect, VoiceResponse, Say, VirtualAgent response = VoiceResponse() response.say('Hello! You will be now be conn
ected to a virtual agent.') connect = Connect(action='https://myactionurl.com/virtualagent_ended') connect.virtual_agent( connector_name='project', status_callback='https://mycallbackurl.com' ) response.append(connect) print(res
ponse)
google-research/google-research
genomics_ood/images_ood/utils.py
Python
apache-2.0
6,511
0.011826
# coding=utf-8 # Copyright 2022 The Google Research 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
t.v1.image.rgb_to_grayscale(x['image']) x['image'] = tf.tile(x['image'], [1, 1, 3]) x['image'] = tf.cast(x['image'], tf.float3
2) return x def compute_auc(neg, pos, pos_label=1): ys = np.concatenate((np.zeros(len(neg)), np.ones(len(pos))), axis=0) neg = np.array(neg)[np.logical_not(np.isnan(neg))] pos = np.array(pos)[np.logical_not(np.isnan(pos))] scores = np.concatenate((neg, pos), axis=0) auc = metrics.roc_auc_score(ys, scores)...
debugger06/MiroX
tv/linux/plat/frontends/widgets/hidemouse.py
Python
gpl-2.0
2,042
0.001959
# Miro - an RSS based video player application # Copyright (C) 2012 # Participatory Culture Foundation # # 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 License, or # (at...
hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to t...
., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the OpenSSL # library. # # You must obey the GNU General Public License in all respects for all of # the code used other than Open...
tlamer/teres
docs/conf.py
Python
lgpl-2.1
8,173
0.00624
# -*- coding: utf-8 -*- # # Teres documentation build configuration file, created by # sphinx-quickstart on Fri Apr 15 09:40:37 2016. # # 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. # # All...
ctory
) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style shee...
matrix-org/sydent
sydent/http/federation_tls_options.py
Python
apache-2.0
4,003
0.0005
# Copyright 2019 New Vector Ltd # # 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 License. import logging from typing import Callable from OpenSSL import SSL from twisted.internet imp...
Azure/azure-sdk-for-python
sdk/keyvault/azure-keyvault-certificates/samples/issuers_async.py
Python
mit
4,030
0.003226
# ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ import os import asyncio from azure.identity.aio import DefaultAzureCredential from azure.keyvault.certificates.aio import CertificateClient from azure.keyvault.certific...
ntacts) for contact in issuer1.admin_contacts: print(contact.first_name) print(contact.last_name) print(contact.email) print(contact.phone) # Now w
e will list all of the certificate issuers for this key vault. To better demonstrate this, we will first create another issuer. await client.create_issuer(issuer_name="issuer2", provider="Test", account_id="keyvaultuser", enabled=True) issuers = client.list_properties_of_issuers() async for issuer in issu...
Aleks31/pychess
testing/bitboard.py
Python
gpl-3.0
1,674
0.01135
import unittest import random import operator from functools
import reduce from pychess.Utils.lutils.bitboard import * class BitboardTestCase(unittest.TestCase): def setUp (self): self.positionSets = [] # Random positions. Ten of each length. Will also include range(64) and # range(0) for i in range(10): for length in range
(64): if length: positions = random.sample(range(64), length) board = reduce(operator.or_, (1<<(63-i) for i in positions)) self.positionSets.append( (positions, board) ) else: self.positionSets.append( ([], 0...
qtile/qtile
test/widgets/test_caps_num_lock_indicator.py
Python
mit
4,137
0.002417
# Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copi...
onfigure(fake_qtile, fakebar) text = widget.poll() assert text == "Caps off Num on" def test_cnli_caps_on(fake_qtile, patched_cnli, fake_window): widget = patched_cnli.CapsNumLockIndicator() # Simulate Caps on MockCapsNumLockIndicator.index = 1 fakebar = FakeBar([widget], window=fake_window...
qtile, fakebar) text = widget.poll() assert text == "Caps on Num on" def test_cnli_error_handling(fake_qtile, patched_cnli, fake_window): widget = patched_cnli.CapsNumLockIndicator() # Simulate a CalledProcessError exception MockCapsNumLockIndicator.is_error = True fakebar = FakeBar([widget...
dbock/bocklab_public
temca2data/SNR/snrscript.py
Python
mit
9,484
0.030894
""" Script for the paper """ import time import numpy as np import snr_of_images import urllib import zlib from io import BytesIO import cv2 import h5py import os import matplotlib.pyplot as plt import json import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning #Following if it gives a...
op_im = h5py.File('aplus.h5','r') temca = crop_im['volumes']['raw'] crop_im = h5py.File('bplus.h5','r
') temca = np.append(temca,crop_im['volumes']['raw'],axis=0) crop_im = h5py.File('cplus.h5','r') temca = np.append(temca,crop_im['volumes']['raw'],axis=0) temca_random = np.random.permutation(len(temca))[:150] temcas = np.zeros(n_comp) count = 0 for i,j in enumerate(temca_random): if temca_skip is True: ...
great-expectations/great_expectations
great_expectations/cli/v012/toolkit.py
Python
apache-2.0
22,960
0.002047
import datetime import os import subprocess import sys import warnings from typing import Optional, Union import click from ruamel.yaml import YAML from ruamel.yaml.compat import StringIO from great_expectations import exceptions as ge_exceptions fr
om great_expectations.checkpoint import Checkpoint, LegacyCheckpoint from great_expectations.cli.v012.cli_messages import SECTION
_SEPARATOR from great_expectations.cli.v012.datasource import get_batch_kwargs from great_expectations.cli.v012.docs import build_docs from great_expectations.cli.v012.upgrade_helpers import GE_UPGRADE_HELPER_VERSION_MAP from great_expectations.cli.v012.util import cli_colorize_string, cli_message from great_expectatio...
bobloy/Fox-Cogs
whatsmyip/whatsmyip.py
Python
agpl-3.0
546
0.001832
import ipgetter from di
scord.ext import commands from cogs.utils import checks class WhatsMyIP: """ Assign roles based on trust rating """ def __init__(self, bot): self.bot = bot @commands.command(pass_context=True) @checks.is_owner() async def whatsmyip(self, ctx: commands.Context): """Print ...
end_message(ctx.message.author, "Your IP address is {}".format(my_ip)) def setup(bot): bot.add_cog(WhatsMyIP(bot))
khughitt/ete
examples/phylogenies/orthology_and_paralogy_prediction.py
Python
gpl-3.0
3,023
0.002646
from ete_dev import PhyloTree # Loads an example tree nw = """ ((Dme_001,Dme_002),(((Cfa_001,Mms_001),((Hsa_001,Ptr_001),Mmu_001)), (Ptr_002,(Hsa_002,Mmu_002)))); """ t = PhyloTree(nw) print t # /-Dme_001 # /--------| # | \-Dme_002 # | # | ...
# | \-Mmu_001 # | # | /-Ptr_002 # \--------| # | /-Hsa_002 # \--------| # \-Mmu_002 # # To obtain all the evolutio...
) human_seq = matches[0] # Obtains its evolutionary events events = human_seq.get_my_evol_events() # Print its orthology and paralogy relationships print "Events detected that involve Hsa_001:" for ev in events: if ev.etype == "S": print ' ORTHOLOGY RELATIONSHIP:', ','.join(ev.in_seqs), "<====>", ','.join...
ilogue/fexpect
ilogue/fexpect/__init__.py
Python
bsd-2-clause
80
0
from ilogue.fexpect
.api import expect,
controlchar, expecting, run, sudo, local
varunkumta/azure-linux-extensions
VMEncryption/main/oscrypto/ubuntu_1604/encryptstates/UnmountOldrootState.py
Python
apache-2.0
5,976
0.004351
#!/usr/bin/env python # # VM Backup extension # # Copyright 2015 Microsoft Corporation # # 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 # # U...
chine should enter unmount_oldroot state") if not super(UnmountOldrootState, self).should_enter(): return False self.context.logger.log("Performing enter checks for unmount_oldroot state") self.command_executor.ExecuteInBash('[ -e "/oldroot" ]', True) if s...
return False return True def enter(self): if not self.should_enter(): return self.context.logger.log("Entering unmount_oldroot state") self.command_executor.Execute('systemctl rescue', True) self.command_executor.Execute('systemctl st...
sdrave/simdb
simdb/db.py
Python
bsd-2-clause
14,333
0.002861
# -*- coding: utf-8 -*- # Copyright (c) 2014, 2015, Stephan Rave # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this #...
raise ValueError('No data has been written to unfinished dataset {}.'.format(self.name)) if PY2: with open(os.path.join(self.path, 'DATA'), 'rb') as f:
self._data = load(f) else: try: with open(os.path.join(self.path, 'DATA'), 'rb') as f: self._data = load(f) except UnicodeDecodeError: # this happens when loading numpy arrays which have been # pickled with Python 2 ...
OpenDrift/opendrift
examples/example_long_selafin.py
Python
gpl-2.0
1,371
0.019694
#!/usr/bin/env python """ Use Telemac (selafin) output ================================== """ from datetime import timedelta, datetime from os import sep from pyproj import Proj from opendrift.readers import reader_telemac_selafin from opendrift.models.oceandrift impo
rt OceanDrift o = OceanDrift(loglevel=0) filename='{}Telemac_3D{}r3d_tide_open_drift.slf'.format(o.test_data_folder(),sep) #Lambert North proj="+proj=lcc +lat_1=49.50000000000001 +lat_0=49.50000000000001 +lon_0=0 \ +k_0=0.999877341 +x_0=600000 +y_0=200000 +a=6378249.2 +b=6356515 \ +units=m +no_defs" start_t...
art_time) o.add_reader(selafin) o.set_config('general:coastline_action', 'previous') # start_time = selafin.start_time generally wrong time_step = timedelta(seconds=selafin.slf.tags["times"][1]) length=timedelta(seconds=selafin.slf.tags["times"][-1]) num_steps = len(selafin.slf.tags["times"]) # center seeds in the midd...