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 |
|---|---|---|---|---|---|---|---|---|
ac-seguridad/ac-seguridad | project/manejador/mensajes.py | Python | apache-2.0 | 256 | 0.003906 | TIPOS_MENSAJES = {
'entrada': "entrada", |
'salida': "salida",
'pago_ticket': "pago de ticket",
}
MENSAJES = {
'entrada': "Se ha reportado en el sistema una entrada ",
'salida' | : "salida",
'pago_ticket': "pago de ticket",
}
def
|
google/makani | avionics/motor/monitors/motor_ina219.py | Python | apache-2.0 | 2,535 | 0 | # Copyright 2020 Makani Technologies 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... |
gin_a2 = gin_a1
gin_a3 = [
dict(ina219_32v_160mv, name='12v', address=0x41, shunt_resistor=0.05),
dict(ina219_16v_80mv, name='1v2', add | ress=0x42, shunt_resistor=0.05),
dict(ina219_16v_80mv, name='3v3', address=0x45, shunt_resistor=0.05),
]
ina219_config = (rev.MotorHardware, {
rev.MotorHardware.GIN_A1: gin_a1,
rev.MotorHardware.GIN_A2: gin_a2,
rev.MotorHardware.GIN_A3: gin_a3,
rev.MotorHardware.GIN_A4_CLK16: gin_a3,
rev.MotorH... |
GZakharov1525/SOFE3770 | Assignment2/plot_lines.py | Python | gpl-3.0 | 2,119 | 0.003303 | import csv
import sys
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
def parse(file_name):
"Parses the data sets from the csv file we are given to work with"
try:
file = open(file_name)
except IOError:
print "Failed to open the data file"
sys.exit()
... | a new sublist every time
listSize = len(unorderedData)
for x in range(0, listSi | ze):
orderedData[0].append(unorderedData[x][0]) # Seperates the x-cords
for y in range(0, listSize):
orderedData[1].append(unorderedData[y][1]) # Seperates the y-cords
return orderedData
def main():
newData = []
f_line_x = []
f_line_y = []
file_name = "data.csv"
data = par... |
ak110/pytoolkit | pytoolkit/bin/h5ls.py | Python | mit | 1,745 | 0.001826 | #!/usr/bin/env python3
"""*.h5 の値の最小・最大などを確認するスクリプト。"""
import argparse
import pathlib
import sys
import h5py
import numpy as np
try:
import pytoolkit as tk
except ImportError:
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent.parent))
import pytoolkit as tk
logger = tk.log.get(__name... | for weight_name in weight_names:
w = np.asarray(g[weight_name])
key = f"/model_weights/{layer_name}/{weight_name}"
if w.size == 1:
logger.info(f"{key}\t value={np.ravel(w)[0]:.2f}")
else:
logger.info(
... | an={w.mean():.2f} std={w.std():.2f}"
)
absmax_list.append((key, np.abs(w).max()))
logger.info("abs Top-10:")
for key, absvalue in list(sorted(absmax_list, key=lambda x: -x[1]))[:10]:
logger.info(f"{absvalue:6.1f}: {key}")
if __name__ == "__main__":
main()
|
espadrine/opera | chromium/src/third_party/chromite/buildbot/remote_try_unittest.py | Python | bsd-3-clause | 7,349 | 0.006668 | #!/usr/bin/python
# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import json
import mox
import os
import sys
import shutil
import time
import constants
sys.path.insert(0, constants.SOURCE_ROOT)
f... | repository.IsARepoRoot(mox.IgnoreArg()).AndReturn(False)
self.mox.ReplayAll()
job = self._CreateJob()
file1 = submit_helper('test1')
# Tryjob file names are based on timestamp, so delay one second to avoid two
# jobfiles having the same name.
time.sleep(1)
file2 = submit_helper('test2')
... | , file2)
def testSimpleTryJob(self, version=None):
"""Test that a tryjob spec file is created and pushed properly."""
self.mox.StubOutWithMock(repository, 'IsARepoRoot')
repository.IsARepoRoot(mox.IgnoreArg()).AndReturn(True)
self.mox.StubOutWithMock(repository, 'IsInternalRepoCheckout')
reposito... |
allen1989127/WhereRU | org/sz/tools.py | Python | gpl-3.0 | 508 | 0.015748 | '''
base tools
'''
# -*- coding: utf-8 -*-
import re
def is_ipv4(ip) :
pattern = r'^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2 | })(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})){3}$'
matcher = re.match(pattern, ip)
if matcher is not None :
return True
return False
def is_domain(domain) :
pattern = r'[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?'
matcher = re.match(pattern, | domain)
if matcher is not None :
return True
return False
|
yxliang/fast-rcnn | tools/_init_paths.py | Python | mit | 637 | 0.00314 | # ----------------------------------------------------- | ---
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""Set up paths for Fast R-CNN."""
import os.path as osp
import sys
def add_path(path):
if path not in sys.path:
... | osp.join(this_dir, '..', 'caffe-fast-rcnn', 'python')
add_path(caffe_path)
# Add lib to PYTHONPATH
lib_path = osp.join(this_dir, '..', 'lib')
add_path(lib_path)
|
atbentley/aiohttp-rest | tests/test_endpoint.py | Python | mit | 2,542 | 0.003541 | from asyncio import coroutine
import pytest
from aiohttp import HttpBadRequest, HttpMethodNotAllowed
from fluentmock import create_mock
from aiohttp_rest import RestEndpoint
class CustomEndpoint(RestEndpoint):
def get(self):
pass
def patch(self):
pass
@pytest.fixture
def endpoint():
r... | p1)))
request = create_mock(method='MATCH_INFO', match_info={'prop1': 1, 'prop2': 2} | )
assert await endpoint.dispatch(request) == (2, 1)
@pytest.mark.asyncio
async def test_dispatch_raises_bad_request_when_match_info_does_not_exist(endpoint: RestEndpoint):
endpoint.register_method('BAD_MATCH_INFO', coroutine(lambda no_match: no_match))
request = create_mock(method='BAD_MATCH_INFO', match... |
nastya/droidbot | droidbot/adapter/droidbot_ime.py | Python | mit | 3,282 | 0.000612 | # coding=utf-8
import logging
import time
from adapter import Adapter
DROIDBOT_APP_PACKAGE = "io.github.ylimit.droidbotapp"
IME_SERVICE = D | ROIDBOT_APP_PACKAGE + "/.DroidBotIME"
class DroidBotImeException(Exception):
"""
Exception in telnet connection
"""
pass
class DroidBotIme(Adapter):
"""
a connection with droidbot ime app.
"""
def __init__(self, device=None):
"""
initiate a emulator console via telnet... | if device is None:
from droidbot.device import Device
device = Device()
self.device = device
self.connected = False
def set_up(self):
device = self.device
if DROIDBOT_APP_PACKAGE in device.adb.get_installed_apps():
self.logger.debug("DroidBot app... |
fernandog/Medusa | ext/sqlalchemy/dialects/postgresql/json.py | Python | gpl-3.0 | 9,821 | 0.000204 | # postgresql/json.py
# Copyright (C) 2005-2018 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from __future__ import absolute_import
import json
import collections
from .base... | = [util.text_type(elem)for elem in value]
v | alue = "{%s}" % (", ".join(tokens))
if super_proc:
value = super_proc(value)
return value
return process
def literal_processor(self, dialect):
super_proc = self.string_literal_processor(dialect)
def process(value):
assert isinstance(valu... |
Kozea/Radicale | radicale/app/options.py | Python | gpl-3.0 | 1,395 | 0 | # This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2008 Nicolas Kandel
# Copyright © 2008 Pascal Halter
# Copyright © 2008-2017 Guillaume Ayoub
# Copyright © 2017-2018 Unrud <unrud@outlook.com>
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GN... | y
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This library 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 t | he
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Radicale. If not, see <http://www.gnu.org/licenses/>.
from http import client
from radicale import httputils, types
from radicale.app.base import ApplicationBase
class ApplicationPar... |
photo/openphoto-python | tests/functional/test_tags.py | Python | apache-2.0 | 3,889 | 0.000771 | try:
import unittest2 as unittest # Python2.6
except ImportError:
import unittest
from tests.functional import test_base
@unittest.skipIf(test_base.get_test_server_api() == 1,
"The tag API didn't work at v1 - see frontend issue #927")
class TestTags(test_base.TestBase):
testcase_name = "t... | t the tag.update endpoint, "
"since there are no fields that can be updated")
def test_update(self):
""" Test that a tag can be updated """ |
# Update the tag using the Trovebox class, passing in the tag object
owner = "test1@trovebox.com"
ret_val = self.client.tag.update(self.tags[0], owner=owner)
# Check that the tag is updated
self.tags = self.client.tags.list()
self.assertEqual(self.tags[0].owner, owner)
... |
Naozumi/hashgen | ni_hashGen.py | Python | mit | 3,412 | 0.036928 | from Tkinter import *
import tkMessageBox
from functools import partial
import os
import sys
import hashlib
import gzip
class niUpdater:
def __init__(self, parent):
self.myParent = parent
self.topContainer = Frame(parent)
self.topContainer.pack(side=TOP, expand=1, fill=X, anchor=NW)
self.btmContainer = Frame(... | #------------------ BUTTON #1 ------------------------------------
button_name = "OK"
# command binding
var = StringVar()
self.button1 = Button(self.topContainer, command=lambda: self.buttonPress(entry1.get(),var,entry2.get()))
# event binding -- p | assing the event as an argument
self.button1.bind("<Return>",
lambda
event :
self.buttonHandler_a(entry1.get(),var)
)
self.button1.configure(text=button_name, width=5)
self.button1.pack(side=LEFT)
self.button1.focus_force() # Put keyboard focus on button1
self.label = Label(self.btmContainer,t... |
hmendozap/auto-sklearn | test/test_pipeline/test_regression.py | Python | bsd-3-clause | 18,360 | 0.000926 | import copy
import resource
import sys
import traceback
import unittest
import mock
import numpy as np
import sklearn.datasets
import sklearn.decomposition
import sklearn.ensemble
import sklearn.svm
from sklearn.utils.testing import assert_array_almost_equal
from HPOlibConfigSpace.configuration_space import Configura... | rops)
inp = props['input']
output = props['output']
self.assertIsInstance(inp, tuple)
self.assertIsInstance(output, tuple)
for i in inp:
self.assertIn(i, (SPARSE, DENSE, SIGNED_DATA, UNSIGNED_DATA))
self.assertEqual(output, (PREDIC... | s['handles_regression'])
self.assertIn('handles_classification', props)
self.assertIn('handles_multiclass', props)
self.assertIn('handles_multilabel', props)
self.assertFalse(props['handles_classification'])
self.assertFalse(props['handles_multiclass'])
... |
jeaye/jeayeson | .ycm_extra_conf.py | Python | bsd-3-clause | 3,051 | 0.041298 | import os
import ycm_core
flags = [
'-Wall',
'-Wextra',
'-Werror',
'-pedantic',
'-std=c++1y',
#'-stdlib=libc++',
'-x',
'c++',
'-Iinclude',
'-Itest/include',
'-Ilib/jest/include',
'-isystem',
'../BoostParts',
'-isystem',
'/System/Library/Frameworks/Python.framework/Headers',
'-isystem',
'../llvm/include',
'-isystem',
... | g in path_flags:
if flag == path_flag:
make_next_absolute = True
break
if flag.startswith( path_flag ):
path = flag[ len( path_flag ): ]
new_flag = path_flag + os.path.join( working_directory, path )
break
if new_flag: |
new_flags.append( new_flag )
return new_flags
def IsHeaderFile( filename ):
extension = os.path.splitext( filename )[ 1 ]
return extension in [ '.h', '.hxx', '.hpp', '.hh' ]
def GetCompilationInfoForFile( filename ):
if IsHeaderFile( filename ):
basename = os.path.splitext( filename )[ 0 ]
fo... |
ut-ras/robotticelli | src/hardware/robot/run-real.py | Python | lgpl-3.0 | 3,189 | 0.007839 | from __future__ import absolute_import
import numpy as np
import conf
from time import sleep
from functools import reduce
from hardware.robot.modules.motor_math import get_triangular_direction_vector
from hardware.robot.modules.com import send_encoder_steps_and_speed |
##
## This is the code that instructs how to get from A to B
## using continual approximation and gradient descent
##
## Motors that have requested to move to the next step
## Only executes when all are true
## Motors have been assigned IDs which will then be
## Used to index motors_requested
## instructions has th... | iter='\t')
motors_requested = [True, True]
last_instruction_index = -1
current_instruction_index = 1
last_instruction = [1, 0, 0]
current_instruction = [1, 0, 0]
def check_all_requested():
## Returns true if all motors_requested values are true
return reduce(lambda x, y: x and y, motors_requested)
## TODO: I... |
manuelm/pyload | module/plugins/hoster/CyberlockerCh.py | Python | gpl-3.0 | 485 | 0.014433 | # -*- coding: utf-8 -*-
from module.plugins.internal.DeadHoster import DeadHoster
class CyberlockerCh(DeadHoster):
__name__ = "CyberlockerCh"
__type__ = "hoster | "
__version__ = "0.06"
__status__ = "stable"
__pattern__ = r'http://(?:www\.)?cyberlocker\.ch/\w+'
__config__ = [] #@TODO: Remove in 0.4.10
__description__ = """Cyberlo | cker.ch hoster plugin"""
__license__ = "GPLv3"
__authors__ = [("stickell", "l.stickell@yahoo.it")]
|
bgporter/wastebook | testData/postTestData.py | Python | mit | 1,496 | 0.004679 | '''
A secret file with data that we can use in unit tests without needing to
clutter up that file with a bunch of raw data structures.
'''
from datetime import datetime
SEARCH_TEST_DATA = [
{
"created" : datetime(2015, 10, 1),
"published": datetime(2015, 10, 1),
"edited": datet... | "author": "bgporter",
"public": False,
"title": "Second Post",
"status": "published",
"slug": "",
"text": "a bunch more words #f | oo #baz",
"tags": [],
"type": "Post"
},
{
"created" : datetime(2015, 10, 3),
"published": datetime(2015, 10, 3),
"edited": datetime(2015, 10, 1),
"rendered": None,
"author": "tslothrop",
"public": True,
"title": "Thir... |
FedoraScientific/salome-smesh | doc/salome/examples/defining_hypotheses_ex11.py | Python | lgpl-2.1 | 1,063 | 0.01223 | # Projection 1D2D
# Project triangles from one meshed face to another mesh on the same box
import salome
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
geo | mpy = geomBuilder.New(s | alome.myStudy)
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
smesh = smeshBuilder.New(salome.myStudy)
# Prepare geometry
# Create a box
box = geompy.MakeBoxDXDYDZ(100, 100, 100)
# Get geom faces to mesh with triangles in the 1ts and 2nd meshes
faces = geompy.SubShapeAll(box, geompy.ShapeType["FACE"]... |
babble/babble | include/jython/Lib/test/test_file.py | Python | apache-2.0 | 13,201 | 0.000985 | # From CPython 2.5.1
import sys
import os
import unittest
from array import array
from weakref import proxy
from test.test_support import TESTFN, findfile, is_jython, run_unittest
from UserList import UserList
class AutoFileTests(unittest.TestCase):
# file tests for which a test file is automatically set up
... | could just be tested
# to work when it should work according to the Python language,
# instead of fail when it should fail according to the current CPython
# implement | ation. People don't always program Python the way they
# should, though, and |
amohanta/miasm | example/jitter/unpack_upx.py | Python | gpl-2.0 | 3,028 | 0.000661 | import os
import logging |
from pdb import pm
from elfesteem import pe
from miasm2.analysis.sandbox import Sandbox_Win_x86_32
from miasm2.core import asmbloc
filename = os.environ.get('PYTHONSTARTUP')
if filename and os.path.isfile(filename):
execfile(filename)
# User defined methods
def kernel32_GetProcAddress(jitter):
ret_ad, args... | get_str_ansi(args.fname))
logging.info(fname)
ad = sb.libs.lib_get_add_func(args.libbase, fname, dst_ad)
jitter.func_ret_stdcall(ret_ad, ad)
parser = Sandbox_Win_x86_32.parser(description="Generic UPX unpacker")
parser.add_argument("filename", help="PE Filename")
parser.add_argument('-v', "--verbose",
... |
ugoertz/django-familio | accounts/permissions.py | Python | bsd-3-clause | 6,670 | 0 | """
Extensible permission system for pybbm
"""
from django.db.models import Q
from pybb import defaults
from pybb.models import Topic, PollAnswerUser
from pybb.permissions import DefaultPermissionHandler
class CustomPermissionHandler(DefaultPermissionHandler):
"""
Custom Permission handler for PyBB.
In... | qs):
""" retu | rn a queryset with categories `user` is allowed to see """
if not user.is_authenticated:
return qs.exclude()
return qs.filter(hidden=False) if not user.is_staff else qs
def may_view_category(self, user, category):
""" return True if `user` may view this category, False if not ""... |
JanlizWorldlet/FeelUOwn | sphinx_doc/source/conf.py | Python | mit | 9,220 | 0.005965 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# feeluown documentation build configuration file, created by
# sphinx-quickstart on Fri Oct 2 20:55:54 2015.
#
# 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
# a... | and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Opti | ons for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available ... |
andersinno/kuvaselaamo | hkm/migrations/0019_productorder_total_price_with_postage.py | Python | mit | 554 | 0.001805 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2017-04-11 10:09
from __future__ import unicode_literals
from django.db import migrations, models
class Mi | gration(migrations.Migration):
dependencies = [
('hkm', '0018_auto_20170411_1301'),
]
operations = [
migrations.AddField(
model_name='productorder',
name='total_price_with_postage',
field=models.DecimalField(blank=True, decimal_places=2, max_digi | ts=10, null=True, verbose_name='Total price with postage'),
),
]
|
realityone/flaskbb | flaskbb/forum/forms.py | Python | bsd-3-clause | 3,976 | 0 | # -*- coding: utf-8 -*-
"""
flaskbb.forum.forms
~~~~~~~~~~~~~~~~~~~
It provides the forms that are needed for the forum views.
:copyright: (c) 2014 by the FlaskBB Team.
:license: BSD, see LICENSE for more details.
"""
from flask_wtf import Form
from wtforms import (TextAreaField, StringField, Sele... | w"))
def save(self, user, topic):
post = Post(content=self.content.data)
if self.track_topic.data:
user.track_topic(topic)
return post.save(user=user, topic=topic)
class NewTopicForm(ReplyForm):
title = StringField(_("Topic title"), validators=[
DataRequired(messa... | se choose a title for your topic."))])
content = TextAreaField(_("Content"), validators=[
DataRequired(message=_("You cannot post a reply without content."))])
track_topic = BooleanField(_("Track this topic"), default=False,
validators=[Optional()])
submit = SubmitF... |
GISAElkartea/antxetamedia | antxetamedia/agenda/views.py | Python | agpl-3.0 | 2,216 | 0.002256 | from django.utils.translation import ugettext as _
from django.shortcuts import get_object_or_404
from django.views.generic import ListView, DetailView, DayArchiveView, CreateView,\
TemplateView
from datetime import date
from antxetamedia.agenda.forms import HappeningForm
from antxetamedia.agenda.models impor... | .town)
def get_context_data(self, **kwargs):
c = super(TownHappeningList, self).get_context_data(**kwargs)
c['reason'] = self.town
return c
class OtherTownHappeningList(TownHappeningList):
def get_queryset(self):
self.town = _('Other')
return Happening.objects.filter(t... | ll=True,
other_town__isnull=False)
class DayHappeningList(DayArchiveView):
model = Happening
date_field = 'date'
template_name = 'agenda/happening_list.html'
allow_future = True
month_format = '%m'
def get_context_data(self, **kwargs):
c = super(DayHappenin... |
Pietdagamer/Lanseloet | Old/2.py | Python | mit | 4,586 | 0.006542 | import pygame, sys
from pygame.locals import *
# --- Functions ---
def distance(speed, time):
distance = time * speed
return distance
# --- Classes ---
class Character(object):
def __init__(self, position, direction, sprite):
self.position = position
self.direction = direction
self... | layerPos[0]:
playerPos[0] -= dista | nce(1, frameTime)
if playerPos[1] != nextPlayerPos[1]:
if playerPos[1] < nextPlayerPos[1]:
playerPos[1] += distance(1, frameTime)
elif playerPos[1] > nextPlayerPos[1]:
playerPos[1] -= distance(1, frameTime)
# --- Tile visualisation ---
for y in range(-1,... |
ligovirgo/pyomicron | docs/conf.py | Python | gpl-3.0 | 9,982 | 0.00561 | # -*- coding: utf-8 -*-
#
# PyOmicron documentation build configuration file, created by
# sphinx-quickstart on Tue Apr 26 09:12:21 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
#... | ndex = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C... | ault is True.
#html_show_copyright = True
# If true, an OpenSearch description 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 file... |
JScott/ansible-taiga | templates/opt/taiga/back/settings/local.py | Python | mit | 1,982 | 0.005561 | # 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
# publi | shed by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affer... | long with this program. If not, see <http://www.gnu.org/licenses/>.
from .development import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': '{{ taiga_database_username }}',
'USER': '{{ taiga_database_username }}',
'PASSWORD': '{{ taiga_dat... |
CommunicationsSecurityEstablishment/spartacus | CapuaEnvironment/Instruction/Instruction.py | Python | gpl-2.0 | 4,253 | 0.003292 | #!/usr/bin/env python
# -*- coding: <utf-8> -*-
"""
This file is part of Spartacus project
Copyright (C) 2016 CSE
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, o... | any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT A | NY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street... |
vkotek/kotek_bot | features/toilet_finder.py | Python | unlicense | 1,885 | 0.009549 | #!/usr/local/bin/python3
# coding: utf-8
try:
import json, requests, urllib
from geopy.geocoders import No | minatim
from geopy.distance import vincenty
except:
print("Error importing modules, exiting.")
exit()
api_url = "http://opendata.iprpraha.cz/CUR/FSV/FSV_VerejnaWC_b/WGS_84 | /FSV_VerejnaWC_b.json"
def find(address):
# convert address to latlong
me = locate(address+", Prague")
if me == None:
return None
toilets = getToilets(api_url)
# Get closest toilet
wcID = getClosestID(me, toilets)
wc = toilets[wcID-1]
data = []
try:
address = w... |
NESCent/phylocommons | tools/treebase_scraper/annotate_trees.py | Python | mit | 622 | 0.008039 | #!/usr/bin/env python
import sys
import os
from treestore import Treestore
try: taxonomy = sys.argv[1]
except: taxonomy = None
t = Treestore()
treebase_uri = 'http://purl.org/phylo/treebase/phylows/tree/%s'
tree_files = [x for x in os.listdir('trees') if x.endswith('.nex')]
base_uri = 'http://www. | phylocommons.org/trees/%s'
tree_list = set(t.list_trees())
for tree_uri in tree_list:
if not 'TB2_' in tree_uri: continue
tree_id = t.id_from_uri(tree_uri)
tb_uri = treebase_uri % (tree_id.replace('_', ':'))
print tree_id, tb_uri
t.annotate(tree_u | ri, annotations='?tree bibo:cites <%s> .' % tb_uri)
|
yarikoptic/Fail2Ban-Old-SVNGIT | testcases/datedetectortestcase.py | Python | gpl-2.0 | 2,300 | 0.01913 | # This file is part of Fail2Ban.
#
# Fail2Ban 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.
#
# Fail2Ban is distributed in the hope t... | be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Fail2Ban; if not, write to the Free Software
# Fou... | Revision$
__author__ = "Cyril Jaquier"
__version__ = "$Revision$"
__date__ = "$Date$"
__copyright__ = "Copyright (c) 2004 Cyril Jaquier"
__license__ = "GPL"
import unittest
from server.datedetector import DateDetector
from server.datetemplate import DateTemplate
class DateDetectorTest(unittest.TestCase):
def setUp... |
yasoob/PythonRSSReader | venv/lib/python2.7/dist-packages/samba/tests/samba_tool/base.py | Python | mit | 4,702 | 0.002127 | # Unix SMB/CIFS implementation.
# Copyright (C) Sean Dague <sdague@linux.vnet.ibm.com> 2011
#
# 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 optio... | the command classes do it. It would be better if the command
# classes had a way to more cleanly do this, but this lets us write
# tests for now
cmd = cmd_sambatool.subcommands["user"].subcommands["setexpiry"]
parser, optiongroups = cmd._create_parser("user")
opts, args = parser... |
for option in option_group.option_list:
if option.dest is not None:
del kwargs[option.dest]
kwargs.update(optiongroups)
H = kwargs.get("H", None)
sambaopts = kwargs.get("sambaopts", None)
credopts = kwargs.get("credopts", None)
l... |
sserrot/champion_relationships | venv/Lib/site-packages/pythonwin/pywin/scintilla/configui.py | Python | mit | 9,244 | 0.034401 | from pywin.mfc import dialog
import win32api
import win32con
import win32ui
import copy
import string
from . import scintillacon
# Used to indicate that style should use default color
from win32con import CLR_INVALID
######################################################
# Property Page for syntax formatting options
... | IDC_RADIO1
self.GetDlgItem(win32ui.IDC_RADIO1).GetCheck() != 0
self.scintilla._GetColorizer().bUseFixed = bUseFixed
self.scintilla.ApplyFormattingStyles(0)
return 1
def O | nButThisFont(self, id, code):
if code==win32con.BN_CLICKED:
flags = win32con.CF_SCREENFONTS | win32con.CF_EFFECTS | win32con.CF_FORCEFONTEXIST
style = self.GetSelectedStyle()
# If the selected style is based on the default, we need to apply
# the default to it.
def_format = self.scintilla._GetColorizer... |
AtenrevCode/scChat | users/forms.py | Python | mit | 542 | 0.00738 | from django import forms
from django.contrib.auth.models import Use | r
from django.contrib.auth.forms import UserCreationForm
class RegisterForm(UserCreationForm):
invitation = forms.CharField(max_length=8)
class Meta:
model = User
fields = ('username', 'password1', 'password2', 'invitation')
class SettingsForm(forms.Form):
username = forms.CharField(min_l... | eField(required=False)
class Meta:
model = User
fields = ('username', 'first_name','last_name','ppic',)
|
shark555/websnake_demo | scripts/serve.py | Python | mit | 161 | 0.018634 | #!/usr/bin/python3 -B
exec(open("../index.py").read())
from waitre | ss import serve
serve(application, host='0.0.0.0', port=8080, threads=1, | channel_timeout=1)
|
pelegm/movers | math.py | Python | unlicense | 9,322 | 0.002789 | """
.. math.py
Simple math movers.
"""
## Inheritance
import base
# import library.movers.pushqueue as pq
## Inifinity definition
inf = float("inf")
#########################################
## ----- Special data containers ----- ##
#########################################
class MovingMax(base.Mover):
""" Co... | was None, so increase-only is made
except TypeError:
self._sum += value
| ## Return sum
return self._sum
def _zero(self):
self._deque = base.Deque((), maxlen=self.n)
self._sum = 0
def sgn(x):
""" Return the sign of *x*. """
return 1 if x.real > 0 else -1 if x.real < 0 else 0
class SignTracker(base.Mover):
""" Counts length of successing similar-s... |
alex/taskmaster | src/taskmaster/server.py | Python | apache-2.0 | 6,026 | 0.00083 | """
taskmaster.controller
~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010 DISQUS.
:license: Apache License 2.0, see LICENSE for more details.
"""
import cPickle as pickle
import gevent
import sys
from gevent_zeromq import zmq
from gevent.queue import Queue, Empty
from os import path, unlink, rename
from taskmaster.util im... | QUIT')
else:
self.send('ERROR', 'Unrecognized command')
self.shutdown()
def put_job(self, job):
return self.queue.put(job)
| def first_job(self):
return self.queue.queue[0]
def get_current_size(self):
return self.queue.qsize()
def get_max_size(self):
return self.size
def has_work(self):
return not self.queue.empty()
def is_alive(self):
return self.started
def shutdown(self)... |
Knewton/pettingzoo-python | setup.py | Python | apache-2.0 | 1,447 | 0.041465 | #!/usr/bin/env python
import os.path
import re
from setuptools import Command, find_packages, setup
class PyTest(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import sys,subprocess
errno = subprocess.call([sys.executable, "runtests.py"])
ra... | replaced with the current build number
as part of the jenkins build job"""
build_version = 1
return build_version
def parse_requirements(file_name):
"""Taken from http://cburgmer.posterous.com/pip-requirementstxt-and-setuppy"""
requirements = []
for line in open(os.path.join(os.path.dirname(__file__), "config", ... | ch(r"(^#)|(^$)", line):
continue
requirements.append(line)
return requirements
setup(
name="pettingzoo",
version="0.3.0" % get_version(),
url = "https://wiki.knewton.net/index.php/Tech",
author="Devon Jones",
author_email="devon@knewton.com",
license = "Apache",
packages=find_packages(),
scripts = ["bin/... |
squared9/Robotics | Robotic_PR2_3D_Perception_Pick_And_Place/sensor_stick/src/sensor_stick/features.py | Python | mit | 2,473 | 0.002831 | import matplotlib.colors
import matplotlib.pyplot as plt
import numpy as np
from pcl_helper import *
def rgb_to_hsv(rgb_list):
rgb_normalized = [1.0*rgb_list[0]/255, 1.0*rgb_list[1]/255, 1.0*rgb_list[2]/255]
hsv_normalized = matplotlib.colors.rgb_to_hsv([[rgb_normalized]])[0][0]
return hsv_normalized
de... | d(color[0])
channel_2_vals.append(color[1])
channel_3_vals.append(color[2])
# Compute histograms
# Ta | ke histograms in R, G, and B or similar channels (HSV etc.)
r_hist = np.histogram(channel_1_vals, bins=32, range=(0, 256))
g_hist = np.histogram(channel_2_vals, bins=32, range=(0, 256))
b_hist = np.histogram(channel_3_vals, bins=32, range=(0, 256))
# Concatenate and normalize the histograms
hist_fe... |
mcmcplotlib/mcmcplotlib | api/generated/arviz-plot_forest-3.py | Python | apache-2.0 | 367 | 0.016349 | axes = az.plot_forest(non_centered_ | data,
kind='ridgeplot',
var_names=['theta'],
combined=True,
ridgeplot_overlap=3,
colors='white',
figsize=(9, 7))
axes[0].set_title('Estimated theta for 8 scho... | )
|
cython-testbed/pandas | pandas/tests/indexes/multi/conftest.py | Python | bsd-3-clause | 1,577 | 0 | # -*- coding: utf-8 -*-
import numpy as np
import pytest
from pandas import Index, MultiIndex
@pytest.fixture
def idx():
# a MultiIndex used to test the general functionality of the
# general functionality of this object
major_axis = Index(['foo', 'bar', 'baz', 'qux'])
minor_axis = Index(['one', 'two... | pytest.fixture
def idx_dup():
# compare tests | /indexes/multi/conftest.py
major_axis = Index(['foo', 'bar', 'baz', 'qux'])
minor_axis = Index(['one', 'two'])
major_labels = np.array([0, 0, 1, 0, 1, 1])
minor_labels = np.array([0, 1, 0, 1, 0, 1])
index_names = ['first', 'second']
mi = MultiIndex(levels=[major_axis, minor_axis],
... |
alignan/RIOT | tests/lwip/tests/01-run.py | Python | lgpl-2.1 | 9,890 | 0.003539 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 Martine Lenders <mail@martine-lenders.eu>
#
# Distributed under terms of the MIT license.
from __future__ import print_function
import argparse
import os, sys
import random
import pexpect
import subprocess
import time
import types
DE... | self.serial = serial
self.clean_strategy = CleanStr | ategy(self, clean)
self.build_strategy = BuildStrategy(self, build)
self.flash_strategy = FlashStrategy(self, flash)
self.reset_strategy = ResetStrategy(self, reset)
def __len__(self):
return 1
def __iter__(self):
return self
def next(self):
raise StopItera... |
stalepig/deep-mucosal-imaging | dmi_0.3/Isolate_stack_ROI2.py | Python | gpl-2.0 | 2,120 | 0.034906 | from ij import IJ
from ij.gui import NonBlockingGenericDialog
from ij import WindowManager
from ij.gui import WaitForUserDialog
from ij import ImageStack
from ij import ImagePlus
theImage = IJ.getImage()
sourceImages = []
if theImage.getNChannels() == 1:
IJ.run("8-bit")
sourceImages.append(theImage)
else:
sourceIm... | s = []
for procImage in sourceImages:
newStacks.appen | d(ImageStack(width,height))
ns = newStacks[-1]
for i in range(startSlice,endSlice+1):
procImage.setSliceWithoutUpdate(i)
bp = procImage.getProcessor().duplicate()
bp.fillOutside(roiArray[i-startSlice])
ns.addSlice(bp)
castImages.append(ImagePlus(procImage.getShortTitle()+"_cast",ns))
## Displays the... |
Smart-Torvy/torvy-home-assistant | tests/helpers/test_script.py | Python | mit | 9,704 | 0 | """The tests for the Script component."""
# pylint: disable=too-many-public-methods,protected-access
from datetime import timedelta
from unittest import mock
import unittest
# Otherwise can't test just this file (import order issue)
import homeassistant.components # noqa
import homeassistant.util.dt as dt_util
from h... | lling while the delay is present."""
event = 'test_event'
events = []
def record_event(event):
"""Add recorded event to set."""
events.append(event)
self.hass.bus.listen(event, record_event)
script_obj = script.Script(self.hass, cv.SCRIPT_SCHEMA([
... | ert script_obj.is_running
assert len(events) == 0
script_obj.stop()
assert not script_obj.is_running
# Make sure the script is really stopped.
future = dt_util.utcnow() + timedelta(seconds=5)
fire_time_changed(self.hass, future)
self.hass.block_till_done()
... |
aerkalov/Booktype | lib/booki/channels/group.py | Python | agpl-3.0 | 2,141 | 0.004671 | # This file is part of Booktype.
# Copyright (c) 2012 Aleksandar Erkalovic <aleksandar.erkalovic@sourcefabric.org>
#
# Booktype 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 Li... | .flossmanuals.net/notice/%s">%s: %s</a>' % (m['id'], m['from_user'], m['text']) for m in mess['results']]
return {"list": messages}
def remote_init_group(request, message, groupid):
import sputnik
## get online users
try:
| _onlineUsers = sputnik.smembers("sputnik:channel:%s:users" % message["channel"])
except:
_onlineUsers = []
if request.user.username not in _onlineUsers:
try:
sputnik.sadd("sputnik:channel:%s:users" % message["channel"], request.user.username)
except:
pass
... |
teeple/pns_server | work/install/Python-2.7.4/Modules/_ctypes/libffi/generate-ios-source-and-headers.py | Python | gpl-2.0 | 5,303 | 0.005846 | #!/usr/bin/env python
import subprocess
import re
import os
import errno
import collections
import sys
class Platform(object):
pass
sdk_re = re.compile(r'.*-sdk ([a-zA-Z0-9.]*)')
def sdkinfo(sdkname):
ret = {}
for line in subprocess.Popen(['xcodebuild', '-sdk', sdkname, '-version'], stdout=subprocess.PI... | ,
CFLAGS='-arch %s -isysroot %s -miphoneos-version-min=4.0' % (platform.arch, platform.sdkroot))
working_dir=os.getcwd()
try:
os.chdir(build_dir)
subprocess.check_call(['../configure', '-host', platform.triple], env=env)
move_source_tree('.', None, | '../ios/include',
arch=platform.arch,
prefix=platform.prefix,
suffix=platform.suffix)
move_source_tree('./include', None, '../ios/include',
arch=platform.arch,
pref... |
dominiktomicevic/pedestrian | classifier/extractor.py | Python | mit | 6,723 | 0.000149 | from itertools import product, repeat, chain, ifilter, imap
from multiprocessing import Pool, cpu_count
from sklearn.preprocessing import binarize
from utils.profiling import profile
from numpy.random import randint
from functools import partial
from random import sample
import numpy as np
import logging
logger = logg... | nts to get a flattened list of examples
# containing both positive and negative examples in one list
return list(chain(*zip(positive, negative)))
def | generate(dataset, w, threaded=True):
""" generate a list of classifier data samples from all dataset samples
with a parallel implementation using a thread pool
dataset: object
object containing samples list compatible with the sample class
interface
w: int
... |
amyvmiwei/chromium | webkit/tools/layout_tests/layout_package/test_types_unittest.py | Python | bsd-3-clause | 1,667 | 0.007798 | #!/bin/env python
# Copyright (c) 2006-2008 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.
"""Unittests that verify that the various test_types (e.g., simplified_diff)
are working."""
import difflib
import os |
import unittest
from test_types import simplified_text_diff
class SimplifiedDiffUnittest(unittest.TestCase):
def testSimplifiedDiff(self):
"""Compares actual output with expected output for some test cases. The
| simplified diff of these test cases should be the same."""
test_names = [
'null-offset-parent',
'textAreaLineHeight',
'form-element-geometry',
]
differ = simplified_text_diff.SimplifiedTextDiff(None)
for prefix in test_names:
output_filename = os.path.join(self.GetTestDataDir(... |
etkirsch/legends-of-erukar | erukar/content/enemies/undead/Skeleton.py | Python | agpl-3.0 | 1,103 | 0.012693 | from erukar.system.engine import Enemy, BasicAI
from ..templates.Undead import Undead
from erukar.content.inventory import Shortsword, Buckler
from erukar.content.modifiers import Steel, Oak
class Skeleton(Undead):
ClassName = 'Skeleton'
ClassLevel = 1
BaseMitigations = {
'bludgeoning': (-0.25, 0)... | ersonality(self):
self.ai_module = BasicAI(self)
self.str_ratio = 0.4
self.dex_ratio = 0.3
self.vit_ratio = 0.2
self.acu_ratio = 0.0
self.sen_ratio = 0.0
self.res_ratio = 0. | 1
self.stat_points = 8
def init_inventory(self):
self.left = Buckler(modifiers=[Oak])
self.right = Shortsword(modifiers=[Steel])
self.inventory = [self.left, self.right]
|
Ilias95/guitarchords | chords/sitemaps.py | Python | mit | 977 | 0 | from django.contrib import sitemaps
from django.core.urlresolvers import reverse
from .models import Artist, Song, User
class StaticViewSitemap(sitemaps.Sitemap):
changefreq = "weekly"
priority = 0.5
def items(self):
return ['index', 'popular', 'recently_added', 'search', 'contact']
def loc... | ):
return reverse('chords:' + item)
class SongSitemap(sitemaps.Sitemap):
changefreq = "weekly"
priority = 0.5
def items(self):
return Song.objects.filter(published=True)
def lastmod(self, obj):
return obj.mod_date
class ArtistSitemap(sitemaps.Sitemap):
changefreq = "wee... | items(self):
return User.objects.all()
def location(self, user):
return reverse('chords:user', args=(user.get_username(),))
|
SRL/SRL-5 | doc/sphinx/conf.py | Python | gpl-3.0 | 6,360 | 0.006918 | # -*- coding: utf-8 -*-
#
# SRL 5 documentation build configuration file, created by
# sphinx-quickstart on Sat Oct 16 15:51:55 2010.
#
# 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... | base URL from which the finished HTML is served.
#html_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suf | fix = ''
# Output file base name for HTML help builder.
htmlhelp_basename = 'SRL5doc'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping ... |
rupak0577/ginga | ginga/aggw/ImageViewAgg.py | Python | bsd-3-clause | 6,082 | 0.000658 | #
# ImageViewAgg.py -- a backend for Ginga using the aggdraw library
#
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
import numpy
from io import BytesIO
import aggdraw as agg
from . import AggHelp
from ginga import ImageView
from ginga.aggw.CanvasRenderAg... | def configure_surface(self, width, height):
# create ag | g surface the size of the window
self.surface = agg.Draw("RGBA", (width, height), 'black')
# inform the base class about the actual window size
self.configure(width, height)
def get_image_as_array(self):
if self.surface is None:
raise ImageViewAggError("No AGG surface d... |
ugoertz/igelgrafik | igelmain/models.py | Python | bsd-3-clause | 6,801 | 0.003971 | # -*- coding: utf-8 -*-
import os
import os.path
import tempfile
from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
from django.dispatch import receiver
from registration.signals import user_activated
from imagekit.models import ImageSpecField
from imagekit.proces... | (object):
def process(self, image):
bg = Image.new("RGBA", image.size, (255, 255, 255, 255))
bg.paste(image, (0,0), )
return bg
class Kapitel(models.Model):
'''Ein Kapitel des "Tutorials".'''
KATEGORIE_CHOICES = [('0', 'Einstieg'),
| ('1', 'Schleifen'),
('2', 'Funktionen'),
('3', 'Bedingungen'),
('4', 'Für Fortgeschrittene'),
]
titel = models.CharField(max_length=50)
zusammenfassung = models.TextField(max_length=500)
kategorie = ... |
open-ods/open-ods | tests/test_openods_api_config.py | Python | gpl-3.0 | 421 | 0 | import pytest
def test_app_hostname_is_not_none():
from openods import app
value = app.config['APP_HOSTNAME']
as | sert value is not None
def test_cache_timeout_is_greater_equal_0():
from openods import app
value = app.config['CACHE_TIMEOUT']
assert value >= 0
def test_database_url_is_not_none():
from openods import app
value = app.config['DATABASE_URL']
assert value is not N | one
|
sserrot/champion_relationships | venv/Lib/site-packages/networkx/drawing/tests/test_agraph.py | Python | mit | 3,587 | 0.000836 | """Unit tests for PyGraphviz interface."""
import os
import tempfile
import pytest
import pytest
pygraphviz = pytest.importorskip('pygraphviz')
from networkx.testing import assert_edges_equal, assert_nodes_equal, \
assert_graphs_equal
import networkx as nx
class TestAGraph(object):
def build_graph(sel... | B')]['u'] = 'keyword'
G.edges[('A', 'B')]['v'] = 'keyword'
A = nx.nx_agraph.to_agraph(G)
def test_round_trip(self):
G = nx.Graph()
A = nx.nx_agraph.to_agraph(G)
H = | nx.nx_agraph.from_agraph(A)
#assert_graphs_equal(G, H)
AA = nx.nx_agraph.to_agraph(H)
HH = nx.nx_agraph.from_agraph(AA)
assert_graphs_equal(H, HH)
G.graph['graph'] = {}
G.graph['node'] = {}
G.graph['edge'] = {}
assert_graphs_equal(G, HH)
def test_2d_... |
Thortoise/Super-Snake | Blender/animation_nodes-master/nodes/mesh/edges_of_polygons.py | Python | gpl-3.0 | 685 | 0.00292 | import bpy
from ... base_types.node import AnimationNode
class an_EdgesOfPolygonsNode(bpy. | types.Node, AnimationNode):
bl_idname = "an_EdgesOfPolygonsNode"
bl_label = "Edges of Polygons"
def create(self):
self.newInput("Polygon Indices List", "Polygons", "polygons")
self.newOutput("Edge Indices List", "Edges", "edges")
def execute(self, polygons):
edges = []
... | (startIndex, index) if index > startIndex else (index, startIndex)
edges.append(edge)
return list(set(edges))
|
vmturbo/nova | nova/tests/functional/db/api/test_migrations.py | Python | apache-2.0 | 25,993 | 0.001731 | # 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... | super(NovaAPIMigrationsWalk, self).setUp()
@property
def INIT_VERSION(self):
return migration.db_initial_version('api')
@property
def REPOSITORY(self):
return repository.Repository(
os.path.abspath(os.path.dirname(migrate_repo.__file__)))
@property
def migration_... | migrate_engine(self):
return self.engine
def _skippable_migrations(self):
mitaka_placeholders = list(range(8, 13))
newton_placeholders = list(range(21, 26))
ocata_placeholders = list(range(31, 41))
special_cases = [
30, # Enforcement migration, no changes to te... |
geneanet/certproxy | main.py | Python | bsd-3-clause | 118 | 0 | # | !/usr/bin/python3
# -*- coding: utf-8 -*-
from certproxy.certproxy import run
if __name__ == '__main__':
run() | |
gmm96/Txt2SpeechBot | models/fileProcessing.py | Python | gpl-3.0 | 1,856 | 0.00431 | # !/usr/bin/python3
# -*- coding: utf-8 -*-
import json
import os
from typing import Optional, List, Tuple, Dict, Union
from models.literalConstants import LiteralConstants
class FileProcessing:
BASE_PATH: str = os.getcwd() + "/"
def __init__(self, path: str, file_type: LiteralConstants.FileType) -> None:
... | wb')
if self.file_type == LiteralConstants.FileType.REG or self.file_type == LiteralConstants.FileType.BYTES:
file.write(data)
return True
elif | self.file_type == LiteralConstants.FileType.JSON:
json.dump(data, file)
return True
except EnvironmentError:
LiteralConstants.STA_LOG.logger.exception(LiteralConstants.ExceptionMessages.FILE_CANT_WRITE, exc_info=True)
return False
else:
... |
mzwiessele/GPyNotebook | GPyNotebook/latent/__init__.py | Python | bsd-2-clause | 34 | 0.029412 | f | rom | show_latent import LatentView |
chengduoZH/Paddle | python/paddle/fluid/tests/unittests/test_group_norm_op.py | Python | apache-2.0 | 8,301 | 0.000482 | # 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... | est):
def setUp(self):
self.op_type = "group_norm"
self.data_format = "NCHW"
self.dtype = np.float32
self.shape = (2, 4, 3, 3)
self.attrs = {'epsilon': 1e-5, 'groups': 2, 'data_layout': "NCHW"}
self.compare_between_place = False
self.init_test_case()
... | scale = np.random.random([self.shape[1]]).astype(self.dtype)
bias = np.random.random([self.shape[1]]).astype(self.dtype)
output, mean, var = group_norm_naive(
input, scale, bias, self.attrs['epsilon'], self.attrs['groups'],
self.data_format)
self.inputs = {
... |
stonekyx/binary | vendor/scons-local-2.3.4/SCons/Tool/gfortran.py | Python | gpl-3.0 | 2,256 | 0.00133 | """SCons.Tool.gfortran
Tool-specific initialization for gfortran, the GNU Fortran 95/Fortran
2003 compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001 - 2014 The SCons Foundation
... | an to an
Environment."""
fortran.generate(env)
for dialect in ['F77', 'F90', 'FORTRAN', 'F95', 'F03']:
env['%s' % dialect] = 'gfortran'
env['SH%s' % dialect] = '$%s' % dialect
if env['PLATFORM'] in ['cygwin', 'win32']:
env['SH%sFLAGS' % dialect] = SCons.Util.CLVar('$%sFL... | ['INC%sPREFIX' % dialect] = "-I"
env['INC%sSUFFIX' % dialect] = ""
def exists(env):
return env.Detect('gfortran')
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
|
cydenix/OpenGLCffi | OpenGLCffi/GL/EXT/ARB/sample_shading.py | Python | mit | 109 | 0.027523 | from OpenGLCffi.GL import params
@p | arams(api='gl', prms=['value'])
def | glMinSampleShadingARB(value):
pass
|
magnusmorton/pycket | pycket/prims/numeric.py | Python | mit | 23,301 | 0.008412 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import math
import operator
from pycket import values
from pycket import vector as values_vector
from pycket.arity import Arity
from pycket.error import... | .W_Bool.make(isinstance(n, values.W_Number) and n.isinteger())
@expose("exact-integer?", [values.W_Object])
def exact_integerp(n):
return values.W_Bool.make(isinstance(n, values.W_Integer))
@expose("exact-nonnegative-integer?", [values.W_Object])
def exact_nonneg_integerp(n):
from rpython.rlib.rbigint import ... | ULLRBIGINT
if isinstance(n, values.W_Fixnum):
return values.W_Bool.make(n.value >= 0)
if isinstance(n, values.W_Bignum):
return values.W_Bool.make(n.value.ge(NULLRBIGINT))
return values.w_false
@expose("exact-positive-integer?", [values.W_Object])
def exact_nonneg_integerp(n):
from rpyt... |
odicraig/kodi2odi | addons/plugin.video.salts/scrapers/rlshd_scraper.py | Python | gpl-3.0 | 3,957 | 0.004043 | """
SALTS XBMC Addon
Copyright (C) 2014 tknorris
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.
T... | = scraper_utils.get_quality(video, host, release_quality)
sources[stream_url] = quality
return sources
def get_url(self, video):
return self._blog_get_url(video)
@classmethod
def get_settings(cls):
settings = super(cls, cls).get_settings()
set | tings = scraper_utils.disable_sub_check(settings)
name = cls.get_name()
settings.append(' <setting id="%s-filter" type="slider" range="0,180" option="int" label=" %s" default="30" visible="eq(-3,true)"/>' % (name, i18n('filter_results_days')))
settings.append(' <setting id="%... |
softlayer/softlayer-python | SoftLayer/CLI/vlan/create.py | Python | mit | 2,493 | 0.001604 | """Order/create a VLAN instance."""
# :license: MIT, see LICENSE for more details.
import click
import SoftLayer
from SoftLayer.managers import ordering
from SoftLayer.CLI import environment
from SoftLayer.CLI import exceptions
from SoftLayer.CLI import formatting
@click.command()
@click.option('--name', required=Fa... | ]
ordering_manager = ordering.OrderingManager(env.client)
result = ordering_manager.place_order(package_keyname='NETWORK_VLAN',
| location=datacenter,
item_keynames=item_package,
complex_type=complex_type,
hourly=billing,
extras=extras)
table = formatting.K... |
mdesco/dipy | dipy/reconst/interpolate.py | Python | bsd-3-clause | 1,865 | 0.002681 | """Interpolators wrap arrays to allow the a | rray to be indexed in continuous coordinates
This module uses the trackvis coordinate system, for more information about
this coordinate system please see dipy.tracking.utils
The following modules also use this coordinate system:
dipy.tracking.utils
dipy.tracking.integration
dipy.reconst.interpolate
"""
from numpy imp... | s
class Interpolator(object):
"""Class to be subclassed by different interpolator types"""
def __init__(self, data, voxel_size):
self.data = data
self.voxel_size = array(voxel_size, dtype=float, copy=True)
class NearestNeighborInterpolator(Interpolator):
"""Interpolates data using nearest ... |
JohnyEngine/CNC | heekscnc/STLTools.py | Python | apache-2.0 | 10,565 | 0.015618 | # copied from OpenCAMLib Google code project, Anders Wallin says it was originally from Julian Todd. License unknown, likely to be GPL
# python stl file tools
import re
import struct
import math
import sys
###########################################################################
def TriangleNormal(x0, y0, z... | unpack("<f", struct.pack("@f", 140919.00))[0] == 140919.00)
# print "computer is little endian: ", self.little_endian
# print "f | ile is ascii: ", self.isascii
self.nfacets = 0
self.ndegenerate = 0
self.mr = MeasureBoundingBox()
def IsAscii(self, fdata):
l = fdata.readline(1024)
isascii = l[:5] == "solid" and (len(l) == 5 or (re.search("[^A-Za-z0-9\,\.\/\;\:\'... |
chippey/gaffer | python/GafferUITest/GadgetTest.py | Python | bsd-3-clause | 8,732 | 0.065964 | ##########################################################################
#
# Copyright (c) 2011-2012, John Haddon. All rights reserved.
# Copyright (c) 2011-2012, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted prov... | f.assertEqual( g1. | getVisible(), True )
self.assertEqual( g1.visible(), True )
g1.setVisible( False )
self.assertEqual( g1.getVisible(), False )
self.assertEqual( g1.visible(), False )
g2 = GafferUI.Gadget()
g1.addChild( g2 )
self.assertEqual( g2.getVisible(), True )
self.assertEqual( g2.visible(), False )
g1.setVis... |
serge-sans-paille/pythran | pythran/tests/test_openmp.py | Python | bsd-3-clause | 1,597 | 0.001879 | import unittest
from distutils.errors import CompileError
from pythran.tests import TestFromDir
import os
import pythran
fro | m pythran.syntax import PythranSyntaxError
from pythran.spec import Spec
class TestOpenMP(TestFromDir):
path = os.path.join(os.path.dirname(__file__), "openmp")
class TestOpenMP4(TestFromDir):
path | = os.path.join(os.path.dirname(__file__), "openmp.4")
@staticmethod
def interface(name, file=None):
return Spec({name: []})
@staticmethod
def extract_runas(name, filepath):
return ['#runas {}()'.format(name)]
class TestOpenMPLegacy(TestFromDir):
'''
Test old style OpenMP cons... |
anuragiitg/nixysa | third_party/ply-3.1/test/testyacc.py | Python | apache-2.0 | 13,190 | 0.006444 | # testyacc.py
import unittest
try:
import StringIO
except ImportError:
import io as StringIO
import sys
import os
sys.path.insert(0,"..")
sys.tracebacklimit = 0
import ply.yacc
def check_expected(result,expected):
resultlines = []
for line in result.splitlines():
if line.startswith("WARNING... | en(resultlines) != len(expectedlines):
return False
for rline,eline in zip(resultlines,expectedlines):
if not rline.endswith(eline):
| return False
return True
def run_import(module):
code = "import "+module
exec(code)
del sys.modules[module]
# Tests related to errors and warnings when building parsers
class YaccErrorWarningTests(unittest.TestCase):
def setUp(self):
sys.stderr = StringIO.StringIO()
sys.stdo... |
sudikrt/costproML | staticDataGSir/restful.py | Python | apache-2.0 | 1,107 | 0 | import requests
import json
import restful_webapi
import os
# This example shows how to use the Requests library with RESTful API
# This web service stores arbitrary JSON data under integer keys
# We can use GET/POST/PUT/DELETE HTTP methods to modify the data
# Run a local server that we can use
restful_webapi.run_se... | ost(service, data=data)
created = r.json()['created']
print "Message ID: " + str(created)
print "Showing the message..."
r = requests.get(service + '/' + str(created))
print "Serv | ice returned: " + str(r.json())
print "Updating the message..."
data = json.dumps("Welcome, world")
r = requests.put(service + '/' + str(created), data=data)
print "Service returned: " + str(r.json())
print "Showing the message again..."
r = requests.get(service + '/' + str(created))
print "Service returned: " + str(... |
xupingmao/xnote | handlers/system/system_info.py | Python | gpl-3.0 | 2,138 | 0.013069 | # -*- coding:utf-8 -*-
# @author xupingmao <578749341@qq.com>
# @since 2020/08/22 21:54:56
# @modified 2022/02/26 10:40:22
import xauth
impor | t xtemplate
import xutils
import os
import re
import sys
import platform
import xconfig
from xutils import dateutil
from xutils import fsutil
from xutils import Storage
from xutils import mem_util
try:
import sqlite3
except ImportError:
s | qlite3 = None
def get_xnote_version():
return xconfig.get_global_config("system.version")
def get_mem_info():
mem_used = 0
mem_total = 0
result = mem_util.get_mem_info()
mem_used = result.mem_used
sys_mem_used = result.sys_mem_used
sys_mem_total = result.sys_mem_total
return "%s/%s/%... |
kelvinlawson/pykaraoke | pykplayer.py | Python | lgpl-2.1 | 16,454 | 0.003343 | #
# Copyright (C) 2010 Kelvin Lawson (kelvinl@users.sourceforge.net)
#
# This library 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 2.1 of the License, or (at your option) any later ... | onds).
def GetPos(self):
if self.State == STATE_PLAYING:
return pygame.time.get_ticks() - self.PlayStartTime
else:
return self.PlayTime
def SetupOptions(self, usage = None):
""" Initialise and return optparse OptionParser object,
suitable for parsing the ... | turn manager.SetupOptions(usage, self.songDb)
# Below methods are internal.
def setupDump(self):
# Capture the output as a sequence of numbered frame images.
self.PlayTime = 0
self.PlayStartTime = 0
self.PlayFrame = 0
self.State = STATE_CAPTURING
self.dumpFrame... |
g-weatherill/oq-hazardlib | openquake/hazardlib/tests/gsim/gsim_table_test.py | Python | agpl-3.0 | 29,750 | 0 | # The Hazard Library
# Copyright (C) 2015, GEM Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# T... | n_and_stddev_table(self):
"""
Builds the expected mean and standard deviation tables
"""
expected_means = {
"PGA": np.ones([10, 1, 5, 2]),
"PGV": np.ones([10, 1, 5, 2]),
"SA": np.ones([10, 3, 5, 2])
}
# | For second level revise values
expected_means["PGA"][:, :, :, self.IDX] *= 1.5
expected_means["PGV"][:, :, :, self.IDX] *= 0.5
expected_means["SA"][:, 0, :, self.IDX] *= 1.5
expected_means["SA"][:, 1, :, self.IDX] *= 2.0
expected_means["SA"][:, 2, :, self.IDX] *= 0.5
exp... |
a0x77n/chucky-tools | src/chucky_tools/neighborhood/__init__.py | Python | gpl-3.0 | 55 | 0 | from .ch | ucky_neighborhood_tool import NeighborhoodTool | |
certik/pyjamas | pygtkweb/demos/065-setselection.py | Python | apache-2.0 | 2,570 | 0.002335 | #!/usr/bin/env python
# example setselection.py
import pygtk
pygtk.require('2.0')
import gtk
import time
class SetSelectionExample:
# Callback when the user toggles the selection
def selection_toggled(self, widget, window):
if widget.get_active():
self.have_selection = window.selection_ow... | s the selection
selection_button = gtk.ToggleButton("Claim Selection")
eventbox.add(selection_button)
selection_button.connect("toggled", self.selection_toggled, eventbox)
eventbox.connect_object("selection_clear_event", self.selection_clear,
selection_bu... | _get", self.selection_handle)
selection_button.show()
window.show()
def main():
gtk.main()
return 0
if __name__ == "__main__":
SetSelectionExample()
main()
|
cameres/github-dl | download/download_repos.py | Python | mpl-2.0 | 779 | 0.003851 | import git
def download_repos(dst, repos):
"""
handles downloading paginated gists
Arguments
---------
dst : string
folder to write repositories to
repos : array-like of git.repo.base.Repo
repositori | es to download
"""
for repo in repos:
try:
# we can clone the projects, but we only want to download small projects
print("downloading repo {}/{}".format(repo.owner.login, repo.name))
git.repo.base.Repo.clone_from(repo.git_url, dst + '/' + repo.full_name)
exce... | ady exists and is not an empty directory.\n\''):
raise e
|
jm-begon/taskcarrier | taskcarrier/__init__.py | Python | bsd-3-clause | 764 | 0.001309 | # -*- coding: utf-8 -*-
"""
===========
TaskCarrier
===========
:mod:`taskcarrier` contains a set of tools built on top of the `joblib`
library which allow to use transparently Parallel/Serial code using
simple but nice abstraction.
"""
__author__ = "Begon Jean-Michel <jm.begon@gmail.com>"
__copyright__ = "3-clause BS... | ",
"SerialMapper", "StaticPara | llelMapper", "DynamicParallelMapper",
"MapperInstance"]
|
william-richard/moto | moto/redshift/responses.py | Python | apache-2.0 | 28,522 | 0.001227 | from __future__ import unicode_literals
import json
import xmltodict
from jinja2 import Template
from six import iteritems
from moto.core.responses import BaseResponse
from .models import redshift_backends
def convert_json_error_to_xml(json_error):
error = json.loads(json_error)
code = error["Error"]["Cod... | urn data
class RedshiftResponse(BaseResponse):
@property
def redshift_backend(self):
return redshift_backends[self.region]
def get_response(self, response):
if self.request_json:
return json.dumps(response)
else:
xml = xmltodict.unparse(itemize(response), f... | xml
def call_action(self):
status, headers, body = super(RedshiftResponse, self).call_action()
if status >= 400 and not self.request_json:
body = convert_json_error_to_xml(body)
return status, headers, body
def unpack_complex_list_params(self, label, names):
unpack... |
brotchie/keepnote | keepnote/compat/xmlobject_v3.py | Python | gpl-2.0 | 13,706 | 0.008172 | """
XmlObject
This module allows concise definitions of XML file formats for python
objects.
"""
#
# KeepNote
# Copyright (c) 2008-2009 Matt Rasmussen
# Author: Matt Rasmussen <rasmus@alum.mit.edu>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GN... | f self.name != "":
out.write("</%s>\n" % self.name)
# TODO: remove get?
class TagMany (Tag):
def __init__(self, name, iterfunc, get=None, set=None,
before=None,
| after=None,
tags=[]):
Tag.__init__(self, name,
get=None,
set=set,
tags=tags)
self._iterfunc = iterfunc
self._read_item = get
self._write_item = set
self._beforefunc = before
... |
unreal666/outwiker | plugins/markdown/markdown/markdown_plugin_libs/markdown/extensions/admonition.py | Python | gpl-3.0 | 3,188 | 0.000941 | """
Admonition extension for Python-Markdown
========================================
Adds rST-style admonitions. Inspired by [rST][] feature with the same name.
[rST]: http://docutils.sourceforge.net/docs/ref/rst/directives.html#specific-admonitions # noqa
See <https://Python-Markdown.github.io/extensions/admoniti... | return self.RE.search(block) or \
(block.startswith(' ' * self.tab_length) and sibling is not None and
sibling.get('class', '').find(self.CLASSNAME) != -1)
def run(self, parent, blocks):
sibling = self.lastChild(parent)
block = blocks.pop(0)
m = self.RE. | search(block)
if m:
block = block[m.end():] # removes the first line
block, theRest = self.detab(block)
if m:
klass, title = self.get_class_and_title(m)
div = etree.SubElement(parent, 'div')
div.set('class', '%s %s' % (self.CLASSNAME, klass))
... |
daniell/django-import-export | tests/core/tests/test_fields.py | Python | bsd-2-clause | 2,262 | 0.000442 | from __future__ import unicode_literals
from datetime import date
from django.test import TestCase
from import_export import fields
class Obj:
def __init__(self, name, date=None):
self.name = name
self.date = date
class FieldTest(TestCase):
def setUp(self):
self.field = fields.F... | self.row['name'])
def test_save(s | elf):
self.row['name'] = 'foo'
self.field.save(self.obj, self.row)
self.assertEqual(self.obj.name, 'foo')
def test_save_follow(self):
class Test:
class name:
class follow:
me = 'bar'
test = Test()
field = fields.Field(c... |
stefanv/scipy3 | scipy/integrate/info.py | Python | bsd-3-clause | 1,311 | 0.000763 | ## Automatically adapted for scipy Oct 21, 2005 by
"""
Integration routines
====================
Methods for Integrating Functions given function object.
quad -- General purpose integration.
dblquad -- General purpose double integration.
tplquad -- General purpose triple integration.
... | latively compute integral.
simps -- Use Simpson's rule to compute integral from samples.
romb -- Use Romberg Integration to compute integral from
(2**k + 1) evenly-spaced samples.
See the | special module's orthogonal polynomials (special) for Gaussian
quadrature roots and weights for other weighting factors and regions.
Interface to numerical integrators of ODE systems.
odeint -- General integration of ordinary differential equations.
ode -- Integrate ODE using VODE and Z... |
jmesteve/saas3 | openerp/addons_extra/base_location/state.py | Python | agpl-3.0 | 1,248 | 0.000801 | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Nicolas Bessi. Copyright Camptocamp SA
# Contributor: Pedro Manuel Baeza <pedro.baeza@serviciosbaeza.com>
# Ignacio Ibeas <ignacio@acysos.com>
#
# This program is free software: yo... | nerp.osv import orm, fields
class ResCountryState(orm.Mode | l):
_inherit = 'res.country.state'
_columns = {'better_zip_ids': fields.one2many('res.better.zip', 'state_id', 'Cities')}
|
HybridF5/nova | nova/tests/unit/objects/test_aggregate.py | Python | apache-2.0 | 8,667 | 0 | # Copyright 2013 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | l('aggregate.updatemetadata.end', msg.event_type)
self.assertEqual({'todelete': None, 'toadd': 'myval'},
msg.payload['meta_data'])
self.assertEqual({'foo': 'bar', 'toadd': 'myval'}, agg.metadata)
def test_destroy(self):
self.mox.StubOutWithMock(db, 'aggregate_delete... | =self.context)
agg.id = 123
agg.destroy()
def test_add_host(self):
self.mox.StubOutWithMock(db, 'aggregate_host_add')
db.aggregate_host_add(self.context, 123, 'bar'
).AndReturn({'host': 'bar'})
self.mox.ReplayAll()
agg = aggregate.Aggreg... |
kacperski1/budgie-script-applet | script.py | Python | gpl-2.0 | 1,518 | 0.003953 | #!/usr/bin/env python3
"""
script -- A widget displaying output of a script that lets you interact with it.
"""
import gi.repository, subprocess, sys
gi.require_version('Budgie', '1.0')
gi.require_version('Wnck', '3.0')
from gi.repository import Budgie, GObject, Wnck, Gtk, Gio, GLib
class ScriptPlugin(GObject.GObje... | self.timeout_id = GObject.timeout_add(1000, self.on_timeout, None)
def on_click(self, button):
subprocess.call([GLib.get_user_config_dir()+"/"+self.directory+"/onclick.sh"])
def | on_timeout(self, user_data):
self.button.set_label(subprocess.check_output([GLib.get_user_config_dir()+"/"+self.directory+"/ontimeout.sh"]).decode(sys.stdout.encoding).strip())
return True
|
UmassJin/Leetcode | Array/Search_in_2D_matrix.py | Python | mit | 999 | 0.013013 | ```
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following prope | rties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16 | , 20],
[23, 30, 34, 50]
]
Given target = 3, return true
```
# Good answer !
class Solution:
# @param matrix, a list of lists of integers
# @param target, an integer
# @return a boolean
def searchMatrix(self, matrix, target):
m = len(matrix)
n = len(matrix[0])
left = 0; right =... |
kemayo/sublime-text-git | git/annotate.py | Python | mit | 7,837 | 0.001786 | from __future__ import absolute_import, unicode_literals, print_function, division
import tempfile
import re
import os
import codecs
import sublime
import sublime_plugin
from . import git_root, GitTextCommand
def temp_file(view, key):
if not view.settings().get('git_annotation_temp_%s' % key, False):
fd... | if not line.strip() == '-':
deletion = True
tracked_line_index -= 1
elif line.startswith('+'):
if deletion and not line.strip() == '+':
diff.append(['x', tracked_line_index])
inse... | |
stanfordnqp/spins-b | spins/goos/test_shapes.py | Python | gpl-3.0 | 6,692 | 0.000299 | import numpy as np
from spins import goos
from spins.goos import material
from spins.goos import shapes
def test_pixelated_cont_shape():
def init(size):
return np.ones(size)
var, shape = shapes.pixelated_cont_shape(
init, [100, 100, 10], [20, 30, 10],
var_name="var_name",
na... | low4])
]
assert group.eval(inputs) == goos.ArrayFlow(
[flow2, flow4, flow3, flow1])
assert (group.grad(inputs,
goos.ArrayFlow.Grad(
[grad2, grad4, grad3, grad1])) == [
goos.ArrayFlow.Grad([gr... | oos.ArrayFlow.Grad([grad4])
])
|
OKFNat/offenewahlen-nrw17 | setup.py | Python | mit | 1,452 | 0.002066 | from setuptools import setup, find_packages
import os
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
CLASSIFIERS = [
#'Development Status :: 1 - ',
'Environment :: Web Enviro... | l',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries :: Application Frameworks',
'Topic :: Open Da... | ework :: Django',
'Framework :: Django :: 1.11',
]
INSTALL_REQUIREMENTS = [
'Django==1.11.3'
]
setup(
author='Stefan Kasberger',
author_email='info@offenewahlen.at',
name='offenewahlen_api',
version='0.1',
#version=cms.__version__,
description='Open Election Data API from Austria.',
... |
notfier/touristique | tourists/tests/factories.py | Python | mit | 524 | 0 | # -*- coding: utf-8 | -*-
import factory
from data.tests.factories import DepartmentFactory
from ..models import Tourist, TouristCard
class TouristFactory(factory.DjangoModelFactory):
class Meta:
model = Tourist
first_name = 'Dave'
last_name = 'Greel'
email = 'greel@musicians.com'
class TouristCardFactory(fac... | elFactory):
class Meta:
model = TouristCard
tourist = factory.SubFactory(TouristFactory)
current_department = factory.SubFactory(DepartmentFactory)
|
cigroup-ol/metaopt | metaopt/plugin/print/optimum.py | Python | bsd-3-clause | 1,486 | 0.000673 | # -*- coding: utf-8 -*-
"""
Plugin that logs the current optimum to standard output.
"""
# Future
from __future__ import absolute_import, division, print_function, \
unicode_literals, with_statement
# First Party
from metaopt.plugin.plugin import Plugin
class OptimumPrintPlugin(Plugin): |
"""
Logs new optima for all return values to the standard output on result.
| For example::
Minimum for value: f(a=0.1, b=0.2) = 0.7
"""
def __init__(self):
self._optima = dict() # holds a tuple of args and result for each name
def on_invoke(self, invocation):
# There are no new optima in invokes, so do nothing.
pass
def on_result(self, invoc... |
tschneidereit/shumway | traceLogging/reduce.py | Python | apache-2.0 | 8,311 | 0.006858 | import argparse
import subprocess
import struct
import json
import shutil
import os
import collections
argparser = argparse.ArgumentParser(description='Reduce the logfile to make suitable for online destribution.')
argparser.add_argument('js_file', help='the js file to parse')
argparser.add_argument('output_name', hel... | stChildItem._replace(nextId = self.newId))
else:
assert self.newId == parent + 1
self.writeItem(parentItem._replace(children = 1))
self.writeItem(TreeItem(self.newId, oldItem.start, oldItem.stop, oldItem.textId, 0, 0))
newId = self.newId
self.newId += 1
r... |
class Overview:
def __init__(self, tree, dic):
self.tree = tree
self.dic = dic
self.engineOverview = {}
self.scriptOverview = {}
self.scriptTimes = {}
def isScriptInfo(self, tag):
return tag[0:6] == "script";
def clearScriptInfo(self, tag):
return tag ... |
rebost/django | django/templatetags/static.py | Python | bsd-3-clause | 3,940 | 0 | from urlparse import urljoin
from django import template
from django.template.base import Node
from django.utils.encoding import iri_to_uri
register = template.Library()
class PrefixNode(template.Node):
def __repr__(self):
return "<PrefixNode for %r>" % self.name
def __init__(self, varname=None, na... | base_css %}
{% static variable_with_path as varname %}
"""
return StaticNod | e.handle_token(parser, token)
def static(path):
return StaticNode.handle_simple(path)
|
googleapis/python-compute | google/cloud/compute_v1/services/region_commitments/pagers.py | Python | apache-2.0 | 5,692 | 0.000878 | # -*- coding: utf-8 -*-
# Copyright 2022 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... | either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from typing import (
Any,
AsyncIterator,
Awaitable,
Callable,
Sequence,
Tuple,
Optional,
Iterator,
)
from google.cloud.compute_v1.types import compute
c... | pager for iterating through ``aggregated_list`` requests.
This class thinly wraps an initial
:class:`google.cloud.compute_v1.types.CommitmentAggregatedList` object, and
provides an ``__iter__`` method to iterate through its
``items`` field.
If there are more pages, the ``__iter__`` method will ma... |
0x0all/nupic | tests/unit/py2/nupic/data/aggregator_test.py | Python | gpl-3.0 | 2,186 | 0.001372 | #!/usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions ... | eneral 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.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
"""Unit tests for aggregator modul... | import aggregator
class AggregatorTest(unittest.TestCase):
"""Unit tests for misc. aggregator functions."""
def testFixAggregationDict(self):
# Simplest case.
result = aggregator._aggr_weighted_mean((1.0, 1.0), (1, 1))
self.assertAlmostEqual(result, 1.0, places=7)
# Simple non-uniform case.
... |
GoogleCloudPlatform/PerfKitBenchmarker | perfkitbenchmarker/linux_benchmarks/kubernetes_mongodb_ycsb_benchmark.py | Python | apache-2.0 | 5,544 | 0.005051 | # Copyright 2015 PerfKitBenchmarker 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 applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS ... | YCSB against MongoDB.
YCSB is a load generator for many 'cloud' databases. MongoDB is a NoSQL
database.
MongoDB homepage: http://www.mongodb.org/
YCSB homepage: https://github.com/brianfrankcooper/YCSB/wiki
"""
import functools
import random
import string
import time
from absl import flags
from perfkitbenchmarker ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.