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 |
|---|---|---|---|---|---|---|---|---|
lucky-/django-amazon-buynow | amazon_buttons/models.py | Python | bsd-3-clause | 1,222 | 0.031915 | from django.db import models
# IPN Response
class ipn_response(models.Model):
status = models.CharField(max_length = 100, default='empty')
paymentReason = models.CharField(max_length = 300, default='empty')
operation = models.CharField(max_length=200, default='empty')
datetime = models.DateTimeField('date publi... | s.CharField(max_length=50, default='empty')
transactionAmount = models.CharField(max_length=50, default='empty')
ver_choice = (
('unverified', 'unverified'),
('verified', 'verified'),
('FLAG', 'FLAG'),
| )
ver_status = models.CharField(max_length=50, default='unverified', choices=ver_choice)
def __unicode__(self):
return self.status + ' ' + self.datetime.strftime("%b %d %Y %H:%M") + ' ' + self.ver_status
|
Glottotopia/aagd | moin/local/moin/build/lib.linux-x86_64-2.6/MoinMoin/action/bookmark.py | Python | mit | 1,218 | 0.001642 | # -*- coding: iso-8859-1 -*-
"""
MoinMoin - set or delete bookmarks (in time) for RecentChanges
@copyright: 2000-2004 by Juergen Hermann <[email protected]>,
2006 by MoinMoin:ThomasWaldmann
@license: GNU GPL, see COPYING for details.
"""
import time
from MoinMoin import wikiutil
from Mo... | this action: %(action)s.") % {"action": actname}, "error")
return Page(request, pagename).send_page()
timestamp = request.values.get('time')
if timestamp is not None:
if timestamp == 'del':
tm = None
else:
try:
tm = int(timestamp)
... | imestamp2version(time.time())
if tm is None:
request.user.delBookmark()
else:
request.user.setBookmark(tm)
request.page.send_page()
|
SravanthiSinha/edx-platform | lms/djangoapps/teams/tests/test_views.py | Python | agpl-3.0 | 40,384 | 0.003195 | # -*- coding: utf-8 -*-
"""Tests for the teams API at the HTTP request level."""
import json
import ddt
from django.core.urlresolvers import reverse
from django.conf import settings
from nose.plugins.attrib import attr
from rest_framework.test import APITestCase, APIClient
from courseware.tests.factories import Staf... | led_not_staff(self):
"""
Verifies that a user without global access who is enrolled in the course can access the team dashboard.
"""
CourseEnrollmentFactory.create(user=self.user, course_id=s | elf.course.id)
self.client.login(username=self.user.username, password=self.test_password)
response = self.client.get(self.teams_url)
self.assertContains(response, "TeamsTabFactory", status_code=200)
def test_enrolled_teams_not_enabled(self):
"""
Verifies that a user without... |
zmalik/mesos | support/mesos-gtest-runner.py | Python | apache-2.0 | 9,368 | 0.000107 | #!/usr/bin/env python
#
# 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
# "... | r(nshards)
env['GTEST_SHARD_INDEX'] = str(shard)
try:
output = subprocess.check_output(
executable.split(),
stderr=subp | rocess.STDOUT,
env=env,
universal_newlines=True)
print(Bcolors.colorize('.', Bcolors.OKGREEN), end='')
sys.stdout.flush()
return True, output
except subprocess.CalledProcessError as error:
print(Bcolors.colorize('.', Bcolors.FAIL), end='')
sys.stdout.f... |
ssadedin/seqr | seqr/views/react_app_tests.py | Python | agpl-3.0 | 3,332 | 0.002701 | from django.urls.base import reverse
import mock
from seqr.views.react_app import main_app, no_login_main_app
from seqr.views.utils.test_utils import AuthenticationTestCase, USER_FIELDS
class DashboardPageTest(AuthenticationTestCase):
databases = '__all__'
fixtures = ['users']
def _check_page_html(self,... | self.assertIn('nonce-{}'.format(nonce), response.get('Content-Security-Policy'))
# test static assets are | correctly loaded
content = response.content.decode('utf-8')
self.assertRegex(content, r'static/app(-.*)js')
self.assertRegex(content, r'<link\s+href="/static/app.*css"[^>]*>')
self.assertEqual(content.count('<script type="text/javascript" nonce="{}">'.format(nonce)), 2)
@mock.patch... |
Tesora/tesora-python-troveclient | troveclient/v1/hosts.py | Python | apache-2.0 | 2,242 | 0 | # Copyright 2011 OpenStack Foundation
# Copyright 2013 Rackspace Hosting
# 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/lice... | urce_class(self, res) for res in body[response_key]]
def _action(self, host_id, body):
"""Perform a host "action" -- update."""
url = "/mgmt/hosts/%s/instances/action" % host_id
resp, body = self.api.client.post(url, body=body)
common.check | _for_exceptions(resp, body, url)
def update_all(self, host_id):
"""Update all instances on a host."""
body = {'update': ''}
self._action(host_id, body)
def index(self):
"""Get a list of all hosts.
:rtype: list of :class:`Hosts`.
"""
return self._list("/... |
iurisilvio/soapfish | tests/xsd/xsd_datetime_test.py | Python | bsd-3-clause | 2,625 | 0.001905 | import unittest
from datetime import datetime, timedelta, tzinfo
from lxml import etree
from soapfish import xsd
# TODO: Change import on update to iso8601 > 0.1.11 (fixed in 031688e)
from iso8601.iso8601 import FixedOffset, UTC # isort:skip
class DatetimeTest(unittest.TestCase):
def test_rendering(self):
... | ('flight')
self.assertRaises(Exception, lambda: mixed.render(xmlelement, 'takeoff_datetime', 1))
def test_parsing_utctimezone(self):
class Test(xsd.ComplexType):
datetime = xsd.Element(xsd.DateTime)
XML = '<root><datetime>2011-06-30T00:19:00+0000</datetime></root>'
test ... | ce(tzinfo=None))
def test_parsing_timezone(self):
class Test(xsd.ComplexType):
datetime = xsd.Element(xsd.DateTime)
XML = '<root><datetime>2011-06-30T20:19:00+01:00</datetime></root>'
test = Test.parsexml(XML)
self.assertEqual(datetime(2011, 6, 30, 19, 19, 0), test.datet... |
spcui/tp-qemu | qemu/tests/qmp_command.py | Python | gpl-2.0 | 12,613 | 0 | import logging
import re
from autotest.client.shared import utils, error
from virttest import utils_misc, qemu_monitor
@error.context_aware
def run(test, params, env):
"""
Test qmp event notification, this case will:
1) Start VM with qmp enable.
2) Connect to qmp port then run qmp_capabilities command... | msg += ("\n'%s' is not in QMP command output"
% val)
raise error.TestFail(msg)
elif result_check == "m_in_q":
res = output.splitlines(True)
msg = "Key value from human monitor command is not in"
msg +... | P command output: '%s'" % qmp_o
msg += "\nHuman monitor command output '%s'" % output
for i in range(len(res)):
params = res[i].rstrip().split()
for param in params:
try:
str_o = str(qmp_o.values())
e... |
jjshoe/s3-cloudfront-upload-and-invalidate | s3-cloudfront-upload-and-invalidate.py | Python | agpl-3.0 | 4,503 | 0.01288 | #!/usr/bin/python
import os
import re
import sys
import time
import boto
import hashlib
# md5 function
def md5_for_file(filepath, block_size=2**20):
f = open(filepath, 'rb')
md5 = hashlib.md5()
while True:
data = f.read(block_size)
if not data:
break
md5.update(data)... | configuration['WebsiteCon | figuration']['IndexDocument']['Suffix']
# A list of files to invalidate
invalidate_files = []
# Walk all files
for root, subdirs, files in os.walk(walk_dir):
for filename in files:
disk_path = os.path.join(root, filename)
s3_path = os.path.join(root.replace(os.getcwd(), ''), filename)
# Chec... |
atados/api | atados_core/emails.py | Python | mit | 7,061 | 0.016867 | # -*- coding: utf-8 -*-
from django.core.mail import EmailMultiAlternatives
from django.template import Context, Template
from django.template.loader import get_template
from helpers import ClientRouter, MailAssetsHelper, strip_accents
class UserMail:
"""
This class is responsible for firing emails for User... | ience', subject, self.make_context({
'project_name': apply.project.name,
'feedback_form_url': feedback_form_url,
}), apply.volunteer.user.email)
#+ def sendAfterApply4Weeks(self): # new ruler
#+ """
#+ """
#+ context = Context({'user': self.user.name})
#+ return self.sendEmail('volu... | ~', context)
#+ def send3DaysBeforePontual(self): # new ruler
#+ """
#+ """
#+ context = Context({'user': self.user.name})
#+ return self.sendEmail('volunteer3DaysBeforePontual', '~ ~ ~ ~ ~', context)
class NonprofitMail(UserMail):
"""
This class contains all emails sent to nonprofits
"""
... |
warwick-one-metre/opsd | warwick/observatory/operations/actions/onemetre/initialize.py | Python | gpl-3.0 | 5,291 | 0.001323 | #
# This file is part of opsd.
#
# opsd 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.
#
# opsd is distributed in the hope that it wil... | for camera_id in cameras:
status = cam_status(self.log_name, camera_id)
if 'temperature_locked' not in status:
log.error(self.log_name, 'Failed to check temperature on camera ' + camera_id)
return False
locked[camera_id] = st... | t(CAMERA_CHECK_INTERVAL)
return not self.aborted
def __initialize_telescope(self):
"""Initializes and homes the telescope"""
self.set_task('Initializing Mount')
if not tel_init(self.log_name):
log.error(self.log_name, 'Failed to initialize mount')
return Fal... |
flgiordano/netcash | +/google-cloud-sdk/lib/surface/compute/disk_types/describe.py | Python | bsd-3-clause | 1,301 | 0.00538 | # Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | le Compute Engine disk type',
'DESCRIPTION': """\ |
*{command}* displays all data associated with a Google Compute
Engine disk type.
""",
}
|
hayesgm/cerberus | scripts/cerberus_run.py | Python | mit | 1,413 | 0.009908 | #!/usr/bin/env python
import syslog
from subprocess import call
import urllib2
import json
import re
import docker_login
from user_data import get_user_data
# Starts a docker run for a given repo
# This will effectively call `docker run <flags> <repo>:<tag>`
# This service is monitored by Upstart
# User Data
# docker.... | ','run','--cidfile=/var/run/docker/container.cid'] + flags + [repo_with_tag]) != 0:
raise Exception("Failed to run docker repo | %s" % repo_with_tag)
|
carragom/modoboa | modoboa/limits/__init__.py | Python | isc | 56 | 0 | default_app | _confi | g = "modoboa.limits.apps.LimitsConfig"
|
maggienj/ActiveData | pyLibrary/env/http.py | Python | mpl-2.0 | 11,843 | 0.001604 | # encoding: utf-8
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Author: Kyle Lahnakoski ([email protected])
#
# MIMICS THE requests API (http://docs.python-re... | _future__ import unicode_literals
from copy import copy
from mmap import mmap
from numbers import Number
from tempfile import TemporaryFile
from requests import sessions, Response
import mo_json
from pyLibrary import convert
fr | om mo_logs.exceptions import Except
from mo_logs import Log
from mo_dots import Data, coalesce, wrap, set_default, unwrap
from pyLibrary.env.big_data import safe_size, ibytes2ilines, icompressed2ibytes
from mo_math import Math
from jx_python import jx
from mo_threads import Thread, Lock
from mo_threads import Till
from... |
Fresnoy/kart | common/admin.py | Python | agpl-3.0 | 132 | 0 | from django.contrib import admin
from .models import | Website, BTBeacon
admin.site.register(Website)
admin.site.re | gister(BTBeacon)
|
oh-my-fish/plugin-foreign-env | test.py | Python | mit | 49 | 0 | f | rom os import environ
|
environ['THIS'] = 'that'
|
OpenCCG/openccg | src/ccg2xml/ccg_editor.py | Python | lgpl-2.1 | 52,260 | 0.005243 | #!/usr/bin/python
# Author: Ben Wing <[email protected]>
# Date: April 2006
#############################################################################
# #
# ccg_editor.ply #
# ... | 'sel.last'
FontScale = 0 # use bigger font on linux
if sys.platform[:3] != 'win': # and other non-windows boxes
FontScale = 3
# Initial top-level window; it's not clear we need this.
# FIXME: It | sucks that we have to call Tk() to get the first top-level window
# but Toplevel() for all others. We should be able to call Tk() initially,
# and then Toplevel() to create all top-level windows, including the first.
root = None
# List of all open CFile objects
openfiles = {}
filenames = []
class CTab(Frame):
... |
dnanexus/dx-toolkit | src/python/dxpy/utils/describe.py | Python | apache-2.0 | 52,416 | 0.004293 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2013-2016 DNAnexus, Inc.
#
# This file is part of dx-toolkit (DNAnexus platform client libraries).
#
# 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... | and printing the
contents of describe hashes for various DNAne | xus entities (projects,
containers, dataobjects, apps, and jobs).
'''
from __future__ import print_function, unicode_literals, division, absolute_import
import datetime, time, json, math, sys, copy
import locale
import subprocess
from collections import defaultdict
import dxpy
from .printing import (RED, GREEN, BLUE... |
haizawa/odenos | src/main/python/org/o3project/odenos/core/component/network/flow/ofpflow/ofp_flow_action_pop_mpls.py | Python | apache-2.0 | 1,666 | 0.0006 | # -*- coding:utf-8 -*-
# Copyright 2015 NEC Corporation. #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License... | twork.flow.basic.flow_action import (
FlowAction
)
class OFPFlowActionPopMpls(FlowAction):
MPLS_UNICAST = 0x8847
MPLS_MULTICAST = 0x8848
# property key
ETH_TYPE = "eth_type"
def __init__(self, type_, eth_type):
| super(OFPFlowActionPopMpls, self).__init__(type_)
self._body[self.ETH_TYPE] = eth_type
@property
def eth_type(self):
return self._body[self.ETH_TYPE]
@classmethod
def create_from_packed(cls, packed):
return cls(packed[cls.TYPE], packed[cls.ETH_TYPE])
def packed_obje... |
tedlaz/pyted | misthodosia/m13a/f_newEmployeeWizard.py | Python | gpl-3.0 | 13,202 | 0.016424 | # -*- coding: utf-8 -*-
'''
Created on 15 Φεβ 2013
@author: tedlaz
'''
from PyQt4 import QtCore, QtGui,Qt
from collections import OrderedDict
import utils_db as dbutils
import widgets
from utils_qt import fFindFromList
import osyk
#import classwizard_rc
sqlInsertFpr = u'''
INSERT INTO m12_fpr (epon... | label.setWordWrap(True)
|
layout = QtGui.QVBoxLayout()
layout.addWidget(label)
self.setLayout(layout)
class coDataPage(QtGui.QWizardPage):
def __init__(self, parent=None):
super(coDataPage, self).__init__(parent)
self.setButtonText(QtGui.QWizard.BackButton,u'< Πίσω')
se... |
openwisp/django-x509 | django_x509/migrations/0006_passphrase_field.py | Python | bsd-3-clause | 792 | 0 | # Generated by Django 2.1 on 2018-09-04 12:56
from django.db i | mport migrations, models
class Migration(migrations.Migration):
dependencies = [('django_x509', '0005_organizational_unit_name')]
operations = [
migrations.AddField(
model_name='ca',
name='passphrase',
field=models.CharField(
blank=True,
... |
model_name='cert',
name='passphrase',
field=models.CharField(
blank=True,
help_text='Passphrase for the private key, if present',
max_length=64,
),
),
]
|
sqlalchemy/mako | test/test_cache.py | Python | mit | 18,519 | 0.000162 | import time
from mako import lookup
from mako.cache import CacheImpl
from mako.cache import register_plugin
from mako.lookup import TemplateLookup
from mako.template import Template
from mako.testing.assertions import eq_
from mako.testing.config import config
from mako.testing.exclusions import requires_beaker
from m... | e
class MockCacheImpl(CacheImpl):
realcacheimpl = None
def __init__(self, cache):
self.cache = cache
def set_backend(self, cache, backend):
if backend == "simple":
self.realcacheimpl = SimpleBackend()
else:
self.realcacheimpl = cache._load_impl(backend)
... | def _setup_kwargs(self, kw):
self.kwargs = kw.copy()
self.kwargs.pop("regions", None)
self.kwargs.pop("manager", None)
if self.kwargs.get("region") != "myregion":
self.kwargs.pop("region", None)
def get_or_create(self, key, creation_function, **kw):
self.key = ... |
rymurr/q | tickerplant.py | Python | mit | 1,161 | 0.013781 | from gevent import monkey; monkey.patch_all()
import gevent
import socket
import array
import time
import cStringIO
import bitstring
from q.unparser import format_bits
from q.utils import get_header
from q.parser import parse |
def foo():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost',5010))
login = array.array('b','' + '\x03\x00') #null terminated signed char array (bytes)
sock.send(login.tostring())
result = sock.recv(1) #blocking | recv
sock.send(format_bits('.u.sub[`trade;`]', async=True, symbol=False, endianness='be').tobytes())
while True:
data=cStringIO.StringIO()
header = sock.recv(8)
data.write(header)
data.reset()
_,size = get_header(bitstring.ConstBitStream(bytes=data.read()))
print... |
abramhindle/UnnaturalCodeFork | python/testdata/launchpad/lib/lp/services/webapp/tests/test_session.py | Python | agpl-3.0 | 3,740 | 0 | # Copyright 2009-2012 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
import datetime
from testtools import TestCase
from testtools.matchers import Contains
from lp.services.webapp.login import (
isFreshLogin,
OpenIDCallbackView,
)... | domain,
LaunchpadCookieClientIdManager,
)
from lp.testing import (
person_logged_in,
TestCaseWithFactory,
)
from lp.testing.layers import DatabaseFunctionalLayer
class GetCookieDomainTestCase(TestCase):
def test_base_domain(self):
# Test that the base Launchpad domain gives a domain p... | eter
# that is visible to the virtual hosts.
self.assertEqual(get_cookie_domain('launchpad.net'), '.launchpad.net')
def test_vhost_domain(self):
# Test Launchpad subdomains give the same domain parameter
self.assertEqual(get_cookie_domain('bugs.launchpad.net'),
... |
uwosh/uwosh.grants | tests/testUwoshgrantsProposalWorkflow.py | Python | gpl-2.0 | 3,768 | 0.009023 | import os, sys
from Products.Archetypes.interfaces.layer import ILayerContainer
from Products.Archetypes.atapi import *
from Products.ATContentTypes.tests.utils import dcEdit
from Products.ATContentTypes.tests.utils import EmptyValidator
from Products.ATContentTypes.tests.utils import EmailValidator
if __name__ == '__... | , id="10_it_organizations-33.pdf")
self.login('director1')
pro.setFacultyReviewer(['Reviewer One','Reviewer Two'])
self.portal_workflow.doActionFor( pro, 'sendToPanel')
def test_transition_sendToProposer(self):
pro = self.createProosal()
self.fill_out_proposal(pr | o)
self.login('director1')
#pro.invokeFactory(type_name="File", id="10_it_organizations-4.pdf")
#self.login('director1')
#pro.setFacultyReviewer([1,2])
pro.setProposalApproved(True)
self.portal_workflow.doActionFor( pro, 'sendToProposer')
"""
def test_s... |
disqus/django-old | tests/modeltests/validation/models.py | Python | bsd-3-clause | 3,826 | 0.008364 | from datetime import datetime
from django.core.exceptions import ValidationError
from django.db import models
def validate_answer_to_universe(value):
if value != 42:
raise ValidationError('This is not the answer to life, universe and everything!', code='not42')
class ModelToValidate(models.Model):
na... | count = models.IntegerField(unique_for_date="start_date", unique_for_year="end_date")
order = models.IntegerField(unique_for_month="end_date")
name = models.CharField(max_length=100)
class CustomMessagesModel(models.Model):
other = models.IntegerField(blank=True, null=True)
nu | mber = models.IntegerField(db_column='number_val',
error_messages={'null': 'NULL', 'not42': 'AAARGH', 'not_equal': '%s != me'},
validators=[validate_answer_to_universe]
)
class Author(models.Model):
name = models.CharField(max_length=100)
class Article(models.Model):
title = models.CharFie... |
datsfosure/ansible | lib/ansible/plugins/action/template.py | Python | gpl-3.0 | 8,281 | 0.004468 | # (c) 2015, Michael DeHaan <[email protected]>
#
# This file is part of Ansible
#
# Ansible 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 lat... | host = vars['template_host'],
uid = vars['template_uid'],
file = to_bytes(vars['template_path'])
)
vars['ansible_managed'] = time.strftime(
managed_str,
time.localtime(os.path.getmtime(source))
)
... | preserve_trailing_newlines=True)
self._templar.set_available_variables(old_vars)
except Exception as e:
return dict(failed=True, msg=type(e).__name__ + ": " + str(e))
local_checksum = checksum_s(resultant)
remote_checksum = self.get_checksum(tmp, dest, not directory_prep... |
jian929/stagefright | vp9/omx-components/videocodec/libvpx_internal/libvpx/tools/diff.py | Python | gpl-2.0 | 4,218 | 0.003793 | #!/usr/bin/env python
## Copyright (c) 2012 The WebM project authors. All Rights Reserved.
##
## Use of this source code is governed by a BSD-style license
## that can be found in the LICENSE file in the root of the source
## tree. An additional intellectual property rights grant can be found
## in the file PATENT... | en_b = int(diffrange.group(4))
header = [a_line, b_line, line]
hunk = DiffHunk(header, a, b, start_a, len_a, start_b, len_b)
else:
# Add the current line to the hunk
hunk.Append(line)
# See if the whole hunk has been parsed. If so, yield it a... | l hunks are a parse error
assert hunk is None
|
jmcarp/webargs | webargs/__init__.py | Python | mit | 231 | 0 | # -*- codin | g: utf-8 -*-
__version__ = '0.8.0'
__author__ = 'Steven Loria'
__license__ = 'MIT'
from webargs.co | re import Arg, WebargsError, ValidationError, Missing
__all__ = ['Arg', 'WebargsError', 'ValidationError', 'Missing']
|
Itxaka/libcloud | libcloud/compute/drivers/cloudwatt.py | Python | apache-2.0 | 5,016 | 0 | # 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 ... | JSON', e)
try:
expires = body['access']['token']['expires']
self.auth_token = bo | dy['access']['token']['id']
self.auth_token_expires = parse_date(expires)
self.urls = body['access']['serviceCatalog']
self.auth_user_info = None
except KeyError:
e = sys.exc_info()[1]
raise MalformedResponseError('Auth JSON res... |
abispo/horteloesurbanos | horteloesurbanos/horteloesurbanos/urls.py | Python | gpl-3.0 | 773 | 0 | """horteloesurbanos URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/top | ics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an impo | rt: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls impor... |
dcalacci/Interactive_estimation | game/control/migrations/0001_initial.py | Python | mit | 492 | 0.002033 | # -*- coding: utf- | 8 -*-
# Generated by Django 1.10.1 on 2016-09-11 21:16
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Control',
fi... | ),
]
|
RosesTheN00b/BudgetButlerWeb | butler_offline/test/RequesterStub.py | Python | agpl-3.0 | 1,716 | 0 | from requests.exceptions import ConnectionError
class RequesterStub:
def __init__(self, mocked_requests, mocked_decode='', auth_cookies=''):
self.mocked_requests = mocked_requests
self.call_count = {}
self.mocked_decode = mocked_decode
for url in mocked_requests.keys():
... | f.mocked_requests[url]
print('WARNING, NON MATCHING REQUEST:', url, data)
return None
def post_raw(self, url, data):
return self.post(url, data)
def put(self, url, data, cookies):
if not self.auth_cookies == cookies:
| return 'error, auth not valid'
return self.post(url, data)
def decode(self, request):
return self.mocked_decode
def call_count_of(self, url):
if url not in self.call_count:
return 0
return len(self.call_count[url])
def complete_call_count(self):
... |
lemieuxl/pyplink | pyplink/tests/__main__.py | Python | mit | 1,406 | 0 | # This file is part of pyplink.
#
# The MIT License (MIT)
#
# Copyright (c) 2014 Louis-Philippe Lemieux Perreault
#
# 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, includ... | es 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 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTI... |
ChainsAutomation/chains | lib/chains/services/ircbot/__init__.py | Python | gpl-2.0 | 20,436 | 0.007683 | #! /usr/bin/env python
# encoding: utf-8
# based on
# example program using ircbot.py by Joel Rosdahl <[email protected]>
# ircbot
try:
from irc.bot import SingleServerIRCBot
#from ircbot import SingleServerIRCBot
from irc.client import is_channel, ip_quad_to_numstr, ip_numstr_to_quad, NickMask
from irc... | for cn, co in self.channels.items():
if cn == channel:
chanobj = co
break
if not chanobj:
msg = 'Cannot op %s on %s because I am not joined to that channel' % (nick, channel)
self.connection.notice(self | .channel, msg)
log.warn(msg)
return
if not self.connection.get_nickname() in chanobj.opers():
msg = 'Cannot op %s on %s because I am not op on that channel' % (nick, channel)
self.connection.notice(self.channel, msg)
log.warn(msg)
return
... |
slremy/bioinspiredbackend | websingleton.py | Python | gpl-3.0 | 12,276 | 0.058488 | import web
import time
import timeit
from collections import deque
from sys import exit, exc_info, argv
import math
import os
localport = os.environ.get('PORT', 8080)
from cStringIO import StringIO
clock = timeit.default_timer;
web.config.debug = False;
urls = (
'/u','controller',
'/u2','controller2',
'/... | ][1]);
if angle_d1 > self.angle_max: angle_d1=self.angle_max;
elif angle_d1 < -self.angle_max: angle_d1=-self.angle_max;
u_y = self.AM*(angle_d1*16 - self.X1[-1][1]) + self.BM * (self.X1[-1][1]-self.X1[-2][1])
self.Y1[-3]=self.Y1[-2];self.Y1[-2]=self.Y1[-1];self.Y1[-1]=(u_x,u_y,);
self.file_str.write("%s ... | ulativeError + abs(e_x) #/(duration/h)
self.CumulativeError = self.CumulativeError + abs(e_y) #/(duration/h)
def updatePID(self):
#global X0, X1, Y0, Y1, Theta, StateTime, CumulativeError, Count
self.Count += 1
t = self.Count*self.h;
'''
Determine the desired beam angle based on the ball posit... |
jspargo/AneMo | anemoController/temps/migrations/0006_auto_20170211_2222.py | Python | gpl-2.0 | 547 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [ |
('temps', '0005_auto_20170211_2212'),
]
operations = [
migrations.RenameField(
mo | del_name='tempmanager',
old_name='override',
new_name='logic_state',
),
migrations.RenameField(
model_name='tempmanager',
old_name='state',
new_name='override_state',
),
]
|
kubernetes-client/python | kubernetes/client/models/v2_pods_metric_status.py | Python | apache-2.0 | 4,423 | 0 | # coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: release-1.23
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import si... | elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
| lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"... |
google-research/google-research | tf3d/semantic_segmentation/metric.py | Python | apache-2.0 | 9,713 | 0.007825 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | rics_dict = self.get_metric_dictionary()
return metrics_dict[self.eval_prefix + '_avg/mean_iou']
def get_metric_dictionary(self):
metrics_dict = {}
class_recall_list = [] # used for calculating mean pixel accuracy.
class_iou_list = [] # used for calculating mean iou.
for c in self.class_rang... | trics[c].result()
class_recall = tp / (tp + fn)
class_precision = tf.where(
tf.greater(tp + fn, 0.0), _safe_div(tp, (tp + fp)),
tf.constant(np.NaN))
class_iou = tf.where(
tf.greater(tp + fn, 0.0), tp / (tp + fn + fp), tf.constant(np.NaN))
class_recall_list.append(cl... |
edx/ecommerce | ecommerce/extensions/order/migrations/0025_auto_20210922_1857.py | Python | agpl-3.0 | 1,484 | 0.004717 | # Generated by Django 2.2.24 on 2021-09-22 18:57
from django.db import migrations, models
import django.db.models.deletion
class Migra | tion(migrations.Migration):
dependencies = [
('order', '0024_markordersstatuscompleteconfig'),
]
operations = [
migrations. | AlterField(
model_name='communicationevent',
name='event_type',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='communication.CommunicationEventType', verbose_name='Event Type'),
),
migrations.CreateModel(
name='Surcharge',
... |
KristianHolsheimer/tensorflow_training | sol/ex_while_loop_cumsum.py | Python | gpl-3.0 | 755 | 0.001325 | tf.reset_default_graph()
# input
x_len = 6
x = tf.constant([7, 0, 42, 1, 13, 4])
def cond(i, acc, y):
return i < x_len
def body(i, acc, y):
acc += x[i]
y = tf.concat([y, tf.expand_dims(acc, axis=0)], axis=0) # y.shape = (?,)
i += 1
return i, acc, y
# initial value for y
y_init = tf.zeros(sha... | ial values for the loop variables
loop_vars = [0, 0, y_init]
# specify dynamic shape invariant for y
shape_invariants = [
tf.TensorShape([]), # i.shape
tf.TensorShape([]), # acc.shape
tf.TensorShape([None]), # y.shape
]
# compute the loo | p
i, acc, y = tf.while_loop(cond, body, loop_vars, shape_invariants)
with tf.Session() as s:
print s.run(tf.cumsum(x))
print s.run(y) |
mazvv/travelcrm | travelcrm/views/accounts_items.py | Python | gpl-3.0 | 6,534 | 0.000459 | # -*-coding: utf-8-*-
import logging
from pyramid.view import view_config, view_defaults
from pyramid.httpexceptions import HTTPFound
from . import BaseView
from ..models import DBSession
from ..models.account_item import AccountItem
from ..lib.bl.subscriptions import subscribe_resource
from ..lib.utils.common_utils... | em': account_item,
'title': self._get_title(_(u'Edit')),
}
@view_config(
name='edit',
request_method='POST',
renderer='json',
permission='edit'
)
def _edit(self):
account_item | = AccountItem.get(self.request.params.get('id'))
form = AccountItemForm(self.request)
if form.validate():
form.submit(account_item)
event = ResourceChanged(self.request, account_item)
event.registry()
return {
'success_message': _(u'Saved'... |
SeungGiJeong/SK_FastIR | memory/windows2003ServerMemory.py | Python | gpl-3.0 | 432 | 0.002315 | from __future__ import unicode_literals
from memory.mem import _Memory
class Windows2003 | ServerMemory(_Memory):
def __init__(self, params): |
super(Windows2003ServerMemory, self).__init__(params)
def csv_all_modules_dll(self):
super(Windows2003ServerMemory, self)._csv_all_modules_dll()
def csv_all_modules_opened_files(self):
super(Windows2003ServerMemory, self)._csv_all_modules_opened_files() |
valmynd/MediaFetcher | src/plugins/youtube_dl/youtube_dl/extractor/flickr.py | Python | gpl-3.0 | 3,980 | 0.026884 | from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import (
compat_str,
compat_urllib_parse_urlencode,
)
from ..utils import (
ExtractorError,
int_or_none,
qualities,
)
class FlickrIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.|secure\.)?flickr\.com/photos/[\w\-_@]+/(?... | ,
'view_count': int_or_none(video_info.get('views')),
'tags': [tag.get('_content') for tag in video_info.get('tags', {}).get('tag', [])],
'license': self._LICENSES.get(video_info.get | ('license')),
}
else:
raise ExtractorError('not a video', expected=True)
|
lichengshuang/createvhost | python/cdn/wangsu/bin/wangsu.py | Python | apache-2.0 | 2,674 | 0.017228 | #!/usr/bin/python
#coding:utf-8
from hashlib import sha256
import ConfigParser
import os
import hmac
import json
import base64
import requests
import urlparse
import datetime
import json
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )
def getConfig():
"""
将通用的一些数据读取放在一个函数里。不再每个函数里去写一遍了。
"""
g... | key
def encode(time):
print("encode:"+time.decode())
msg=username+":"+time.decode()
result=base64.b64encode(msg.encode('utf-8'))
print("encode:"+result.decode())
return result
def call():
req = requests.Request(url)
req.add_header('Date', date)
req.add_header('Accept','ap | plication/json')
req.add_header('Content-Type','application/json')
req.add_header('Authorization','Basic '+auth.decode())
#with requests.urlopen(req,data=body.encode('utf-8')) as resu:
# print(resu.read(300).decode('utf-8'))
def rCall():
headers = {'date':date,'Accept':'application/json'... |
mohou/Mohou_Box-master | boxUpdate/boxUpdate.py | Python | apache-2.0 | 19,795 | 0.011111 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf8')
#sys.path.append("/home/pi/oprint/lib/python2.7/si | te-packages/tornado-4.0.1-py2.7-linux-armv7l.egg/")
#sys.path.append("/home/pi/oprint/lib/python2.7/site-packages/backports.ssl_match_hostname-3.4.0.2-py2.7.egg/")
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import uuid
import hash | lib
import time
import logging
import os
import urllib
import httplib
import json
import md5
from tornado.httpclient import HTTPClient
from tornado.escape import json_decode
from tornado.options import define, options
from common import Application
from network_api import get_allwifi_info, get_network_info, get_dns_i... |
mycFelix/heron | heronpy/connectors/pulsar/pulsarspout.py | Python | apache-2.0 | 5,438 | 0.009195 | #!/usr/bin/env python
# -*- encoding: 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 under the Apache... | dir=os.getcwd(), delete=False)
flHandler.write(GenerateLogConfContents(logFileName))
flHandler.flush()
flHandler.close()
return flHandler.name
class PulsarSpout(Spout, StreamletBoltBase):
"""PulsarSpout: reads from a pulsar topic"""
# pylint: disable=too-many-instance-att | ributes
# pylint: disable=no-self-use
def default_deserializer(self, msg):
return [str(msg)]
# TopologyBuilder uses these constants to set
# cluster/topicname
serviceUrl = "PULSAR_SERVICE_URL"
topicName = "PULSAR_TOPIC"
receiveTimeoutMs = "PULSAR_RECEIVE_TIMEOUT_MS"
deserializer = "PULSAR_MESSAGE_... |
EduPepperPDTesting/pepper2013-testing | lms/djangoapps/djangosaml2/unit_tests/settings.py | Python | agpl-3.0 | 5,559 | 0.000899 | # Django settings for tests2 project.
import django
import sys
sys.path.append("../..")
sys.path.append("../../../../..")
from siteconf import *
DEBUG = True
TEMPLATE_DE | BUG = DEBUG
ADMINS = (
# ('Your Name', '[email protected]'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': MYSQL_DB_W,
'USER': MYSQL_USER_W,
'PASSWORD': MYSQL_PASSWORD_W,
'HOST': MYSQL_HOST_W,
'PORT': MYSQL_PO... | one for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. ... |
CS-SI/QGIS | python/plugins/processing/gui/MultipleFileInputDialog.py | Python | gpl-2.0 | 4,837 | 0.000827 | # -*- coding: utf-8 -*-
"""
***************************************************************************
MultipleExternalInputDialog.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
(C) 2013 by CS Systemes d'informatio... | aya'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import os
from qgis.core import QgsSettings
from qgis.PyQt import uic
from qgis.PyQt.QtCore import QByteArray
from qgis.PyQt.QtWidgets import QDialog, QAbstractItemView, QPushButton, QDialogButtonBox, QFileDialog
from... | Model, QStandardItem
pluginPath = os.path.split(os.path.dirname(__file__))[0]
WIDGET, BASE = uic.loadUiType(
os.path.join(pluginPath, 'ui', 'DlgMultipleSelection.ui'))
class MultipleFileInputDialog(BASE, WIDGET):
def __init__(self, options):
super(MultipleFileInputDialog, self).__init__(None)
... |
cfobel/python___pymunk | pymunk/_chipmunk_ffi.py | Python | mit | 2,348 | 0.009796 | """
Contains low level wrapper around the chipmunk_ffi methods exported by
chipmunk_ffi.h as those methods are not automatically generated by the wrapper
generator.
You usually dont need to use this module directly, instead use the high level binding in pymunk
"""
from ctypes import *
from .vec2d import Vec2... | dyIsStatic')
cpBodyLocal2World = (function_pointer(cpVect, POINTER(cpBody), cpVect)).in_dll(chipmunk_lib, '_cpBodyLocal2World')
cpBodyWorld2Local = (function_pointer(cpVect, POINTER(cpBody), cpVect)).in_dll(chipmun | k_lib, '_cpBodyWorld2Local')
cpArbiterGetShapes = (function_pointer(None, POINTER(cpArbiter), POINTER(POINTER(cpShape)), POINTER(POINTER(cpShape)))).in_dll(chipmunk_lib, '_cpArbiterGetShapes')
cpArbiterIsFirstContact = (function_pointer(cpBool, POINTER(cpArbiter))).in_dll(chipmunk_lib, '_cpArbiterIsFirstContact')
... |
aphentik/django-webdriver | django_webdriver/management/commands/test.py | Python | apache-2.0 | 3,072 | 0.005534 | import sys
import os
import socket
from optparse import make_option
from urlparse import urlparse
from django.conf import settings
from django.core.management.base import BaseCommand
from django_nose.management.commands.test import Command
from django_webdriver.message import Message
SETTINGS = getattr(settings, "... | t(Message.build_error(msg))
sys.exit(1)
def _set_exclude(self, **options):
regexp_exclude = '--exclude='
if options.get('isSelenium') or options.get('remote_provider'):
sys.argv.append('--exclude=tests(?!_selen | ium)')
elif not options.get('isAll'):
sys.argv.append('--exclude=tests_selenium*')
def _set_live_server(self, **options):
if options.get('liveserver'):
port = urlparse(options['liveserver']).port
else:
port = '8081'
ip = socket.gethostbyname(s... |
dimtruck/magnum | magnum/tests/unit/db/test_magnum_service.py | Python | apache-2.0 | 4,105 | 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... | utils.create_test_magnum_service()
self.assertRaises(exception.MagnumServiceAlreadyExists,
utils.c | reate_test_magnum_service)
def test_get_magnum_service_by_host_and_binary(self):
ms = utils.create_test_magnum_service()
res = self.dbapi.get_magnum_service_by_host_and_binary(
self.context, ms['host'], ms['binary'])
self.assertEqual(ms.id, res.id)
def test_get_magnum_servi... |
Symphonia/Searcher | ProcessThread.py | Python | mit | 306 | 0.019608 | import os, sys, subprocess
from PySide import QtCore,QtGui
|
class ProcessThread(QtCore.QThread):
def __init__(self,program,p | ath):
super(ProcessThread,self).__init__()
self.path = path
self.program = program
def run(self):
subprocess.call([self.program,self.path])
|
cchamanEE/pydare | test/daretest.py | Python | gpl-3.0 | 2,371 | 0.094053 | from pydare import DareSolver
import numpy
import unittest
class DareTestCase(unittest.TestCase):
def testIterative(self):
a = numpy.matrix([[0.0,0.1,0.0],\
[0.0,0.0,0.1],\
| [0.0,0.0,0.0]])
b = numpy.matrix([[1.0,0.0], \
[0.0,0.0], \
[0.0,1.0]])
r = numpy.matrix([[0.0,0.0], \
[0.0,1.0]])
q = numpy.matrix([[10.0**5.0, 0.0,0.0], \
[0.0,10.0**3.0,0.0], \
[0.0,0.0,-10.0]])
ds = DareSolver(a,b,q,r... |
self.assertAlmostEqual(10.0**3.0,x[1,1],3)
self.assertAlmostEqual(0.0,x[2,2],3)
for i in range(0,3):
for j in range(0,3):
if i != j:
self.assertAlmostEqual(0.0,x[i,j],3)
def testDirect(self):
a = numpy.matrix([[0.8147, 0.1270],[0.9058, 0.9134]])
b = numpy.matrix([[0.6324, 0.2785],[0.097... |
biocommons/eutils | tests/test_eutils_xmlfacades_einforesult.py | Python | apache-2.0 | 495 | 0 | import vcr
@vcr.use_cassette
def test_einfo_dblist(client):
dblist_result = client.einfo()
assert 'protein' in dblist_result.databases
assert 48 == | len(dblist_result.databases)
@vcr.use_cassette
def test_einfo_dbinfo(client):
dbinfo_result = client.einfo(db="protein")
assert "370927433" == dbinfo_result.count
assert "protein" == dbinfo_result.dbname
assert "Protein sequence record" == dbinfo_result.description
assert "P | rotein" == dbinfo_result.menuname
|
sdispater/orator | tests/orm/relations/test_morph_to_many.py | Python | mit | 6,256 | 0.001918 | # -*- coding: utf-8 -*-
import pendulum
from flexmock import flexmock, flexmock_teardown
from ... import OratorTestCase
from ...utils import MockConnection
from orator.query.builder import QueryBuilder
from orator.query.grammars import QueryGrammar
from orator.query.processors import QueryProcessor
from orator.query... | "foo": "bar",
}
]
).and_return(True)
mock_query_builder = flexmock()
relation.get_query().should_receive("get_query").and_return(mock_query_builder)
mock_query_builder.should_receive("new_query").once().and_return(query)
relation.should_receive("t... | uching=lambda: True)
relation = self._get_relation()
query = flexmock()
query.should_receive("from_").once().with_args("taggables").and_return(query)
query.should_receive("where").once().with_args("taggable_id", 1).and_return(
query
)
query.should_receive("whe... |
F5Networks/f5-common-python | f5/bigip/tm/asm/policies/login_enforcement.py | Python | apache-2.0 | 1,423 | 0.000703 | # coding=utf-8
#
# Copyright 2017 F5 Networks Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in | compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either expr... | exception import UnsupportedOperation
class Login_Enforcement(UnnamedResource):
"""BIG-IP® ASM Login Enforcement resource."""
def __init__(self, policy):
super(Login_Enforcement, self).__init__(policy)
self._meta_data['required_json_kind'] = 'tm:asm:policies:login-enforcement:login-enforcement... |
richlanc/KaraKara | website/karakara/scripts/hash_matcher.py | Python | gpl-3.0 | 3,469 | 0.005189 | import hashlib
import re
import os
import pickle
from functools import partial
from externals.lib.misc import file_scan, update_dict
import logging
log = logging.getLogger(__name__)
VERSION = "0.0"
# Constants --------------------------------------------------------------------
DEFAULT_DESTINATION = './files/'
DEF... | le)
if not dry_run:
try:
os.symlink(f.absolute, os.path.join(destination_folder, f.file))
except OSError:
log.info('unable to symlink {0}'.format(f.file))
# ------------------------------------------------------------------------------
de | f move_files():
pass
# Command Line -----------------------------------------------------------------
def get_args():
import argparse
parser = argparse.ArgumentParser(
description="""
Find the duplicates
""",
epilog=""" """
)
# Folders
parser.add_argument('-d'... |
winhamwr/neckbeard | neckbeard/bin/neckbeard.py | Python | bsd-3-clause | 5,380 | 0.000186 | from __future__ import absolute_import
import argparse
import logging
import os.path
from neckbeard.actions import up, view
from neckbeard.configuration import ConfigurationManager
from neckbeard.loader import NeckbeardLoader
from neckbeard.output import configure_logging
from neckbeard.resource_tracker import build_... | guration for %s checks out A-ok!", environment_name)
output_dir = os.path.join(
configuration_directory, '. | expanded_config', environment_name,
)
logger.info("You can see the deets on your nodes in: %s", output_dir)
configuration.dump_environment_config(
environment_name,
output_dir,
)
def do_up(
configuration_directory, environment_name, configuration,
):
logger.info("Running up on ... |
HybridF5/jacket | jacket/tests/storage/unit/db/test_qos_specs.py | Python | apache-2.0 | 9,362 | 0 | # Copyright (C) 2013 eBay Inc.
# Copyright (C) 2013 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/lice... | s")
expected1 = dict(name='Name1', id=spec_id1, consumer='front-end')
expected2 = dict(name='Name2', id=spec_id2, consumer='back-end')
expected3 = dict(name='Name3', id=spec_id3, consumer='back-end')
del value1['consumer']
del value2['consumer']
del value3['consumer']
... | self.assertIn(expected1, specs)
self.assertIn(expected2, specs)
self.assertIn(expected3, specs)
def test_qos_specs_get_by_name(self):
name = str(int(time.time()))
value = dict(consumer='front-end',
foo='Foo', bar='Bar')
specs_id = self._create_qo... |
TeamCohen/GuineaPig | tutorial/wordprob.py | Python | lgpl-3.0 | 667 | 0.032984 | from guineapig import *
import sys
import math
import logging
def tokens(line):
for tok in line.split(): yield tok.lower()
class WordProb(Planner):
| wc = ReadLines('corpus.txt') | Flatten(by=tokens) | Group(by=lambda x:x, reducingTo=ReduceToCount())
total = Group(wc, by=lambda x:'ANY', retaining=lambda (word,count):count, reducingTo=ReduceToSum()) | ReplaceEach(by=lambda (wo | rd,count):count)
wcWithTotal = Augment(wc, sideview=total,loadedBy=lambda v:GPig.onlyRowOf(v))
prob = ReplaceEach(wcWithTotal, by=lambda ((word,count),n): (word,count,n,float(count)/n))
# always end like this
if __name__ == "__main__":
WordProb().main(sys.argv)
|
commaai/openpilot | common/gpio.py | Python | mit | 432 | 0.013889 | def gpio_init(pin, o | utput):
try:
with open(f"/sys/class/gpio/gpio{pin}/direction", 'wb') as f:
f.write(b"out" if output else b"in")
except Exception as e:
print(f"Failed to set gpio {pin} direction: {e}")
def gpio_set(pin, high):
try:
with open(f"/sys/class/gpio/gpio{pin}/value", 'wb') as f:
f.write(b"1" if... | et gpio {pin} value: {e}")
|
rackerlabs/qonos | qonos/tests/functional/v1/test_api_simpledb.py | Python | apache-2.0 | 990 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 Rackspace
| #
# 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
# ... | IND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import sys
from oslo_config import cfg
from qonos.tests.functional.v1 import base
from qonos.tests import utils as utils
CONF = cfg.CONF
def setUpModule():
CONF.db_api =... |
hankcs/HanLP | hanlp/datasets/srl/__init__.py | Python | apache-2.0 | 67 | 0.014925 | # -*- coding:utf-8 -*-
# Author: | hankcs
# Date: 2020-06-22 19:15
| |
alcemirfernandes/irobotgame | lib/level.py | Python | gpl-3.0 | 3,108 | 0.000966 | # -*- encoding: utf-8 -*-
# I Robot? - a dancing robot game for pyweek
#
# Copyright: 2008 Hugo Ruscitti
# License: GPL 3
# Web: http://www.losersjuegos.com.ar
import pyglet
import common
import motion
class Level:
"""Representa una nivel del juego.
Conoce al grupo de robots que baila..."""
def __init_... | group
self.sprites = []
self.dt = 0.0
self._load_motion_images()
def _load_motion_images(self):
self.images = [
| None,
common.load_image('moves/1.png'),
common.load_image('moves/2.png'),
common.load_image('moves/3.png'),
common.load_image('moves/4.png'),
None,
common.load_image('moves/6.png'),
common.load_image('... |
mvaled/sentry | src/sentry/rules/conditions/reappeared_event.py | Python | bsd-3-clause | 283 | 0 | from __future__ import absolute_import
from sentry.rules.conditions.base i | mport E | ventCondition
class ReappearedEventCondition(EventCondition):
label = "An issue changes state from ignored to unresolved"
def passes(self, event, state):
return state.has_reappeared
|
naznadmn/pyblog | manage.py | Python | mit | 617 | 0.004862 | # -*- coding: utf-8 -*-
from app.blog import db
from app.blog import app
from app.blog.models import User, Category, Article
from app.admin.models import CategoryView, ArticleView
from flask_admin import Admin
from flask_script import Manager
# Manager
manager | = Manager(app)
# Admin
admin = Admin(app, name='microblog', template_mode='bootstrap3')
admin.add_ | view(CategoryView(Category, db.session))
admin.add_view(ArticleView(Article, db.session))
@manager.command
def migrate():
"""
Create database and tables
"""
db.create_all()
# Start point
if __name__ == '__main__':
manager.run() |
Stvad/anki | aqt/models.py | Python | agpl-3.0 | 7,018 | 0.000855 | # Copyright: Damien Elmes <[email protected]>
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
from aqt.qt import *
from operator import itemgetter
from aqt.utils import showInfo, askUser, getText, maybeHideClose, openHelp
import aqt.modelchooser, aqt.clayout
from anki import stdmodels
from ... | n list(n.keys()):
n[name] = "("+name+")"
try:
if "{{cloze:Text}}" in self.model['tmpls'][0]['qfmt']:
n['Text'] = _("This is a {{c1::sample}} cloze deletion.")
except:
# invalid cloze
pass
return n
| def onFields(self):
from aqt.fields import FieldDialog
n = self._tmpNote()
FieldDialog(self.mw, n, parent=self)
def onCards(self):
from aqt.clayout import CardLayout
n = self._tmpNote()
CardLayout(self.mw, n, ord=0, parent=self, addMode=True)
# Cleanup
#... |
xybydy/kirilim | db.py | Python | gpl-2.0 | 1,832 | 0.002183 | __author__ = 'fatihka'
from sqlalchemy import Column, Integer, String, Unicode, Float, Boolean, create_engine, Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# db_name = 'ww.db'
db_name = ':memory:'
tanimlar = {'company': 'Fatih Ka.', 'optional': 'NO'}
periodss =... | class Hesaplar(Base):
__table__ = Table('hes | aplar', Base.metadata,
Column('id', Integer, primary_key=True),
Column('number', String, nullable=True),
Column('ana_hesap', String, nullable=True),
Column('name', Unicode, nullable=True),
C... |
Sophist-UK/Sophist_picard | scripts/pyinstaller/macos-library-path-hook.py | Python | gpl-2.0 | 1,066 | 0.001876 | # -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019 Philipp Wolfer
#
# 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
# o | f the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS | FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You 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, Fifth Floor, Boston, MA 02110-1301, USA.
import os
import sys
... |
TeamSPoon/logicmoo_workspace | packs_web/butterfly/lib/python3.7/site-packages/virtualenv/config/env_var.py | Python | mit | 844 | 0.001185 | from __future__ import absolute_import, unicode_literals
import os
from virtualenv.util | .six import ensure_str, ensure_text
from .convert import convert
def get_env_var(key, as_type):
"""Get the environment variable option.
:param | key: the config key requested
:param as_type: the type we would like to convert it to
:return:
"""
environ_key = ensure_str("VIRTUALENV_{}".format(key.upper()))
if os.environ.get(environ_key):
value = os.environ[environ_key]
# noinspection PyBroadException
try:
s... |
eduNEXT/edx-platform | common/lib/xmodule/xmodule/modulestore/inheritance.py | Python | agpl-3.0 | 16,569 | 0.002957 | """
Support for inheritance of fields down an XBlock hierarchy.
"""
from django.utils import timezone
from xblock.core import XBlockMixin
from xblock.fields import Boolean, Dict, Float, Integer, List, Scope, String
from xblock.runtime import KeyValueStore, KvsFieldData
from xmodule.fields import Date, Timedelta
from... | lems. However, if the course-wide setting is a specific number, you cannot set the Maximum Attempts for individual problems to unlimited."), # lint-amnesty, | pylint: disable=line-too-long
values={"min": 0}, scope=Scope.settings
)
matlab_api_key = String(
display_name=_("Matlab API key"),
help=_("Enter the API key provided by MathWorks for accessing the MATLAB Hosted Service. "
"This key is granted for exclusive use in this cou... |
queria/my-tempest | tempest/api/compute/v3/servers/test_server_rescue.py | Python | apache-2.0 | 1,828 | 0 | # Copyright 2013 Hewlett-Packard Development Company, L.P.
# 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... | or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.api.compute import base
from tempest import config
from tempest import test
CONF = config.CONF
class ServerRescueV3Test(base.BaseV3ComputeTest):
@classmethod
def resource_se... | if not CONF.compute_feature_enabled.rescue:
msg = "Server rescue not available."
raise cls.skipException(msg)
super(ServerRescueV3Test, cls).resource_setup()
# Server for positive tests
resp, server = cls.create_test_server(wait_until='BUILD')
cls.server_id... |
developersociety/django-glitter | glitter/assets/models.py | Python | bsd-3-clause | 1,508 | 0.000663 | from django.db import models
from .mixins import FileMixin
class BaseCategory(models.Model):
title = models.CharField(max_length=100, unique=True)
class Meta:
abstract = True
ordering = ('title',)
def __str__(self):
return self.title
class FileCategory(BaseCategory):
class... | index=True)
file = models.FileField(upload_to='assets/file')
file_size = models.PositiveIntegerField(default=0, editable=False)
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
class ImageCategory(BaseCategory):
class Meta(BaseCategory.Meta):
... | bose_name_plural = 'image categories'
class Image(FileMixin, models.Model):
category = models.ForeignKey(ImageCategory, blank=True, null=True)
title = models.CharField(max_length=100, db_index=True)
file = models.ImageField(
'Image', upload_to='assets/image', height_field='image_height', width_fie... |
riklaunim/django-examples | ember-drf-example/manage.py | Python | mit | 252 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "drf_ember.settings") |
from django.core.management import ex | ecute_from_command_line
execute_from_command_line(sys.argv)
|
jgsogo/django-generic-filters | django_genericfilters/models.py | Python | bsd-3-clause | 56 | 0 | """Must be | kept even empty. That makes a Djan | go app."""
|
sambayless/monosat | examples/python/shortestpath_benchmark.py | Python | mit | 5,539 | 0.02334 | #!/usr/bin/env python3
from monosat import *
import argparse
from itertools import tee
import random
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
parser = argparse.ArgumentParser(description='BGAMapper')
parser.add_argument("--seed"... | t("-n",type=int,help="Number of reachability | constraints",default=1)
parser.add_argument("--max-distance",type=float,help="Max distance (as a multiple of width) ",default=2.7)
parser.add_argument("--min-distance",type=float,help="Min distance (as a multiple of width) ",default=2.3)
args = parser.parse_args()
if args.height is None:
args.height = args.width... |
kaiping/incubator-singa | examples/onnx/backend.py | Python | apache-2.0 | 1,642 | 0 | #
# 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 this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http | ://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissio... |
TomAugspurger/pandas | pandas/tests/frame/test_query_eval.py | Python | bsd-3-clause | 46,046 | 0.000804 | from io import StringIO
import operator
import numpy as np
import pytest
import pandas.util._test_decorators as td
import pandas as pd
from pandas import DataFrame, Index, MultiIndex, Series, date_range
import pandas._testing as tm
from pandas.core.computation.check import _NUMEXPR_INSTALLED
PARSERS = "python", "pa... | (res2, exp)
# list equality (really just set membership)
res1 = df.query('color == ["red"]', parser=parser, engine=engine)
res2 = df.query('["red"] == color', parser=parser, engine=engine)
exp = df[ind.isin([ | "red"])]
tm.assert_frame_equal(res1, exp)
tm.assert_frame_equal(res2, exp)
res1 = df.query('color != ["red"]', parser=parser, engine=engine)
res2 = df.query('["red"] != color', parser=parser, engine=engine)
exp = df[~ind.isin(["red"])]
tm.assert_frame_equal(res1, exp)
... |
leyondlee/HoneyPy-Docker | HoneyPy-0.6.2/plugins/FTPUnix/__init__.py | Python | gpl-3.0 | 129 | 0 | # C | opyright (c) 2016 foospidy
# https://github.com/foospidy/HoneyPy |
# See LICENSE for details
from FTPUnix import pluginFactory
|
mewbak/idc | transf/parse/_builtins.py | Python | lgpl-2.1 | 373 | 0 | # Builtin namespace
from transf.lib.base import *
from transf.lib.combine import *
from t | ransf.lib.traverse import *
from transf.lib.unify import *
from transf.lib | .lists import *
from transf.lib.strings import tostr
from transf.lib.arith import *
from transf.lib.iterate import *
from transf.lib import *
from transf import lib
import transf
from __builtin__ import *
|
e-koch/VLA_Lband | 16B/16B-236/imaging/transform_and_uvsub.py | Python | mit | 2,125 | 0 |
'''
Split out each SPW from the combined MS (concat_and_split.py), convert
to LSRK, and subtract continuum in uv-p | lane
'''
import os
import sys
from tasks import mstransform, uvcontsub, partition, split
myvis = '16B-236_lines.ms'
spw_num = int(sys.argv[-1])
# Load in the SPW dict in the repo on cedar
execfile(os.path.expanduser("~/code/VLA_Lband/16B/spw_setup.py"))
default('mstransform')
casalog.post("On SPW {}".format(spw... | n to look for
# absorption features. Split the uvsubtraction into a separate function
out_vis = "16B-236_{0}_spw_{1}_LSRK.ms"\
.format(linespw_dict[spw_num][0], spw_num)
out_vis_mms = "16B-236_{0}_spw_{1}_LSRK.mms"\
.format(linespw_dict[spw_num][0], spw_num)
mstransform(vis=myvis, outputvis=out_vis_mms, spw=... |
cpausmit/Kraken | filefi/014/debug.py | Python | mit | 1,936 | 0.01343 | # $Id: debug.py,v 1.3 2010/10/23 12:43:55 ceballos Exp $
import FWCore.ParameterSet.Config as | cms
process = cms.Process('FILLER')
# import of standard configurations
process.load('Configuration/StandardSequences/Services_cff')
process.load('FWCore/MessageService/MessageLogger_cfi')
process.load('Configuration/StandardSequences/GeometryIdeal_cff')
process.load('Configuration/StandardSequences/MagneticField_38... | tions_GlobalTag_cff')
process.load('Configuration/EventContent/EventContent_cff')
process.configurationMetadata = cms.untracked.PSet(
version = cms.untracked.string('Mit_014a'),
annotation = cms.untracked.string('RECODEBUG'),
name = cms.untracked.string('BambuProduction')
)
process.maxEvents = cm... |
AcademicsToday/py-academicstoday | academicstoday_project/teacher/tests/test_assignment.py | Python | apache-2.0 | 26,573 | 0.003838 | # Django & Python
from django.core.urlresolvers import resolve
from django.http import HttpRequest
from django.http import QueryDict
from django.test import TestCase
from django.test import Client
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.contrib... | ()
user = User.objects.get(email=TEST_USER_EMAIL)
teacher = Teacher.objects.create(user=user)
# Create a test course | .
Course.objects.create(
id=1,
title="Comics Book Course",
sub_title="The definitive course on comics!",
category="",
teacher=teacher,
).save()
course = Course.objects.get(id=1)
Assignment.objects.create(
assign... |
otaviosoares/search-artist-challenge | src/search_artists/search_artists/sorter.py | Python | gpl-3.0 | 258 | 0 | cla | ss MedianSorter():
def __init__(self, median):
self.__median = median
def __call__(self, value1, value2):
v1 = value1['age']
v2 = value2['age']
return -1 if abs(self.__median - v1) < abs(self.__median - v2) else 1 | |
ebigelow/LOTlib | LOTlib/Testing/old/Examples/Number/SearchTest.py | Python | gpl-3.0 | 461 | 0.008677 | """
class to test Search.py
follows the standards in https://docs.python.org/2/library/unittest.html
"""
import unittest
fro | m LOTlib.Examples.Number. | Run import *
class SearchTest(unittest.TestCase):
# initialization that happens before each test is carried out
def setUp(self):
pass
# function that is executed after each test is carried out
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()
|
TeamSPoon/logicmoo_workspace | packs_web/butterfly/lib/python3.7/site-packages/virtualenv/seed/wheels/acquire.py | Python | mit | 4,426 | 0.003615 | """Bootstrap"""
from __future__ import absolute_import, unicode_literals
import logging
import os
import sys
from operator import eq, lt
from virtualenv.util.path import Path
from virtualenv.util.six import ensure_str
from virtualenv.util.subprocess import Popen, subprocess
from .bundle import from_bundle
from .util... | or_py_version=for_py_version,
search_dirs=search_dirs,
app_data=app_data,
to_folder=app_data.house,
)
return wheel
def download_wheel(distribution, version_spec, for_py_version, search_dirs, app_data, to_folder):
| to_download = "{}{}".format(distribution, version_spec or "")
logging.debug("download wheel %s %s to %s", to_download, for_py_version, to_folder)
cmd = [
sys.executable,
"-m",
"pip",
"download",
"--progress-bar",
"off",
"--disable-pip-version-check",
... |
kyleterry/tenyks-contrib | src/tenyksscripts/scripts/goatthrower.py | Python | mit | 1,487 | 0.01076 | import random
def run(data, settings):
if data['payload'] == 'goat thrower':
if random.randint(0, 110) == 0:
outcome = random.randint(0, 2)
if outcome == 0:
return "{nick}: The goat thrower engulfs you in a billowing wave of goat. Goats swim over your body as they re... | ction in biodiversity.".format(nick = data['nick'])
else:
distance = random.randrange(0, 100)
num_goats = random.randrange(1, 5)
judgement = ""
if distance < 25:
judgement = "Fucking awful."
elif distance < 50:
judgement... | better next time."
elif distance < 75:
judgement = "Not bad. I've seen better."
elif distance < 100:
judgement = "Nice throw, idiot. Why are you throwing goats?"
else:
judgement = "Calm down, kingpin"
return '{nick}: You ma... |
aashish24/tangelo | data-processing/charitynet-join.py | Python | apache-2.0 | 1,019 | 0.000981 | import sys
import pymongo
donors = pymongo.Connection("mongo")["xdata"]["charitynet.normalized.donors"]
donors.ensure_index("accountNumber")
transactions = pymongo.Connection("mongo")["xdata"]["charitynet.normalized.transactions"]
transactions.ensure_index("date")
transactions.ensure_index("charity_id")
count = 0
for... | ion in transactions.find():
if count > 0 and count % 1000 == 0:
sys.stderr.write("%d\n" % count)
count = count + 1
if "loc" not in transaction:
| donor = donors.find_one({"accountNumber": transaction["person_id"]})
if donor:
if "state" in donor:
transaction["state"] = donor["state"]
if "county" in donor:
transaction["county"] = donor["county"]
if "block" in donor:
tran... |
ibis-inria/wellFARE | wellfare/preprocessing/__init__.py | Python | lgpl-3.0 | 150 | 0 | __a | ll__ = ["remove_bumps", "filter_outliers"]
from .preprocessing import (
remove_bumps, filter_outliers, filter_outliersnew, calibration_cur | ve)
|
youtube/cobalt | third_party/llvm-project/lldb/packages/Python/lldbsuite/test_event/build_exception.py | Python | bsd-3-clause | 709 | 0.00141 | class BuildError(Exception):
def __init__(self, called_process_error):
super(BuildError, self).__init__("Error when b | uilding test | subject")
self.command = called_process_error.lldb_extensions.get(
"command", "<command unavailable>")
self.build_error = called_process_error.lldb_extensions.get(
"stderr_content", "<error output unavailable>")
def __str__(self):
return self.format_build_error(self.... |
markovmodel/PyEMMA | pyemma/plots/tests/__init__.py | Python | lgpl-3.0 | 881 | 0.001135 |
# This file is part of PyEMMA.
#
# Copyright (c) 2015, 2014 Computational Molecular Biology Group, Freie Universitaet Berlin (GER)
#
# PyEMMA 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 vers... | or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
def teardown_module():
# close all figures
import matplotlib.pylab ... | plt.close('all')
|
francocurotto/GraphSLAM | src/python-helpers/commons/g2o2lab.py | Python | gpl-3.0 | 1,819 | 0.003848 | '''
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 distributed in the hope that it will be useful,
but WITHOUT... | lt file in g2o format
resdir: directory to output leb format
"""
resDir = "res_lab/"
guessData = slamData(guessPath)
optData = slamData(optPath)
fd = open(resDir + 'deadReckoning.dat', 'w')
for i in range(len(guessData.poseX)):
fd.wr | ite(str(i) + " " + str(guessData.poseX[i]) + " " + str(guessData.poseY[i]) + " " + str(guessData.poseA[i]) + "\n")
fd.close()
fp = open(resDir + 'particlePose.dat', 'w')
for i in range(len(optData.poseX)):
fp.write(str(i) + " 0 " + str(optData.poseX[i]) + " " + str(optData.poseY[i]) + " " + str(opt... |
echinopsii/net.echinopsii.ariane.community.cli.python3 | tests/acceptance/directory/nic_at.py | Python | agpl-3.0 | 5,270 | 0.000949 | # Ariane CLI Python 3
# NICard acceptance tests
#
# Copyright (C) 2015 echinopsii
#
# 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) ... | tion='my new subnet',
ip='192.168.12.0',
mask='255.255.255.0',
routing_area_id=self.new_routing_area.id)
self.new_subnet.save()
se | lf.new_os_instance = OSInstance(name='my_new_osi',
description='my new osi',
admin_gate_uri='ssh://admingateuri')
self.new_os_instance.save()
self.new_ipAddress = IPAddress(fqdn="my new fqdn",
... |
TGM-Oldenburg/earyx | earyx/experiments/sine_after_noise.py | Python | gpl-2.0 | 2,853 | 0.004907 | from earyx.experiments import AFCExperiment
from earyx.order import Sequential
from earyx.utils import gensin, fft_rect_filt, hanwin, rms
import numpy as np
import earyx.ui as UI
import earyx
class SineAfterNoise(AFCExperiment,Sequential):
def init_experiment(self, exp):
"""Set all parameters for one's ow... | et signals
cur_run.between_signal = np.zeros(np.round(
pauselen*cur_run.sample_rate)) # m_quiet
cur_run.post_signal = cur_run.between_signal[
0:len(cur_run.between_sign | al)/2] # m_postsig
cur_run.pre_signal = cur_run.between_signal # m_presig
def init_trial(self, trial):
"""Set signal for variable."""
noise_dur = 0.3 # duration of noise
pause_dur = 0.03 # pause between noise and sine
sine_dur = 0.015 # durat... |
TheSolvingMachine/kangrouter-py | kangrouter.py | Python | apache-2.0 | 3,278 | 0.020439 | import time
from tsm.common.app import exception
import requests
import json
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
KANGROUTER_WEBSERVICE_APPLICATION_ROOT="/kangrouter/srv/v1"
class KangRouterClient:
pathbase = "https://thesolvingmachine.com/kangrouter/srv... | te(self,problem,**kwargs):
path = self.pathbase
payload=json.dumps(problem)
params = self.params.copy()
params.update(kwargs)
req = self.session.post(path,
params=params,
headers=self.headers,
data=payload)
self.validat... | d):
path = "{base}/{solverId}".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.delete(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def stop(self,s... |
jorgb/airs | gui/images/icon_about.py | Python | gpl-2.0 | 7,076 | 0.013002 | #----------------------------------------------------------------------
# This file was generated by D:\personal\src\airs\gui\images\make_images.py
#
from wx import ImageFromStream, BitmapFromImage, EmptyIcon
import cStringIO, zlib
def getData():
return zlib.decompress(
'x\xda\x01}\x08\x82\xf7\x89PNG\r\n... | xef\xb9B\x11\x1b\xd7g\x006\x86Xn^\xe1\xb5z\x8b\xc5R\
\xf1\xaeu\xc1\xcf\xa | 4/H\x83l\xdd\xb5}{gg\xc7\x86U\xa9\x16\x9fkUPJ\xb6\xa8D\
\x90\xd7\xb7\xc2\xee\xde\xb1sxN\x14\x1b\xa2pC\xef\xa1\x0f\xa7|\x0c\xef\xda\
\xbaq9M\r\xd9k\x1d\x96\x98\x99I\xaacWL)lni\xd5\xd9|\xcbl\xa8\x9f\xf8\xf9\xf3\
\xb7\xdf\xb5\xf3\xc1\xbb\xb7\xccLU\x04\xe9\xe3\x97\xaa\xfb\x1f^\x9f\x92$\xc0\
0\x03\x00^\x98\x8de&\xfd\xce... |
amonszpart/SMASH | smash_blender_plugin/pathList.py | Python | mpl-2.0 | 4,464 | 0.010977 | import bpy
import bpy.props as prop
class MY_UL_List(bpy.types.UIList):
def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index):
# We could write some code to decide which icon to use here...
custom_icon = 'OBJECT_DATAMODE'
# Make sure your code suppo... | new_index = index - 1
elif self.direction == 'DOWN':
new_index = index + 1
new_index = max(0, min( | new_index, list_length))
index = new_index
def execute(self, context):
list = context.scene.physacq_path_list
index = context.scene.list_index
if self.direction == 'DOWN':
neighbor = index + 1
queue.move(index,neighbor)
self.move_index()
... |
squilter/ardupilot | libraries/AP_HAL_ChibiOS/hwdef/scripts/STM32F407xx.py | Python | gpl-3.0 | 20,891 | 0.081901 | #!/usr/bin/env python
'''
these tables are generated from the STM32 datasheets for the
STM32F40x
'''
# additional build information for ChibiOS
build = {
"CHIBIOS_STARTUP_MK" : "os/common/startup/ARMCMx/compilers/GCC/mk/startup_stm32f4xx.mk",
"CHIBIOS_PLATFORM_MK" : "os/hal/ports/STM32/STM32F4xx/platform.mk"
... | " : 15,
"PB4:I2S3EXT_SD" : 7,
"PB4:NJTRST" : 0,
"PB4:SPI1_MISO" : 5,
"PB4:SPI3_MISO" : 6,
| "PB4:TIM3_CH1" : 2,
"PB5:CAN2_RX" : 9,
"PB5:DCMI_D10" : 13,
"PB5:ETH_PPS_OUT" : 11,
"PB5:EVENTOUT" : 15,
"PB5:FMC_SDCKE1" : 12,
"PB5:I2C1_SMBA" : 4,
"PB5:I2S3_SD" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.