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 |
|---|---|---|---|---|---|---|---|---|
fidals/refarm-site | images/migrations/0003_auto_20161027_0940.py | Python | mit | 456 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-10-27 09:40
from __future__ import unicode_literals
from django.db import migrations, m | odels
class Migration(migrations.Migration):
dependencies = [
('images', '0002_alter_fields'),
]
operations = [
migrations.AlterField(
model_name='image',
name='description',
| field=models.TextField(blank=True, default=''),
),
]
|
CS-SI/QGIS | tests/src/python/test_qgslayoutlegend.py | Python | gpl-2.0 | 9,958 | 0.000402 | # -*- coding: | utf-8 -*-
"""QGIS Unit tests for QgsLayoutItemLegend.
.. note:: This program is free software; you can redistribute it and/or modify
it under the term | s 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.
"""
__author__ = '(C) 2017 by Nyall Dawson'
__date__ = '24/10/2017'
__copyright__ = 'Copyright 2017, The QGIS Project'
# This will get replaced with a git SHA1 when y... |
jespino/coval | tests/es_tests.py | Python | bsd-3-clause | 4,205 | 0.004518 | import unittest
from coval.es import *
class CodeValidatorEsTestCase(unittest.TestCase):
def setUp(self):
pass
def test_cif(self):
self.assertTrue(cif('A58818 | 501'))
self.assertTrue(cif('B00000000'))
self.assertTrue(cif('C0000000J'))
self.assertTrue(cif('D00000000'))
self.assertTrue(cif('E00000000')) |
self.assertTrue(cif('F00000000'))
self.assertTrue(cif('G00000000'))
self.assertTrue(cif('H00000000'))
self.assertFalse(cif('I00000000'))
self.assertFalse(cif('I0000000J'))
self.assertTrue(cif('J00000000'))
self.assertTrue(cif('K0000000J'))
self.assertTrue... |
BrendonKing32/Traffic-Assistant | map/views.py | Python | gpl-3.0 | 135 | 0 | from django.shortcuts i | mport render
from django.http import Http404
def index(request):
return render(request, 'map/index.html | ')
|
Nocturnal42/runmyrobot | hardware/maestro-servo.py | Python | apache-2.0 | 1,417 | 0.007763 | # You will need maestro.py from https://github.com/FRC4564/Maestro
#
# This is also just a place holder, it has not be tested with an actual
# bot.
import sys
import | time
try:
import hardware/maestro
except ImportError:
print "You are missing the maestro.py file from the hardware subdirectory."
print "Please download it from here https://github.com/FRC4564/Maestro"
sys.exit()
servo = None
def setup(robot_config):
global servo
servo = maestro.Controller()... | ':
servo.setTarget(0, 12000)
servo.setTarget(1, 12000)
time.sleep(straightDelay)
servo.setTarget(0, 6000)
servo.setTarget(1, 6000)
elif direction == 'B':
servo.setTarget(0, 0)
servo.setTarget(1, 0)
time.sleep(straightDelay)
servo.setTar... |
OpenMOOC/moocng | moocng/courses/urls.py | Python | apache-2.0 | 2,701 | 0.001481 | # -*- coding: utf-8 -*-
# Copyright 2012-2013 UNED
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.conf.urls import include, patterns, url... |
urlpatterns = patterns(
'moocng.courses.views',
url(r'^$', 'home', name='home'),
url(r'^course/$', RedirectView.as_view(url='/'), name='course-index'),
# Flatpages
url(r'^faq/$', 'flatpage', {'page': 'faq'}, name='faq'),
url(r'^methodology/$', 'flatpage', {'page': 'methodology'},
name... |
Podemos-TICS/Creaci-n-Wordpress | scripts/deploy/Constants.py | Python | gpl-2.0 | 54 | 0 | zone_file = | '/etc/bind/zones/db | .circulospodemos.info'
|
alexoneill/py3status | py3status/modules/netdata.py | Python | bsd-3-clause | 5,963 | 0.000674 | # -*- coding: utf-8 -*-
"""
Display network speed and bandwidth usage.
Configuration parameters:
cache_timeout: refresh interval for this module (default 2)
format: display format for this module
*(default '{nic} [\?color=down LAN(Kb): {down}↓ {up}↑]
[\?color=total T(Mb): {download}↓ {upload}↑ ... | holders:
{nic} network interface
{down} | number of download speed
{up} number of upload speed
{download} number of download usage
{upload} number of upload usage
{total} number of total usage
Color thresholds:
{down} color threshold of download speed
{total} color threshold of total usage
@author Shahin Azad <isha... |
beratdogan/arguman.org | web/newsfeed/management/commands/create_initial_newsfeed.py | Python | mit | 557 | 0 | from django.core.management import BaseCommand
from newsfeed.models import Entry
from premises.models import Contention
class Command(BaseCommand):
def handle(self, *args, **options):
| for contention in Contention.objects.all():
Entry.objects.create(
| object_id=contention.id,
news_type=contention.get_newsfeed_type(),
sender=contention.get_actor(),
related_object=contention.get_newsfeed_bundle(),
date_creation=contention.date_creation
)
|
haastt/analisador | src/Analyzer.py | Python | mit | 8,325 | 0.008892 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import mmap
import re
import collections
import math
import detectlanguage
import codecs
detectlanguage.configuration.api_key = "d6ed8c76914a9809b58c2e11904fbaa3"
class Analyzer:
def __init__(self, passwd):
self.evaluation = {}
self._passwd = passwd
... | ""
hasUpper = (self.upperCount != 0 if 1 else 0)
hasLower = (self.lowerCount != 0 if 1 else 0)
hasSpecial = (self.specialCount != 0 if 1 else 0)
hasNumber = (self.numberCount != 0 if 1 else 0)
self.entropy = math.log(math.pow(((hasUpper*27) + (hasLower*27) + (hasSpecial*33)+(has... | n(self._passwd)),2)
print('Entropy: {0} bits'.format(self.entropy))
def distanceInKeyboard(self,char1, char2):
"""
Estimate de distance between two characters in the keyboard
"""
firstKeyboardRow = [('1','!'),('2','@'),('3,'',#'),('4','$'),('5','%'),('6','¨'),('7','&'),('8'... |
release-engineering/releng-sop | releng_sop/__init__.py | Python | mit | 39 | 0 | """To | p-level module for releng-sop.""" | |
south-coast-science/scs_dfe_eng | src/scs_dfe/time/ds1338.py | Python | mit | 5,825 | 0.006695 | """
Created on 16 May 2017
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
Note: time shall always be stored as UTC, then localized on retrieval.
"""
from scs_core.data.rtc_datetime import RTCDatetime
from scs_host.bus.i2c import I2C
from scs_host.lock.lock import Lock
# -------------------------------... | -------------------------------------------------------------------------------
# RTC...
@classmethod
def init(cls, enable_square_wave=False):
try:
cls.obtain_lock()
# use 24 hour...
hours = cls.__read_reg(cls.__REG_HOURS)
hours = hours & | ~cls.__HOURS_MASK_24_HOUR
cls.__write_reg(cls.__REG_HOURS, hours)
# enable square wave output...
control = cls.__read_reg(cls.__REG_CONTROL)
control = control | cls.__CONTROL_MASK_SQW_EN if enable_square_wave \
else control & ~cls.__CONTROL_MASK_SQW_EN
... |
a25kk/dpf | src/dpf.sitecontent/dpf/sitecontent/browser/frontpage.py | Python | mit | 3,589 | 0 | # -*- coding: utf-8 -*-
"""Module providing views for the site navigation root"""
from Acquisition import | aq_inner
from Products.Five.browser import BrowserView
from Products.ZCatalog.interfaces import ICatalogBrain
from plone import api
from plone.app.contentlisting.interfaces import IContentListing
from plone.app.contentlisting.interfaces import IContentListingObject
from plone. | app.contenttypes.interfaces import INewsItem
from zope.component import getMultiAdapter
from zope.component import getUtility
from dpf.sitecontent.interfaces import IResponsiveImagesTool
IMG = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs='
class FrontPageView(BrowserView):
""" General ... |
yuwen41200/biodiversity-analysis | src/view/temporal_analysis_widget.py | Python | gpl-3.0 | 1,068 | 0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from PyQt5 import QtWidgets
from view.analysis_widget import AnalysisWidget
# noinspection PyPep8Naming
class TemporalAnalysisWidget(AnalysisWid | get):
# noinspection PyArgumentList
def __init__(self, mplCanvas):
"""
Construct the Temporal Analysis page in the main window. |br|
A ``ScatterPlot.mplCanvas`` will be shown on this page.
:param mplCanvas: The ``ScatterPlot.mplCanvas`` widget.
"""
super().__in... | upperLabel.setMargin(1)
upperLabel.setBuddy(mplCanvas)
lowerLabel = QtWidgets.QLabel("Temporal Correlation &Quotient:")
lowerLabel.setMargin(1)
lowerLabel.setBuddy(self.tableWidget)
mainLayout = QtWidgets.QVBoxLayout()
mainLayout.addWidget(upperLabel)
mainLa... |
Jonqora/whiskers | checks.py | Python | gpl-3.0 | 5,290 | 0.006994 | from discord.ext import commands
import discord.utils
def is_owner_check(ctx):
author = str(ctx.message.author)
owner = ctx.bot.config['master']
return author == owner
def is_owner():
return commands.check(is_owner_check)
def check_permissions(ctx, perms):
#if is_owner_check(ctx):
# return... | if check_raidchannel(ctx):
return check_raidactive(ctx)
return commands.check(predicate)
def cityraidchannel():
def predicate(ctx):
if check_raidchannel(ctx) == True:
return True
elif check_citychannel(ctx) == True:
return True
return commands.check(p... | return True
elif check_citychannel(ctx) == True:
return True
return commands.check(predicate)
|
pararthshah/libavg-vaapi | src/python/ui/scrollarea.py | Python | lgpl-2.1 | 7,235 | 0.002626 | # -*- coding: utf-8 -*-
# libavg - Media Playback Engine.
# Copyright (C) 2003-2011 Ulrich von Zadow
#
# 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 of the License, o... | ic License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Current versions can be found at www.libavg.de
#
fro | m libavg import avg
from libavg.ui import slider, gesture
class ScrollPane(avg.DivNode):
def __init__(self, contentNode, parent=None, **kwargs):
super(ScrollPane, self).__init__(crop=True, **kwargs)
self.registerInstance(self, parent)
self.appendChild(contentNode)
self._c... |
2013Commons/HUE-SHARK | apps/filebrowser/src/filebrowser/settings.py | Python | apache-2.0 | 946 | 0 | #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you u | nder 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 i... | ,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
DJANGO_APPS = ['filebrowser']
NICE_NAME = "File Browser"
REQUIRES_HADOOP = False
ICON = "/filebrowser/static/art/icon_filebrowser_24.png"
M... |
xiaonanln/myleetcode-python | src/61. Rotate List.py | Python | apache-2.0 | 732 | 0.080601 | # Defin | ition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head: return None
p = head
listLen = 0 # calculate list le... | p2 = p2.next
assert p2
while p2.next:
p1 = p1.next
p2 = p2.next
newHead = p1.next
p1.next = None
p2.next = head
return newHead
from utils import *
printlist(Solution().rotateRight(makelist(1,2 ,3 ,4 ,5), 2)) |
piraz/firenado | tests/util/sqlalchemy_util_test.py | Python | apache-2.0 | 3,289 | 0 | #!/usr/bin/env python
#
# Copyright 2015-2021 Flavio Garcia
#
# 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... | )
self.assertEqual(dict_from_base['username'], self.test_object.username)
self.assertEqual(dict_from_base['first_name'],
self.test_object.first_name)
self.assertTrue("password" not in dict_from_base)
self.assertTrue("last_name" not in dict_from_base)
self... | _base)
|
twitter-forks/bazel | tools/ctexplain/types.py | Python | apache-2.0 | 3,539 | 0.010455 | # Lint as: python3
# Copyright 2020 The Bazel 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 requir... |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The core data types ctexplain manipulates."""
from typing import Mapping
from typing import Optional
from typing import Tuple
# Do not ed... |
from dataclasses import dataclass
from dataclasses import field
from frozendict import frozendict
@dataclass(frozen=True)
class Configuration():
"""Stores a build configuration as a collection of fragments and options."""
# Mapping of each BuildConfiguration.Fragment in this configuration to the
# FragmentOpti... |
christiansandberg/canopen | canopen/sdo/server.py | Python | mit | 7,569 | 0.001057 | import logging
from .base import SdoBase
from .constants import *
from .exceptions import *
logger = logging.getLogger(__name__)
class SdoServer(SdoBase):
"""Creates an SDO server."""
def __init__(self, rx_cobid, tx_cobid, node):
"""
:param int rx_cobid:
COB-ID that the server r... | check_writable=True)
res_command = RESPONSE_SEGMENT_DOWNLOAD
# Add toggle bit
res_command |= self | ._toggle
# Toggle bit for next message
self._toggle ^= TOGGLE_BIT
response = bytearray(8)
response[0] = res_command
self.send_response(response)
def send_response(self, response):
self.network.send_message(self.tx_cobid, response)
def abort(self, abort_code=0x0... |
pyfa-org/Pyfa | gui/fitCommands/gui/projectedModule/add.py | Python | gpl-3.0 | 1,334 | 0.002999 | import wx
import eos.db
import gui.mainFrame
from gui import globalEvents as GE
from gui.fitCommands.calc.module.projectedAdd import CalcAddProjectedModuleCommand
from gui.fitCommands.helpers import InternalCommandHistory, ModuleInfo
from service.fit import Fit
class GuiAddProjectedModuleCommand(wx.Command):
de... | Fit.getInstance()
if cmd.needsGuiRecalc:
eos.db.flush()
sFit.recalc(self.fitID)
sFit. | fill(self.fitID)
eos.db.commit()
wx.PostEvent(gui.mainFrame.MainFrame.getInstance(), GE.FitChanged(fitIDs=(self.fitID,)))
return success
def Undo(self):
success = self.internalHistory.undoAll()
eos.db.flush()
sFit = Fit.getInstance()
sFit.recalc(self.fitID)
... |
moble/scri | tests/test_rotations.py | Python | mit | 10,004 | 0.003898 | # Copyright (c) 2015, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/scri/blob/master/LICENSE>
import pytest
import numpy as np
from numpy import *
import quaternion
import spherical_functions as sf
import scri
from conftest import linear_waveform, constant_waveform, random_waveform, delta_wa... | ) # This SHOULD change
assert W_out.ell_min == W_in.ell_min
assert W_out.ell_max == W_in.ell_max
assert np.array_equal(W_out.LM, W_in.LM)
for h_in, h_out in zip(W_in.history[:-3], W_out.history[:-5]):
assert h_in == h_out.replace(
f"{type(W_out).__name__}_{str(W_out. | num)}", f"{type(W_in).__name__}_{str(W_in.num)}"
) or (h_in.startswith("# ") and h_out.startswith("# "))
assert W_out.frameType == W_in.frameType
assert W_out.dataType == W_in.dataType
assert W_out.r_is_scaled_out == W_in.r_is_scaled_out
assert W_out.m_is_scaled_out == W_in.m_is_scaled_out
a... |
ChristopheVuillot/qiskit-sdk-py | qiskit/qasm/_node/_nodeexception.py | Python | apache-2.0 | 1,054 | 0 | # -*- coding: utf-8 -*-
# Copyright 2017 IBM RESEARCH. 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 OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================
"""
Exception fo... |
nistormihai/superdesk-core | apps/publish/__init__.py | Python | agpl-3.0 | 2,426 | 0.004122 | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import loggi... | nit_app(app):
endpoint_name = 'archive_publish'
service = ArchivePublishService(endpoint_name, backend=get_backend())
ArchivePublishResource(endpoint_name, app=app, service=service)
endpoint_name = 'archive_kill'
service = KillPublishService(endpoint_name, backend=get_backend())
KillPublishRes... | int_name, backend=get_backend())
CorrectPublishResource(endpoint_name, app=app, service=service)
endpoint_name = 'published'
service = PublishedItemService(endpoint_name, backend=get_backend())
PublishedItemResource(endpoint_name, app=app, service=service)
endpoint_name = 'archive_resend'
serv... |
tensorflow/agents | tf_agents/networks/categorical_q_network_test.py | Python | apache-2.0 | 6,673 | 0.001049 | # coding=utf-8
# Copyright 2020 The TF-Agents 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | self.assertEqual(num_actions, 2)
observations_spec = tensor_spec.TensorSpec(
[3, 3, num_state_dims], tf.float32)
observations = tf.random.uniform([batch_size, 3, 3, num_state_dims])
next_observations = tf.random.uniform([batch_size, 3, 3, num_state_dims])
| time_steps = ts.restart(observations, batch_size)
next_time_steps = ts.restart(next_observations, batch_size)
# Note: this is cleared in tearDown().
gin.parse_config("""
CategoricalQNetwork.conv_layer_params = [(16, 2, 1), (15, 2, 1)]
CategoricalQNetwork.fc_layer_params = [4, 3, 5]
... |
qiyeboy/SpiderBook | ch03/3.2.3.7.py | Python | mit | 91 | 0.012048 | #coding:utf-8
'''
Timeouts超时设置
requests.get('http://githu | b.com', timeout=2)
'''
| |
mlperf/training_results_v0.6 | Fujitsu/benchmarks/resnet/implementations/mxnet/tests/python/gpu/test_kvstore_gpu.py | Python | apache-2.0 | 6,181 | 0.003721 | # 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 u... | e('row_sparse'))
push_ctxs = [mx.cpu(i) if is_push_cpu else mx.gpu(i) for i in range(2)]
kv.push('e', [mx.nd.ones(shape, ctx=context).tostype('row_sparse') for context in push_ctxs])
def check_rsp_pull(kv, ctxs, sparse_pull, is_same_rowid=False, use_slice=False):
count = len(ctxs)
... | ange(num_rows)
vals = [mx.nd.sparse.zeros(shape=shape, ctx=ctxs[i], stype='row_sparse') for i in range(count)]
if is_same_rowid:
row_id = np.random.randint(num_rows, size=num_rows)
row_ids = [mx.nd.array(row_id)] * count
elif use_slice:
... |
archsh/tg2ext.express | example/tg2express/tests/__init__.py | Python | mit | 2,131 | 0 | # -*- coding: utf-8 -*-
"""Unit and functional test suite for tg2express."""
from os import getcwd, path
from paste.deploy import loadapp
from webtest import TestApp
from gearbox.commands.setup_app import SetupAppCommand
from tg import config
from tg.util import Bunch
from tg2express import model
__all__ = ['setup... | and(Bunch(options=Bunch(verbose_level=1)), Bunch())
cmd.run(Bunch(config_file='config:test.ini', section_name=None))
def setup_db():
"""Create the database schema (not needed when you run setup_app)."""
engine = config['tg.app_globals'].sa_engine |
model.init_model(engine)
model.metadata.create_all(engine)
def teardown_db():
"""Destroy the database schema."""
engine = config['tg.app_globals'].sa_engine
model.metadata.drop_all(engine)
class TestController(object):
"""Base functional test case for the controllers.
The tg2express ap... |
pbmanis/acq4 | acq4/analysis/tools/ScriptProcessor.py | Python | mit | 13,216 | 0.004994 | # -*- coding: utf-8 -*-
from __future__ import print_function
"""
ScriptProcessor processes a script f | ile (generally), loading data using the requested
loading routine and printing
This is part of Acq4
Paul B. Manis, Ph.D.
2011-2013.
Pep8 compliant (via pep8.py) 10/25/2013
Refactoring begun 3/21/2015
"""
import os
import os.path
import numpy as np
import re
import gc
from acq4.analysis.AnalysisModule import Analy... | Qt
from acq4.pyqtgraph.widgets.ProgressDialog import ProgressDialog
class ScriptProcessor(AnalysisModule):
def __init__(self, host):
AnalysisModule.__init__(self, host)
def setAnalysis(self, analysis=None, fileloader=None, template=None, clamps=None, printer=None, dbupdate=None):
"""
... |
NickCarneiro/curlconverter | fixtures/python/get_with_single_header.py | Python | mit | 114 | 0 | import requests
headers = {
'foo': 'bar',
}
respo | nse = requests.get('http://exa | mple.com/', headers=headers)
|
philgyford/django-spectator | spectator/events/migrations/0028_dancepieces_to_works.py | Python | mit | 1,326 | 0 | # Generated by Django 2.0 on 2018-02-08 11:45
from django.db import migrations
def forwards(apps, schema_editor):
"""
Change all DancePiece objects into Work objects, and their associated
data into WorkRole and WorkSelection models, then delete the DancePiece.
"""
DancePiece = apps.get_model("spe... | endencies = [
("s | pectator_events", "0027_classicalworks_to_works"),
]
operations = [
migrations.RunPython(forwards),
]
|
lewfish/django-social-news | manage.py | Python | mit | 259 | 0.003861 | #!/usr/bin/ | env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "social_news_site.settings")
from django.core.management import execu | te_from_command_line
execute_from_command_line(sys.argv)
|
endlessm/chromium-browser | third_party/chromite/lib/replication_lib.py | Python | bsd-3-clause | 5,370 | 0.007263 | # -*- coding: utf-8 -*-
# Copyright 2019 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.
"""An implementation of the ReplicationConfig proto interface."""
from __future__ import print_function
import json
import os
im... | lementedError('Replicate not implemented for file type %s' %
rule.file_type)
if rule.replication_type == replication_config_pb2.REPLICATION_TYPE_COPY:
if rule.destination_fields.paths:
raise ValueError(
'Rule with REPLICATION_TYPE_COPY cannot use destination_fields | .')
elif rule.replication_type == replication_config_pb2.REPLICATION_TYPE_FILTER:
if not rule.destination_fields.paths:
raise ValueError(
'Rule with REPLICATION_TYPE_FILTER must use destination_fields.')
else:
raise NotImplementedError(
'Replicate not implemented for replication type... |
zofuthan/airmozilla | airmozilla/manage/tests/views/test_errors.py | Python | bsd-3-clause | 1,278 | 0 | import mock
from nose.tools import eq_, ok_, assert_raises
from funfactory.urlresolvers import reverse
from .base import ManageTestCase
class TestErrorTrigger(ManageTestCase):
def test_trigger_error(self):
url = reverse('manage:error_trigger')
response = self.client.get(url)
assert self... | def test_trigger_error_with_raven(self, mocked_client):
url = reverse('manage:error_trigger')
assert self.user.is_superuser
raven_config = {
'dsn': 'fake123'
}
with self.settings(RAVEN_CONFIG=raven_config):
response = self.client.post(url, {
... | .captureException.assert_called_with()
|
forance/django-q | djangoq_demo/order_reminder/migrations/0002_auto_20160318_1759.py | Python | mit | 858 | 0.001166 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-03-18 09:59
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('order_reminder', '0001_initial'),
]
operations = [
| migrations.AddField(
model_name='orders',
name='creater',
field=models.CharField(max_length=200, null=True, unique=True),
| ),
migrations.AddField(
model_name='orders',
name='currency',
field=models.CharField(max_length=200, null=True, unique=True),
),
migrations.AlterField(
model_name='orders',
name='order_id',
field=models.CharField(max_l... |
kreopt/aioweb | wyrm/modules/generate/test/controller.py | Python | mit | 1,437 | 0.004175 | import sys
import os
brief = "create a test for controller"
def usage(argv0):
print("Usage: {} | generate test controller CONTROLLER_NAME METHOD [METHOD] [...]".format(argv0))
sys.exit(1)
aliases = ['c']
def execute(argv, argv0, engine):
import lib, inflection
os.environ.setdefaul | t("AIOWEB_SETTINGS_MODULE", "settings")
from aioweb import settings
sys.path.append(os.getcwd())
if len(argv) < 2:
usage(argv0)
controller_name = inflection.camelize(argv[0]) + "Controller"
controller_file_name = inflection.underscore(argv[0]) + ".py"
methods = argv[1:]
dest_file ... |
roboDocs/rf-extension-boilerplate | build.py | Python | mit | 2,609 | 0.000383 | '''build RoboFont Extension'''
import os
from AppKit import NSCommandKeyMask, NSAlternateKeyMask, NSShiftKeyMask
from mojo.extensions import ExtensionBundle
# get current folder
basePath = os.path.dirname(__file__)
# source folder for all extension files
sourcePath = os.path.join(basePath, 'source')
# folder with p... | d extensions
with open(requirementsPath) as requirements:
B.requirements = requirements.read()
# | expiration date for trial extensions
B.expireDate = '2020-12-31'
# compile and save the extension bundle
print('building extension...', end=' ')
B.save(extensionPath, libPath=libPath, htmlPath=htmlPath, resourcesPath=resourcesPath)
print('done!')
# check for problems in the compiled extension
print()
print(B.validat... |
adityacs/ansible | lib/ansible/modules/web_infrastructure/ansible_tower/tower_host.py | Python | gpl-3.0 | 5,874 | 0.005958 | #!/usr/bin/python
#coding: utf-8 -*-
# (c) 2017, Wayne Witzel III <wayne@riotousliving.com>
#
# This module 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... | module.params.get('variables')
if variables:
if variables.startswith('@'):
filename = os.path.expanduser(variables[1:])
variables = module.contents_from_file(filename)
json_output = {'host': name, 'state': state}
tower_auth = tower_auth_config(module)
with settings.run... | tower_check_mode(module)
host = tower_cli.get_resource('host')
try:
inv_res = tower_cli.get_resource('inventory')
inv = inv_res.get(name=inventory)
if state == 'present':
result = host.modify(name=name, inventory=inv['id'], enabled=enabled,
... |
procangroup/edx-platform | common/djangoapps/student/tests/test_activate_account.py | Python | agpl-3.0 | 8,881 | 0.002365 | """Tests for account activation"""
import unittest
from uuid import uuid4
from django.conf import settings
from django.core.urlresolvers import reverse
from django.test import TestCase, override_settings
from mock import patch
from edxmako.shortcuts import render_to_string
from openedx.core.djangoapps.site_configurat... | t(reverse('dashboard'))
self.assertNotCont | ains(response, expected_message, html=True)
def test_account_activation_notification_on_logistration(self):
"""
Verify that logistration page displays success/error/info messages
about account activation.
"""
login_page_url = "{login_url}?next={redirect_url}".format(
... |
kaoree/fresco | run_comparison.py | Python | bsd-3-clause | 7,775 | 0.002058 | #!/usr/bin/env python
# This file provided by Facebook is for non-commercial testing and evaluation
# purposes only. Facebook reserves all rights not expressly granted.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL... | ley' and scenario_n | ame != 'drawee-volley')
def main():
args = parse_args()
scenarios = []
sources = []
if args.scenarios:
scenarios = args.scenarios
else:
scenarios = TESTS
if args.sources:
sources = args.sources
else:
sources = TEST_SOURCES
install_apks(args.cpu)
fo... |
jdeblese/ergovolve | proposals.py | Python | mit | 3,554 | 0.037141 | #!/usr/bin/env python
ergodoxian = (
("KEY_DeleteBackspace","1x2"),
("KEY_DeleteForward","1x2"),
('KEY_ReturnEnter', '1x2'),
('KEY_Spacebar', '1x2'),
('SPECIAL_Fn', '1x2'),
('KEY_Shift', '1.5x1'),
('KEY_Shift', '1.5x1'),
("KEY_Dash_Underscore", "1.5x1"),
("KEY_Equal_Plus", "1.5x1"),
('KEY_ReturnEnter', '1.5x1'),
("KEY... | ,
('KEY_Spacebar', '1x2'),
('SPECIAL_Fn', '1x2'),
('KEY_Shift', '1.5x1'),
('KEY_Shift', '1.5x1'),
("KEY_Dash_Underscore", "1.5x1"),
("KEY_Equal_Plus", "1.5x1"),
('KEY_ReturnEnter', '1.5x1'),
("KEY_Escape", "1.5x1"),
("KEY_DeleteForward","1.5x1"),
('SPECIAL_Fn', '1x1.5'),
("KEY_LeftBracket_LeftBrace", "1x1.5"),
("KEY_Ri... |
new4 = (
('KEY_Shift', '1x2'),
("KEY_DeleteForward","1x2"),
('KEY_ReturnEnter', '1x2'),
('KEY_Spacebar', '1x2'),
('SPECIAL_Fn', '1x2'),
('KEY_Shift', '1.5x1'),
('KEY_Shift', '1.5x1'),
("KEY_Dash_Underscore", "1.5x1"),
("KEY_Equal_Plus", "1.5x1"),
('KEY_ReturnEnter', '1.5x1'),
("KEY_Escape", "1.5x1"),
("KEY_DeleteForwa... |
dougthor42/TPEdit | tpedit/main.py | Python | gpl-3.0 | 33,403 | 0.000419 | # -*- coding: utf-8 -*-
"""
@created: Thu Jul 02 10:56:57 2015
Usage:
main.py
Options:
-h --help # Show this screen.
--version # Show version.
"""
### Imports
# Standard Library
from __future__ import print_function, division
from __future__ import absolute_import
... | s = ("1.xml", "2.xml", "3.xml")
# Uncomment this to auto-load some temp files
# self.open_files((os.path.join(ROOT_PATH, _fn) for _fn in _fns) | )
@logged
def _create_menus(self):
""" Create each menu for the menu bar """
self._create_file_menu()
self._create_edit_menu()
self._create_view_menu()
# self._create_tools_menu()
# self._create_options_menu()
# self._create_help_menu()
@log... |
inf0-warri0r/l_viewer | display.py | Python | agpl-3.0 | 9,288 | 0.002046 | """
Author : tharindra galahena (inf0_warri0r)
Project: l_viewer
Blog : http://www.inf0warri0r.blogspot.com
Date : 30/04/2013
License:
Copyright 2013 Tharindra Galahena
l_viewer is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Fr... | try:
thread.start_new_thread(self.thread_func, ())
except Exception, e:
dialog.showerror(title='ERROR !!', message='Thread error')
def read_file(self, name):
f = open(name, 'r')
try:
cat = f.read()
... | lf.angle = float(lines[1])
self.ang = float(lines[2])
num_rules = int(lines[3])
for i in range(4, num_rules + 4):
rule = lines[i].split('=')
self.lst_rules.append((rule[0], rule[1]))
num_symbols = int(lines[num_rules + 4])
for ... |
arunkgupta/gramps | gramps/gen/lib/styledtexttag.py | Python | gpl-2.0 | 4,127 | 0.005331 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2008 Zsolt Foldvari
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) ... | = ranges
def serialize(self):
"""Convert the object | to a serialized tuple of data.
:returns: Serialized format of the instance.
:returnstype: tuple
"""
return (self.name.serialize(), self.value, self.ranges)
def to_struct(self):
"""
Convert the data held in this object to a structure (eg,
... |
batra-mlp-lab/DIGITS | digits/model/tasks/train.py | Python | bsd-3-clause | 19,069 | 0.002203 | # Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved.
import time
import os.path
from collections import OrderedDict, namedtuple
import gevent
import flask
from digits import device_query
from digits.task import Task
from digits.utils import subclass, override
# NOTE: Increment this everytime the pic... | els']
if '_gpu_socketio_thread' in state:
del state['_gpu_socketio_thread']
return state
def __setstate__(self, state):
if state['pickver_task_train'] < 2:
state['train_outpu | ts'] = OrderedDict()
state['val_outputs'] = OrderedDict()
tl = state.pop('train_loss_updates', None)
vl = state.pop('val_loss_updates', None)
va = state.pop('val_accuracy_updates', None)
lr = state.pop('lr_updates', None)
if tl:
st... |
BrainIntensive/OnlineBrainIntensive | resources/HCP/ciftify/tests/test_cifti_vis_map.py | Python | mit | 7,233 | 0.002627 | #!/usr/bin/env python
import unittest
import importlib
import random
from mock import patch
vis_map = importlib.import_module('ciftify.bin.cifti_vis_map')
class TestUserSettings(unittest.TestCase):
temp = '/tmp/fake_temp_dir'
palette = 'PALETTE-NAME'
def test_snap_set_to_none_when_in_index_mode(self):
... | esample_nifti_set(
self, mock_docmd):
args = self.get_default_arguments()
args['nifti-snaps'] = True
nifti = '/some/path/my_map.nii'
args['<map.nii>'] = nifti
args['--resample-nifti'] = True
settings = vis_map.UserSe | ttings(args, self.temp)
# Reset mock_docmd to clear call_args_list
mock_docmd.reset_mock()
settings._UserSettings__convert_nifti(nifti)
args_list = mock_docmd.call_args_list[0][0][0]
assert '--resample-voxels' in args_list
@patch('ciftify.utilities.docmd')
def test_nif... |
rven/odoo | addons/website_sale_coupon_delivery/controllers/main.py | Python | agpl-3.0 | 2,386 | 0.004191 | # -*- coding: utf-8 -*-
from odoo import http
from odoo.addons.website_sale_delivery.controllers.main import WebsiteSaleDelivery
from odoo.http import request
class WebsiteSaleCouponDelivery(WebsiteSaleDelivery):
@http.route()
def update_eshop_carrier(self, **post):
Monetary = request.env['ir.qweb.fi... | carrier_id, **kw):
Monetary = request.env['ir.qweb.field.monetary']
order = request.website.sale_get_order(force_create=True)
free_shipping_lines = order._get_free_shipping_lines()
# Avoid computing carrier price delivery is free (coupon). It means if
# the carrier has error (eg... | n it.
if free_shipping_lines:
return {
'carrier_id': carrier_id,
'status': True,
'is_free_delivery': True,
'new_amount_delivery': Monetary.value_to_html(0.0, {'display_currency': order.currency_id}),
'error_message': Non... |
LLNL/spack | var/spack/repos/builtin.mock/packages/version-test-dependency-preferred/package.py | Python | lgpl-2.1 | 794 | 0.001259 | # Cop | yright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Ident | ifier: (Apache-2.0 OR MIT)
class VersionTestDependencyPreferred(AutotoolsPackage):
"""Dependency of version-test-pkg, which has a multi-valued
variant with two default values (a very low priority optimization
criterion for clingo is to maximize their number)
"""
homepage = "http://www.spack.org"
... |
negrinho/deep_architect | deep_architect/searchers/successive_narrowing.py | Python | mit | 3,234 | 0 | import deep_architect.searchers.common as se
import numpy as np
# NOTE: this searcher does not do any budget adjustment and needs to be
# combined with an evaluator that does.
class SuccessiveNarrowing(se.Searcher):
def __init__(self, search_space_fn, num_initial_samples, reduction_factor,
reset... | xt round of architectures by keeping the best ones.
if self.num_remaining == 0:
num_samples = int(self.reduction_factor * len(self.queue))
assert num_samples > 0
top_idxs = np.argsort(self.vals)[::-1][:num_samples]
self.queue = [self.queue[idx] for idx in top_idxs... | r _ in range(num_samples)]
self.num_remaining = num_samples
self.idx = 0
# run simple successive narrowing on a single machine.
def run_successive_narrowing(search_space_fn, num_initial_samples,
initial_budget, get_evaluator, extract_val_fn,
... |
andreasots/lrrbot | lrrbot/systemd.py | Python | apache-2.0 | 992 | 0.025202 | import logging
import os
import ctypes
import ctypes.util
log = logging.getLogger("lrrbot.systemd")
try:
libsystemd = ctypes.CDLL(ctypes.util.find_library("systemd"))
libsystemd.sd_notify.argtypes = [ctypes.c_int, ctypes.c_char_p]
def notify(status):
libsystemd.sd_notify(0, status.encode('utf-8'))
except OSErr... | timeout, self.watchdog)
self.subsystems = {"irc"}
def watchdog(self):
notify("WATCHDOG=1")
self.watchdog_handle = self.loop. | call_later(self.timeout, self.watchdog)
def subsystem_started(self, subsystem):
if subsystem in self.subsystems:
self.subsystems.remove(subsystem)
if self.subsystems == set():
notify("READY=1")
|
CellModels/tyssue | tyssue/behaviors/sheet/basic_events.py | Python | gpl-2.0 | 6,721 | 0.001785 | """
Small event module
=======================
"""
import numpy as np
import logging
logger = logging.getLogger(__name__)
from ...utils.decorators import face_lookup
from ...geometry.sheet_geometry import SheetGeometry
from ...topology.sheet_topology import cell_division
from .actions import (
exchange,
r... | contraction_spec["critical_area"]) or (
sheet.face_df.loc[face, contraction_spec["contraction_column"]]
> contraction_spec["max_contractility"]
):
return
increase(
sheet,
"face",
face,
contraction_spec["contractile_increase"],
contraction_spec["con... | ometry,
}
@face_lookup
def type1_transition(sheet, manager, **kwargs):
"""Custom type 1 transition event that tests if
the the shorter edge of the face is smaller than
the critical length.
"""
type1_transition_spec = default_type1_transition_spec
type1_transition_spec.update(**kwargs)
face... |
RobinQuetin/CAIRIS-web | cairis/cairis/RiskScatterPanel.py | Python | apache-2.0 | 3,503 | 0.017985 | # 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... | xSizer(wx.VERTICAL)
self.vbox.Add(self.toolbar, 0, wx.EXPAND)
self.vbox.Add(self.envCombo,0, wx.EXPAND)
self.vbox.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
self.SetSizer(self.vbox)
self.vbox.Fit(self)
self.drawScatter(envs[0])
def drawScatter(self,en | vName):
self.axes.clear()
self.axes.grid(True)
self.axes.set_xlabel('Severity')
self.axes.set_ylabel('Likelihood')
self.axes.set_xbound(0,4)
self.axes.set_ybound(0,5)
xs,ys,cs = self.dbProxy.riskScatter(envName)
ccs = []
for c in cs:
ccs.append(riskColourCode(c))
i... |
layuplist/layup-list | apps/web/models/__init__.py | Python | gpl-3.0 | 279 | 0 | from course import Course
from course_offering import CourseOffering
from distributive_requirement import DistributiveRequirement
fro | m instructor import Instructor
from course_median import CourseMedian
from review import Review
from v | ote import Vote
from student import Student
|
rohitranjan1991/home-assistant | homeassistant/components/elmax/common.py | Python | mit | 5,658 | 0.001414 | """Elmax integration common classes and utilities."""
from __future__ import annotations
from datetime import timedelta
import logging
from logging import Logger
import async_timeout
from elmax_api.exceptions import (
ElmaxApiError,
ElmaxBadLoginError,
ElmaxBadPinError,
ElmaxNetworkError,
)
from elmax... |
@property
def available(self) -> bool:
"""Return | if entity is available."""
return super().available and self._panel.online
|
cgre-aachen/gempy | examples/integrations/gempy_striplog.py | Python | lgpl-3.0 | 5,611 | 0.006595 | """
Transform 2019: Integrating Striplog and GemPy
==============================================
"""
# %%
# ! pip install welly striplog
# %%
# Authors: M. de la Varga, Evan Bianco, Brian Burnham and Dieter Werthmüller
# | Importing GemPy
import gempy as gp
# Importing auxiliary libraries
import numpy as np
import pandas as pn
import matplotlib.pyplot as plt
import os
import welly
from welly import Location, Project
import glob
from striplog import Striplog, Legend, Decor
pn.set_option('precision', 2)
# %%
# Creating striplog object
... | s
well_heads = {'alpha': {'kb_coords': (0, 0, 0)},
'beta': {'kb_coords': (10, 10, 0)},
'gamma': {'kb_coords': (12, 0, 0)},
'epsilon': {'kb_coords': (20, 0, 0)}}
# %%
# Reading tops file
cwd = os.getcwd()
if 'examples' not in cwd:
data_path = os.getcwd() + '/examples'
else... |
scivey/goosepp | scripts/benchmark_python_goose.py | Python | mit | 648 | 0.00463 | import time
from goose import Goose
de | f load_jezebel():
with open('resources/additional_html/jezebel1.txt') as f:
data = f.read()
return data
def bench(iterations=100):
data = load_jezebel()
goose = Goose()
times = []
for _ in xrange(iterations):
t1 = time.time()
goose.extract(raw_html=data)
t2 = tim... | es.append(iteration_time)
return (sum(times) / float(len(times)))
if __name__ == '__main__':
start = time.time()
print bench()
end = time.time()
total_len = end - start
print "total test length: %f" % total_len
|
jayshonzs/ESL | SVM/SMO.py | Python | mit | 5,230 | 0.005354 | '''
Created on 2014-8-1
@author: xiajie
'''
import numpy as np
def fmax(a, b):
if a >= b:
return a
else:
return b
def fmin(a, b):
if a <= b:
return a
else:
return b
def radia_kernel(x1, x2):
return np.transpose(x1).dot(x2)
def kernel(x1, x2):
d = x1 -... | return 1
def secondheuristic(alphas, E, E1, i2, C):
N = len(E)
best_i = None
if E1 >= 0:
min_e = 999999999.
for i in range(N):
if i != i2 and alphas[i] > 0 and alphas[i] < C:
if E[i] < min_e:
min_e = E[i]
best_i = i
| else:
max_e = -999999999.
for i in range(N):
if i != i2 and alphas[i] > 0 and alphas[i] < C:
if E[i] > max_e:
max_e = E[i]
best_i = i
return best_i
def examineExample(X, Y, alphas, b, E, i2, tol=0.001, C=10):
y2 = Y[i2]
a... |
DONIKAN/django | tests/gis_tests/rasterapp/models.py | Python | bsd-3-clause | 292 | 0.003425 | from ..models import models
class RasterModel(models.Model):
rast = models.RasterField('A Verbose Raster | Name', null=True, srid=4326, spatial_index=True, blank=True)
cl | ass Meta:
required_db_features = ['supports_raster']
def __str__(self):
return str(self.id)
|
Livefyre/awscensus | ec2/tabular.py | Python | mit | 990 | 0 | """
super simple utitities to display tabular data
columns is a list of tuples:
- name: header name for the column
- f: a function which takes one argument *row* and returns the value to
display for a cell. the function which be called for each of the rows
supplied
"""
import sys
import csv
def... | or _, f in columns])
def pprint(columns, rows, key=lambda x: x):
lengths = {}
for name, _ in columns:
lengths[name] = len(name) + 1
for row in rows:
for name, f in columns:
lengths[name] = max(lengths[name], len(str(f(row)))+1)
fmt = ' '.join(['{:<%s}' % lengths[x] for x... | row in sorted(rows, key=key):
print fmt.format(*[f(row) for _, f in columns])
|
tta/gnuradio-tta | gr-uhd/apps/uhd_rx_cfile.py | Python | gpl-3.0 | 5,930 | 0.006071 | #!/usr/bin/env python
#
# Copyright 2011 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your option)
... | U Radio 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 G... | on, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
"""
Read samples from a UHD device and write to file formatted as binary
outputs single precision complex float values or complex short values
(interleaved 16 bit signed short integers).
"""
from gnuradio import gr, eng_notation
from gnuradio import uhd
... |
noironetworks/heat | heat/engine/resources/openstack/heat/random_string.py | Python | apache-2.0 | 9,442 | 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
# ... | for char_class in char_classes]
return password_gen.generate_password(length,
seq_mins + char_class_mins | )
def validate(self):
super(RandomString, self).validate()
char_sequences = self.properties[self.CHARACTER_SEQUENCES]
char_classes = self.properties[self.CHARACTER_CLASSES]
def char_min(char_dicts, min_prop):
if char_dicts:
return sum(char_dict[min_prop]... |
Guest007/vgid | manage.py | Python | mit | 247 | 0 | #!/usr/bin/env python
import os
import sys
if | __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "vgid.settings")
from django.core. | management import execute_from_command_line
execute_from_command_line(sys.argv)
|
KlubJagiellonski/Politikon | accounts/tests.py | Python | gpl-2.0 | 18,113 | 0.000276 | # -*- coding: utf-8 -*-
"""
Test accounts module
"""
import os
from decimal import Decimal
from mock import patch
from django.core.urlresolvers import reverse
from django.http import HttpResponseForbidden
from django.test import TestCase
from .factories import UserFactory, UserWithAvatarFactory, AdminFactory
from .mo... | turn_new_user_object(self):
"""
Return new user object
"""
user = UserProfile.objects.return_new_user_object(
username='j_smith',
password='password9',
)
self.assertIsInstance(user, UserProfile)
self.assertEqual('j_smith', user.username)
... | d9'))
with self.assertRaises(ValueError):
UserProfile.objects.return_new_user_object(
username=None,
)
def test_create_user(self):
"""
Create user
"""
user = UserProfile.objects.create_user(
username='j_smith',
... |
ptisserand/ansible | lib/ansible/plugins/strategy/__init__.py | Python | gpl-3.0 | 51,787 | 0.002819 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# 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) an... | if isinstance(result, StrategySentinel):
break
else:
strategy._results_lock.acquire()
strategy._results.append(result)
strategy._results_lock.release()
except (IOError, EOFError):
break
except Queue.Empty:
... | tor, one_pass=False, max_passes=None):
status_to_stats_map = (
('is_failed', 'failures'),
('is_unreachable', 'dark'),
('is_changed', 'changed'),
('is_skipped', 'skipped'),
)
# We don't know the host yet, copy the previous states, for lookup after ... |
pllim/astropy | astropy/utils/tests/test_introspection.py | Python | bsd-3-clause | 3,422 | 0.000292 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# namedtuple is needed for find_mod_objs so it can have a non-local module
from collections import namedtuple
from unittest import mock
import pytest
import yaml
from astropy.utils import introspection
from astropy.utils.introspection import (find_curre... | current_module(0, [introspection]).__name__ == thismodnm
assert find_current_module(0, ['astropy.utils.introspection']).__name__ == thismodnm
with pytest.raises(ImportError):
find_current_module(0, ['faddfdsasewrweriopunjlfiur | rhujnkflgwhu'])
def test_find_mod_objs():
lnms, fqns, objs = find_mod_objs('astropy')
# this import is after the above call intentionally to make sure
# find_mod_objs properly imports astropy on its own
import astropy
# just check for astropy.test ... other things might be added, so we
# sh... |
edisonlz/fruit | web_project/base/site-packages/gdata/tlslite/SharedKeyDB.py | Python | apache-2.0 | 1,914 | 0.00209 | """Class for storing shared keys."""
from utils.cryptomath import *
from utils.compat import *
from mathtls import *
from Session import Session
from BaseDB import BaseDB
class SharedKeyDB(BaseDB):
"""This class represent an in-memory or on-disk database of shared
keys.
A SharedKeyDB can be passed to a s... | if len(value)>=48:
raise ValueError("shared key too long")
| return value
def _checkItem(self, value, username, param):
newSession = self._getItem(username, param)
return value.masterSecret == newSession.masterSecret |
jromang/retina-old | distinclude/spyderlib/plugins/ipython.py | Python | gpl-3.0 | 2,012 | 0.006464 | # -*- coding: utf-8 -*-
#
# Copyright © 2011 Pierre Raybaut
# Licensed under the terms of the MIT License
# (see spyderlib/__init__.py for details)
"""IPython v0.11+ Plugin"""
from spyderlib.qt.QtGui import QHBoxLayout
# Local imports
from spyderlib.widgets.ipython import create_widget
from spyderlib.plu... | l_widget = kernel_widget
self.kernel_name = kernel_name
self.ipython_widget = create_widget(argv=args.split())
layout = QHBoxLayout()
layout.addWidget(self.ipython_widget)
self.setLayout(layout)
|
# Initialize plugin
self.initialize_plugin()
def toggle(self, state):
"""Toggle widget visibility"""
if self.dockwidget:
self.dockwidget.setVisible(state)
#------ SpyderPluginWidget API ---------------------------------------------
... |
ruibarreira/linuxtrail | usr/lib/python3/dist-packages/orca/scripts/toolkits/J2SE-access-bridge/script.py | Python | gpl-3.0 | 10,245 | 0.001659 | # Orca
#
# Copyright 2006-2009 Sun Microsystems Inc.
# Copyright 2010 Joanmarie Diggs
#
# 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 op... | mplied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., Franklin Street, Fifth F... | USA.
__id__ = "$Id$"
__version__ = "$Revision$"
__date__ = "$Date$"
__copyright__ = "Copyright (c) 2005-2009 Sun Microsystems Inc., " \
"Copyright (c) 2010 Joanmarie Diggs"
__license__ = "LGPL"
import pyatspi
import orca.scripts.default as default
import orca.input_event as input_eve... |
mtrgroup/django-mtr-sync | mtr/sync/__init__.py | Python | mit | 51 | 0 | default_app_confi | g = 'mtr.sync | .apps.MtrSyncConfig'
|
bloodstalker/mutator | bfd/codegen.py | Python | gpl-3.0 | 1,436 | 0.008357 | #!/bin | /python3
import argparse
import code
import readline
import signal
import sys
import capstone
from load import ELF
def SigHandler_SIGINT(signum, frame):
print()
sys.exit(0)
class Argparser(object):
def __init__(self):
parser = argparse.ArgumentParser()
parser.add_argument("--arglist", nar... | g) code, otherwise generate int", default=False)
self.args = parser.parse_args()
self.code = {}
class Call_Rewriter(object):
def __init__(self, obj_code, arch, mode):
self.obj_code = obj_code
#self.md = Cs(CS_ARCG_X86, CS_MODE_64)
self.md = Cs(arch, mode)
def run():
... |
ArtemMIPT/sentiment_analysis | vk_parser.py | Python | mit | 2,902 | 0.005513 | import vk
import json
from sentiment_classifiers import SentimentClassifier, binary_dict, files
class VkFeatureProvider(object):
def __init__(self):
self._vk_api = vk.API(vk.Session())
self._vk_delay = 0.3
self._clf = SentimentClassifier(files['binary_goods'], binary_dict)
def _vk_grac... | f, entry_uid, fname=None, lname=None):
try:
friend_list = self._vk_api.friends.get(user_id=entry_uid, fields='personal', name_case='nom')
self._vk_grace()
except:
return []
return [x for x in friend_list
if (not fname or fnam | e in x['first_name']) and (not lname or lname in x['last_name'])]
def get_uid_set_info(self, uid_set):
result = []
for friend_uid in uid_set:
try:
friend = self._vk_api.users.get(user_id=friend_uid, fields='sex,personal', name_case='nom')
self._vk_grace()... |
Uli1/mapnik | scons/scons-local-2.4.0/SCons/Tool/FortranCommon.py | Python | lgpl-2.1 | 10,707 | 0.006538 | """SCons.Tool.FortranCommon
Stuff for processing Fortran, common to all fortran dialects.
"""
#
# Copyright (c) 2001 - 2015 The SCons Foundation
#
# 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 So... | ermit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyrigh | t notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMEN... |
patrick-winter-knime/deep-learning-on-molecules | smiles-vhts/generate_features.py | Python | gpl-3.0 | 769 | 0.007802 | import gc
import os
import argparse
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
from util import generate_features
def get_arguments():
parser = argparse.ArgumentParser(description='Generate features using a previously trained model')
parser.add_argument('data', type=str, help='File containing the input smiles m... | ault=100, help='Size of the batc | hes (default: 100)')
return parser.parse_args()
args = get_arguments()
generate_features.generate_features(args.data, args.model, args.features, args.batch_size)
gc.collect()
|
stevenmizuno/QGIS | python/plugins/processing/algs/grass7/ext/r_li_richness_ascii.py | Python | gpl-2.0 | 1,514 | 0 | # -*- coding: utf-8 -*-
"""
***************************************************************************
r_li_richness_ascii.py
----------------------
Date : February 2016
Copyright : (C) 2016 by Médéric Ribreux
Email : medspx at medspx dot fr
**************... | e Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
"""
__author__ = 'Méd... | s will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
from .r_li import checkMovingWindow, configFile, moveOutputTxtFile
def checkParameterValuesBeforeExecuting(alg, parameters, context):
return checkMovingWindow(alg, parameters, context, True)
def processCommand(alg, para... |
rzzzwilson/morse | morse/test.py | Python | mit | 682 | 0.005865 | import pyaudio
impor | t wave
#CHUNK = 1024
CHUNK = 1
FORMAT = pyaudio.paInt16
#CHANNELS = 2
CHANNELS = 1
#RATE = 44100
RATE = 10025
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
... | ata=%s, len=%d' % (str(data), len(data)))
# print(str(data))
# print('%d' % ord(data))
print("* done recording")
stream.stop_stream()
stream.close()
p.terminate()
|
eayunstack/neutron | neutron/tests/unit/plugins/ml2/drivers/openvswitch/agent/openflow/native/test_br_int.py | Python | apache-2.0 | 17,011 | 0.002116 | # Copyright (C) 2014,2015 VA Linux Systems Japan K.K.
# Copyright (C) 2014,2015 YAMAMOTO Takashi <yamamoto at valinux co jp>
# 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 t... | ofpp.OFPActionOutput(6666, 0),
]),
],
match=ofpp.OFPMatch(
eth_d | st=dst_mac,
vlan_vid=vlan_tag | ofp.OFPVID_PRESENT),
priority=4,
table_id=60)),
]
self.assertEqual(expected, self.mock.mock_calls)
def test_delete_dvr_to_src_mac(self):
network_type = 'vxlan'
vlan_tag = 1111
dst_mac = '00:0... |
aagusti/osipkd-json-rpc | jsonrpc/scripts/DbTools.py | Python | lgpl-2.1 | 3,322 | 0.003612 | import re
import transaction
from ..models import DBSession
SQL_TABLE = """
SELECT c.oid, n.nspname, c.relname
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relname = :table_name
AND pg_catalog.pg_table_is_visible(c.oid)
ORDER BY 2, 3
"""
SQL_TABLE_SCHEM... | _type t
WHERE c.oid = a.attcollation
AND t.oid = a.atttypid
AND a.attcollation <> t.typcollation) AS attcollation,
NULL AS indexdef,
NULL AS attfdwoptions
FROM pg_catalog.pg_attribute a
WHERE a.attrelid = :table_id AND a.attnu | m > 0 AND NOT a.attisdropped
ORDER BY a.attnum"""
def get_table_seq(table_name):
t = table_name.split('.')
if t[1:]:
schema = t[0]
table_name = t[1]
sql = text(SQL_TABLE_SCHEMA)
q = engine.execute(sql, schema=schema, table_name=table_name)
else:
sql = text(SQL_TAB... |
ngageoint/gamification-server | gamification/badges/migrations/0002_auto__add_field_projectbadge_awardLevel__add_field_projectbadge_multip.py | Python | mit | 8,179 | 0.007214 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'ProjectBadge.awardLevel'
db.add_column(u'badges_projectbadge', 'awardLevel',
... | [], {'to': u"orm['badges.ProjectBadge']"}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'd... | abel': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_lengt... |
ast0815/mqtt-hub | mqtt_logger/migrations/0003_auto_20161119_1840.py | Python | mit | 664 | 0.003012 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-19 18:40
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('mqtt_logger', '0002_mqttsubscription_active'),
]
operations = [
migra | tions.AlterModelOptions(
name='mqttmessage',
options={'verbose_name': 'MQTT message', 'verbose_name_plural': 'MQTT messages'},
),
migrations.AlterModelOptions(
name='mqttsubscription',
options={'verbose_name': 'MQTT subscription', 'verbose_name_plural': 'M... | ptions'},
),
]
|
Flexget/Flexget | flexget/utils/soup.py | Python | mit | 491 | 0.004073 | # Hack, hide DataLossWarnings
# Based on html5lib code namespaceHTMLElement | s=False should do it, but nope ...
# Also it doesn't seem to be available in older version from html5lib, removing it
import warnings
from typing import IO, Union
from bs4 import BeautifulSoup
from html5lib.constants import DataLossWarning
warnings.simplefilter('ignore', DataLossWarning)
def get_soup( | obj: Union[str, IO, bytes], parser: str = 'html5lib') -> BeautifulSoup:
return BeautifulSoup(obj, parser)
|
ictofnwi/coach | test_lrs.py | Python | agpl-3.0 | 305 | 0.019672 | import reques | ts
LRS = "http://cygnus.ic.uva.nl:8000/XAPI/statements"
u = raw_input("LRS username: ")
p = raw_input("LRS password: ")
r = requests.get(LRS,headers={"X-Experience-API-Version":"1.0"},auth=(u,p));
if r.status_code == 200:
print "Success"
e | lse:
print "Server returns",r.status_code
|
evernym/zeno | plenum/test/view_change_with_delays/test_view_change_with_propagate_primary_on_one_delayed_node.py | Python | apache-2.0 | 1,269 | 0.001576 | import pytest
from plenum.test.helper import perf_monitor_disabled
from plenum.test.node_catchup.helper import ensure_all_nodes_have_same_data
from plenum.test.view_change_with_delays.helper import \
do_view_change_with_propagate_primary_on_one_delayed_node
# This is needed only with current view change implement... | er nodes in the new view. After that
verify that all the nodes have the same ledgers and state.
"""
do_view_change_with_propagate_primary_on_one_delayed_node(
txnPoolNodeSet[-1], txnPoolNodeSet, looper, sdk_pool_handle, sdk_wallet_client)
e | nsure_all_nodes_have_same_data(looper, txnPoolNodeSet)
|
maxalbert/sumatra | sumatra/versioncontrol/_git.py | Python | bsd-2-clause | 6,219 | 0.002573 | """
Defines the Sumatra version control interface for Git.
Classes
-------
GitWorkingCopy
GitRepository
:copyright: Copyright 2006-2015 by the Sumatra team, see doc/authors.txt
:license: BSD 2-clause, see LICENSE for details.
"""
from __future__ import print_function
from __future__ import absolute_import
from __fu... | shutil
from distutils | .version import LooseVersion
from configparser import NoSectionError, NoOptionError
try:
from git.errors import InvalidGitRepositoryError, NoSuchPathError
except:
from git.exc import InvalidGitRepositoryError, NoSuchPathError
from .base import Repository, WorkingCopy, VersionControlError
from ..core import comp... |
rspavel/spack | var/spack/repos/builtin/packages/claw/package.py | Python | lgpl-2.1 | 1,854 | 0.004854 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Claw(CMakePackage):
"""CLAW Compiler targets performance portability problem in climate an... | (self):
args = []
spec = self.spec
args.append('-DOMNI_CONF_OPTION=--with-libxml2={0}'.
format(spec['libxml2'].prefix))
args.append('-DCMAKE_Fortran_COMPILER={0}'.
| format(self.compiler.fc))
return args
|
m00nlight/hackerrank | algorithm/Graph-Theory/Breadth-First-Search-Shortest-Reach/main.py | Python | gpl-2.0 | 1,017 | 0.00295 | from __future__ import division
from sys import stdin, stdout
from collections import deque
def solve(n, edges, s):
def build_graph(n, edges):
graph = [[] for _ in range(n)]
for (a, b) in edges:
a, b = a - 1, b - 1
graph[a].append(b)
graph[b].append(a)
re... | urn dis
if __name__ == '__main__':
t = int(stdin.readline())
for _ in range | (t):
edges = []
n, m = map(int, stdin.readline().strip().split())
for _ in range(m):
a, b = map(int, stdin.readline().strip().split())
edges.append((a, b))
s = int(stdin.readline())
print ' '.join(map(str, solve(n, edges, s - 1))) |
uclouvain/osis_louvain | base/migrations/0260_auto_20180416_1839.py | Python | agpl-3.0 | 4,812 | 0.003117 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-04-16 16:39
from __future__ import unicode_literals
import base.models.learning_unit_year
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
... | ='learningcontaineryear',
name='common_title_english',
field=models.CharField(blank=True, max_length=250, null=True, verbose_name='common_official_english_title'),
),
migrations.AlterField(
model_name='learningcontaineryear',
name='container_type',
... | ISSERTATION', 'DISSERTATION'), ('OTHER_COLLECTIVE', 'OTHER_COLLECTIVE'), ('OTHER_INDIVIDUAL', 'OTHER_INDIVIDUAL'), ('MASTER_THESIS', 'MASTER_THESIS'), ('EXTERNAL', 'EXTERNAL')], max_length=20, verbose_name='type'),
),
migrations.AlterField(
model_name='learningcontaineryear',
nam... |
linkedin/indextank-service | nebu/rpc.py | Python | apache-2.0 | 48 | 0.041667 | from api_l | ink | ed_rpc import * #@UnusedWildImport
|
midonet/Chimata-No-Kami | stages/midonet_cli/fabfile.py | Python | apache-2.0 | 363 | 0.00551 |
puts(green("installing MidoNet cli on %s" % env.host_string))
args = {}
Puppet.apply('midonet::midonet_cli', args, metadata)
run("""
|
cat >/root/.midonetrc <<EOF
[cli]
api_url = http://%s:8080/midonet-api
username = admin
password = admin
project_id = admin
tenant = admin
EOF
""" % metadata.servers[metadata.roles['midonet_api'][0]]['ip' | ])
|
Arcbot-Org/Arcbot | tests/core/test_interval.py | Python | gpl-3.0 | 910 | 0 | import unittest
from bolt.core.plugin import Plugin
from bolt import interval
from bolt import Bot
import yaml
class TestIntervalPlugin(Plugin):
@interval(60)
def intervaltest(self):
pass
class TestInterval(unittest.TestCase):
def setUp(self):
self.config_file = "/t | mp/bolt-test-config.yaml"
fake_config = {
"api_key": "1234",
"log_dir": "/tmp/"
}
with open(self.config_file, "w") as tempconfig:
tempconfig.write(yaml.dump(fake_config))
def test_interval_decos(self):
bot = Bot(self.config_file)
plugin =... |
def test_interval_will_run(self):
bot = Bot(self.config_file)
plugin = TestIntervalPlugin(bot)
plugin.load()
self.assertTrue(plugin.intervals[0].ready())
|
raoariel/PennApps-F15 | pennapps/pennapps/settings.py | Python | mit | 2,659 | 0 | """
Django settings for pennapps project.
Generated by 'django-admin startproject' using Django 1.8.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build pat... | 'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.c | ontext_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'pennapps.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#database... |
interhui/py-text | text_test/grep_test.py | Python | apache-2.0 | 1,719 | 0.016289 | # coding=utf-8
import unittest
from text import grep
from text import string_utils
import text_test
class GrepTest(unittest.TestCase):
def test_grep(self):
log_list = text_test.read_log()
linux_syslog_head = '(\S+\s+\d+)\s+(\d+:\d+:\d+)\s+(\S+)\s+'
group_data = grep.grep... | startswith(group_data[4] | , '12'))
self.assertTrue(string_utils.startswith(group_data[5], '19'))
group_data = grep.grep(log_list, None, True, 'e')
self.assertEqual(len(group_data), 19)
group_data = grep.grep(log_list, grep_action, True, 'a')
self.assertEqual(len(group_data), 3)
... |
Forkk/Sporkk-Pastebin | sporkk/views.py | Python | mit | 4,231 | 0.022453 | # Copyright (C) 2013 Andrew Okin
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribu... | apping)
# If nothing is found, act like the URL ID doesn't even exist.
return redirect("/")
@app.route('/<type_spec>/<url_id>')
def url_type_spec_view(type_spec, url_id):
"""View that goes to the URL of the given type that the given ID maps to"""
for utype in url_types:
# If the given type spec matches one of ... | the URL type's model type as well.
if type(mapping) is utype.get_model_type():
return utype.handle_view(url_id, mapping)
# It's not valid, so go home.
return redirect("/")
####################
#### INITIALIZE ####
####################
# Load URL type modules.
import shortenedurl
import pastebinurl
# FIXME... |
Pikecillo/genna | external/PyXML-0.8.4/test/test_filter.py | Python | gpl-2.0 | 5,625 | 0.000533 | import pprint
import sys
from xml.dom import xmlbuilder, expatbuilder, Node
from xml.dom.NodeFilter import NodeFilter
class Filter(xmlbuilder.DOMBuilderFilter):
whatToShow = NodeFilter.SHOW_ELEMENT
def startContainer(self, node):
assert node.nodeType == Node.ELEMENT_NODE
if node.tagName == "s... | n another skipped element
checkResult('''\
<doc>Text.
<skipthis>Nested text.
<nested-element>
<skipthis>Nested text in skipthis element.</skipthis>
More nested text.
</nested-element>
More text.
</skipthis>Oute | r text.</doc>
''')
checkResult("<doc><rejectbefore/></doc>")
checkResult("<doc><rejectafter/></doc>")
checkResult('''\
<doc><rejectbefore>
Text.
<?my processing instruction?>
<more stuff="foo"/>
<!-- a comment -->
</rejectbefore></doc>
''')
checkResult('''\
<doc><rejectafter>
Text.
<?my processing instr... |
gsterjov/Myelin | bindings/python/myelin/introspection/value.py | Python | gpl-3.0 | 11,453 | 0.024797 | #
# Copyright 2009-2010 Goran Sterjov
# This file is part of Myelin.
#
# Myelin is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) a... | ype
elif type(value) is int or type(value) is long:
if atom is not None:
if atom == Type.type_char(): self.set_char (value)
elif atom == Type.type_uchar(): self.set_uchar (value)
elif at | om == Type.type_int(): self.set_int (value)
elif atom == Type.type_uint(): self.set_uint (value)
elif atom == Type.type_long(): self.set_long (value)
elif atom == Type.type_ulong(): self.set_ulong (value)
# for long only
... |
jdahlin/pygobject | tests/test_everything.py | Python | lgpl-2.1 | 23,544 | 0.000935 | # -*- Mode: Python; py-indent-offset: 4 -*-
# coding=utf-8
# vim: tabstop=4 shiftwidth=4 expandtab
import unittest
import sys
sys.path.insert(0, "../")
import sys
import copy
try:
import cairo
has_cairo = True
except ImportError:
has_cairo = False
from gi.repository import GObject
from gi.repository imp... | o_surface(self):
surface = Everything.test_cairo_surface_none_return()
self.assertTrue(isinstance(surface, cairo.ImageSurface))
self.assertTrue(isinstance(surface, cairo.Surface))
self.assertEqual(surface.get_format(), cairo.FORMAT_ARGB32)
self.assertEqual(surface.get_width(), 10... | self.assertTrue(isinstance(surface, cairo.ImageSurface))
self.assertTrue(isinstance(surface, cairo.Surface))
self.assertEqual(surface.get_format(), cairo.FORMAT_ARGB32)
self.assertEqual(surface.get_width(), 10)
self.assertEqual(surface.get_height(), 10)
surface = cairo.ImageSurf... |
lewisodriscoll/sasview | test/sasdataloader/test/utest_red2d_reader.py | Python | bsd-3-clause | 844 | 0.009479 | """
Unit tests for the red2d (3-7-column) reader
"""
import warnings
warnings.simplefilter("ignore")
import unittest
from sas.sascalc.dataloader.loader import Loader
import os.path
class abs_reader(unittest.TestCase):
def setUp(self):
self.loader = Loader()
def test_checkdata(self):
""... | assertEqual(f.Q_unit, '1/A')
self.assertEqual(f.I_unit, '1/cm')
self.assertEqual(f.meta_data['loader'],"IGOR/DAT 2D Q_map")
if __name__ == '__main_ | _':
unittest.main()
|
oVirt/ovirt-scheduler-proxy | src/ovirtscheduler/runner.py | Python | apache-2.0 | 2,775 | 0 | #
# Copyright 2013 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may n | ot 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 CONDITION... |
from threading import Thread
from ovirtscheduler import utils
class PythonMethodRunner(Thread):
def __init__(self, path, module, cls, method, args, request_id=''):
super(PythonMethodRunner, self).__init__(group=None)
logger = logging.getLogger()
self._log_adapter = utils.RequestAdapter(
... |
JetChars/vim | vim/bundle/python-mode/pymode/libs3/rope/contrib/codeassist.py | Python | apache-2.0 | 25,419 | 0.000669 | import keyword
import sys
import warnings
import rope.base.codeanalyze
import rope.base.evaluate
from rope.base import pyobjects, pyobjectsdef, pynames, builtins, exceptions, worder
from rope.base.codeanalyze import SourceLinesAdapter
from rope.contrib import fixsyntax
from rope.refactor import functionutils
def cod... | n None
pyobject = pyname.get_object()
return PyDocExtractor().get_calltip(pyobject, ignore_unknown, remove_self)
def get_definition_location(project | , source_code, offset,
resource=None, maxfixes=1):
"""Return the definition location of the python name at `offset`
Return a (`rope.base.resources.Resource`, lineno) tuple. If no
`resource` is given and the definition is inside the same module,
the first element of the retu... |
pgroudas/pants | tests/python/pants_test/tasks/test_cache_manager.py | Python | apache-2.0 | 4,697 | 0.006813 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licens | ed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, | with_statement)
import shutil
import tempfile
from pants.base.build_invalidator import CacheKey, CacheKeyGenerator
from pants.base.cache_manager import InvalidationCacheManager, InvalidationCheck, VersionedTarget
from pants_test.base_test import BaseTest
class AppendingCacheKeyGenerator(CacheKeyGenerator):
"""Gen... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.