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
slashdd/sos
sos/cleaner/mappings/username_map.py
Python
gpl-2.0
1,265
0
# Copyright 2020 Red Hat, Inc. Jake Hunsaker <jhunsake@redhat.com> # This file is part of the sos project: https://github.com/sosreport/sos # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and c
onditions of # version 2 of the GNU General Public License. # # See the LICENSE file in the source distribution for further information. from sos.cleaner.mappings import SoSMap class SoSUsernameMap(SoSMap): """Mapping to store usernames ma
tched from ``lastlog`` output. Usernames are obfuscated as ``obfuscateduserX`` where ``X`` is a counter that gets incremented for every new username found. Note that this specifically obfuscates user_names_ and not UIDs. """ name_count = 0 def load_names_from_options(self, opt_names): ...
LLNL/spack
var/spack/repos/builtin/packages/py-ilmbase/package.py
Python
lgpl-2.1
1,026
0.004873
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyIlmbase(AutotoolsPackage): """The PyIlmBase libraries provides python bindings for the I...
ies.""" homepage = "https://github.com/AcademySof
twareFoundation/openexr/tree/v2.3.0/PyIlmBase" url = "https://github.com/AcademySoftwareFoundation/openexr/releases/download/v2.3.0/pyilmbase-2.3.0.tar.gz" version('2.3.0', sha256='9c898bb16e7bc916c82bebdf32c343c0f2878fc3eacbafa49937e78f2079a425') depends_on('ilmbase') depends_on('boost+python') ...
ponyorm/pony
pony/orm/tests/test_prop_sum_orderby.py
Python
apache-2.0
5,191
0.000385
from
__future__ import absolute_import, print_function, division import unittest from pony.orm.core import * from pony.orm.tests.testutils import * from pony.orm.tests import setup_database, teardown_database db = Database() db = Database('sqlite', ':memory:') class Product(db.Entity): id = PrimaryKey(int) nam...
ired(str) comments = Set('Comment') @property def sum_01(self): return coalesce(select(c.points for c in self.comments).sum(), 0) @property def sum_02(self): return coalesce(select(c.points for c in self.comments).sum(), 0.0) @property def sum_03(self): return coal...
jbasko/pytest-random-order
tests/test_cli.py
Python
mit
503
0.001988
def test_help_message(testdir): result = testdir.runpytest( '--help', ) result.stdout.fnmatch_lines([
'pytest-random-order options:', '*--random-order-bucket={global,package,module,class,parent,grandparent,none}*', '*--random-order-seed=*', ]) def test_markers_message(testdir): result = testdir.runpytest( '--markers', ) result.stdout.fnmatch_lines(
[ '*@pytest.mark.random_order(disabled=True): disable reordering*', ])
gfxprim/gfxprim
tests/pylib/test_gfx.py
Python
lgpl-2.1
3,030
0.032013
"core.Pixmap tests" from unittest import SkipTest from testutils import * from gfxprim.core import Pixmap from gfxprim import gfx, core def test_gfx_submodule_loads(): "gfx is present in a Pixmap" c = Pixmap(1, 1, core.C.PIXEL_RGB888) assert c.gfx def test_gfx_submodule_has_C(): "gfx contains C" c = Pix...
nd(13, 12, core.C.PIXEL_RGB888, seed=42) c2 = PixmapRand(13, 12, core.C.PIXEL_RGB888, seed=42) assert c1 == c0 c1.gfx.polygon([1,2,0,4,7,9,5,4,3,2], 43) c2.gfx.polygon([(1,2),(0,4),(7,9),(5,4),(3,2)], 43) assert c1 == c2 assert c1 != c0 def test_FillPolygon(): "FillPolygon() works" c0 = PixmapRand(13, ...
assert c1 == c0 c1.gfx.fill_polygon([1,2,0,4,7,9,5,4,3,2], 0) c2.gfx.fill_polygon([(1,2),(0,4),(7,9),(5,4),(3,2)], 0) assert c1 == c2 assert c1 != c0
pudo/aleph
aleph/migrate/versions/2979a1322381_cleanup.py
Python
mit
712
0.001404
"""Clean up notifications schema, some other parts. Revision ID: 2979a1322381 Revises: 2b478162b2b7 Create Date: 2020-03-03 07:32:54.113550 """ from alembic import op # revision identifiers, used by Alembic. revision = "2979a1322381" down_revision = "2b478162b2b7" def upgrade(): op.drop_index("ix_notification_...
op.drop_table("notification") op.drop_column("diagram", "data") op.drop_constraint("document_parent_id_fkey", "document", type_="foreignkey") # op.alter_column('role', 'is_muted', # ex
isting_type=sa.BOOLEAN(), # nullable=False) op.drop_column("role", "notified_at") def downgrade(): pass
JFriel/honours_project
venv/lib/python2.7/site-packages/nltk/corpus/reader/panlex_lite.py
Python
gpl-3.0
5,153
0.004463
# Natural Language Toolkit: PanLex Corpus Reader # # Copyright (C) 2001-2016 NLTK Project # Author: David Kamholz <kamholz@panlex.org> # URL: <http://nltk.org/> # For license information, see LICENSE.TXT """ CorpusReader for PanLex Lite, a stripped down version of PanLex distributed as an SQLite database. See the READ...
t and the second element is the transl
ation quality. :rtype: list(tuple) """ from_lv = self._uid_lv[from_uid] to_lv = self._uid_lv[to_uid] return self._c.execute(self.TRANSLATION_Q, (from_lv, from_tt, to_lv)).fetchall() class Meaning(dict): """ Represents a single PanLex meaning. A meaning is a translation...
iohannez/gnuradio
gr-filter/python/filter/qa_pfb_arb_resampler.py
Python
gpl-3.0
8,395
0.004169
#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you c
an redistri
bute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERC...
joalcava/space_invaders
heart.py
Python
gpl-3.0
626
0.004808
#! /usr/bin/python3 import pygame from colors import Colors class Heart(pygame.sprite.Sprite): def __init__(self, pos): pygame.sprite.Sprite.__init__(self) self.image, self.rect = self.load_image("heart.
png") self.rect.x = pos[0]
self.rect.y = pos[1] def load_image(self, name, colorkey=None): image = pygame.image.load(name) image = image.convert_alpha() if colorkey is not None: if colorkey is -1: colorkey = image.get_at((0,0)) image.set_colorkey(colorkey, RLEACCEL) r...
BigFatNoob-NCSU/x9115george2
hw/code/2/4_3.py
Python
mit
1,206
0.024876
__author__ = 'panzer' from swampy.TurtleWorld import * from math import radians, sin def initTurtle(delay = 0.01): """ Initializes a turtle object :param delay: Delay before each action of the turtle. Lower it is the faster the turtle moves. :return: turtle object """ TurtleWorld() t = Turtle() t.delay...
h: length of each side :return: Draws a Pie(Spiked polygon) """ angle = float(360.0/n) eq_side = length/2.0/sin(radians(angle/2.0)) for _ in range(n): isosceles(t, eq_side, length, 180 - (180 - angle)/2.0) lt(t, 180) if __name__ == '__main__': # Figure 4.2 a pie(initTurtle(), 5, 100) # Figure ...
) wait_for_user()
nschloe/pyfvm
src/pyfvm/__about__.py
Python
gpl-3.0
22
0
__version__
= "0.3.9"
dave-the-scientist/brugia_project
get_knockout_info.py
Python
gpl-3.0
20,007
0.006998
""" Notes: - Brugia protein sequences: https://www.ncbi.nlm.nih.gov/bioproject/PRJNA10729 - wBm protein sequences: https://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?id=292805 - BLASTP against Reference proteins (refseq protein) from Human, using BLOSUM45 matrix. - BLASTP against nr proteins from O. volvulus and ...
) double_ko_data = double_reaction_deletion(model, double_rxn_ids[:5], number_of_processes=3) d_r1, d_r2, d_rates = double_ko_data['y'], double_ko_data['x'], double_ko_data['data'] def find_model_deficiencies(model, orig_f,
new_f, r_id): deficiencies = [] ob = model.reactions.get_by_id(r_id).bounds model.reactions.get_by_id(r_id).bounds = (0,0) diffs = id_bottleneck_metabolites(model, new_f, 'BIOMASS', threshold=1.0) for recovered_f, mtb_id in diffs: def_str = '%s (%.1f)' % (mtb_id, recovered_f/orig_f*100) ...
WladimirSidorenko/SentiLex
scripts/rao.py
Python
mit
8,962
0
#!/usr/bin/env python2.7 # -*- mode: python; coding: utf-8; -*- """Module for generating lexicon using Rao and Ravichandran's method (2009). """ ################################################################## # Imports from __future__ import unicode_literals, print_function from blair_goldensohn import build_mtx...
rm irow = a_Y.getrow(idx).toarray() # print("irow =", repr(irow)) ipol = irow.argmax(axis=1)[0] iscore = irow[0, ipol] # print("ipol =", repr(ipol)) # print("iscore =", repr(iscore)) if ipol != NEUT_IDX: ipol = IDX2CLS[ipol] if iword in lex...
dx][SCORE_IDX]): ret[lidx][POL_IDX] = ipol ret[lidx][SCORE_IDX] = iscore else: lex2lidx[iword] = len(ret) ret.append([iword, ipol, iscore]) return ret def _sign_normalize(a_Y, a_terms2idx, a_pos, a_neg, a_neut, ...
JamesHyunKim/myhdl
hdlmake/tools/aldec/aldec.py
Python
gpl-3.0
3,541
0.003106
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2013, 2014 CERN # Author: Pawel Szostek (pawel.szostek@cern.ch) # Multi-tool support by Javier D. Garcia-Lasheras (javier@garcialasheras.com) # # This file is part of Hdlmake. # # Hdlmake is free software: you can redistribute it and/or modify # it under the t...
= string.Template("""TOP_MODULE := ${top_module} ALDEC_CRAP := \ run.command \ li
brary.cfg #target for performing local simulation sim: sim_pre_cmd """) makefile_text_1 = makefile_tmplt_1.substitute( top_module=top_module.top_module ) self.write(makefile_text_1) self.writeln("\t\techo \"# Active-HDL command file, generated by HDLMake\" > run.command") ...
benschmaus/catapult
telemetry/telemetry/internal/actions/loop_unittest.py
Python
bsd-3-clause
2,356
0.002971
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry import decorators from telemetry.internal.actions import loop from telemetry.testing import tab_test_case import py_utils AUDIO_1_LOOP_CHEC...
timeout_in_seconds=10) action.WillRunAction(self._tab) action.RunAction(sel
f._tab) # Assert only first video has played. self.assertTrue(self._tab.EvaluateJavaScript(VIDEO_1_LOOP_CHECK)) self.assertFalse(self._tab.EvaluateJavaScript(AUDIO_1_LOOP_CHECK)) @decorators.Disabled('android', 'linux') # crbug.com/418577 def testLoopWithAllSelector(self): """Tests that Loop actio...
plotly/python-api
packages/python/plotly/plotly/validators/sankey/link/hoverlabel/_font.py
Python
mit
1,877
0.000533
import _plotly_utils.basevalidators class FontValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__( self, plotly_name="font", parent_name="sankey.link.hoverlabel", **kwargs ): super(FontValidator, self).__init__( plotly_name=plotly_name, parent_name=p...
Provide multiple font f
amilies, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com or on-premise) generates images on a server, where only a ...
earl/beanstalkc
beanstalkc.py
Python
apache-2.0
10,921
0.000458
#!/usr/bin/env python """beanstalkc - A beanstalkd Client Library for Python""" import logging import socket import sys __license__ = ''' Copyright (C) 2008-2016 Andreas Bolka Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obt...
= self._read_response() if status in expected_ok: return results elif status in expected_err: raise CommandFailed(command.split()[0], status, results) else: raise UnexpectedResponse(command.split()[0], status, results) def _
read_response(self): line = SocketError.wrap(self._socket_file.readline) if not line: raise SocketError() response = line.split() return response[0], response[1:] def _read_body(self, size): body = SocketError.wrap(self._socket_file.read, size) SocketErro...
bowenliu16/deepchem
deepchem/dock/__init__.py
Python
gpl-3.0
637
0.00157
""" Imports all submodul
es """ from __future__ import print_function from __future__ import division from __future__ import unicode_literals from deepchem.dock.pose_generation import PoseGenerator from deepchem.dock.pose_generation import VinaPoseG
enerator from deepchem.dock.pose_scoring import PoseScorer from deepchem.dock.pose_scoring import GridPoseScorer from deepchem.dock.docking import Docker from deepchem.dock.docking import VinaGridRFDocker from deepchem.dock.docking import VinaGridDNNDocker from deepchem.dock.binding_pocket import ConvexHullPocketFinder...
mapattacker/cheatsheets
python/pyspark.py
Python
mit
10,361
0.02326
import findspark #pyspark can't be detected if file is at other folders than where it is installed findspark.init('/home/jake/spark/spark-2.2.0-bin-hadoop2.7') ## 1) SPARK DATAFRAME #-------------------------------------------------------- from pyspark.sql import SparkSession from pyspark.sql.functions import ...
.select(year(df['Date'])).show() #year ## 2) USING RDD (Resilient Distributed Dataset) # spark is transiting slowly to spark dataframe, but its stil good to learn the original parsing in RDD # especially when data is non-datafra
me type #-------------------------------------------------------- from pyspark import SparkConf, SparkContext # set configuration & spark context object conf = SparkConf().setMaster("local").setAppName("MinTemperatures")
songrun/VectorSkinning
src/bezier_constraint_odd_solver.py
Python
apache-2.0
9,730
0.063412
from generate_chain_system import * class BezierConstraintSolverOdd( BezierConstraintSolver ): ''' Free direction, magnitude fixed (for G1 or A). ''' def update_system_with_result_of_previous_iteration( self, solution ): ### Iterate only over the parts of the matrix that will change, ### such as the lagrange...
for i in range(dim): Left[ i*4:(i+1)*4, i*4:(i+1)*4 ] = MAM[:,:] return Left*length def system_for_
curve_with_arc_length( self, bundle ): ''' ## Solve the same integral as system__for_curve only with dt replaced by ds ''' length = bundle.length ts = bundle.ts dts = bundle.dts dim = 2 Left = zeros( ( 8, 8 ) ) tbar = ones( ( 4, 1 ) ) MAM = zeros( ( 4, 4 ) ) for i in range(len(dts)): t = (ts...
jwren/intellij-community
python/testData/completion/dictLiteralCompletion/EmptyLiteralsInCallExpressionsWithQuotes/main.py
Python
apache-2.0
142
0
from typing import TypedDict class Point(TypedDict): x: int y:
int def is_even(x: Poin
t) -> bool: pass is_even({'<caret>'})
lixiangning888/whole_project
modules/signatures_merge_tmp/static_authenticode.py
Python
lgpl-3.0
876
0.002326
# -*- coding: utf-8 -*- # Copyright (C) 2014 Accuvant, Inc. (bspengler@accuvant.com) # This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org # See the file 'docs/LICENSE' for copying permission. from lib.cuckoo.common.abstracts import Signature class Authenticode(Signature): name = "static_authentico...
lf.results: if "digital_signers" in self.results["static"] and self.results["static"]["digital_
signers"]: for sign in self.results["static"]["digital_signers"]: self.data.append(sign) found_sig = True return found_sig
kalbermattenm/historic_cadastre
setup.py
Python
gpl-2.0
1,011
0.000989
# -*- coding: utf-8 -*- try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages setup(
name='historic_cadastre', version='0.1', description='SITN, a sitn project', author='sitn', author_email='sitn@ne.ch', url='http://www.ne.ch/sitn', install_requires=[ 'pyramid', 'SQLAlchemy', 'transaction',
'pyramid_tm', 'pyramid_debugtoolbar', 'pyramid-mako', 'zope.sqlalchemy', 'waitress', 'sqlahelper', 'JSTools', 'httplib2', 'simplejson' ], packages=find_packages(exclude=['ez_setup']), include_package_data=True, zip_safe=False, entry_po...
plumgrid/plumgrid-nova
nova/api/openstack/compute/contrib/os_tenant_networks.py
Python
apache-2.0
7,948
0.000881
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 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.apach...
bel")} class NetworkController(object): def __init__(self, network_api=None): self.network_api = nova.network.API() self._default_networks = [] def _refresh_default_networks(self): self._default_networks = [] if CONF.use_neutron_default_nets == "True": try: ...
rks") def _get_default_networks(self): project_id = CONF.neutron_default_tenant_id ctx = nova_context.RequestContext(user_id=None, project_id=project_id) networks = {} for n in self.network_api.get_all(ctx): networks[n['id']] = n...
postlund/home-assistant
tests/components/axis/test_switch.py
Python
apache-2.0
2,374
0.000842
"""Axis switch platform tests.""" from unittest.mock import Mock, call as mock_call from homeassistant.components import axis import homeassistant.components.switch as switch from homeassistant.setup import async_setup_component from .test_device import NAME, setup_axis_integration EVENTS = [ { "operati...
= Mock() await hass.services.async_call( "switch", "turn_on", {"entity_id": f"switch.{NAME}_doorbell"}, blocking=True ) await hass.services.async_call( "switch", "turn_off", {"entity_id": f"switch.{NAME}_doorbell"}, blocking=True ) assert device.a
pi.vapix.ports["0"].action.call_args_list == [ mock_call("/"), mock_call("\\"), ]
ecometrica/gdal2mbtiles
tests/test_spatial_reference.py
Python
apache-2.0
1,178
0
# -*- coding: utf-8 -*- import pytest from numpy import array from numpy.testing import assert_array_almost_equal from gdal2mbtiles.constants import (EPSG_WEB_MERCATOR, EPSG3857_EXTENTS) from gdal2mbtiles.gdal import SpatialReference @pytest.fixture def epsg_3857_from_proj4(): ...
al_ref def test_epsg_3857_proj4(epsg_3857_from_proj4): extents = epsg_3857_from_proj4.GetWorldExtents() extents = array(extents) assert_array_almost_equal(extents, EPSG3857_EXTENTS, decimal=3) def test_epsg_3857_from_epsg(epsg_3857_from_epsg): extents = epsg_3857_from_epsg.GetWorldExtents() exte...
al(extents, EPSG3857_EXTENTS, decimal=3)
F5Networks/f5-openstack-agent
f5_openstack_agent/lbaasv2/drivers/bigip/icontrol_driver.py
Python
apache-2.0
112,266
0
# coding=utf-8# # Copyright (c) 2014-2018, F5 Networks, 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 applicabl...
vers.bigip.cluster_manager import \ ClusterManager from f5_openstack_agent.lbaasv2.drivers.bigip import constants_v2 as
f5const from f5_openstack_agent.lbaasv2.drivers.bigip.esd_filehandler import \ EsdTagProcessor from f5_openstack_agent.lbaasv2.drivers.bigip import exceptions as f5ex from f5_openstack_agent.lbaasv2.drivers.bigip.lbaas_builder import \ LBaaSBuilder from f5_openstack_agent.lbaasv2.drivers.bigip.lbaas_driver imp...
HomeRad/TorCleaner
test.py
Python
gpl-2.0
32,033
0.00103
#!/usr/bin/python # -*- coding: utf-8 -*- # # SchoolTool - common information systems platform for school administration # Copyright (c) 2003 Shuttleworth 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...
# output verbosity verbosity = 0 # verbosity level (-v) quiet = 0 # do not print anything on success (-q) first_doctest_failure = False # report first doctest failure (-1) print_import_time =
True # print time taken to import test modules # (currently hardcoded) progress = False # show running progress (-p) colorize = False # colorize output (-c) coverage = False # produce coverage reports (--coverage) coverdir = 'coverage'...
greggy/python-ipgeobase
cidr_create.py
Python
bsd-3-clause
1,230
0.010906
# -*- coding: utf-8 -*- import cPickle as pickle GEO_FILES = './geo_files' def gen_db(): u'''Функция для генерации pickle базы ipgeobase.ru ''' res = [] tmp_list = [] cities_dict = {} # cidr_optim.txt for line in open('%s/cidr_optim.txt' % GEO_FILES, 'r'): a = line.split('\t'...
f item[0] == res[c-1][0]: res.remove(item) c += 1 # cities.txt cities_file = open('%s/cities.txt' % GEO_FILES, 'r').read() lines = cities_file.decode('CP1251').split('\n') for line in lines:
a = line.split('\t') if len(a) > 3: cities_dict.update({int(a[0]): (a[1], a[2])}) f = open('%s/cidr_pickle.db' % GEO_FILES, 'w') pickle.dump((res, cities_dict), f) f.close() if __name__ == '__main__': gen_db()
OpenConextApps/OpenConextApps-MediaWiki
includes/zhtable/Makefile.py
Python
gpl-2.0
13,107
0.036927
#!/usr/bin/python # -*- coding: utf-8 -*- # @author Philip import tarfile as tf import zipfile as zf import os, re, shutil, sys, platform pyversion = platform.python_version() islinux = platform.system().lower() == 'linux' if pyversion[:3] in ['2.6', '2.7']: import urllib as urllib_request import codecs ...
return table def customRules( path ): fp = open( path, 'rb', 'U8' ) ret = dict() for line in fp: elems = line.split( '#' )[0].split() if len( elems ) > 1: ret[elems[0]] = elems[1] return ret def dictToSortedList( src_table, pos ): return sorted( src_table.items(), key...
j in range( len( text ) - i, 0, -1 ): f = text[i:][:j] t = conv_table.get( f ) if t: text = text[:i] + t + text[i:][j:] i += len(t) - 1 break i += 1 return text def manualWordsTable( path, conv_table, reconv_table ): fp...
stuarteberg/lazyflow
tests/testRESTfulBlockwiseFileset.py
Python
lgpl-3.0
7,468
0.014596
############################################################################### # lazyflow: data flow based lazy parallel computation framework # # Copyright (C) 2011-2014, the ilastik developers # <team@ilastik.org> # # This program is free software; you can redistribute it and/o...
.description.shape) data = volume.readData( roi ) assert data.shape == (25,20,20) assert volume.getBlockStatus( ([0,0,0]) ) == BlockwiseFileset.BLOCK_AVAILABLE assert vo
lume.getBlockStatus( ([20,0,0]) ) == BlockwiseFileset.BLOCK_AVAILABLE assert volume.getBlockStatus( ([20,20,0]) ) == BlockwiseFileset.BLOCK_AVAILABLE assert volume.getBlockStatus( ([0,20,0]) ) == BlockwiseFileset.BLOCK_AVAILABLE def test_4_OffsetDownload(self): volume = RESTfulBlockwiseFile...
jjgomera/pychemqt
lib/elemental.py
Python
gpl-3.0
7,567
0.000264
#!/usr/bin/python3 # -*- coding: utf-8 -*- '''Pychemqt, Chemical Engineering Process simulator Copyright (C) 2009-2017, Juan José Gómez Romera <jjgomera@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 Softwar...
5681", "#B92D2D", "#B8873A", "#D7C848", "#94738F", "#6186AC", "#88AE62", "#94
9692", "#BF924E", "#C44343"] color_phase = ["#DDDDDD", "#BB8F4A", "#7BB245", "#5D82A8"] NUMERIC_VALUES = ["density_Solid", "density_Liq", "density_Gas", "date", "atomic_mass", "atomic_volume", "atomic_radius", "covalent_radius", "vanderWaals_radius", "electronegativity...
iPlantCollaborativeOpenSource/cyverse-sdk
src/scripts/template2json.py
Python
bsd-3-clause
1,718
0.001164
#!/usr/bin/env python import os import sys import argparse import json # tempate2json.py -k SYSTEM=lonestar.tacc.utexas.edu # PATH=/home/vaughn/apps -i template.jsonx -o file.json if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-k", dest='keys', help='Spac...
*') parser.add_argument("-i", dest='input', help='Input (template.jsonx)') parser.add_argument("-o", dest="output", help="Output (output.json)") args = parser.parse_args() try: with open(args.input
) as f: s = f.read() except TypeError, e: print >> sys.stderr, "[FATAL]", "No filename was provided for -i" sys.exit(1) except IOError, e: print >> sys.stderr, "[FATAL]", args.input, "was not available for reading" print >> sys.stderr, "Exception: %s" % str(e) ...
Luminarys/Bioinformatics
Scripts/GetRPKM.py
Python
gpl-2.0
1,450
0.006207
#!/usr/bin/env python #Takes a table and index of Exon Lens, calculates RPKMs import sys import os import re import fileinput from decimal import Decimal from decimal import getcontext from fractions import Fraction def main(table,index): indf = open(index) out_file = "%s_rpkm.table" % os.path.splitext(table)...
leinput.input(index): (key, val) = line.split('\t') if val == 0: print "We Ffd up at " + str(key) dic[str(key.rstrip())] = Decimal(val) print dic["Vocar20014554m.g.2.0"] with open(out_file,'w') as fout: start = True tb = "\t" for line in fileinput.inpu...
'\t') head = listl[0] vals = listl[1:] for i in xrange(len(vals)): comp = Decimal(vals[i]) div = Decimal(dic[head.rstrip()]) print head.rstrip() ot = "%.2f" % float(Decimal(co...
khosrow/metpx
pxStats/lib/LogFileAccessManager.py
Python
gpl-2.0
12,296
0.024723
#! /usr/bin/env python """ ###########################################################################################
## # # # Name: LogFileAccessManager.py # # @author: Nicholas Lemay # # @license: MetPX Copyright (C) 2004-2006 Environment Canada # MetPX comes with ABSOLUTELY NO WARRANTY; For details type see the file # named COPYING in the root of the source directory tree. # # Description : Utility class used t...
o make sure everything still works properly. Feel free to add tests if needed. # # While using this class, you can either use only one file with all your entries # and give a different identifier to all of you entries, or you can use different # files. # # Using a single file howev...
cchurch/ansible
test/units/modules/storage/netapp/test_netapp_e_volume.py
Python
gpl-3.0
58,947
0.005038
# coding=utf-8 # (c) 2018, NetApp Inc. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type try: from unittest import mock except ImportError: import mock from ansible.module_utils.net...
"diskPool": True, "flashCached": False, "metadata": [{"key": "workloadId", "value": "4200000002000000000000000000000000000000"},
{"key": "volumeTypeId", "value": "Micah"}], "dataAssurance": False, "currentControllerId": "070000000000000000000002", "cacheSettings": {"readCacheEnable": True, "writeCacheEnable": False, ...
andersx/cclib
src/cclib/writer/xyzwriter.py
Python
lgpl-2.1
4,078
0.000981
# This file is part of cclib (http://cclib.github.io), a library for parsing # and interpreting the results of computational chemistry packages. # # Copyright (C) 2014, the cclib development team # # The library is free software, distributed under the terms of # the GNU Lesser General Public version 2.1 or later. You s...
verged geometry, which for any job other than # a geometry optimization would be the single/only geometry. # 3. Write the very first geometry, which for any job other than a # geometry optimization would be the single/only geometry. # 4. Write the first and last geometries from a geo...
lencoords = len(self.ccdata.atomcoords) if lencoords == 1: xyzblock.append(self._xyz_from_ccdata(-1)) elif self.do_allgeom: for index in range(lencoords): xyzblock.append(self._xyz_from_ccdata(index)) elif self.do_firstgeom and self.do_lastgeom: ...
centaurialpha/pireal
setup.py
Python
gpl-3.0
91
0
#!/usr/bin/env python from setuptools i
mpo
rt setup if __name__ == "__main__": setup()
LettError/glyphNameFormatter
Lib/glyphNameFormatter/rangeProcessors/helper_arabic_ligature_exceptions.py
Python
bsd-3-clause
1,516
0.005937
from __future__ import print_function from glyphNameFormatter.tools import camelCase doNotProcessAsLigatureRanges = [ (0xfc5e, 0xfc63), (0xfe70, 0xfe74), #(0xfc5e, 0xfc61), (0xfcf2, 0xfcf4), (0xfe76, 0xfe80), ] def process(self): # Specifically: do not add suffixes to these ligatures, ...
'FINAL FORM', "fina") self.replace('ISOLATED FORM', "isol") self.replace('WITH SUPERSCRIPT', "") self.replace('WITH', "")
self.replace("LIGATURE", "") self.replace("ARABIC", "") self.replace("SYMBOL", "") self.replace("LETTER", "") self.lower() self.camelCase() return True return False if __name__ == "__main__": from glyphNameFormatter import Gly...
zhaochl/python-utils
utils/except_util.py
Python
apache-2.0
134
0.014925
#!/usr/bin/env python # coding=utf-8 import traceback try: raise SyntaxError
, "traceback test" except: traceback.pr
int_exc()
ksterker/wastesedge
scripts/schedules/mapcharacters/sarin.py
Python
gpl-2.0
2,833
0.012354
# # (C) Copyright 2001/2002 Kai Sterker <kaisterker@linuxgames.com> # Part of the Adonthell Project http://adonthell.linuxgames.com # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License. # This program is distributed in the hope that it will...
f __init__ (self, map
characterinstance): self.myself = mapcharacterinstance # -- Borders of the area he should stay in self.min_x = 1 self.max_x = 6 self.min_y = 2 self.max_y = 6 self.direction = self.myself.get_val ("direction") # -- make random remarks self.speech...
gnocchixyz/python-gnocchiclient
gnocchiclient/v1/resource_cli.py
Python
apache-2.0
10,591
0
# # 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 # ...
ptions(parsed_args)) if parsed_args.formatter == 'table': return self._list2cols(list(map(normalize_metrics, resources))) return self._list2cols(resources) class CliResourceSearch(CliResourceList): """Search resources with specified query rules.""" def get_parser(self, prog_name):...
er) return parser def take_action(self, parsed_args): resources = utils.get_client(self).resource.search( resource_type=parsed_args.resource_type, query=parsed_args.query, **utils.get_pagination_options(parsed_args)) # Do not dump metrics because it makes...
avlach/univbris-ocf
vt_manager/src/python/agent/xen/provisioning/configurators/ofelia/OfeliaDebianVMConfigurator.py
Python
bsd-3-clause
6,611
0.039782
import shutil import os import jinja2 import string import subprocess import re from xen.provisioning.HdManager import HdManager from settings.settingsLoader import OXA_XEN_SERVER_KERNEL,OXA_XEN_SERVER_INITRD,OXA_DEBIAN_INTERFACES_FILE_LOCATION,OXA_DEBIAN_UDEV_FILE_LOCATION, OXA_DEBIAN_HOSTNAME_FILE_LOCATION, OXA_DEB...
ackup current files shutil.copy(path+OXA_DEBIAN_INTERFACES_FILE_LOCATION,path+OXA_DEBIAN_INTERFACES_FILE_LOCATION+".bak") shutil.copy(path+OXA_DEBIAN_UDEV_FILE_LOCATION,path+OXA_DEBIAN_UDEV_FILE_LOCATION+".bak") except Exception as e: pass with open(path+OXA_DEBIAN_INTERFACES_FILE_LOCATION,'w') as o...
tor.__configureUdevFile(vm,openudev) except Exception as e: OfeliaDebianVMConfigurator.logger.error(str(e)) raise Exception("Could not configure interfaces or Udev file") @staticmethod def _configureLDAPSettings(vm,path): try: file = open(path+OXA_DEBIAN_SECURITY_ACCESS_FILE_LOCATION, "r") text = fil...
theskumar/django-unsubscribe
unsubscribe/tests/test_utils.py
Python
bsd-3-clause
329
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals
from django.test import TestCase class UtilsTests(TestCase): """docstring for UtilsTests""" def setUp(self): self.username = 'theskumar' self.email = 'theskumar@example.com' def test_foo(self): self.assertEqual('foo',
"foo")
fbeutler/Metropolis-Hastings
Metropolis_Hastings2.py
Python
gpl-2.0
579
0.008636
import numpy as np import matplotli
b.pyplot as pl def f(x): return np.exp(-x**2) def main(): N = 100000 x = np.arange(N,dtype=np.float) x[0] = 0.2 counter = 0 for i in range(0, N-1): x_next = np.random.normal(x[i], 1.) if np.random.random_sample() < min(1, f(x_next)/f(x[i])):
x[i+1] = x_next counter = counter + 1 else: x[i+1] = x[i] print("acceptance fraction is ", counter/float(N)) pl.hist(x, bins=50, color='blue') pl.show() if __name__ == '__main__': main()
google/TaglessCRM
src/plugins/pipeline_plugins/hooks/ads_uac_hook.py
Python
apache-2.0
9,520
0.004832
# python3 # coding=utf-8 # Copyright 2020 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
{3}-?[a-f0-9]{12}$' _RDID_REGEX = re.compile(_RDID_PATTERN, re.IGNORECAS
E) _APP_CONVERSION_TRACKING_PATH = 'pagead/conversion/app/1.0' _REQUIRED_FIELDS = ('dev_token', 'link_id', 'app_event_type', 'rdid', 'id_type', 'lat', 'app_version', 'os_version',...
nickpack/reportlab
src/reportlab/pdfgen/pdfgeom.py
Python
bsd-3-clause
3,119
0.00545
#Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/pdfgen/pdfgeom.py __version__=''' $Id: pdfgeom.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" This module includes any mathematical methods ...
x = (x2-x1)/2. ry = (y2-y1)/2. halfAng = fragAngle * pi / 360. kappa = abs(4. / 3. * (1. - cos(halfAng)) / sin(halfAng)) if fragAngle < 0: sign = -1 else: sign = 1 pointList = [] for i in range(Nfrag): theta0 = (startAng + i*fragAngle) * pi / 180. ...
pointList.append((x_cen + rx * cos(theta0), y_cen - ry * sin(theta0), x_cen + rx * (cos(theta0) - kappa * sin(theta0)), y_cen - ry * (sin(theta0) + kappa * cos(theta0)), x_cen + rx * (cos(theta1...
thiswind/nn_practice
tensorflow/calculate_pi_old.py
Python
gpl-3.0
581
0.032702
import tensorflow as tf import matplotlib.pyplot as plt import math x_node = tf.random_uniform([1], minval=-1, maxval=1, dtype=tf.float32, name='x_node') y_node = tf.random_uniform([1], minval=-1, maxval=1, dtype=tf.float32, name='y_node') times = 5000 hits = 0 pis = [] with tf.Session() as sessio...
[math.pi, math.
pi]) plt.show()
theonion/djes
djes/mapping.py
Python
mit
5,823
0.002919
from django.db import models from django.db.models.fields.related import ManyToOneRel, ForeignObjectRel from elasticsearch_dsl.mapping import Mapping from elasticsearch_dsl.field import Field from djes.conf import settings FIELD_MAPPINGS = { "AutoField": {"type": "long"}, "BigIntegerField": {"type": "long"},...
and hasattr(cls, "Mapping"): return cls.Mapping for base in cls.__bases__: mapping = get_first_mapping(base) if mapping: return mapping return None class EmptyMeta(object): pass class DjangoMapping(Mapping): """A subclass of the elasticsearch_dsl Mapping, allowing...
f, model): from .models import Indexable self.model = model if not hasattr(self, "Meta"): self.Meta = EmptyMeta default_name = "{}_{}".format(self.model._meta.app_label, self.model._meta.model_name) name = getattr(self.Meta, "doc_type", default_name) super(...
asimshankar/tensorflow
tensorflow/contrib/model_pruning/python/pruning.py
Python
apache-2.0
21,323
0.00469
# 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...
he gradual sparsity function sparsity_function_exponent: float exponent = 1 is linearly varying sparsity between initial and final. exponent > 1 varies more slowly towards the end than the beginning use_tpu: False Indicates whether to use TPU We use the following sparsity function: n...
rget_sparsity)* [1-step/(num_steps -1)]**exponent + target_sparsity Args: None Returns: tf.HParams object initialized to default values """ return hparam.HParams( name='model_pruning', begin_pruning_step=0, end_pruning_step=-1, weight_sparsity_map=[''], ...
tensorflow/lingvo
lingvo/jax/base_model.py
Python
apache-2.0
37,124
0.004067
# Lint as: python3 # Copyright 2021 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 ...
avg_xe
nt=(predictions.avg_xent, avg_xent_weight), aux_loss=(predictions.aux_loss, jnp.array(1.0, predictions.aux_loss.dtype)), log_pplx=(predictions.avg_xent, avg_xent_weight), fraction_of_correct_next_step_preds=(mean_acc, metric_weight), num_prediction...
PhonologicalCorpusTools/PolyglotDB
polyglotdb/query/base/complex.py
Python
mit
2,772
0.000722
class ComplexClause(object): type_string = '' def __init__(self, *args): self.clauses = args self.add_prefix(self.type_string) def is_matrix(self): for c in self.clauses: if not c.is_matrix(): return False return True def involves(self, an...
def for_cypher(self): """ Return a Cypher representation of the clause. """ temp = ' AND '.join(x.for_cypher() for x in self.clauses) temp
= "(" + temp + ")" return temp
crypotex/taas
taas/user/views.py
Python
gpl-2.0
6,005
0.001166
import logging from django.conf import settings from django.contrib import messages from django.contrib.auth import views as auth_views, get_user_model, update_session_auth_hash, logout from django.contrib.auth.tokens import default_token_generator from django.contrib.messages.views import SuccessMessageMixin from dja...
equest.POST) if form.is_valid(): form.save() messages.add_
message(request, messages.SUCCESS, _('Your password has been set. You may go ahead and log in now.'), fail_silently=True) logger.info('Password for user %s has been reset.' % user.email) ...
hylje/Lyra
lyra/forms.py
Python
bsd-3-clause
3,064
0.00359
# -*- encoding: utf-8 -*- import datetime from django import forms from django.db.models import Q from django.utils.translation import ugettext_lazy as _ from django.core import exceptions as django_exceptions from lyra import models class Reservation(forms.ModelForm): def __init__(self, *args, **kw...
leaned_data class ReservationExclusiveEnable(ReservationExclusive): exclusive = forms.BooleanField( label=_(u"No overlap"), required=False) class ReservationExclusiveDisable(ReservationExclusive): exclusive = forms.BooleanField( label=_(u"No overlap"), require...
initial=True) class ConfirmForm(forms.Form): confirm = forms.BooleanField()
xuweiliang/Codelibrary
openstack_dashboard/dashboards/project/routers/ports/views.py
Python
apache-2.0
3,508
0
# Copyright 2012, Nachi Ueno,
NTT MCL, 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 a
t # # 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 l...
asobolev/nix4nest
nix4nest/test/test_nest_api/test_multimeter.py
Python
lgpl-3.0
967
0.001034
import unittest import nest from nix4nest.nest_api.models.multimeter import NestMultimeter class TestNode(unittest.TestCase): def setUp(self): nest.ResetKernel() self.neuron_id = nest.Create('iaf_neuron')[0] rec_params = {'record_from': ['V_m'], 'withtime': True} self.mm_id = n...
] nest.Connect([self.mm_id], [self.neuron_id]) self.mm = NestMultimeter(self.mm_id, 'V_m') def tearDown(self): nest.ResetKernel() def test_properties(self): for k in nest.GetStatus([self.mm_id])[0].keys(): assert(k in self.mm
.properties) def test_data(self): assert(len(self.mm.data) == 0) nest.Simulate(50) assert(len(self.mm.data) == 0) self.mm.refresh() assert(len(self.mm.data) == 49) assert(self.neuron_id in self.mm.senders) assert((self.mm.senders == self.neuron_id).all()...
trishika/home-monitor
monitor.py
Python
gpl-3.0
2,393
0.033445
#!/usr/bin/env python2.7 # -*- encoding: utf-8 -*- """ Home-monitor ~~~~~~~~~~~~ :copyright: (c) 2013 by Aurélien Chabot <aurelien@chabot.fr> :license: GP
Lv3, see COPYING for more details. """ try: import threadin
g import sys, os, time, datetime import json import urllib2 from ConfigParser import SafeConfigParser except ImportError as error: print 'ImportError: ', str(error) exit(1) try: sys.path.insert(0, '../rest/') sys.path.insert(0, '/usr/local/bin/') from restClientLib import get_nodes, set_switch, update_sensor,...
datavisyn/tdp_core
tdp_core/config.py
Python
bsd-3-clause
688
0.011628
from phovea_server.ns import Namespace, abort from phovea_server.util import jsonify from phovea_server.config import get as
get_config from phovea_server.plugin import list as list_plugins import logging app = Namespace(__name__) _log = logging.getLogger(__name__) @app.route('/<path:path>') def _config(path): path = path.split('/'
) key = path[0] plugin = next((p for p in list_plugins('tdp-config-safe-keys') if p.id == key), None) if plugin is None: _log.error('404: config key "{}" not found'.format(key)) abort(404, 'config key "{}" not found'.format(key)) path[0] = plugin.configKey return jsonify(get_config('.'.join(path)))...
jim-easterbrook/pywws
src/pywws/service/pwsweather.py
Python
gpl-2.0
3,827
0.001045
# pywws - Python software for USB Wireless Weather Stations # http://github.com/jim-easterbrook/pywws # Copyright (C) 2018 pywws contributors # 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; ei...
import timedelta import logging import os import sys import requests import pywws.service __docformat__ = "restructuredtext en" service_name = os.path.splitext(os.path.basename(__file__))[0] logger = logging.getLogger(__name
__) class ToService(pywws.service.CatchupDataService): config = { 'station' : ('', True, 'ID'), 'password': ('', True, 'PASSWORD'), } fixed_data = {'action': 'updateraw', 'softwaretype': 'pywws'} logger = logger service_name = service_name template = """ #live# #idx ...
hagifoo/gae-pomodoro
app/src/application/handler/__init__.py
Python
mit
2,303
0.000868
# coding: utf-8 import json import logging import webapp2 from webapp2_extras import sessions from google.appengine.api.taskqueue import TombstonedTaskError, TaskAlreadyExistsError, DuplicateTaskNameError from domain.entity import User import error class BaseHandler(webapp2.RequestHandler): def dispatch(self): ...
DuplicateTaskNameError) as e: logging.error(e) def signin_user_only(f): """Raise UnauthorizedException if session user is None Examples: class MyHandler(BaseHandler): @singin_user_only def get(self): # following code is executed only if user is signed in....
elf, *args, **keywords): if not self.user: raise error.UnauthorizedException('Need sign in') else: return f(self, *args, **keywords) return wrapper
legacysurvey/pipeline
py/legacyanalysis/fix-model-selection.py
Python
gpl-2.0
4,976
0.007838
from glob import glob import fitsio import sys from astrometry.util.fits import * from astrometry.util.file import * from astrometry.util.starutil_numpy import * from astrometry.libkd.spherematch import * from collections import Counter from legacypipe.oneblob import _select_model from legacypipe.survey import wcs_for_...
omp'], d)) mod = _select_model(dchisqs, nparams, galaxy_margin, rex) ttype = ttype.strip() # The DUP elements appear a
t the end, and we *zip* A and T8; A does not contain the DUPs # so is shorter by the number of DUP elements. assert(ttype != 'DUP') newtype = typemap[mod] # type unchanged if ttype == newtype: continue # Copy fit values from the "newtype" entries in all-...
cloudControl/cctrl
cctrl/error.py
Python
apache-2.0
7,677
0.00482
# -*- coding: utf-8 -*- """ Copyright 2010 cloudControl UG (haftungsbeschraenkt) 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 ...
ion is required. You need to upgrade before using this program. To upgrade run: (sudo) pip install {0} --upgrade' class CctrlException(Exception): def __init__(self, error_key): self.error_message = messages[error_key] def __str__(self): return '[
ERROR]' + ' ' + self.error_message class InputErrorException(CctrlException): """ This exception is raised if for some reason someone put something in we could not understand at all. """ pass class PasswordsDontMatchException(Exception): """ This exception is raised if the pa...
ibus/ibus-qt
src/interfaces/introspect_panel.py
Python
gpl-2.0
130
0.007692
#!/usr/bin/env python import ibus import dbus bus = dbus.SessionBus() e = i
bus.interface.IPanel() print e.Introspect("/", bus
)
joshmoore/zeroc-ice
py/demo/Ice/latency/Client.py
Python
gpl-2.0
1,349
0.005189
#!/usr/bin/env python # ********************************************************************** # # Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved. # # This copy of Ice is licensed to you under the terms described in the # ICE_LICENSE file included in this distribution. # # *************************************...
**************************** import sys,
time, traceback, Ice Ice.loadSlice('Latency.ice') import Demo class Client(Ice.Application): def run(self, args): if len(args) > 1: print self.appName() + ": too many arguments" return 1 ping = Demo.PingPrx.checkedCast(self.communicator().propertyToProxy('Ping.Proxy')) ...
Hemisphere-Project/HPlayer2
core/interfaces/regie.py
Python
gpl-3.0
10,996
0.012095
from .base import BaseInterface import eventlet from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler from flask import Flask, render_template, session, request, send_from_directory from flask_socketio import SocketIO, emit, join_room, leave_room, close_room, rooms, disconnect ...
project = file.read() return project # parse locally for programatic execution def reload(self): try: self._project = json.loads(self.projectRaw()) except: self._project = None self.log("Error while parsing project..") ...
# print(self._project) return self._project # play sequence def playseq(self, sceneIndex, seqIndex): self.log("PLAYSEQ") try: # self.log('PLAYSEQ', seqIndex, sceneIndex, boxes) orderz = [] boxes = [b for b in self._projec...
dnjohnstone/hyperspy
hyperspy/misc/export_dictionary.py
Python
gpl-3.0
7,725
0.000647
# -*- coding: utf-8 -*- # Copyright 2007-2020 The HyperSpy developers # # This file is part of HyperSpy. # # HyperSpy 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...
lags, list): flags = parse_flag_string(flags) if 'sig' in flags: if isinstance(value,
dict): from hyperspy.signal import BaseSignal value = BaseSignal(**value) value._assign_subclass() return value if 'fn' in flags: ifdill, thing = value if ifdill is None: return thing if ifdill in [True, 'True', b'True']: r...
discreteoptimization/setcover
cp_homebrew_003/validator.py
Python
mit
2,676
0.002242
#!/usr/bin/env python # encoding: utf-8 """ For local testing purposes """ from itertools import compress, chain, product, ifilter from functools import partial from reader import read_input, list_files def is_valid(task, solution): """ :param reader.Task task: :param list[1|0] solution: :return bool...
lution) items_covered = set(chain.from_iterable(s.items for s in sets)) return len(items_covered) == task.item_count def calc_cost(task, solution): """ :param reader.Task task: :param list[1|0] solution: :return int: """ sets = compress(task.sets, solution)
return sum(s.cost for s in sets) def bruteforce_solver(task): """ As simple solution as we can make. It finds the optimal solution, but it can't work on big inputs (say, 20 sets take a few seconds, 25 sets - take a few minutes) :param reader.Task task: :return list[1|0]: """ all_...
frappe/erpnext
erpnext/stock/report/cogs_by_item_group/cogs_by_item_group.py
Python
gpl-3.0
5,496
0.025291
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt import datetime from collections import OrderedDict from typing import Dict, List, Tuple, Union import frappe from frappe import _ from frappe.utils import date_diff from erpnext.accounts.report.gen...
def get_item_groups_map(svd_list: SVDList) -> Dict[str, str]: item_codes = set(i['item_code'] for i in svd_list) ig_list = frappe.get_list( 'Item', fields=['item_code','item_group'], filters=[('item_code', 'in', item_codes)] ) return {i['item_code']:i['item_group'] for i in ig_list} def get_item_groups_di
ct() -> ItemGroupsDict: item_groups_list = frappe.get_all("Item Group", fields=("name", "is_group", "lft", "rgt")) return {(i['lft'],i['rgt']):{'name':i['name'], 'is_group':i['is_group']} for i in item_groups_list} def update_leveled_dict(leveled_dict: OrderedDict) -> None: for k in leveled_dict: leveled_dict[...
ggaughan/dee
DeeCluster.py
Python
mit
1,475
0.008814
"""DeeCluster: provides a namespace for a set of DeeDatabases""" __version__ = "0.1" __author__ = "Greg Gaughan" __copyright__ = "Copyright (C) 2007 Greg Gaughan" __license__ = "MIT" #see Licence.txt for licence information from Dee import Relation, Tuple from DeeDatabase import Database class Cluster(dict):...
here (Called once on cluster creation) """ dict.__init__(self) self.name=name self.databases = Relation(['database_name'], self.vdatabases) #todo should really have relations, attributes etc. to define this... def __getattr__(self, key): if se...
se? self[key] = value #todo delattr def __contains__(self, item): if item in self.__dict__: if isinstance(self.__dict__[item], Database): return True return False def __iter__(self): for (k, v) in self.items(): #for (k, v) i...
freezmeinster/teh-manis
django/conf/global_settings.py
Python
bsd-3-clause
21,140
0.00175
# Default Django settings. Override these with settings in the module # pointed-to by the DJANGO_SETTINGS_MODULE environment variable. # This is defined here as a do-nothing function because we can't import # django.utils.translation -- that module depends on the settings. gettext_noop = lambda s: s #################...
ations for, out of the box. The language name # should be the utf-8 encoded local name for the language. LANGUAGES = ( ('ar', gettext_noop('Arabic')), ('az', gettext_noop('Azerbaijani')), ('bg', gettext_noop('Bulgarian')), ('bn', gettext_noop('Bengali')), ('bs', gettext_noop('B
osnian')), ('ca', gettext_noop('Catalan')), ('cs', gettext_noop('Czech')), ('cy', gettext_noop('Welsh')), ('da', gettext_noop('Danish')), ('de', gettext_noop('German')), ('el', gettext_noop('Greek')), ('en', gettext_noop('English')), ('en-gb', gettext_noop('British English')), ('es',...
wojtask/CormenPy
test/test_chapter16/test_problem16_1.py
Python
gpl-3.0
1,843
0.00217
import io import math import random from contextlib import redirect_stdout from unittest import TestCase from hamcrest import * from array_util import get_random_unique_array from chapter16.problem16_1 import greedy_make_change, make_change, print_change from datastructures.array import Array from util import between...
teforce(n - denom, d)) return min_ch
ange class TestProblem16_1(TestCase): def test_greedy_make_change(self): n = random.randint(1, 20) d = Array([1, 2, 5, 10, 20, 50]) actual_change = greedy_make_change(n) expected_change_size = get_min_change_size_bruteforce(n, d) actual_change_sum = sum(actual_change[i] ...
Tigerwhit4/taiga-back
taiga/projects/tasks/api.py
Python
agpl-3.0
7,479
0.002541
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be> # Copyright (C) 2014 Jesús Espino <jespinog@gmail.com> # Copyright (C) 2014 David Barragán <bameda@dbarragan.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 F...
om taiga.base.decorators import list_route from taiga.base.api import ModelCrudViewSet from taiga.projects.models import Project, TaskStatus from django.http import HttpResponse from taiga.projects.notifications.mixins import WatchedResourceMixin from taiga.projects.history.mixins import HistoryResourceMixin from taig...
. import models from . import permissions from . import serializers from . import services class TaskViewSet(OCCResourceMixin, HistoryResourceMixin, WatchedResourceMixin, ModelCrudViewSet): model = models.Task permission_classes = (permissions.TaskPermission,) filter_backends = (filters.CanViewTasksFilte...
m4ll0k/Spaghetti
plugins/fingerprint/waf/jiasule.py
Python
gpl-3.0
587
0.040886
#!/usr/bin/env python # -*- coding:utf-8 -*- # # @name: Wascan - Web Application Scanner # @repo
: https://github.com/m4ll0k/Wascan # @author: Momo Outaadi (M4ll0k) # @license: See the file 'LICENSE.txt from re import search,I def jiasule(headers,content): _ = False for header in headers.items(): _ |= search(r'__jsluid=|jsl_tracking',header[1],I) is not None _ |= search(r'jiasule-waf',header[1],I) is ...
s not None if _ : return "Jiasule Web Application Firewall (Jiasule)"
RedHatSatellite/satellite-sanity
satellite_sanity_lib/rules/sat5_cobbler_config.py
Python
gpl-3.0
3,726
0.021202
#!/usr/bin/env python # -*- coding: UTF-8 -*- import re tags = ['Satellite_5', 'Spacewalk'] name = 'Basic Cobbler settings are correct' def etc_cobbler_settings(data): """ Verify settings in /etc/cobbler/settings: redhat_management_type: "site" redhat_management_server: "satellite.example.com" server...
[] opts_found = 0 etc_cobbler_modules_conf_authentication_module = '' section_
auth = False for line in data['etc_cobbler_modules_conf']: if re.match('^\s*\[.*\]\s*$', line): section_auth = False if re.match('^\s*\[authentication\]\s*$', line): section_auth = True continue if section_auth and re.match('^\s*module\s*=', line): opts_found += 1 val = ...
tamland/trakt-sync
xbmc_library.py
Python
gpl-3.0
4,438
0.001127
# -*- coding: utf-8 -*- # # Copyright (C) 2015 Thomas Amland # # 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 ...
vshowid, season=r['season'], episode=r['episode'], x
bmcid=r['episodeid'], playcount=r['playcount'], ) def jsonrpc(method, params=None): if params is None: params = {} payload = { 'jsonrpc': '2.0', 'id': 1, 'method': method, 'params': params, } payload = json.dumps(payload, encoding='utf-8') try: ...
flypy/flypy
flypy/tests/test_calling_conv.py
Python
bsd-2-clause
1,235
0.004049
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import import unittest from flypy import jit class TestCallingConventionFromPython(unittest.TestCase): def test_varargs(self): @jit def f(a, b, *args): return [a, b, args[1]] self.assertEqual(f...
lass TestCallingFlypyConvention(unittest.TestCase): def test_varargs(self): @jit def g(a, b, *args): return [a, b, args[1]] @jit def f(a, b, c, d, e): return g(a, b, c, d, e) self.assertEqual(f(1, 2, 0, 3, 0), [1, 2, 3]) def test_unpacking(self...
2, 3]) def test_unpacking2(self): raise unittest.SkipTest("unpacking with additional varargs") @jit def g(a, b, *args): return [a, b, args[0]] @jit def f(*args): return g(*args) self.assertEqual(f(1, 2, 3), [1, 2, 3]) # TODO: Test unpac...
pettersoderlund/fondout
script/StockScraper-master/import_symbols_from_industry.py
Python
bsd-3-clause
1,827
0.004379
""" Scrape yahoo industry database through YQL """ import mysql.connector import stockretriever import sys cnx = mysql.connector.connect(user='root', password='root', database='yahoo') cursor = cnx.cursor() add_employee = ("INSERT INTO stocks "
"(symbol, name, industry) " "VALUES (%s, %s, %s) " "ON DUPLICATE KEY UPDATE industry=VALUES(industry)") sectors = stockretriever.get_industry_ids() for sector in sectors: for industry in sector['industry']: try: print "\nProcessing", industry['name'], indust...
cept TypeError as E: print E continue industry_index = stockretriever.get_industry_index(industry['id']) try: industry_name = industry_index['name'] industry_companies = industry_index['company'] industry_id = industry_index['...
abrenaut/mrot
mrot/cli.py
Python
mit
1,423
0.003514
# -*- coding: utf-8 -*- import logging import argparse from .imdb import find_movies logger = logging.getLogger('mrot') def parse_args(): parser = argparse.ArgumentParser(prog='mrot', description='Show movie ratings over time.', formatter_class=argparse.ArgumentDefaultsHelpF...
number of concurrent requests to the wayback machine") parser.add_argument("-d", "--delta", type=int, default=365, help="minimum number of days between two ratings") parser.add_argument("-q", "--quiet", action="store_true", help="don't print progress") args = parser.parse_args() return args def main...
ck machine concurrency = min(args.concurrency, 10) # Find the movies corresponding to the given movie name imdb_movies = find_movies(args.movie_name) if len(imdb_movies) > 0: # Show rating for the first movie matching the given name imdb_movie = imdb_movies[0] imdb_movie.plot_r...
jamielapointe/PyPassiveRangingFilters
pyPassiveRanging/dynamicsModels/cartState.py
Python
mit
236
0.016949
''' Created on Apr 30, 2017 @author: jamie ''' impo
rt numpy as np class CartState(object): ''' Defines a Cartesian state information ''' pos_I = np.array([0., 0., 0.]) vel_I = np.array([0., 0., 0.])
pixelpicosean/my-godot-2.1
version.py
Python
mit
89
0
short_name = "godot" name
= "Godot Engine" major =
2 minor = 1 patch = 4 status = "beta"
lucashanke/houseofdota
app/util/match_util.py
Python
mit
2,180
0.005046
from __future__ import division import datetime import pytz from app.models import Patch def get_match_patch(match_date): utc = pytz.UTC #pylint: disable=no-value-for-parameter match_date = utc.localize(datetime.datetime.fromtimestamp(match_date)) for patch in Patch.objects.all().order_by('-start_dat...
md, public, league, team, solo, ranked) is True \ and check_game_mode(gmd, ap, cm, ar, rap) is True \ and check_abandon(gmd) is False #pylint: disable=invalid-name,too-many-arguments def check_lobby_type(match, public=None, league=None, team=None, solo=None, ranked=None): if pub
lic is None and league is None and team is None and solo is None and ranked is None: public = league = team = solo = ranked = True if match is not None: match_type = match['lobby_type'] #pylint: disable=too-many-boolean-expressions if (public and match_type == 0) or \ ...
Sigmapoint/notos
src/notos/migrations/0001_initial.py
Python
mit
3,961
0.007321
# -*- 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 model 'PushResult' db.create_table(u'notos_pushresult', ( (u'id', self.gf('django.db.mo...
elds.DateTimeField')(auto_now_add=True, blank=True)), ('send_at', self.gf('django.db.models.fields.DateTimeField')()), ('canceled_at', self.gf('django.db.models.fields.DateTimeF
ield')(null=True, blank=True)), ('registration_id', self.gf('django.db.models.fields.CharField')(max_length=4095)), ('result', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['notos.PushResult'], unique=True, null=True, blank=True)), ('attempt_no', self.gf('django.db....
adithyabhatkajake/kompile
domains/migrations/0004_auto_20161103_1044.py
Python
gpl-2.0
678
0.001475
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-11-03 10:44 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migratio
n): dependencies = [ ('domains', '0003_auto_20161103_1031'), ] operations = [ migrations.RemoveField( model_name='domain',
name='subtopics', ), migrations.AddField( model_name='subtopic', name='dmain', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='subtopics', to='domains.domain'), ), ]
jhaase1/zapdos
tests/reflections/low_initial/ToCSV.py
Python
lgpl-2.1
586
0.003413
from paraview.simple import * import os import sys import numpy as np path = os.getcwd() + "/" file_name = sys.argv[1] inp = file_name + ".e" outCSV = file_name + ".csv" reader = ExodusIIReader(FileName=path+inp) tsteps = reader.TimestepValues writer = CreateWriter(path+file_name+"_Cells.c
sv", reader) writer.FieldAssociation = "Cells" # or "Points" writer.UpdatePipeline(time=tsteps[len(tsteps)-1]) del writer writer = CreateWriter(path+file_name+"_Points.csv", reader) writer.FieldAssociation = "Points" # or "Cells" writer.UpdatePipeline(time=tsteps[len(
tsteps)-1]) del writer
dhuang/incubator-airflow
airflow/providers/ssh/hooks/ssh.py
Python
apache-2.0
14,364
0.001601
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
self.compress = True self.no_host_key_check = True self.allow_host_key_change = False self.host_proxy = None self.host_k
ey = None self.look_for_keys = True # Placeholder for deprecated __enter__ self.client = None # Use connection to override defaults if self.ssh_conn_id is not None: conn = self.get_connection(self.ssh_conn_id) if self.username is None: se...
openprocurement/reports
reports/helpers.py
Python
apache-2.0
9,179
0.000545
import os.path import argparse import arrow import iso8601 import requests import json import re import datetime from yaml import load from repoze.lru import lru_cache from dateutil.parser import parse from time import sleep from retrying import retry from logging import getLogger RE = re.compile(r'(^.*)@(\d{4}-\d{...
ev", to="UTC", format="%Y-%m-%dT%H:%M:%S.%f" ): date = arrow.get(parse(date), timezone) return date.to
(to).strftime(format) def prepare_report_interval(period=None): if not period: return ("", "9999-12-30T00:00:00.000000") if len(period) == 1: return (convert_date(period[0]), "9999-12-30T00:00:00.000000") if len(period) == 2: return (convert_date(period[0]), convert_date(period[1])...
sanSS/programming-contests
project-euler/problem142.py
Python
gpl-3.0
1,119
0.003575
#!/usr/bin/env python3 ######################################################################## # Solves problem 142 from projectEuler.net. # ??? # Copyright (C) 2011 Santiago Alessandri # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public L...
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, see <http://www.gnu.org/licenses/>. # # You can contact me at san.lt.ss@gmail.com # Visit my wiki at http://san-ss.is-a-gee
k.com.ar ######################################################################## # x + y = a # x + z = b # y + z = c # x - y = d # x - z = e # y - z = f # e = a - c # f =
Gaia3D/QGIS
python/ext-libs/owslib/iso.py
Python
gpl-2.0
36,451
0.005816
# -*- coding: ISO-8859-15 -*- # ============================================================================= # Copyright (c) 2009 Tom Kralidis # # Authors : Tom Kralidis <tomkralidis@gmail.com> # Angelos Tzotsos <tzotsos@gmail.com> # # Contact email: tomkralidis@gmail.com # ================================...
.name = util.testXMLValue(val) val = md.find(util.nspath_eval('gmd:organi
sationName/gco:CharacterString', namespaces)) self.organization = util.testXMLValue(val) val = md.find(util.nspath_eval('gmd:positionName/gco:CharacterString', namespaces)) self.position = util.testXMLValue(val) val = md.find(util.nspath_eval('gmd:contactInfo/gmd:CI_Con...
adler-j/lie_grp_diffeo
examples/deformation_closest_pt_2d.py
Python
gpl-3.0
3,110
0.000322
import lie_group_diffeo as lgd import odl import numpy as np # Select space and interpolation space = odl.uniform_discr([-1, -1], [1, 1], [200, 200], interp='linear') # Select template and target as gaussians template = space.element(lambda x: np.exp(-(5 * x[0]**2 + x[1]**2) / 0.4**2)) target = space.element(lambda x...
ion, W.size) elif regularizer == 'point': W = odl.ProductSpace(odl.rn(space.ndim), 3) w = W.element([[0, 0], [0, 1], [1, 0]]) # Create regularizing functional regularizer = 0.01 * odl.solvers.L2NormSquared(W).translated(w) # Create action if lie_grp_type =...
on = lgd.MatrixVectorAffineAction(lie_grp, W[0]) else: point_action = lgd.MatrixVectorAction(lie_grp, W[0]) regularizer_action = lgd.ProductSpaceAction(point_action, W.size) elif regularizer == 'determinant': W = odl.rn(1) w = W.element([1]) # Create regularizing functional regularizer ...
renalreg/radar
tests/auth/test_passwords.py
Python
agpl-3.0
1,704
0.000587
from radar.auth.passwords import ( check_password_hash, generate_password, generate_password_hash, get_password_length, is_strong_password, password_to_nato_str, ) from radar.models.users import User def test_password_to_nato_str(): password = 'aAzZ123' assert password_to_nato_str(pass...
'uehnpqjarf' suffix = 'hello418' username_password = user.username + suffix email_password = user.email + suffix first_name_password = user.first_n
ame + suffix last_name_password = user.last_name + suffix with app.app_context(): assert is_strong_password(username_password) assert is_strong_password(email_password) assert is_strong_password(first_name_password) assert is_strong_password(last_name_password)
immanetize/nikola
nikola/packages/tzlocal/windows_tz.py
Python
mit
26,452
0
# This file is autogenerated by the get_windows_info.py script # Do not edit. win_tz = { 'AUS Central Standard Time': 'Australia/Darwin', 'AUS Eastern Standard Time': 'Australia/Sydney', 'Afghanistan Standard Time': 'Asia/Kabul', 'Alaskan Standard Time': 'America/Anchorage', 'Arab Standard Time': 'A...
, 'Africa/Blantyre': 'South Africa Standard Time', 'Africa/Brazzaville': 'W. Central Africa Standard Time', 'Africa/Bujumbura': 'South Africa Standard Time', 'Africa/Cairo': 'Egypt Standard Time', 'Africa/Casablanca': 'Morocco Standard Time', 'Africa/Ceuta': 'Romance Standard Time', 'Africa/...
Africa Standard Time', 'Africa/Douala': 'W. Central Africa Standard Time', 'Africa/El_Aaiun': 'Morocco Standard Time', 'Africa/Freetown': 'Greenwich Standard Time', 'Africa/Gaborone': 'South Africa Standard Time', 'Africa/Harare': 'South Africa Standard Time', 'Africa/Johannesburg': 'South Afri...
Kitware/arctic-viewer
scripts/examples/vtk/medical/head-ct-volume.py
Python
bsd-3-clause
3,622
0.002485
# ----------------------------------------------------------------------------- # Download data: # - Browser: # http://midas3.kitware.com/midas/folder/10409 => VisibleMale/vm_head_frozenct.mha # - Terminal # curl "http://midas3.kitware.com/midas/download?folders=&items=235235" -o vm_head_frozenct.mha # ----...
) else: scalarOpacity.AddPoint(dataRang
e[0], 0.0) scalarOpacity.AddPoint(center - halfSpread, 0.0) scalarOpacity.AddPoint(center, 1.0) if (center + halfSpread) >= dataRange[1]: scalarOpacity.AddPoint(dataRange[1], 0.0) else: scalarOpacity.AddPoint(center + halfSpread, 0.0) scalarOpacity.AddPoint(dataRange[1],...
SymbiFlow/prjxray
utils/xjson.py
Python
isc
558
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright (C) 2017-2020 The Project X-Ray Authors. # # Use of
this source code is governed by a ISC-style # license that can be found in the LICENSE file or at # https://opensource.org/licenses/ISC # # SPDX-License-Identifier: ISC import sys import json from prjxray.xjson import pprint if __name__ == "__main__": if len(sys.argv) == 1: import doctest doctest.t...
d = json.load(open(sys.argv[1])) pprint(sys.stdout, d)
naparuba/check-linux-by-ssh
check_ntp_sync_by_ssh.py
Python
mit
8,784
0.006717
#!/usr/bin/env python2 # Copyright (C) 2013: # Gabes Jean, naparuba@gmail.com # Pasche Sebastien, sebastien.pasche@leshop.ch # # 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...
stname = opts.hostname or '' ntpq = opts.ntpq if ntpq: NTPQ_PATH=ntpq ssh_key_file = opts.ssh_key_file or os.path.expanduser('~/.ssh/id_rsa') user = opts.user or 'shinken' passphrase = opts.passphrase or '' chrony = opts.chrony if not chrony: # Try to get numeic warning/c...
L warning, critical = schecks.get_warn_crit(s_warning, s_critical) else: if opts.warning: warning_delay = float(opts.warning.split(',')[0]) warning_offset = float(opts.warning.split(',')[1]) else: warning_delay = float(DEFAULT_DELAY_WARNING) wa...
PeRDy/performance-tools
performance_tools/urls_flow/backends/base.py
Python
gpl-2.0
2,681
0.001865
# -*- coding: utf-8 -*- from __future__ import unicode_literals from abc import ABCMeta import csv from performance_tools.exceptions import ProgressBarException, ElasticsearchException from performance_tools.utils.progress_bar import create_progress_bar class BaseURLFlowBackend(object): """Collect URL flow fro...
ex=None): """Extract origin url and destination url for each entry in result and con
struct a list with them. :param result: results obtained from backend in each iteration. :type result: object :param regex: Regular expression to normalize id's in URL. :type regex: re :return: List of origin urls and destination urls. :rtype: list """ ra...
megarcia/GT16_JGRA
source/process_NCEI_03_prcp_180d.py
Python
gpl-3.0
5,554
0
""" Python script 'process_NCEI_03_prcp_180d.py' by Matthew Garcia, PhD student Dept. of Forest and Wildlife Ecology University of Wisconsin - Madison matt.e.garcia@gmail.com Copyright (C) 2015-2016 by Matthew Garcia Licensed Gnu GPL v3; see 'LICENSE_GnuGPLv3.txt' for complete terms Send questions, bug reports, any re...
ncols = np.copy(h5infile['ncols']) prcp_180d = np.copy(h5infile['prcp_180d']) message('extracting station lists') prcp_180d_stns = get_stn_lists(path, prev_year, 'prcp_180d_stns') else: # otherwise, initialize the variable space(s) h5infname = '%s/%d_NCEI_grids_2.h5' % (path, dates[0]) mess...
s']) ncols = np.copy(h5infile['grid/ncols']) message('establishing prcp_180d datacube') prcp_180d = np.zeros((180, nrows, ncols)) prcp_180d_stns = [] message(' ') # for date in dates: h5infname = '%s/%d_NCEI_grids_2.h5' % (path, date) message('extracting PRCP grid from %s' % h5infname) w...
leopoul/mupy
muparse/__init__.py
Python
apache-2.0
582
0.001718
# Copyright 2012 Leonidas Poulopoulos # # 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 L...
cense for the specific language governing permissions and # limitations under the License.
patrickm/chromium.src
build/android/pylib/linker/test_runner.py
Python
bsd-3-clause
3,271
0.007031
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Runs linker tests on a particular device.""" import logging import os.path import sys import traceback from pylib import constants from pylib.base impor...
unner, self).__init__(device, tool,
push_deps, cleanup_test_files) #override def InstallTestPackage(self): apk_path = os.path.join( constants.GetOutDirectory(), 'apks', '%s.apk' % _PACKAGE_NAME) if not os.path.exists(apk_path): raise Exception('%s not found, please build it' % ap...
EverythingAbout/Python
Searches/linear_search.py
Python
mit
775
0.009032
def linear_search(lst,size,value): i = 0 while i < size: if lst[i] == value: return i i = i + 1 return -1 def main(): lst = [-31, 0, 1, 2, 2, 4, 65, 83, 99, 782] size = len(lst) original_list = "" value = int(input("\nInput a value to search for: ")) print...
) else: print(str(value) + " was found at index " + str(index)) if __name_
_ == '__main__': main()
tocubed/noisily
tests/test_noise.py
Python
apache-2.0
2,684
0.007079
import pytest import numpy as np import noisily as ns # FIXME This has got to be an abuse of fixtures, right? @pytest.fixture(scope='module', params=[(1, 1), (37, 57), (128, 128)]) def indices2D(request): shape = request.param return np.transpose(np.indices(shape)) @pytest.fixture(scope='module', params=[(1...
s.cell2D_manhattan_inv,
ns.cell2D_manhattan_value]) def noise2D(request): return request.param @pytest.fixture(scope='module', params=[ns.perlin3D, ns.value3D, ns.open_simplex3D, ns.cell3D_range, ns.cell3D_range_inv, ns.cell3D_value, ns.cell3D_manhattan, ns.cell3D_manhattan_inv, ns.cell3D_manhattan_value]) def noise3D(request): retur...