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 |
|---|---|---|---|---|---|---|---|---|
gglyptodon/tmp | Pysickle/pysickle/pysickle.py | Python | gpl-3.0 | 24,572 | 0.016238 | #!/usr/bin/env python
'''
Copyright (C) 2014 Janina Mass
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 program is dist... | onsCaused)) * insertionP | enalty\
+ len(self.uniqueInsertionsCaused) * uniqueInsertionPenalty\
+ len(self.mismatchShared)* mismatchPenalty\
+ len(self.matchShared) *matchReward
return(res)
class FastaParser(object):
def read_fasta(self, fasta, delim = None, asID = 0):
"""read from fast... |
red-hood/calendarserver | txdav/xml/extensions.py | Python | apache-2.0 | 1,673 | 0.000598 | # Copyright (c) 2009 Twisted Matrix Laboratories.
# See LICENSE for details.
##
# Copyright (c) 2005-2015 Apple Inc. All rights reserved.
#
# 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 wi... | oftware, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in a | ll
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE L... |
MobicoTIC/MongoLite | mongolite/mongo_exceptions.py | Python | bsd-3-clause | 2,399 | 0.010004 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2011, Nicolas Clairon
# All rights reserved.
# R | edistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in | binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the University of California, Berkeley nor the
# names of its contributors may be use... |
senttech/Cura | plugins/USBPrinting/__init__.py | Python | agpl-3.0 | 1,268 | 0.007098 | # | Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from . import USBPrinterOutputDeviceManager
from PyQt5.QtQml import qmlRegisterType, qmlRegisterSingletonType
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("cura")
def getMetaData():
return {
"type"... |
"version": "1.0",
"api": 3,
"description": i18n_catalog.i18nc("@info:whatsthis","Accepts G-Code and sends them to a printer. Plugin can also update firmware.")
}
}
def register(app):
# We are violating the QT API here (as we use a factory, which is technically not a... |
Geosyntec/python-tidegates | tidegates/analysis.py | Python | bsd-3-clause | 15,076 | 0.000862 | """ Top-level functions for python-tidegates.
This contains main functions to evaluate the extent of floodinga and
damage due to floods.
(c) Geosyntec Consultants, 2015.
Released under the BSD 3-clause license (see LICENSE file for more info)
Written by Paul Hobson ([email protected])
"""
import os
import sy... | efmt)
tem | p_filename = "_temp_FloodedZones_" + datestring
else:
temp_filename = utils.create_temp_filename(filename, filetype='shape', num=num)
# compute floods of zoned areas of topo
flooded_array = utils.flood_zones(
zones_array=zones_array,
topo_array=topo_array,
elevation=elevatio... |
aocks/ox_herd | ox_herd/core/plugins/awstools_plugin/test_awstools.py | Python | bsd-2-clause | 1,442 | 0 | """Tests for awstools plugin.
"""
import shutil
import os
import tempfile
from ox_herd.core.plugins.awstools_plugin import core
class TestableBackupTask(core.BackupPostgresToAWS):
"""Sub-class of BackupPostgresToAWS for testing.
"""
@classmethod
def make_dump_cmdline(cls, ox_herd_task, outfile):
... | bucket_name='@'+backup_loc)
result = task.main_call(task)
assert result['return_value'].split()[:4] == [
'Finished', 'dump:', 'extra', 'messages="b\'\'".']
finally:
for name in [db_loc]:
if os.path.exists(name):
os.remove(name)
i | f os.path.exists(backup_loc):
shutil.rmtree(backup_loc)
|
kallewoof/bitcoin | test/functional/wallet_send.py | Python | mit | 29,974 | 0.004704 | #!/usr/bin/env python3
# Copyright (c) 2020-2021 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the send RPC command."""
from decimal import Decimal, getcontext
from itertools import product
f... | struct options dictionary
options = {}
if add_to_wallet is not None:
options["add_to_wallet"] = add_to_wallet
else:
| if psbt:
add_to_wallet = False
else:
add_to_wallet = from_wallet.getwalletinfo()["private_keys_enabled"] # Default value
if psbt is not None:
options["psbt"] = psbt
if conf_target is not None:
options["conf_target"] = conf_target
... |
limscoder/amfast | examples/auth/python/utils.py | Python | mit | 1,088 | 0.001838 | """Utility functions."""
import sys
import logging
import amfast
from amfast.encoder import Encoder
from amfast.decoder import Decoder
from amfast.remoting import Service, CallableTarget
import controller
def setup_channel_set(channel_set):
"""Configures an amfast.remoting.channel.ChannelSet object."""
# Se... | (CallableTarget(cont_obj.echo, 'echo', secure=True))
channel_set.service_mapper.mapService(service)
# Set the ChannelSet's 'checkCredentials' attribute
# to enable authentication.
#
# In this example, we're usi | ng a method from the
# controller to check credentials.
channel_set.checkCredentials = cont_obj.checkCredentials
|
rproepp/spykeutils | spykeutils/plugin/data_provider_neo.py | Python | bsd-3-clause | 40,506 | 0.000321 | import os
import sys
from copy import copy
from collections import OrderedDict
import traceback
import atexit
import neo
from data_provider import DataProvider
from .. import conversions as convert
class NeoDataProvider(DataProvider):
""" Base class for data providers using NEO"""
# Dictionary of block lis... | o_file(filename, lazy, force_io, read_params)
if io and not lazy and not cls.cascade_lazy and hasattr(io, 'close'):
io.close()
return blocks
@classmethod
def _load_neo_file(cls, filename, lazy, force_io, read_params):
""" Returns a NEO io object and a list of contain | ed blocks for a
file name. This function also caches all loaded blocks
:param str filename: The full path of the file (relative or absolute).
:param bool lazy: Determines if lazy mode is used for Neo io.
:param force_io: IO class to use for loading. If None, determined
by fi... |
k04la/ijust_server | project/controllers/api_1/contest.py | Python | gpl-3.0 | 51,483 | 0.001049 | # -*- coding: utf-8 -*-
__author__ = 'AminHP'
# python imports
import os
import shutil
import zipfile
import StringIO
import base64
# flask imports
from flask import jsonify, request, g, send_file, abort
# project | imports
from project | import app
from project.extensions import db, auth
from project.modules.datetime import utcnowts
from project.modules.paginator import paginate
from project.models.contest import Contest, Problem, ContestDateTimeError
from project.models.team import Team
from project.models.user import User
from project.forms.problem ... |
tyb0807/angr | angr/engines/vex/dirty.py | Python | bsd-2-clause | 14,622 | 0.005061 | import claripy
import logging
import time
from ... import sim_options as o
l = logging.getLogger("angr.engines.vex.dirty")
#####################
# Dirty calls
#####################
# they return retval, constraints
# Reference:
# http://www-inteng.fnal.gov/Integrated_Eng/GoodwinDocs/pdf/Sys%20docs/PowerPC/PowerP... | )
SET_ABCD(0x00000f5a, 0x00000505, 0x00000000, 0x21d3fbff, 0x80000001)
SET_ABCD(0x20444d41, 0x6574704f, 0x206e6f72, 0x296d7428, 0x80000002)
SET_ABCD(0x6f725020, 0x73736563, 0x3820726f, 0x00003834, 0x80000003)
SET_ABCD(0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x80000004)
SET_ABCD(0xff08ff08, | 0xff20ff20, 0x40020140, 0x40020140, 0x80000005)
SET_ABCD(0x00000000, 0x42004200, 0x04008140, 0x00000000, 0x80000006)
SET_ABCD(0x00000000, 0x00000000, 0x00000000, 0x0000000f, 0x80000007)
SET_ABCD(0x00003028, 0x00000000, 0x00000000, 0x00000000, 0x80000008)
return None, [ ]
amd64g_dirtyhelper_CPUID_avx_... |
dbbhattacharya/kitsune | vendor/packages/pylint/test/input/func_noerror_except_pass.py | Python | bsd-3-clause | 204 | 0.004902 | """
#3205: W0704 (except doesn't do anything) false positive if some statements
follow a | "pass" |
"""
__revision__ = None
try:
A = 2
except ValueError:
pass # pylint: disable-msg=W0107
print A
|
oscurart/BlenderAddons | oscurart_tools/oscurart_animation.py | Python | gpl-2.0 | 2,647 | 0.001511 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# 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 your option) any later version.
#
# This program is distrib... | xt.scene.quick_animation_in)
| a = Matrix(target.matrix_world)
a.invert()
i = Matrix(ob.matrix)
for frame in range(inf, out):
bpy.context.scene.frame_set(frame=frame)
ob.matrix = target.matrix_world * a * i
bpy.ops.anim.keyframe_insert(type="LocRotScale")
else:
target = ... |
DuinoDu/label_ellipse | label.py | Python | mit | 6,224 | 0.01446 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
python label.py [imgdir]
Usage:
d -> delete current label
n -> next picture
q -> exit
'''
import os, sys
import cv2
import numpy as np
import math
import copy
import xml.etree.ElementTree as ET
x1,y1, x2, y2 = 0,0,0,0
state = 0
# ellipse parameter
x0, y0 = 0, 0
angl... | in(imgdir, x) for x in sorted(os.listdir(imgdir)) if x.endswith('.JPG') or x.endswith('.jpg')])
annodir = os.path.join(root, 'Annotations')
if not os.path.exists(annodir):
| os.makedirs(annodir)
global im
global filename
cv2.namedWindow('img')
cv2.setMouseCallback('img', onmouse)
#for f in imgfiles:
img_ind = 0
while True:
if img_ind >= len(imgfiles):
print("Finish.")
break
img_ind = 0 if img_ind < 0 else img_ind
... |
parkbyte/electrumparkbyte | gui/qt/qrwindow.py | Python | mit | 3,180 | 0.001887 | #!/usr/bin/env python
#
# Electrum - lightweight ParkByte client
# Copyright (C) 2014 Thomas Voegtlin
#
# 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 withou... | oxLayout()
self.qrw | = QRCodeWidget()
main_box.addWidget(self.qrw, 1)
vbox = QVBoxLayout()
main_box.addLayout(vbox)
self.address_label = QLabel("")
#self.address_label.setFont(QFont(MONOSPACE_FONT))
vbox.addWidget(self.address_label)
self.label_label = QLabel("")
vbox.addW... |
Uruwolf/pyshop | products/admin.py | Python | gpl-3.0 | 1,218 | 0.00821 | '''
This file is part of pyShop
pyShop 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.
pyShop is distributed in the hope that it will be us... | objects
Currently set to display the name and catergory,
be filterable by catergory
and searchabl | e via name and description.'''
list_display = ('name', 'catergory')
list_filter = ['catergory']
search_fields = ['name', 'description']
admin.site.register(Product, ProductAdmin)
|
PaddlePaddle/Paddle | python/paddle/fluid/layers/tensor.py | Python | apache-2.0 | 67,174 | 0.002799 | # Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed un | der the Apache License, Version 2.0 (the "Li | cense");
# 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
#
# Unlessf required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT ... |
mastizada/kuma | vendor/packages/ipython/IPython/rlineimpl.py | Python | mpl-2.0 | 1,760 | 0.002841 | # -*- coding: utf-8 -*-
""" Imports and provides the 'correct' version of readline for the platform.
Readline is used throughout IPython as 'import IPython.rlineimpl as readline'.
In addition to normal readline stuff, this module provides have_readline
boolean and _outputfile variable used in genutils.
"""
import sy... | instead of GNU readline.
# Thanks to Boyd Waters for this patch.
uses_libedit = False
if sys.platform == 'darwin' and have_readline:
import commands
(status, result) = commands.getstatusoutput( "otool -L %s | grep l | ibedit" % _rl.__file__ )
if status == 0 and len(result) > 0:
# we are bound to libedit - new in Leopard
_rl.parse_and_bind("bind ^I rl_complete")
print "Leopard libedit detected."
uses_libedit = True
# the clear_history() function was only introduced in Python 2.4 and is
# actually... |
syci/ingadhoc-odoo-addons | report_extended/models/__init__.py | Python | agpl-3.0 | 983 | 0.001017 | # -*- coding: utf-8 -*-
##############################################################################
#
# Ingenieria ADHOC - ADHOC SA
# https://launchpad.net/~ingenieria-adhoc
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public Lice... | e
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
... | eceived a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import report
import company
|
astagi/chickenfoot | chickenfoot/modules_register.py | Python | mit | 443 | 0.009029 | from modules.front_motor import FrontMotor
from modules.back_motor import BackMotor
from services.temperature_sensor import TemperatureSensor
modules = {}
def get_module(module_name, **data):
return modules[module_name] | (**data)
def register_module(module_name, cls):
modules[module_name] = cls
register_module('FrontMotor', FrontMotor)
register_module('BackMotor', BackMotor)
register_module('Temperatur | eSensor', TemperatureSensor) |
timberline-secondary/hackerspace | src/djcytoscape/tests/test_views.py | Python | gpl-3.0 | 5,010 | 0.002994 | from django.contrib.auth import get_user_model
# from django.urls import reverse
from model_bakery import baker
from tenant_schemas.test.cases import TenantTestCase
from tenant_schemas.test.client import TenantClient
# from siteconfig.models import SiteConfig
from hackerspace_online.tests.utils import ViewTestUtilsMix... | t_student1 = User.objects.create_user('test_student', password=self.test_password)
self.map = baker.make('djcytoscape.CytoScape')
def test_all_page_status_codes_for_anonymous(self):
''' If not logged in then all views should redirect to home page '''
self.assertRedirectsLogin('djcytoscap... | cape:quest_map', args=[1])
self.assertRedirectsLogin('djcytoscape:quest_map_personalized', args=[1, 1])
self.assertRedirectsLogin('djcytoscape:quest_map_interlink', args=[1, 1, 1])
self.assertRedirectsLogin('djcytoscape:list')
self.assertRedirectsAdmin('djcytoscape:regenerate', args=[1]... |
guillon/mdi | examples/mini/scripts/generate_executions.py | Python | mit | 3,906 | 0.003584 | #!/usr/bin/env python
#
# Machine Description Interface C API
#
# This software is delivered under the terms of the MIT License
#
# Copyright (c) 2016 STMicroelectronics
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Softwar... |
from __future__ imp | ort print_function
import sys
class ENUM:
instructions_list = []
def __init__(self, ID, mnemonic, properties, parsing, encoding, short_desc, execution, description):
self.ID = ID
self.mnemonic = mnemonic
self.properties = properties
self.parsing = parsing
self.encoding ... |
Kleptobismol/scikit-bio | skbio/format/sequences/tests/test_fastq.py | Python | bsd-3-clause | 1,232 | 0 | #!/usr/bin/env python
import numpy as np
from unittest import TestCase, main
from skbio.format.sequences import format_fastq_record
from skbio.format.sequences.fastq import _phred_to_ascii33, _phred_to_ascii64
class FASTQFormatTests(TestCase):
def setUp(self):
self.qual_scores = np.array([38, 39, 40], d... | exp = b"@abc\ndef\n+\nGHI\n"
obs = format_fastq_record(*self.args, phred_offset=33)
self.assertEqual(obs, exp)
def test_format_fastq_record_phred_offset_64(self):
exp = b"@abc\ndef\n+\nfgh\n"
obs = format_fastq_record(*self.args, phred_offset=64)
self.assertEqual(obs, exp)... | ef test_phred_to_ascii33(self):
obs = _phred_to_ascii33(self.qual_scores)
self.assertEqual(obs, b'GHI')
def test_phred_to_ascii64(self):
obs = _phred_to_ascii64(self.qual_scores)
self.assertEqual(obs, b'fgh')
if __name__ == '__main__':
main()
|
BenoitDherin/data-analysis-with-R | website/plugins/gzip_cache/gzip_cache.py | Python | mit | 1,902 | 0.002629 | '''
Copyright (c) 2012 Matt Layman
Gzip cache
----------
A plugin to create .gz cache files for optimization.
'''
import gzip
import logging
import os
from pelican import signals
logger = logging.getLogger(__name__)
# A list of file types to exclude from possible compression
EXCLUDE_TYPES = [
# Compressed typ... | ssing: %s' % filepath | )
compressed = gzip.open(compressed_path, 'wb')
compressed.writelines(uncompressed)
except Exception as ex:
logger.critical('Gzip compression failed: %s' % ex)
finally:
compressed.close()
def register():
signals.finalized.connect(create_gzip_cache)
|
kelle/astropy | astropy/vo/client/tests/test_conesearch.py | Python | bsd-3-clause | 9,454 | 0 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Tests for `astropy.vo.client.conesearch` and `astropy.vo.client.async`."""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
# STDLIB
import os
import time
import warnings
# THIRD-PARTY
import... |
assert async_search_all.done()
except AssertionError as exc:
pytest.xfail(str(exc))
else:
for tab in all_results.values():
assert tab.array.size > 0
@pytest.mark.parametrize(('center', 'radius'),
[((SCS_RA, SCS_DEC), ... | re not very accurate but will have to do."""
t_1, tab_1 = conesearch.conesearch_timer(
center, radius, catalog_db=self.url,
pedantic=self.pedantic, verbose=self.verbose)
n_1 = tab_1.array.size
t_2, n_2 = conesearch.predict_search(
self.url, center, radius,
... |
peterayeni/dash | dash/orgs/models.py | Python | bsd-3-clause | 12,481 | 0.001602 | from __future__ import absolute_import, unicode_literals
from datetime import datetime
import json
import random
import pytz
from smartmin.models import SmartModel
from temba import TembaClient
from django.conf import settings
from django.contrib.auth.models import User, Group
from django.core.cache import cache
from... | ue, blank=True, max_length=255, unique=True,
error_messages=dict(unique=_("This domain is not available")),
help_text=_("The custom domain for this organization"))
timezone = models.CharField(
verbose_name=_("Timezone"), max_length=64, default='UTC',
help_te | xt=_("The timezone your organization is in."))
api_token = models.CharField(
max_length=128, null=True, blank=True,
help_text=_("The API token for the RapidPro account this dashboard "
"is tied to"))
config = models.TextField(
null=True, blank=True,
help_tex... |
litui/openparliament | parliament/accounts/models.py | Python | agpl-3.0 | 3,041 | 0.004604 | from base64 import urlsafe_b64encode
import datetime
import os
from django.core import urlresolvers
from django.core.mail import send_mail
from django.db import models
from django.template import loader
from jsonfield import JSONField
class User(models.Model):
email = models.EmailField(unique=True, db_index=Tr... | our email to your browser's address bar.")
if lt.used:
raise TokenError("That login code has already been used. You can request another login email on this page.",
email=lt.email)
if (datetime.datetime.now() - lt.created) > cls.MAX_TOKEN_AGE:
raise TokenError("T... | ter your email again, then click the link within a few hours.", email=lt.email)
lt.login_ip = login_ip
lt.used = True
lt.save()
return lt
|
alexras/bread | docs/source/conf.py | Python | mit | 8,030 | 0.007347 | # -*- coding: utf-8 -*-
#
# Bread documentation build configuration file, created by
# sphinx-quickstart on Wed Aug 7 20:51:04 2013.
#
# 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 c... | n file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML ... | p_basename = 'Breaddoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'prea... |
ganadist/adb_downloader | lib/adb.py | Python | apache-2.0 | 2,027 | 0.008387 | # coding: utf8
import sys, os
import subprocess
class AdbException(Exception):
def __init__(self, code, msg):
Exception.__init__(self, code, msg)
def __repr__(self):
code, msg = self.args
return 'AdbException: code:%s %s'%(code, msg)
class Adb:
SERIAL_NO = None
def adb(f):
... | cmd = f(*args, **kwds)
if not cmd:
cmd = (f.__name__, ) + args
if Adb.SERIAL_NO:
cmd = (g.ADB, '-s', Adb.SERIAL_NO) + cmd
else:
cmd = (g.ADB, ) + cmd
proc = subprocess.Popen(cmd, stdout = subprocess.PIPE)
p... | rn output
return wrap
@staticmethod
@adb
def devices(*args): pass
@staticmethod
@adb
def push(*args): pass
@staticmethod
@adb
def root(*args): pass
@staticmethod
@adb
def shell(*args): pass
@staticmethod
@adb
def forward(src, dst = None):
... |
tabdon/crmeasyapp | crmapp/communications/admin.py | Python | mit | 207 | 0.009662 | from django.contrib import admin
from .models import Communication
class CommunicationAdmin(admin.ModelAdmin):
list_d | isplay = ('subject', 'uui | d')
admin.site.register(Communication, CommunicationAdmin)
|
itielshwartz/BackendApi | lib/pyasn1_modules/pkcs12.py | Python | apache-2.0 | 1,204 | 0.004983 | #
# PKCS#12 syntax
#
# ASN.1 source from:
# ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12.asn
#
# Sample captures could be obtained with "openssl pkcs12" command
#
from pyasn1_modules.rfc2459 import *
from pyasn1_modules import rfc2251
class Attributes(univ.SetOf):
componentType = rfc2251.Attribute()
class... | NamedType('attributes',
Attributes().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0)))
)
class Signature(univ.BitString): pass
class SignatureAlgorithmIdentifier(AlgorithmIdentifier): pass
class CertificationRequest(univ.Sequence):
componentType = ... | natureAlgorithmIdentifier()),
namedtype.NamedType('signature', Signature())
)
|
NeCTAR-RC/horizon | openstack_dashboard/test/integration_tests/tests/test_router.py | Python | apache-2.0 | 8,645 | 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
# d... | ers_page.is_router_active(self.ROUTER_NAME))
self.home_pg.go_to_admin_overviewpage()
admin_routers_page = self.home_pg.go_to_admin_network_routerspage()
self.assertTrue(routers_page.is_router_present(self.ROUTER_NAME))
self.assertTrue(routers_page.is_router_active(self.ROUTER_NAME))
... | self.assertTrue(
admin_routers_page.find_message_and_dismiss(messages.SUCCESS))
self.assertFalse(
admin_routers_page.find_message_and_dismiss(messages.ERROR))
self.assertTrue(
|
whardier/holder.graphics | passenger_wsgi.py | Python | mit | 3,866 | 0.006467 | import os
import tempfile
import re
import bottle
import PIL.Image
import PIL.ImageDraw
import PIL.ImageFont
formats = {
'png': {
'format': 'PNG',
'mimetype': 'image/png'
},
'jpg': {
'format': 'JPEG',
'mimetype': 'image/jpeg'
},
'gif': {
'format': 'GIF',
... | fg_color
except:
pass
try:
if int(guide_color, 16):
guide_color = '#' + guide_color
except:
pass
if not format in | formats:
return bottle.HTTPError(code=404, output="That format is not supported")
image_file = tempfile.NamedTemporaryFile(suffix='.' + format, dir='/home/spencersr/holder.graphics/tmp/images/', delete=True)
image = PIL.Image.new('RGB', size=(width, height), color=bg_color)
draw = PIL.Ima... |
p2pu/learning-circles | studygroups/migrations/0109_auto_20190308_1617.py | Python | mit | 1,852 | 0.00054 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2019-03-08 16:17
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('studygroups', '0108_auto_20181204_0729'),
]
operations = [
migrations.AddFi... | migrations.AddField(
model_name='course',
name='tagdorsement_counts',
field=models.TextField(default='{}'),
),
migrations.AddField(
model_name='course',
name='tagdorsements',
field=models.CharF | ield(blank=True, max_length=256),
),
migrations.AddField(
model_name='course',
name='total_ratings',
field=models.SmallIntegerField(blank=True, null=True),
),
migrations.AddField(
model_name='course',
name='total_reviewers',
... |
bcongdon/Data-Science-Projects | election_tweets/tweet_tokenizer.py | Python | gpl-3.0 | 1,301 | 0.01691 | import re,json
import numpy as | np
import scipy.stats as sp
emoticons_str = r"""
(?:
[ | :=;] # Eyes
[oO\-]? # Nose (optional)
[D\)\]\(\]/\\OpP] # Mouth
)"""
regex_str = [
emoticons_str,
r'<[^>]+>', # HTML tags
r'(?:@[\w_]+)', # @-mentions
r"(?:\#+[\w_]+[\w\'_\-]*[\w_]+)", # hash-tags
r'http[s]?://(?:[a-z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-f][0-9a-f]))+', # URLs
... |
abigailStev/stingray | stingray/pulse/pulsar.py | Python | mit | 25,604 | 0.000273 | """
Basic pulsar-related functions and statistics.
"""
import functools
from collections.abc import Iterable
import warnings
from scipy.optimize import minimize, basinhopping
import numpy as np
import matplotlib.pyplot as plt
from .fftfit import fftfit as taylor_fftfit
from ..utils import simon, jit
from . import HAS... | l exposure for part of the profile.
start_phase = np.fmod(g0 / period, 1)
end_phase = nraw - nper + start_phase
limits = [[start_phase, end_phase]]
# start_phase is always < 1. end_phase not always. In this case...
if end_phase > 1:
limits = [[0, end_phase - 1], [sta... | 1, phs[:, 1] >= l0)
idxs = np.arange(len(phs), dtype=int)[goodbins]
for i in idxs:
start = np.max([phs[i, 0], l0])
stop = np.min([phs[i, 1], l1])
w = stop - start
expo[i] += w
return expo / np.max(expo)
def fold_events(times,... |
notthatbreezy/phl-play | django/phlplay/wsgi.py | Python | apache-2.0 | 452 | 0.002212 | """
WSGI config for gis_photo p | roject.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
from dj_static import Cling, MediaCling
os.environ.setdefault("... | tion())) |
hypriot/compose | tests/unit/project_test.py | Python | apache-2.0 | 8,045 | 0.000994 | from __future__ import unicode_literals
from .. import unittest
from compose.service import Service
from compose.project import Project
from compose.container import Container
from compose import config
import mock
import docker
class ProjectTest(unittest.TestCase):
def test_from_dict(self):
project = Pro... | lf.assertEqual(project.get_service('db').name, 'db')
self.assertEqual(project.get_service('db').options['image'], 'busybox:latest')
def test_get_service(self):
web = Service(
project='composetest',
| name='web',
client=None,
image="busybox:latest",
)
project = Project('test', [web], None)
self.assertEqual(project.get_service('web'), web)
def test_get_services_returns_all_services_without_args(self):
web = Service(
project='composetest',
... |
ricsatjr/mplstereonet | mplstereonet/contouring.py | Python | mit | 9,471 | 0.002428 | import numpy as np
from . import stereonet_math
def _count_points(lons, lats, func, sigma, gridsize=(100,100), weights=None):
"""This function actually calculates the point density of the input ("lons"
and "lats") points at a series of counter stations. Creates "gridsize"
regular grid of counter stations i... | g circle comprising 1% of the total area of the
| hemisphere. Does not take into account sample size. Units are in
points per 1% area.
sigma : int or float, optional
The number of standard deviations defining the expected number of
standard deviations by which a random sample from a uniform
distribution of points would be ex... |
dps/simplescheduler | tests/test_scheduler.py | Python | bsd-2-clause | 2,897 | 0.041767 | # -*- coding: utf-8 -*-
from simplescheduler import Scheduler, Job
from datetime import timedelta
import unittest
class FakeRedis(object):
def __init__(self):
self._r = {}
self._ledger = []
def sadd(self, key, member):
self._ledger.append('SADD %s:%s' % (key, member))
if n... | )
l = sorted(self._r[key], key=lambda x:x[0])
r = []
for i in l:
if i[0] >= start and i[0] <= end:
r.append | (i)
for remove in r:
self._r[key].remove(remove)
return len(r)
def expire(self, key, seconds):
self._ledger.append('EXPIRE %s %d' % (key, seconds))
def clear_ledger(self):
self._ledger = []
def get_ledger(self):
return self._ledger
job_data = {}
def job1():
print 'job... |
dcorbacho/libcloud | libcloud/test/compute/test_digitalocean_v2.py | Python | apache-2.0 | 11,147 | 0.000179 | # 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 use ... | est_create_key_pair(self):
DigitalOceanMockHttp.type = 'CREATE'
key = self.driver.create_key_pair(
name="test1",
public_key="ssh-rsa AAAAB3NzaC1yc2EAAAADAQsxRiUKn example"
)
self.assertEqual(key.name, "test1")
self.assertEqual(key.fingerprint,
... | f.driver.list_key_pairs()[0]
result = self.driver.delete_key_pair(key)
self.assertTrue(result)
def test__paginated_request_single_page(self):
nodes = self.driver._paginated_request('/v2/droplets', 'droplets')
self.assertEqual(nodes[0]['name'], 'example.com')
self.assertEqual... |
MDXDave/ModernWebif | plugin/controllers/ER.py | Python | gpl-2.0 | 2,362 | 0.019475 | # -*- coding: utf-8 -*-
##############################################################################
# 2013 E2OpenPlugins #
# #
# This file is open source software; you can redistribute... | add', EPGRefreshAddRemoveServiceResource(EPGRefreshAddRemoveServiceResource.TYPE_ADD))
self.putChild('del', EPGRefreshAddRemoveServiceResource(EPGRefreshAddRemoveServiceResource.TYPE_DEL))
try:
from Plugins.Extensions.EPGRefresh.EPGRefreshResource import EPGRefreshPreviewServicesResource
except ImportError:
... | request):
request.setResponseCode(http.OK)
request.setHeader('Content-type', 'application/xhtml+xml')
request.setHeader('charset', 'UTF-8')
try:
from Plugins.Extensions.EPGRefresh.EPGRefresh import epgrefresh
request.setHeader('Content-type', 'application/xhtml+xml')
request.setHeader('charset', 'UTF-... |
CodeforLeipzig/fog | fog/config/settings/public.py | Python | bsd-3-clause | 1,254 | 0.001595 | from configurations import values
from . import common, databases, email
from .. import __version__
class Raven(object):
"""Report uncaught exceptions to the Sentry server."""
INSTALLED_APPS = common.Common.INSTALLED_APPS + ('raven.contrib.django.raven_compat',)
RAVE | N_CONFIG = {
'dsn': values.URLValue(environ_name='RAVEN_CONFIG_DSN'),
'release': __version__,
}
class Sentry404(Raven):
"""Log 404 events to the Sentry server."""
MIDDLEWARE_CLASSES = (
| 'raven.contrib.django.raven_compat.middleware.Sentry404CatchMiddleware',
) + common.Common.MIDDLEWARE_CLASSES
class Public(email.Email, databases.Databases, common.Common):
"""General settings for public projects."""
SECRET_KEY = values.SecretValue()
CSRF_COOKIE_HTTPONLY = True
SECURE_BROWSER_... |
riolet/SAM | spec/python/test_server.py | Python | gpl-3.0 | 3,851 | 0.000519 | from spec.python import db_connection
import sam.common
import sam.constants
import web
app = web.application(sam.constants.urls, globals(), autoreload=False)
sam.common.session_store = web.session.DBStore(db_connection.db, 'sessions')
sam.common.session = web.session.Session(app, sam.common.session_store)
# TODO: th... | s ping the prod server instead of the test server for the session table.
# If the prod server is missing, these fail.
# I'm not sure why they do that.
def test_404():
with db_connection.env(login_active=False):
req = app.request('/invalidendpoint', method='GET')
assert req.status == "40... | ound"
def test_exists_map():
with db_connection.env(login_active=False):
req = app.request('/map', method='POST')
assert req.status == "405 Method Not Allowed"
req = app.request('/map?q=42', method='GET')
assert req.status == "200 OK"
def test_exists_stats():
with db_connecti... |
jdemel/gnuradio | gr-channels/python/channels/impairments.py | Python | gpl-3.0 | 4,926 | 0.004669 | #!/usr/bin/env python
##################################################
# Gnuradio Python Flow Graph
# Title: Radio Impairments Model
# Author: mettus
# Generated: Thu Aug 1 12:46:10 2013
##################################################
from __future__ import absolute_import
from __future__ import division
from __... | mport firdes
import math
#Import locally
from .phase_noise_gen import phase_noise_gen
from .iqbal_gen import iqbal_gen
from .distortion_2_gen import distortion_2_gen
from .distortion_3_gen import distortion_3_gen
class impairments(gr.hier_block2):
def __init__(self, phase_noise_mag=0, mag | bal=0, phasebal=0, q_ofs=0, i_ofs=0, freq_offset=0, gamma=0, beta=0):
gr.hier_block2.__init__(
self, "Radio Impairments Model",
gr.io_signature(1, 1, gr.sizeof_gr_complex*1),
gr.io_signature(1, 1, gr.sizeof_gr_complex*1),
)
###################################... |
wavefrontHQ/python-client | wavefront_api_client/models/response_status.py | Python | apache-2.0 | 5,837 | 0.000171 | # coding: utf-8
"""
Wavefront REST API Documentation
<p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the W... | ResponseStatus(object):
"""NOTE: This class is auto generated by the swagger code generator program | .
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
... |
bendtherules/pontoon | pontoon/mocking.py | Python | mit | 9,262 | 0.002483 | # -*- coding: utf-8 -*-
import re
import sys
import contextlib
from random import randrange
from datetime import datetime, timedelta
from .exceptions import ClientException
# Python 2/3 compatibility for capture_stdout
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
class Dat... | {
'id': 4, 'name': 'Bar 6.0 x32', 'distribution': 'Bar',
},
],
'snapshots': [
{
'id': 1024, 'name': 'snapshot-foo',
'distribution': 'Foobuntu',
},
{
'id': 2048, 'name | ': 'snapshot-bar-2013-10-10',
'distribution': 'Foobuntu',
},
{
'id': 4096, 'name': 'snapshot-baz-pre-install',
'distribution': 'Foobuntu',
},
],
'sizes': [
{
'id': 1, 'name': '512MB',
},
{
'id': 2, 'name'... |
blancltd/blanc-basic-news | blanc_basic_news/feeds.py | Python | bsd-3-clause | 1,350 | 0.001481 | from django.conf import settings
from django.contrib.sites.models import Site
from django.contrib.syndication.views import Feed
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import get_object_or_404
from django.utils import timezone
from .models import Category, Post
class BasicNewsFeed(Fee... | date(self, obj):
return obj.date
def item_guid(self, obj):
return '%s:news:%d' % (Site.objects.get_current().domain, obj.pk)
class Basic | NewsCategoryFeed(BasicNewsFeed):
def get_object(self, request, slug):
return get_object_or_404(Category, slug=slug)
def title(self, obj):
return '%s - %s' % (getattr(settings, 'NEWS_TITLE', 'News'), obj.title)
def link(self, obj):
return obj.get_absolute_url()
def items(self, ... |
babyliynfg/cross | tools/project-creator/Python2.6.6/Lib/idlelib/ScriptBinding.py | Python | mit | 7,992 | 0.000375 | """Extension to execute code outside the Python shell window.
This adds the following commands:
- Check module does a full syntax check of the current module.
It also runs the tabnanny to catch any inconsistent tabs.
- Run module executes the module's code in the __main__ namespace. The window
must have... |
message=msg,
icon=tkMessageBox.QUESTION,
| type=tkMessageBox.OKCANCEL,
default=tkMessageBox.OK,
master=self.editwin.text)
return mb.show()
def errorbox(self, title, message):
# XXX This should really be a function of EditorWindow...
... |
scheib/chromium | testing/trigger_scripts/PRESUBMIT.py | Python | bsd-3-clause | 883 | 0 | # Copyright 2015 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.
"""Top-level presubmit script for testing/trigger_scripts.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about... | .
"""
USE_PYTHON3 = True
def CommonChecks(input_api, output_api):
return input_api.canned_checks.RunUnitTestsInDirectory(
input_api,
output_api,
'.',
files_to_check=['.*test.py'],
run_on_python2=not USE_PYTHON3,
run_on_python3=USE_PYTHON3,
skip_shebang_ch | eck=True)
def CheckChangeOnUpload(input_api, output_api):
return CommonChecks(input_api, output_api)
def CheckChangeOnCommit(input_api, output_api):
return CommonChecks(input_api, output_api)
|
koenbok/Cactus | cactus/tests/data/skeleton/plugins/version.py | Python | bsd-3-clause | 1,339 | 0.004481 | from __future__ import print_function
import os
INFO = {
'name': 'Version | Updater',
'description': 'Add a version to /versions.txt after each deploy'
}
# Set up extra django template tags
def templateTags():
pass
# Build actions
# def preBuild(site):
# print 'preBuild'
#
# def postBuild(site):
# print 'postBuild'
# Build page actions
# def preBuildPage(site, pa... |
def preDeploy(site):
# Add a deploy log at /versions.txt
import urllib2
import datetime
import platform
import codecs
import getpass
url = site.config.get('aws-bucket-website')
data = u''
# If this is the first deploy we don't have to fetch the old file
if url:
try:
... |
pombredanne/similarityPy | tests/algorihtm_tests/find_nearest_test.py | Python | mit | 651 | 0.001536 | from unittest import TestCase
from similarityPy.algorithms.find_nearest import FindNearest
from tests import te | st_logger
__author__ = 'cenk'
class FindNearestTest(TestCase):
def setUp(self):
pass
def test_algorithm(self):
test_logger.debug("FindNearestTest - test_algorithm Starts")
points = "abcdef"
point = "abcdefg"
with self.assertRaises(TypeError) as context:
... | context.exception.message)
test_logger.debug("FindNearestTest - test_algorithm Starts") |
pipermerriam/flex | tests/loading/definition/schema/test_read_only.py | Python | mit | 1,126 | 0 | import pytest
from flex.constants import (
STRING,
BOOLEAN,
INTEGER,
)
from flex.error_messages import MESSAGES
from flex.exceptions import ValidationError
from flex.loading.definitions.schema import schema_validator
from tests.utils import (
assert_path_no | t_in_er | rors,
assert_message_in_errors,
)
def test_read_only_is_not_required():
try:
schema_validator({})
except ValidationError as err:
errors = err.detail
else:
errors = {}
assert_path_not_in_errors('readOnly', errors)
@pytest.mark.parametrize(
'value',
(None, {'a': 1}... |
plotly/plotly.py | packages/python/plotly/plotly/validators/histogram2d/_xsrc.py | Python | mit | 388 | 0.002577 | import _plotly_utils.basevalidators
class XsrcValidator(_plotly_utils.basevalidators.SrcValidator):
| def __init__(self, plotly_name="xsrc", parent_name="histogram2d", **kwargs):
super(XsrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "none"),
| **kwargs
)
|
kshcherban/acme-nginx | acme_nginx/DigitalOcean.py | Python | gpl-3.0 | 3,177 | 0.000315 | import json
from os import getenv
try:
from urllib.request import urlopen, Request # Python 3
from urllib.error import HTTPError
except ImportError:
from urllib2 import urlopen, Request # Python 2
from urllib2 import HTTPError
class DigitalOcean(object):
def __init__(self):
self.token =... | ) != 200:
raise Exception(json.loads(response.read().decode("utf8")))
domains = json.loads(response.read().decode("utf8"))["domains"]
for d in domains:
if d["name"] in domain:
return d["name"]
def create_record(self, name, data, domain):
"""
C... | record data
domain, string, dns domain
Return:
record_id, int, created record id
"""
registered_domain = self.determine_domain(domain)
api = self.api + "/" + registered_domain + "/records"
request_headers = {
"Content-Type": "application/json",... |
kwilliams-mo/iris | lib/iris/tests/test_pp_to_cube.py | Python | gpl-3.0 | 10,648 | 0.001784 | # (C) British Crown Copyright 2010 - 2013, Met Office
#
# This file is part of Iris.
#
# Iris is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any l... | iris.load_cube(data_path)
self.assertEqual(cube.standard_name, 'air_temperature')
def test_cell_methods(self):
# Test cell methods are created for correct values of lbproc
orig_file = tests.get_data_path(('PP', 'aPPglob1', 'global.pp'))
# Values that result in cell methods being cr... | , 8192 : "maximum"}
# Make test values as list of single bit values and some multiple bit values
single_bit_values = list(iris.fileformats.pp.LBPROC_PAIRS)
multiple_bit_values = [(128 + 64, ""), (4096 + 2096, ""), (8192 + 1024, "")]
test_values = list(single_bit_values) + multiple_bit_v... |
lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_08_01/models/route_filter_py3.py | Python | mit | 2,701 | 0.002962 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | 'type': {'readonly': True},
'provisioning_state': {'readonly': True},
'etag': {'readonly': True},
}
_attribute_map = {
'id': {'key': | 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'rules': {'key': 'properties.rules', 'type': '[RouteFilterRule]'},
'peerings': ... |
chregu/cf-php-varnish-buildpack | extensions/composer/extension.py | Python | apache-2.0 | 16,172 | 0.000804 | # 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 use ... | oads, installs and runs Composer.
"""
import os
import os.path
import sys
import logging
import re
import json
import StringIO
from build_pack_utils import utils
from build_pack_utils import stream_output
from extension_helpers import ExtensionHelper
from build_pack_utils.compile_extens | ions import CompileExtensions
_log = logging.getLogger('composer')
def find_composer_paths(ctx):
build_dir = ctx['BUILD_DIR']
webdir = ctx['WEBDIR']
json_path = None
lock_path = None
json_paths = [
os.path.join(build_dir, 'composer.json'),
os.path.join(build_dir, webdir, 'compos... |
EnTeQuAk/dotfiles | sublime-text-3/Packages/shellenv/all/shellenv/_osx/open_directory.py | Python | unlicense | 4,675 | 0.001497 | # coding: utf-8
from __future__ import unicode_litera | ls, division, absolute_import, print_function
from getpass import getuser
import ctypes
from ctypes.util import find_library
from ctypes import c_voi | d_p, c_uint32, POINTER, c_bool, byref
from .core_foundation import CoreFoundation, unicode_to_cfstring, cfstring_to_unicode
from .._types import str_cls, type_name
od_path = find_library('OpenDirectory')
OpenDirectory = ctypes.CDLL(od_path, use_errno=True)
ODAttributeType = CoreFoundation.CFStringRef
ODMatchType = ... |
pytest-dev/pytest | scripts/publish-gh-release-notes.py | Python | mit | 3,049 | 0.001968 | """
Script used to publish GitHub release notes extracted from CHANGELOG.rst.
This script is meant to be executed after a successful deployment in GitHub actions.
Uses the following environment variables:
* GIT_TAG: the name of the tag of the current commit.
* GH_RELEASE_NOTES_TOKEN: a personal access token with 're... | "doc/en/changelog.rst"
changelog_lines = p.read_text(encoding="UTF-8").splitlines()
title_regex = re.compile(r"pytest (\d\.\d+\.\d+) \(\d{4}-\d{2}-\d{2}\)")
consuming_version = False
version_lines = []
for line in changelog_lines:
m = title_regex.match(line)
if m:
# foun... | to consume lines until we find the next version title
if m.group(1) == tag_name:
consuming_version = True
# found a new version title while parsing the version we want: break out
elif consuming_version:
break
if consuming_version:
v... |
blckshrk/Weboob | modules/vlille/test.py | Python | agpl-3.0 | 1,148 | 0.000871 | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Bezleputh
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your opt... | .
from weboob.tools.test import BackendTest
class Vlille | Test(BackendTest):
BACKEND = 'vlille'
def test_vlille(self):
l = list(self.backend.iter_gauges())
self.assertTrue(len(l) > 0)
gauge = l[0]
s = list(self.backend.iter_sensors(gauge))
self.assertTrue(len(s) > 0)
sensor = s[0]
self.assertTrue(self.backend.... |
gnocchixyz/gnocchi | gnocchi/tests/test_carbonara.py | Python | apache-2.0 | 38,695 | 0 | # -*- encoding: utf-8 -*-
#
# Copyright © 2014-2016 eNovance
#
# 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... | reed 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 datetime
import functools
import math
import operator
import fixtures
import iso8601
import numpy
import six
from ... |
luotao1/Paddle | python/paddle/fluid/tests/unittests/test_op_function_generator.py | Python | apache-2.0 | 3,921 | 0.000255 | # Copyright (c) 2018 PaddlePaddle 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 app... | = False
res1 = layers.elementwise_add(x, y)
res2 = _C_ops.elementwise_add(x, y)
self.assertTrue(np.array_eq | ual(res1.numpy(), res2.numpy()))
def test_elementwise_mul(self):
with fluid.dygraph.guard():
a = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
b = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
x = fluid.dygraph.to_variable(a)
y = fluid.d... |
Micronaet/micronaet-sql | base_mssql_accounting/__openerp__.py | Python | agpl-3.0 | 1,509 | 0.001988 | # -*- coding: utf-8 -*-
###############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2001-2015 Micronaet S.r.l. (<http://www.micronaet.it>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the... | ##############################################
{
'name': 'Base MS SQL import accounting',
'version': '0.0.1',
'category': 'Generic Modules/Customization',
'description': """
MS SQL acco | unting ETL module:
provide query for open standar import tables
""",
'author': 'Micronaet s.r.l.',
'website': 'http://www.micronaet.it',
'depends': [
'base',
'base_mssql',
'product',
],
'init_xml': [],
'data': ['security/ir.model.access.csv', ],
'... |
kapy2010/treeherder | tests/webapp/api/test_job_log_url_api.py | Python | mpl-2.0 | 1,524 | 0 | from django.core.urlresolvers import reverse
from tests.test_utils import create_generic_job
from treeherder.model.models import JobLog
def test_get_job_log_urls(test_repository, result_set_stored,
failure_classifications,
generic_reference_data, webapp):
job1 ... | 'http://yahoo.com',
status=JobLog.PARSED)
resp = webapp.get(reverse('job-log-url-list',
kwargs={"project": test_repository.na | me}) +
'?job_id=1')
assert resp.status_int == 200
assert len(resp.json) == 2
resp = webapp.get(reverse('job-log-url-list',
kwargs={"project": test_repository.name}) +
'?job_id=1&job_id=2')
assert resp.status_int == 200
assert len(res... |
otlet/JestemGraczem.pl | stream/url_converters.py | Python | agpl-3.0 | 584 | 0.003425 | # path('mixer/(?P<username>v+)/', views.mixer, name='stream.mixer'),
# p | ath('twitch/(?P<username>[a-zA-Z0-9_]+)/', views.twitch, name='stream.twitch'),
# path('live/', cache_page(60 * 1)(views.stream_api), name='stream.live'),
# path('live/esport', cache_page(60 * 10)(views.esport_stream_api), name='stream.live.esport'),
# path('(?P<username>[a-zA-Z0-9_]+)/', views.streamer,... | return int(value)
def to_url(self, value):
return str(value)
|
huggingface/transformers | src/transformers/models/deberta/tokenization_deberta.py | Python | apache-2.0 | 10,189 | 0.004318 | # coding=utf-8
# Copyright 2020 Microsoft and the HuggingFace Inc. team.
#
# 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... | ist[int]`, *optional*):
Optional second list of IDs for s | equence pairs.
Returns:
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
"""
if token_ids_1 is None:
return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
cls = [self.cls_token_id]
sep = [self.sep_token... |
mfraezz/osf.io | osf/management/commands/addon_deleted_date.py | Python | apache-2.0 | 3,358 | 0.001787 | import datetime
import logging
from django.core.management.base import BaseCommand
from django.db import connection, transaction
from framework.celery_tasks import app as celery_app
logger = logging.getLogger(__name__)
TABLES_TO_POPULATE_WITH_MODIFIED = [
'addons_zotero_usersettings',
'addons_dropbox_userset... | settings',
'addons_datave | rse_usersettings',
'addons_s3_nodesettings',
'addons_s3_usersettings',
'addons_twofactor_usersettings',
'addons_wiki_nodesettings',
'addons_zotero_nodesettings'
]
UPDATE_DELETED_WITH_MODIFIED = """UPDATE {} SET deleted=modified
WHERE id IN (SELECT id FROM {} WHERE is_deleted AND deleted IS NULL... |
spookylukey/django-nyt | setup.py | Python | apache-2.0 | 2,187 | 0.000914 | from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
# -*- coding | : utf-8 -*-
import os
from django_nyt import VERSION
from setuptools import setup, find_packages
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to typ | e in the README file than to put a raw
# string in below ...
def get_path(fname):
return os.path.join(os.path.dirname(os.path.abspath(__file__)), fname)
def read(fname):
return open(get_path(fname)).read()
packages = find_packages()
try:
import pypandoc
long_description = pypandoc.convert(get_path... |
bptripp/grasp-convnet | py/visualize.py | Python | mit | 741 | 0.012146 | __author__ = 'bptripp'
import numpy as np
import matplotlib.pyplot as plt
def plot_kernels(weights):
print(weights.shape)
side = int(np.ceil(np.sqrt(weights.shape[0])))
print(side)
plt.figure()
for i in range(weights.shape[0]):
plt.subplot(side,side,i)
plt.imshow(weights[i,0,:,:])... | plotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D
im_width = matrix.shape[0]
fig = plt.figure()
X = np.arange(0, im_width)
Y = np.arange(0, im_width)
X, Y = np.meshgrid(X, Y)
ax = fig.add_subplot(1,1,1,proj | ection='3d')
ax.plot_wireframe(X, Y, matrix)
plt.show()
|
dvu4/Data-Wrangling-with-MongoDB | Lesson_5_Analyzing_Data/14-Using_push/push.py | Python | agpl-3.0 | 2,726 | 0.012839 | #!/usr/bin/env python
"""
$push is similar to $addToSet. The difference is that rather than accumulating only unique values
it aggregates all values into an array.
Using an aggregation query, count the number of tweets for each user. In the same $group stage,
use $push to accumulate all the tweet texts for each user... | {
"_id" : "$user.screen_name",
"tweet_texts" :{"$push" : "$text"},
"count" : {"$sum" : 1}
}
},
{
"$sort" :
{
"count" : -1
}
},
{
... | db('twitter')
pipeline = make_pipeline()
result = aggregate(db, pipeline)
assert len(result["result"]) == 5
assert result["result"][0]["count"] > result["result"][4]["count"]
import pprint
pprint.pprint(result)
|
ungarj/mapchete | mapchete/io/_geometry_operations.py | Python | mit | 10,253 | 0.000975 | from fiona.transform import transform_geom
import logging
import pyproj
from rasterio.crs import CRS
from shapely.errors import TopologicalError
from shapely.geometry import (
box,
GeometryCollection,
shape,
mapping,
MultiPoint,
MultiLineString,
MultiPolygon,
Polygon,
LinearRing,
... | """
Segmentize Polygon outer ring by segmentize value.
Just Polygon geometry type supported.
Parameters
----------
geometry : ``shapely.geometry``
segmentize_value: float
Returns
-------
geometry : ``shapely.geometry``
"""
if geometry.geom_type != "Polygon":
ra... | p
# pick polygon linestrings
for l in map(
lambda x: LineString([x[0], x[1]]),
zip(geometry.exterior.coords[:-1], geometry.exterior.coords[1:]),
)
# interpolate additional points in between and don't fo... |
nekia/incubator-superset-dev | superset/connectors/sqla/views.py | Python | apache-2.0 | 11,596 | 0.000604 | """Views used by the SqlAlchemy connector"""
import logging
from past.builtins import basestring
from flask import Markup, flash, redirect
from flask_appbuilder import CompactCRUDMixin, expose
from flask_appbuilder.models.sqla.interface import SQLAInterface
import sqlalchemy as sa
from flask_babel import lazy_gettex... | ssion as supported by the underlying backend. "
"Example: `count(DISTINCT userid)`", True),
'is_restricted': _("Whether the access to this metric is restricted "
"to certain roles. Only roles with the permission "
"'metric access on XXX (the name... | 'd3format': utils.markdown(
"d3 formatting string as defined [here]"
"(https://github.com/d3/d3-format/blob/master/README.md#format). "
"For instance, this default formatting applies in the Table "
"visualization and allow for different metric to use different "
... |
gohackfelipe/luiza | luiza.py | Python | mit | 1,285 | 0.007004 | import asyncio
import sys
import config
import sender
import receiver
print(sys.argv)
async def receiveMessageFromSerial():
return "Message"
def help():
print('Luiza 1.0 - ([email protected])')
p | rint('Usage: python3 app.py [Options][Message][source][dest]')
print('')
print('SENDING MESSAGE')
print(' You will send a message from source to dest. 3 containing the text "Sending Message from | Luiza"')
print(' python3 app.py --send "Sending Message from Luiza" 1 3')
print('RECEIVING MESSAGE')
print(' You will receive a message using the address 3')
print(' python3 app.py --read 3')
quit()
if len(sys.argv) == 1:
help()
if(sys.argv[1] == '--send'):
if len(sys.argv) < 3:... |
googleapis/python-aiplatform | .sample_configs/param_handlers/predict_sample.py | Python | apache-2.0 | 1,015 | 0.003941 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | he specific language governing permissions and
# limitations under the License.
#
def make_endpoint(endpoint: str) -> str:
endpoint = endpoint
return endpoint
def make_instances(instance_dict: Dict) -> typing.Sequence[google.protobuf.struct_pb2.Value]:
in | stance = to_protobuf_value(instance_dict)
instances = [instance]
return instances
def make_parameters() -> google.protobuf.struct_pb2.Value:
parameters_dict = {}
parameters = to_protobuf_value(parameters_dict)
return parameters
|
SunDwarf/KCProxy | config_gunicorn.py | Python | mit | 712 | 0.001404 | import multiprocessing
bind = "0.0.0.0:7869"
workers = multiprocessing.cpu_count() * 2 + 1
# Choose one as appropriate.
# worker_class = "sync"
# worker_class = "eventlet"
# worker_class = "gevent"
# worker_class = "tornado"
| worker_class = "gthread"
# Change to true to enable daemonising.
daemon = False
# Change to specify the user gunicorn will run as.
# user = "nobody"
# Change to specify the group gunicorn will run as.
# group = "nogroup"
# SSL settings.
# If you are running the server without a reverse proxy (nginx or apache), this... | def when_ready(server):
print("Server ready on address {}.".format(bind))
|
kineticadb/kinetica-api-python | gpudb/packages/avro/avro_py3/tool.py | Python | mit | 5,599 | 0.012859 | #!/usr/bin/env python3
# -*- mode: python -*-
# -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you... | en(args[6], 'rb')
datum_reader = io.DatumReader()
dfr = datafile.DataFileReader(reader, datum_reader)
datum = dfr.next()
elif args[5] == "-data":
print("JSON Decoder not yet implemented.")
return 1
else:
| print(usage_str)
return 1
run_server(uri, proto, msg, datum)
elif args[1] == "rpcsend":
usage_str = "Usage: %s rpcsend uri protocol_file " % args[0]
usage_str += "message_name (-data d | -file f)"
if len(args) not in [5, 7]:
print(usage_str)
return 1
uri, proto, msg = args[2:5... |
zurfyx/simple | simple/projects/activities/abstract_models.py | Python | mit | 2,648 | 0 | from django.db import models
from django.utils import timezone
from config import constants as globalConstants
from core.fields import RestrictedFile
from projects.abstract_models import AbstractTimeStamped
from projects.models import Project
from users.models import User
class AbstractProjectActivity(AbstractTimeSt... | =200, unique=True)
body = models.CharField(max_length=2000, blank=True, null=True)
start_date = models.DateTimeField()
due_date = models.DateTimeField()
responses = models.ManyToManyField(User, through='ProjectActivityResponse',
related_name='responded_activity')
... | def is_closed(self):
now = timezone.now()
return now < self.start_date or now > self.due_date
def __str__(self):
return self.title
class Meta:
abstract = True
verbose_name_plural = 'project activities'
class AbstractProjectActivityAttachment(models.Model):
activit... |
andrewv587/pycharm-project | myFCN/myVgg16.py | Python | apache-2.0 | 3,915 | 0.001277 | # -*- coding: utf-8 -*-
"""VGG16 model for Keras.
# Reference
- [Very Deep Convolutional Networks for Large-Scale Image Recognition](https://arxiv.org/abs/1409.1556)
"""
from __future__ import absolute_import
from __future__ import print_function
from keras.engine import Input
from keras.engine import Model
from ke... | lock1_conv2(x)
x = self.block1_poo | l(x)
x = self.block2_conv1(x)
l2 = x
x = self.block2_conv2(x)
x = self.block2_pool(x)
x = self.block3_conv1(x)
l3 = x
x = self.block3_conv2(x)
c = x
x = self.block3_conv3(x)
x = self.block3_pool(x)
x = self.block4_conv1(x)
... |
kansanmuisti/kamu | utils/populate-cms.py | Python | agpl-3.0 | 4,030 | 0.001985 | #!/usr/bin/python
# A script to write initial content data into database
import sys
import os
import codecs
from datetime import datetime
from django.core.management import setup_environ
my_path = os.path.abspath(os.path.dirname(__file__))
kamu_path = os.path.normpath(my_path + '/..')
# Change this if you have your... | )
mtime = datetime.fromtimestamp(os.path.getmtime(full_fname))
if revision and revision.date >= mtime:
print("\tSkipping based on file mtime")
| return
f = codecs.open(full_fname, mode="r", encoding="utf8")
if category_name == "news":
# Newsfiles contain the subject as first line
subject = f.readline()[:-1]
# Summary is defined as being all the text after subject until
# marker "[full]" alone at the beginning of line... |
HumanBrainProject/neuroglancer-scripts | src/neuroglancer_scripts/file_accessor.py | Python | mit | 6,613 | 0 | # Copyright (c) 2016, 2017, 2018 Forschungszentrum Juelich GmbH
# Author: Yann Leprince <[email protected]>
#
# This software is made available under the MIT licence, see LICENCE.txt.
"""Access to a Neuroglancer pre-computed dataset on the local filesystem.
See the :mod:`~neuroglancer_scripts.accessor` module ... | _coords),
self.base_path, exc)) from e | xc
def store_chunk(self, buf, key, chunk_coords,
mime_type="application/octet-stream",
overwrite=True):
chunk_path = self._chunk_path(key, chunk_coords)
mode = "wb" if overwrite else "xb"
try:
os.makedirs(str(chunk_path.parent), exist_ok=T... |
sqlalchemy/alembic | alembic/migration.py | Python | mit | 41 | 0 | from .runtime.migration | import * # noqa
| |
UManPychron/pychron | pychron/envisage/tasks/editor_task.py | Python | apache-2.0 | 6,344 | 0.000631 | # ===============================================================================
# Copyright 2013 Jake Ross
#
# 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... | ditor_area.active_editor')
editor_area = Instance(IEditorAreaPane)
def set_editor_layout(self, layout):
ea = self.editor_area
| ea.set_layout(layout)
def split_editors(self, a, b, h1=-1, h2=-1, orientation='horizontal'):
layout = Splitter(PaneItem(id=a, height=h1),
PaneItem(id=b, height=h2),
orientation=orientation)
self.set_editor_layout(layout)
def db_save_inf... |
zhimin711/nova | nova/tests/unit/objects/test_image_meta.py | Python | apache-2.0 | 12,384 | 0.000242 | # Copyright 2014 Red Hat, 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 agreed to in writing, ... | si',
},
'size': 213581824,
'name': 'f16-x86_64-openstack-sda',
'checksum': '755122332caeb9f661d5c978adb8b45f',
'created_at': '2014-12-10T16:23:14.000000',
'disk_format': 'qcow2',
'id': 'c8b1790e-a07d-4... | m_dict(image)
self.assertEqual('active', image_meta.status)
self.assertEqual('bare', image_meta.container_format)
self.assertEqual(0, image_meta.min_ram)
self.assertIsInstance(image_meta.updated_at, datetime.datetime)
self.assertEqual(0, image_meta.min_disk)
self.assertE... |
pglauner/misc | src/cs212/pig_game.py | Python | gpl-2.0 | 3,539 | 0.003956 | '''
Created on Oct 12, 2013
@author: pglauner
'''
import random
from my_decorators import memo
from uncertainty import best_action
goal = 40
other = {1:0, 0:1}
def roll(state, d):
"""Apply the roll action to a state (and a die roll d) to yield a new state:
If d is 1, get 1 point (losing any accumulated 'pe... | )):
"""Play a game of pig between two players, represented by their strategies.
Each time through the main loop we ask the current player for one decision,
which must be 'hold' or 'roll', and we update the state accord | ingly.
When one player's score exceeds the goal, return that player."""
strategies = [A, B]
state = (0, 0, 0, 0)
while True:
(p, me, you, _) = state
if me >= goal:
return strategies[p]
elif you >= goal:
return strategies[other[p]]
else:
... |
dallascard/guac | core/lda/lda_preprocessing.py | Python | apache-2.0 | 4,593 | 0.004137 | from optparse import OptionParser
import re
import os
import sys
import numpy as np
from ..util import dirs
from ..util import file_handling as fh
from ..preprocessing import data_splitting as ds
from ..feature_extractors.vocabulary_with_counts import VocabWithCounts
def main():
usage = "%prog project"
pars... | 0
for k in documents:
tokens = [t for t in tokenized[k] if t in vocab.token2index]
n_words += len(tokens)
tokenized[k] = tokens
n_documents = len(documents)
| n_vocab = len(vocab)
print n_documents, "documents"
print n_vocab, "word types"
print n_words, "word tokens"
# create the count matrices
vocab_assignments = np.zeros(n_words, dtype=int) # vocab index of the ith word
#topic_assignments = np.zeros(n_words, dtype=int) # topic of the i... |
opennode/nodeconductor-assembly-waldur | src/waldur_openstack/openstack_tenant/migrations/0016_internalip_device_info.py | Python | mit | 605 | 0 | # Generated by Django 2.2.13 on 2021-01-12 11:54
from | django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('openstack_tenant', '0015_add_fixed_ips'),
]
operations = [
migrations.AddField(
model_name='internalip',
name='device_id',
field=models.CharField(blank=True,... | Field(blank=True, max_length=100, null=True),
),
]
|
knights-lab/NINJA-DOJO | dojo/scripts/extract_ncbi_tid_from_mp2_gold.py | Python | gpl-2.0 | 1,651 | 0.001817 | #!/usr/bin/env python
import os
from collections import defaultdict
from glob import glob
import click
import csv
from ninja_utils.parsers import FASTQ
from dojo.taxonomy.maps import RefseqCatalogMap
@click.command()
@click.argument('path', type=click.Path(exists=True))
@click.option('-v', '--verbose', is_flag=Tru... | r = header.split('|')
if len(header_arr) > 3:
refseq_acc = header_arr[3]
acc = refseq_acc[:refseq_acc.find('.')]
tid = rf.refseq_accession2ncbi_tid[acc] |
if not tid == 0:
outf.write('@ncbi_tid|%s|%s\n' % (tid, header))
outf.write(seq + '\n')
outf.write('+\n%s\n' % qual)
tid_counts[tid] += 1
with open(os.path.join(path, '%s.nin... |
0vercl0k/rp | src/third_party/beaengine/tests/0f3a0b.py | Python | mit | 2,498 | 0.000801 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# 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... | F3A.WIG 0b /r ib
# Vroundsd xmm1, xmm2, xmm3/m64, imm8
myVEX = VEX('VEX.LIG.66.0F3A.WIG')
Buffer = bytes.fromhex('{}0b1033'.format(myVEX.c4()))
myDisasm = Disasm(Buffer)
myDisasm.r | ead()
assert_equal(myDisasm.infos.Instruction.Opcode, 0x0b)
assert_equal(myDisasm.infos.Instruction.Mnemonic, b'vroundsd')
assert_equal(myDisasm.repr(), 'vroundsd xmm10, xmm0, qword ptr [r8], 33h')
# EVEX.LIG.66.0F3A.W0 0b /r ib
# VRNDscalesd xmm1 {k1}{z}, xmm2, xmm3/m64{sae}, i... |
Scan-o-Matic/scanomatic | scanomatic/models/phases_models.py | Python | gpl-3.0 | 1,102 | 0.001815 | from __future__ import | absolute_import
import scanomatic.generics.model as model
class SegmentationModel(model.Model):
def __init__(self, dydt=None, dydt_ranks=None, dydt_signs=None, d2yd2t=None,
d2yd2t_signs=None, phases=None, offset=0, log2_curve=None, times=None,
plate=None, pos=None):
se... | """
self.times = times
""":type : numpy.ndarray"""
self.plate = plate
""":type : int"""
self.pos = pos
""":type : (int, int)"""
self.dydt = dydt
""":type : numpy.ndarray"""
self.dydt_ranks = dydt_ranks
""":type : numpy.ndarray"""
s... |
tensorflow/tfx | tfx/utils/topsort_test.py | Python | apache-2.0 | 5,388 | 0.002598 | # Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | ),
get_child_nodes=(
lambda n: [node_map[name] for name in n.downstream_nodes]))
| self.assertEqual([['A'], ['B']],
[[node.name for node in layer] for layer in layers])
def test_topsorted_layers_ignore_duplicate_child_node(self):
nodes = [
Node('A', [], ['B', 'B']), # Duplicate child node 'B'
Node('B', ['A'], []),
]
node_map = {node.name: node for ... |
stack-of-tasks/rbdlpy | tutorial/lib/python2.7/site-packages/OpenGL/raw/GL/VERSION/GL_4_1.py | Python | lgpl-3.0 | 13,612 | 0.057229 | '''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GL import _types as _cs
# End users want this...
from OpenGL.raw.GL._types import *
from OpenGL.raw.GL import _errors
from OpenGL.constant import Constant as _C
import ctypes
_... | )
GL_HIGH_FLOAT=_C('GL_HIGH_FLOAT',0x8DF2)
GL_HIGH_INT=_C('GL_HIGH_INT',0x8DF5)
GL_I | MPLEMENTATION_COLOR_READ_FORMAT=_C('GL_IMPLEMENTATION_COLOR_READ_FORMAT',0x8B9B)
GL_IMPLEMENTATION_COLOR_READ_TYPE=_C('GL_IMPLEMENTATION_COLOR_READ_TYPE',0x8B9A)
GL_LAYER_PROVOKING_VERTEX=_C('GL_LAYER_PROVOKING_VERTEX',0x825E)
GL_LOW_FLOAT=_C('GL_LOW_FLOAT',0x8DF0)
GL_LOW_INT=_C('GL_LOW_INT',0x8DF3)
GL_MAX_FRAGMENT_UNI... |
manuelm/pyload | module/common/packagetools.py | Python | gpl-3.0 | 4,869 | 0.001027 | #!/usr/bin/env python
# JDownloader/src/jd/controlling/LinkGrabberPackager.java
import re
from urlparse import urlparse
def matchFirst(string, *args):
""" matches against list of regexp and returns first match"""
for patternlist in args:
for pattern in patternlist:
r = pattern.search(stri... | e)
if r is not None:
name = name.replace(r.group(0), "")
patternMa | tch = True
r = pat2.search(name)
if r is not None:
name = name.replace(r.group(0), "")
patternMatch = True
# additional checks if extension pattern matched
if patternMatch:
# remove extension
index = name.rfind(".")
if index <... |
Endika/event | website_event_sale_legal/__openerp__.py | Python | agpl-3.0 | 742 | 0 | # -*- coding: utf-8 -*-
# © 2015 Antiun Ingeniería, S.L. - Jairo Llopis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Legal terms per event",
"summary": "Make attendees to accept legal terms per event",
"version": "8.0.1.0.0",
"category": "Marketing",
"website": "ht... | p://www.antiun.com",
"author": "Antiun Ingeniería S.L., Odoo Community A | ssociation (OCA)",
"license": "AGPL-3",
"application": False,
"installable": True,
"auto_install": True,
"depends": [
"website_event_sale",
"website_sale_product_legal",
],
"data": [
"views/event_event_view.xml",
"views/legal_term_view.xml",
"views/tem... |
arnaudsj/milk | milk/supervised/multi_view.py | Python | mit | 1,957 | 0.009198 | # -*- coding: utf-8 -*-
# Copyright (C) 2008-2011, Luis Pedro Coelho <[email protected]>
# vim: set ts=4 sts=4 sw=4 expandtab smartindent:
#
# License: MIT. See COPYING.MIT file in the milk distribution
import numpy as np
__all__ = [
'multi_view_learner',
]
class multi_view_model(object):
def __init__(s... | /(1-Pi) > 1. return 1
# if \sum \log( Pi/(1-Pi) ) > 0. return 1
return np.sum( np.log(Ps/(1-Ps)) ) > 0
class multi_view_learner(object):
'''
Multi View Learner
This learner learns different classifiers on multiple sets of features and
combines them for classification.
'''
def... | sedlabels=False):
features = zip(*features)
if len(features) != len(self.bases):
raise ValueError('milk.supervised.multi_view_learner: ' +
'Nr of features does not match classifiser construction (got %s, expected %s)'
% (len(features) ,len(self... |
webrian/ProcessingDiagramPlugin | DiagramAlgorithmProvider.py | Python | gpl-2.0 | 4,094 | 0.001221 | # -*- coding: utf-8 -*-
"""
***************************************************************************
__init__.py
---------------------
Date : March 2016
Copyright : (C) 2016 by Adrian Weber
Email : webrian at gmx dot net
*********************************... | call the parent method, since it takes care
or automatic | ally adding a setting for activating or
deactivating the algorithms in the provider.
"""
AlgorithmProvider.initializeSettings(self)
def unload(self):
"""Setting should be removed here, so they do not appear anymore
when the plugin is unloaded.
"""
AlgorithmPr... |
DanteLore/national-rail | loadstations.py | Python | mit | 1,412 | 0.002833 | import argparse
from osgb import osgb_to_lonlat
from osgb.convert import eastnorth_to_osgb
from utils.database import insert_into_db, empty_table, execute_sql
# Loads data from here: https://data.gov.uk/dataset/naptan
def read_stations(filename):
with open(filename, 'r') as input_file:
for line in inpu... | r.add_argument('--filename', hel | p='Input CSV file', default="data/RailReferences.csv")
parser.add_argument('--db', help='SQLite DB Name', default="data/trains.db")
args = parser.parse_args()
execute_sql(args.db, "create table if not exists stations (crs TEXT, name TEXT, easting INT, northing INT, latitude DOUBLE, longitude DOUBLE);")
... |
zpace/SparsePak-SFH | ppxf_util.py | Python | mit | 12,608 | 0.003411 | #######################################################################
#
# Copyright (C) 2001-2014, Michele Cappellari
# E-mail: cappellari_at_astro.ox.ac.uk
#
# This software is provided as is without any warranty whatsoever.
# Permission to use, for non-commercial purposes is granted.
# Permission to modify for pers... | w).
# NB: This rebinning of the error-spectrum is very *approximate* as
# it does not consider the correlation introduced by the rebinning!
#
# CALLING SEQUENCE:
# LOG_REBIN, lamRange, spec, specNew, logLam, $
# OVERSAMPLE=oversample, VELSCALE=velScale, /FLUX
#
# INPUTS:
# LAMRANGE: two elements vector co... | t and last pixels in the spectrum, which is assumed
# to have constant wavelength scale! E.g. from the values in the
# standard FITS keywords: LAMRANGE = CRVAL1 + [0,CDELT1*(NAXIS1-1)].
# It must be LAMRANGE[0] < LAMRANGE[1].
# SPEC: input spectrum.
#
# OUTPUTS:
# SPECNEW: logarithmically rebinned... |
genomoncology/related | tests/ex06_json/models.py | Python | mit | 765 | 0 | from enum import Enum, unique
import related
@unique
class DayType(Enum):
NORMAL = "Normal"
HOLIDAY = "Holiday"
@related.immutable
| class DayData(object):
date = related.DateField()
logged_on = related.TimeField("%H:%M")
open_at = related.TimeField()
closed_on = related.TimeField()
customers = related.IntegerField()
day_type = related.ChildField(DayType)
sales = related.FloatField(required=False)
@related.immutable
cla... | data_to = related.DateTimeField()
days = related.SequenceField(DayData)
price = related.DecimalField()
|
mlperf/training_results_v0.7 | NVIDIA/benchmarks/maskrcnn/implementations/pytorch/maskrcnn_benchmark/utils/c2_model_loading.py | Python | apache-2.0 | 7,055 | 0.002268 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import logging
import pickle
from collections import OrderedDict
import torch
from maskrcnn_benchmark.utils.model_serialization import load_state_dict
from maskrcnn_benchmark.utils.registry import Registry
def _rename_basic_resnet_weights(layer... | ister("R-101-FPN-RETINANET")
@C2_FORMAT_LOADER.register("R-152-FPN")
def load_resnet_c2_format(cfg, f):
state_dict = _load_c2_pickled_weights(f)
conv_body = cfg.MODEL.BACKBONE.CONV_BODY
arch = conv_body. | replace("-C4", "").replace("-C5", "").replace("-FPN", "")
arch = arch.replace("-RETINANET", "")
stages = _C2_STAGE_NAMES[arch]
state_dict = _rename_weights_for_resnet(state_dict, stages)
return dict(model=state_dict)
def load_c2_format(cfg, f):
return C2_FORMAT_LOADER[cfg.MODEL.BACKBONE.CONV_BODY]... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.