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 |
|---|---|---|---|---|---|---|---|---|
BackupTheBerlios/kimchi | src/ui/mvc/delegate/KTableDelegate.py | Python | bsd-3-clause | 2,652 | 0.00905 | # coding: utf-8
'''
Copyright (c) 2010, Alexandru Dancu
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of condit... | NY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
'''
from PyQt4.QtCore import | *
from PyQt4.QtGui import *
from properties import NEW_TABLE
class KTableDelegate(QItemDelegate):
def __init__(self, parent = None):
super(KTableDelegate, self).__init__(parent)
# def createEditor(self, parent, option, index):
#
# editor = QLineEdit(parent)
# ... |
rbaravalle/imfractal | imfractal/Algorithm/MFS_3D.py | Python | bsd-3-clause | 11,780 | 0.00798 | """
Copyright (c) 2013 Rodrigo Baravalle
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following... | e distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILIT... | E LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
... |
stvstnfrd/edx-platform | lms/djangoapps/courseware/testutils.py | Python | agpl-3.0 | 11,543 | 0.002512 | """
Common test utilities for courseware functionality
"""
from abc import ABCMeta, abstractmethod
from datetime import datetime, timedelta
import ddt
import six
from mock import patch
from six.moves.urllib.parse import urlencode
from lms.djangoapps.courseware.field_overrides import OverrideModulestoreFieldData
fro... | cal, it is LTI specifically that must never include them.
'vertical_block': ['<div class="bookmark-button-wrapper"'],
'html_block': [],
| }
def setUp(self):
"""
Clear out the block to be requested/tested before each test.
"""
super(RenderXBlockTestMixin, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
# to adjust the block to be tested, update block_name_to_be_tested before calling setup_... |
googleapis/python-channel | google/cloud/channel_v1/types/entitlements.py | Python | apache-2.0 | 11,801 | 0.001271 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | ing ID of the
entitlement. For Google Workspace, this is the
underlying Subscription ID. For Google Cloud
Platform, this is the Billing Account ID of the
billing subaccount.".
product_id (str):
Output only. The product pertaining to the
pro... | d in the Offer.
sku_id (str):
Output only. The SKU pertaining to the
provisioning resource as specified in the Offer.
"""
provisioning_id = proto.Field(proto.STRING, number=1,)
product_id = proto.Field(proto.STRING, number=2,)
sku_id = proto.Field(proto.STRING, number=3,... |
google/fuzzbench | docs/reference/benchmarks.py | Python | apache-2.0 | 6,523 | 0.000307 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softw... | UILD_PREFIX
):-len(BUILD_ARCHIVE_EXTENSION)]
benchmark = get_real_benchmark_name(benchmark)
parent_dir = os.path.dirname(build_path)
benchmark_path = os.path.join(parent_dir, benchmark)
filesystem.create_directory(benchmark_path)
with tarfile.open(build_path) as tar_fil... | nchmark_path)
has_dictionary = bool(fuzzer_utils.get_dictionary_path(fuzz_target_path))
seeds = get_seed_count(benchmark_path, fuzz_target_path)
num_guards = get_num_guards(fuzz_target_path)
size = get_binary_size_mb(fuzz_target_path)
return BenchmarkInfo(benchmark, fuzz_target, has_dictionary, see... |
xiang12835/python_web | py2_web2py/web2py/applications/admin/languages/bg.py | Python | apache-2.0 | 35,738 | 0.020631 | # -*- coding: utf-8 -*-
{
'!langcode!': 'bg',
'!langname!': 'Български',
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN',
'"User Exceptio... | elete': 'Check to delete',
'Checking for upgrades...': 'Checking for upgrades...',
'Clean': 'clean',
'Clear': 'Clear',
'Clear CACHE?': 'Clear CACHE?',
'Clear DISK': 'Clear DISK',
'Clear RAM': 'Clear RAM',
'click her | e for online examples': 'щракни тук за онлайн примери',
'click here for the administrative interface': 'щракни тук за административния интерфейс',
'Click row to expand traceback': 'Click row to expand traceback',
'Click row to view a ticket': 'Click row to view a ticket',
'click to check for upgrades': 'click to check ... |
mruffalo/sysv_ipc | extras/memory_leak_tests.py | Python | bsd-3-clause | 20,971 | 0.000763 | # Python modules
import gc
import os
import subprocess
import random
import re
import sys
# My module
import sysv_ipc
S | KIP_SEMAPHORE_TESTS = False
SKIP_SHARED_MEMORY_TESTS = False
SKIP_MESSAGE_QUEUE_TESTS = False
# TEST_COUNT = 10
TEST_COUNT = 1024 * 100
PY_MAJOR_VERSION = sys.version_info[0]
# ps output looks like this:
# RSZ VSZ
# 944 75964
ps_output_regex = re.compile("""
^
\s* # whitespace before first hea... | before first numeric value
(\d+) # first value
\s+ # whitespace between values
(\d+) # second value
\s* # trailing whitespace if any
$
""", re.MULTILINE | re.VERBOSE)
# On OS X, Ubuntu and OpenSolaris, both create/destroy tests show some growth
# is rsz and vsz. (e.g. 3248 versus 3240 -- I gues... |
miguelsdc/nao_robot | nao_driver/scripts/nao_behaviors.py | Python | bsd-3-clause | 5,440 | 0.0125 | #!/usr/bin/env python
#
# ROS node to control NAO's built-in and user-installed behaviors using NaoQI
# Tested with NaoQI: 1.12
#
# Copyright (c) 2012, 2013 Miguel Sarabia
# Imperial College London
#
# Redistribution and use in source and binary forms, with or | without
# modification, are permitted provided that the followin | g conditions are met:
#
# # Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# # Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# ... |
Sunhick/hacker_rank | Algorithms/Dynamic Programming/The-Coin-Change-Problem.py | Python | mit | 496 | 0.010081 | def count(S, m, n):
table = [[0 for x in range(m)] for x | in range(n+1)]
for i in range(m):
table[0][i] = 1
for i in range(1, n+1):
for j in range(m):
x = table[i - S[j]][j] if i-S[j] >= 0 else 0
y = table[i][j-1] if j >= 1 else 0
table[i][j] = x + y
| return table[n][m-1]
n,m = [int(a) for a in raw_input().strip().split(' ')]
s = [int(a) for a in raw_input().strip().split(' ')]
print count(s, m, n)
|
sgammon/libcloud | libcloud/compute/drivers/gandi.py | Python | apache-2.0 | 20,171 | 0.00005 | # 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 ... | 'description': vm.get('description')
}
)
def _to_nodes(self, vms):
return [self._to_node(v) for v in vms]
def _to_volume(self, disk):
extra = {'can_snapshot': disk['can_snapshot']}
return StorageVolume(
id=disk['id'],
name=disk['name'... | o_volume(d) for d in disks]
def list_nodes(self):
vms = self.connection.request('hosting.vm.list').object
ips = self.connection.request('hosting.ip.list').object
for vm in vms:
vm['ips'] = []
for ip in ips:
if vm['ifaces_id'][0] == ip['iface_id']:
... |
Ebag333/Pyfa | eos/effects/weaponupgradescpuneedbonuspostpercentcpulocationshipmodulesrequiringmissilelauncheroperation.py | Python | gpl-3.0 | 517 | 0.003868 | # weaponUpgradesCpuNeedBonusPostPercentCpuLocatio | nShipModu | lesRequiringMissileLauncherOperation
#
# Used by:
# Implants named like: Zainou 'Gnome' Launcher CPU Efficiency LE (6 of 6)
# Skill: Weapon Upgrades
type = "passive"
def handler(fit, container, context):
level = container.level if "skill" in context else 1
fit.modules.filteredItemBoost(lambda mod: mod.item.re... |
overfl0/Bulletproof-Arma-Launcher | src/utils/requests_wrapper.py | Python | gpl-3.0 | 2,188 | 0.001828 | # Bulletproof Arma Launcher
# Copyright (C) 2017 Lukasz Taczuk
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# b... | fetching of the data in case an exception occurrs.
"""
retries_total = 3
for retries_left in reversed(range(retries_total)):
try:
return _download_url(*args, **kwargs)
except Exception as ex:
if retries_left > 0:
Logger.error('download_url: retryin... | continue
raise
def _download_url(domain, *args, **kwargs):
"""
Helper function that adds our error handling to requests.get.
Feel free to refactor it.
"""
if not domain:
domain = "the domain"
try:
res = requests.get(*args, **kwargs)
except requests.ex... |
mrosenstihl/PulsePrograms | make_clean.py | Python | bsd-2-clause | 679 | 0.041237 | #!/usr/bin/env python
import os
print "Cleaning directory %s"%(os.path.realpath('.'))
rubbish_filetypes = ('h5','hdf','.dat','.pyc', '.png', '.pdf', '.tar.gz')
rubb | ish_startnames = ('job','logdata','Amplitude','Real','spool','pool')
choosing = raw_input("Continue [yes/anykey_for_NO] ?")
if choosing == 'yes':
print "Cleaning directory"
for root,dir,files in os.walk('.'):
if dir != ".bzr":
print dir
for file in files:
print file,
if file.endswith(rubbish_filetype... | ile.startswith(rubbish_startnames):
delete_file = os.path.join(root,file)
os.remove(delete_file)
print "...delete"
else:
print "...skipped"
print "finnished"
|
rven/odoo | addons/sale_management/models/sale_order.py | Python | agpl-3.0 | 12,391 | 0.00347 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import timedelta
from odoo import api, fields, mo | dels, _
from odoo.exceptions import UserError, ValidationError
class SaleOrder(models.Model):
_inherit = 'sale.order'
@api.model
def default_get(self, fields_list):
defa | ult_vals = super(SaleOrder, self).default_get(fields_list)
if "sale_order_template_id" in fields_list and not default_vals.get("sale_order_template_id"):
company_id = default_vals.get('company_id', False)
company = self.env["res.company"].browse(company_id) if company_id else self.env.co... |
fdemian/Morpheus | api/LoadOptions.py | Python | bsd-2-clause | 3,767 | 0.00876 | from tornado.options import define, options
def load_options(config_file):
# General application settings
define('port', type=int, group='application', help='Port to run the application from.')
define('compress_response', type=bool, group='application', help='Whether or not to compress the response.')
... | mail_template', type=str, group='application', help='Locat | ion of the mail template (relative to /static).')
define('mail_subject', type=str, group='application', help='Subject of the confirmation mail.')
define('mail_host', type=str, group='application', help='Host used to send emails.')
define('mail_port', type=int, group='application', help='Port used to send em... |
AndrewNeo/hybridius | forms.py | Python | mit | 1,328 | 0.024849 | from wtforms import Form, BooleanField, TextField, PasswordField, validators
import re
illegal_shortcode_names = ["admin"]
legal_shortcode_regex = "^[a-zA-Z0-9\.\_\-\~\!\$\&\'\(\)\*\,\;\=]*$"
def shortcode_validator(form, field):
if field.data is not None:
if (field.data in illegal_shortcode_names):
raise valid... | shortcode_validator
])
target_url = TextField("Destination | ", [
validators.Required(),
validators.Length(max=1024, message="Max limit 1024 characters.")
])
class LoginForm(Form):
username = TextField("Username", [validators.Required()])
password = PasswordField("Password", [validators.Required()])
login_validator = None
def validate(self):
... |
milankl/swm | calc/process/var_subset_last.py | Python | gpl-3.0 | 1,070 | 0.018692 | ## READ VARIABLE FROM SEVERAL NCFILES and store subset of it as NPY
from __future__ import print_function
path = '/network/aopp/cirrus/pred/kloewer/swm_bf_cntrl/data/'
#path = '/network/aopp/cirrus/pred/kloewer/swm_back_ronew/'
import os; os.chdir(path) # change working directory
import numpy as np
from netCDF4 impor... | e last time step from run %i') % r)
## read data
runpath = path+'run%04i' % r
ncu = Dataset(runpath+'/u.nc')
u = ncu['u'][-s,:,:]
ncu.close()
print('u read.')
np.save(runpath+'/u_last.npy',u)
del u
ncv = Dataset(runpath+'/v.nc')
v = ncv['v'][-s,:,:] |
ncv.close()
print('v read.')
np.save(runpath+'/v_last.npy',v)
del v
nceta = Dataset(runpath+'/eta.nc')
eta = nceta['eta'][-s,:,:]
#time = nceta['t'][::sub] # in seconds
#t = time / 3600. / 24. # in days
nceta.close()
print('eta read.')
np.save(runpath+'/eta_last.npy',eta... |
hplustree/trove | trove/common/wsgi.py | Python | apache-2.0 | 23,631 | 0.000296 | # Copyright 2011 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/licenses/LICENSE-2.0
#
# Unless requ... | data = data
| self.status = status
def data(self, serialization_type):
"""Return an appropriate serialized type for the body.
serialization_type is not used presently, but may be
in the future, so it stays.
"""
if hasattr(self._data, "data_for_json"):
return self._d... |
Crosse/vcard4 | vcard4/parameters/RFCParameters.py | Python | bsd-2-clause | 413 | 0.002421 | """
This module provides vCard parameters that are | defined by the vCard 4.0
RFC.
"""
from vcard4.parameters import BaseParameter
class Language(BaseParameter):
"""
A LANGUAGE | parameter.
Example:
ROLE;LANGUAGE=tr:hoca
"""
def __init__(self, language):
super(Language, self).__init__('LANGUAGE', language)
def __repr__(self):
return 'Language(%r)' % self.value
|
Four-Stooges/Server | public/resources/scripts/latestupload.py | Python | mit | 392 | 0.012755 | import sys
from pymong | o import MongoClient
# Connecting to the mongo client
client = MongoClient('localhost',27017)
# Connecting to the database
db = client['rescueHomeless']
# Connecting to the required collection
collection = db['userDB']
userEmail | = sys.argv[1]
result = collection.find({'email':userEmail})
pIDs = result['personIDs']
if len(pIDs)==0:
exit(1)
print(pIDs.pop())
exit(0) |
krux/adspygoogle | examples/adspygoogle/dfp/v201204/inventory_service/create_ad_units.py | Python | apache-2.0 | 2,765 | 0.008318 | #!/usr/bin/python
#
# Copyright 2012 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 b... | 'adUnitSizes': [ad_unit_size]
}
mobile_ad_unit = {
'name': 'Mobile_ad_unit_%s' % Utils.GetUniqueName(),
'parentId': parent_id,
'description': 'Mobile ad unit description.',
'targetWindow': 'BLANK',
'targetPlatform': 'MOBILE',
'adUnitSizes': [ad_unit_size]
}
# Add ad units.... | nt ('Ad unit with ID \'%s\', name \'%s\', and target platform \'%s\' '
'was created.' % (ad_unit['id'], ad_unit['name'],
ad_unit['targetPlatform']))
if __name__ == '__main__':
# Initialize client object.
dfp_client = DfpClient(path=os.path.join('..', '..', '..', '..', '..'))... |
rohitranjan1991/home-assistant | homeassistant/components/zha/siren.py | Python | mit | 5,710 | 0.000876 | """Support for ZHA sirens."""
from __future__ import annotations
import functools
from typing import Any
from zigpy.zcl.clusters.security import IasWd as WD
from homeassistant.components.siren import (
ATTR_DURATION,
SUPPORT_DURATION,
SUPPORT_TURN_OFF,
SUPPORT_TURN_ON,
SirenEntity,
)
from homeas... | None:
"""Set up the Zigbee Home Automation siren from config entry."""
entities_to_create = hass.data[DATA_ZHA][Platform.SIREN]
unsub = async_dispatcher_connect(
hass,
SIGNAL_ADD_ENTITIES,
functools.partial(
discovery.async_add_entities,
async_add_entities,
... | tities_to_create,
update_before_add=False,
),
)
config_entry.async_on_unload(unsub)
@MULTI_MATCH(channel_names=CHANNEL_IAS_WD)
class ZHASiren(ZhaEntity, SirenEntity):
"""Representation of a ZHA siren."""
def __init__(
self,
unique_id: str,
zha_device: ZhaDe... |
dana-i2cat/felix | vt_manager/src/python/vt_manager/communication/sfa/methods/reset_slice.py | Python | apache-2.0 | 1,080 | 0.007407 | from vt_manager.communication.sfa.util.xrn import urn_to_hrn
from vt_manager.communication.sfa.util.method import Method
from vt_manager.communication.sfa.util.parameter import Parameter, Mixed
class reset_slice(Method):
"""
Reset the specified slice
@param cred credential string specifying the rig... | ble name of slice to instantiate (hrn or urn)
@return 1 is successful, faults otherwise
"""
interfaces = ['aggregate', 'slicemgr', 'component']
accepts = [
Parameter(str, "Credential string"),
Parameter(str, "Human readable name of slice to instantiate (hrn or urn)"),
Mix... | = Parameter(int, "1 if successful")
def call(self, cred, xrn, origin_hrn=None):
hrn, type = urn_to_hrn(xrn)
self.api.auth.check(cred, 'resetslice', hrn)
self.api.manager.reset_slice (self.api, xrn)
return 1
|
chuck211991/django-pyodbc | tests/basic/models.py | Python | bsd-3-clause | 15,295 | 0.001896 | # coding: utf-8
"""
1. Bare-bones model
This is a basic model with only two non-primary-key fields.
"""
# Python 2.3 doesn't have set as a builtin
try:
set
except NameError:
from sets import Set as set
# Python 2.3 doesn't have sorted()
try:
sorted
except NameError:
from django.utils.itercompat import... | odels.DateTimeField()
class Meta:
ordering = ('pub_date','headline')
def __unicode__(self):
return self.headline
__test__ = {'API_TESTS': """
# No articles are in the system yet.
>>> Article.objects.all()
[]
# Create | an Article.
>>> from datetime import datetime
>>> a = Article(id=None, headline='Area man programs in Python', pub_date=datetime(2005, 7, 28))
# Save it into the database. You have to call save() explicitly.
>>> a.save()
# Now it has an ID. Note it's a long integer, as designated by the trailing "L".
>>> a.id
1L
# ... |
HubSpot/vitess | test/cluster/sandbox/sandbox_utils.py | Python | apache-2.0 | 1,777 | 0.009004 | # Copyright 2017 Google 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 wr | iting, 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 governi | ng permissions and
# limitations under the License.
"""Sandbox util functions."""
import datetime
import os
import random
def create_log_file(log_dir, filename):
"""Create a log file.
This function creates a timestamped log file, and updates a non-timestamped
symlink in the log directory.
Example: For a l... |
pjdelport/feincms | feincms/module/medialibrary/modeladmins.py | Python | bsd-3-clause | 8,526 | 0.004926 | # ------------------------------------------------------------------------
# coding=utf-8
# ------------------------------------------------------------------------
from __future__ import absolute_import
import os
from django import forms
from django.conf import settings as django_settings
from django.contrib import... | ry.objects.order_by('title')
return super(MediaFileAdmin, self).changelist_view(request, extra_context=extra_context)
def admin_thumbnail(self, obj | ):
image = admin_thumbnail(obj)
if image:
return mark_safe(u"""
<a href="%(url)s" target="_blank">
<img src="%(image)s" alt="" />
</a>""" % {
'url': obj.file.url,
'image': image,})
return ''
... |
whutch/atria | cwmud/libs/miniboa.py | Python | mit | 35,233 | 0 | # -*- coding: utf-8 -*- line endings: unix -*-
"""A bare-bones cross-platform Telnet server."""
# miniboa.py
# Copyright 2009 Jim Storch
# 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://w... | Wont; deny option request
DO = chr(253) # Do = Request or confirm remote option
DONT = chr(254) # Don't = Demand or confirm option halt
IAC = chr(255) # Interpret as Command
SEND = chr(1) # Sub-process negotiation SEND command
IS = chr(0) # Sub-process negotiation I | S command
# Telnet options
BINARY = chr(0) # Transmit Binary
ECHO = chr(1) # Echo characters back to sender
RECON = chr(2) # Reconnection
SGA = chr(3) # Suppress Go-Ahead
TTYPE = chr(24) # Terminal Type
NAWS = chr(31) # Negotiate About Window Size
LINEMODE = chr(34) # Line Mode
_COMMAND_NAMES = {
SE: "SE"... |
longde123/MultiversePlatform | client/Scripts/AnimationState.py | Python | mit | 2,968 | 0.012803 | #
# The Multiverse Platform is made available under the MIT License.
#
# Copyright (c) 2012 The Multiverse 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 Software without restrict... | state
def __setattr__(self, attrname, value):
AnimationState.__setattr__(self, attrname, value)
class AnimationStateEventWrapper:
def __init__(self, state, handler, triggerTime):
self.animState = sta | te
self.realHandler = handler
state._state.RegisterTimeEventHandler(triggerTime, self.Handler)
def Handler(self, axiomState, triggerTime):
self.realHandler(self.animState, triggerTime)
|
tdent/pycbc | pycbc/waveform/bank.py | Python | gpl-3.0 | 39,353 | 0.002338 | # Copyright (C) 2012 Alex Nitz, Josh Willis, Andrew Miller
#
# 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 p... | . This
can be passed directly to `FieldArray.parse_boolargs`.
"""
if not isinstance(approximant_strs, list):
approximant_strs = [approximant_strs]
return [tuple(arg.split(':')) for arg in approximant_strs]
def add_approximant_arg(parser, default=None, help=None):
"""Adds an approximant... | ent parser to add the argument to.
default : {None, str}
Specify a default for the approximant argument. Defaults to None.
help : {None, str}
Provide a custom help message. If None, will use a descriptive message
on how to specify the approximant.
"""
if help is None:
hel... |
TADT1909/PythonProjects | ImageToText.py | Python | mit | 1,698 | 0.043401 | #! python3
# Python 3 Image to text
# 20.07.17 fixed bugs
# require | to install pillow, numpy
# pip install pillow
# pip install numpy
# -*- coding: UTF-8 -*-
from PIL import Image
import numpy as np
import random
import math
def convert(num) :
a0 = ['■','■','■','■','■','■','■','■']
a1 = ['$','#','%','$','&','@','@']
a2 = ['Q','W','E','R','Y','U','O']
a3 = [... | t(0,6)
if num in range(0,40) :
return a6[rand]
if num in range(40,90) :
return a5[rand]
if num in range(90,130) :
return a4[rand]
if num in range(130,170) :
return a3[rand]
if num in range(170,200) :
return a2[rand]
if num in range(200,230) :
... |
sonofeft/XYmath | xymath/newtGreg2.py | Python | gpl-3.0 | 5,126 | 0.02419 | from __future__ import absolute_import
from __future__ import division
from builtins import zip
from builtins import map
from builtins import range
from builtins import object
from past.utils import old_div
import bisect
class quadNG(object): # quadratic Newton-Gregory Interpolation
''' quadratic Ne... | or i in range( len(x) - 1 ):
dif1.append( old_div((y[i+1]-y[i]), (x[i+1]-x[i])) )
dif2 = []
for i in range( len(x) - 2 ):
dif2.append( old_div((dif1[i+1]-dif1[i]), (x[i+2]-x[i])) )
for i in range( len(x)-2):
self.a.append( y[i] )
self.b.append( d... |
def __call__(self, xval=0.0):
return self.getValue( xval )
def getIndex(self, xval=0.0):
'''Override this for computed index version'''
i = bisect.bisect_left(self.x, xval) - 1
if i<0:
return 0
elif i>self.iMax:
... |
reuterbal/photobooth | photobooth/worker/PictureMailer.py | Python | agpl-3.0 | 3,515 | 0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Photobooth - a flexible photo booth software
# Copyright (C) 2018 Balthasar Reuter <photobooth at re - web dot eu>
#
# 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
# t... | onfig.get('Mailer', 'sender')
self._recipient = config.get('Mailer', 'recipient')
self._subject = config.get('Mailer', 'subject')
self._message = config.get('Mailer', 'message')
self._server = config.get('Mailer', 'server')
self._po | rt = config.getInt('Mailer', 'port')
self._is_auth = config.getBool('Mailer', 'use_auth')
self._user = config.get('Mailer', 'user')
self._password = config.get('Mailer', 'password')
self._is_tls = config.getBool('Mailer', 'use_tls')
def do(self, picture, filename):
logging.... |
aboganas/frappe | frappe/utils/jinja.py | Python | mit | 5,056 | 0.028877 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
def get_jenv():
import frappe
if not getattr(frappe.local, 'jenv', None):
from jinja2 import Environment, DebugUndefined
# frappe will be loaded last, so app templates wil... | jinja template
:param context: dict of properties to pass to the template
:param is_path: (optional) assert that the `template` parameter is a path'''
# if it ends with .html then its a freaking path, not html
if (is_path
or template.startswith("templates/")
or (template.endswith('.html') and '\n' not in templ... | ntext)
else:
return get_jenv().from_string(template).render(context)
def get_allowed_functions_for_jenv():
import os
import frappe
import frappe.utils
import frappe.utils.data
from frappe.utils.autodoc import automodule, get_version
from frappe.model.document import get_controller
from frappe.website.utils i... |
FedoraScientific/salome-smesh | src/Tools/blocFissure/gmu/sortFaces.py | Python | lgpl-2.1 | 497 | 0.018109 | # -*- coding: utf-8 -*-
import logging
from geomsmesh import geompy
# -------------------------------------------------------------------- | ---------
# --- tri par surface de faces
def sortFaces(facesToSort):
"""
tri des faces par surface
"""
logging.info('start')
surFaces = [(geompy.BasicProperties(face)[1], i, face) for i, face in enumerate(facesToSort)]
surFaces.sort()
facesSorted = [face for surf, i, face in surFaces]
return facesSort... | ], surFaces[-1][0]
|
YaniLozanov/Software-University | Python/PyCharm/03.Logical checks/09.Password Guess.py | Python | mit | 348 | 0 | # Problem:
# Write a program that enters a password (one line with any text) and
# checks if it is entered matches the phrase "s3cr3t! P @ ssw0rd".
# In case of a collision, bring "Welcome".
# In case of inconsistency "Wrong Password!"
password = input()
if passw | ord == "s3cr3t!P@ssw0rd":
print("Welcome")
else:
pri | nt("Wrong password!")
|
18F/regulations-site | regulations/tests/views_preamble_tests.py | Python | cc0-1.0 | 10,884 | 0 | # -*- coding: utf-8 -*-
from mock import patch
from unittest import TestCase
from datetime import date, timedelta
from django.http import Http404
from django.test import RequestFactory, override_settings
from fr_notices.navigation import make_preamble_nav
from regulations.generator.layers import diff_applier
from re... | ata['sub_context']['node']['text'], '4')
| self.assertEqual(
response.context_data['sub_context']['node']['children'], [])
# layer data is present
self.assertEqual(
response.context_data['sub_context']['node']['meta'], 'something')
self.assertEqual(
response.context_data['preamble_toc'],
m... |
ducksboard/libsaas | libsaas/filters/auth.py | Python | mit | 6,734 | 0 | import base64
from hashlib import sha1
import hmac
import time
import random
from libsaas import http, port
class BasicAuth(object):
"""
Adds a Basic authentication header to each request.
"""
def __init__(self, username, password):
self.username = username
self.passw | ord = password
def __call__(self, request):
# According to RFC2617 the username and password are *TEXT, which
# RFC2616 says may con | tain characters from outside of ISO-8859-1 if
# they are MIME-encoded. Our first approach was to assume latin-1 in
# username and password, but practice has proved us wrong (services
# like Zendesk allow non-latin-1 characters in both, which are used
# in basic auth for their API). To be... |
MontrealCorpusTools/polyglot-server | iscan/templatetags/extra_tags.py | Python | mit | 253 | 0.003953 | from django imp | ort template
from django.conf import settings
from django.template.defaultfilters import stringfilter
register = template.Library()
@register.simple_tag
@stringfilter
def get_settings_val(setting):
return | getattr(settings, setting)
|
jesusaurus/openstack-tests | swift/swiftTest.py | Python | apache-2.0 | 9,677 | 0.002273 | #!/usr/bin/env python
# Copyright 2012-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.a... | print
def get_account(self, deep=True):
if not self.http_conn:
self.connect()
account_info = swift.head_account(url=self.swift_url,
token=self.token,
http_conn=self.http_conn)
account_head, c... | token=self.token,
http_conn=self.http_conn)
if self.debug:
print(account_info)
print(account_head)
for container in containers:
print(container)
print
if de... |
mhnatiuk/phd_sociology_of_religion | scrapper/build/pyOpenSSL/examples/simple/client.py | Python | gpl-2.0 | 1,260 | 0.003968 | # -*- coding: latin-1 -*-
#
# Copyright (C) AB Strakt
# Copyright (C) Jean-Paul Calderone
# See LICENSE for details. |
"""
Simple SSL client, using blocking I/O
"""
f | rom OpenSSL import SSL
import sys, os, select, socket
def verify_cb(conn, cert, errnum, depth, ok):
# This obviously has to be updated
print 'Got certificate: %s' % cert.get_subject()
return ok
if len(sys.argv) < 3:
print 'Usage: python[2] client.py HOST PORT'
sys.exit(1)
dir = os.path.dirname(sy... |
dongfangyixi/HypeNet-tensorflow | model.py | Python | apache-2.0 | 9,884 | 0.030763 | #coding:utf-8
import tensorflow as tf
from TFCommon.Layers import EmbeddingLayer
from TFCommon.RNNCell import LSTMCell
class HypeNet(object):
def __init__(self,word_num,word_embd_dim,pos_num,pos_embd_dim,
parse_num,parse_embd_dim,LSTM_dim,x_vector_dim,y_vector_dim,classification_dim):
se... | ut_direct=tf.expand_dims(input_direct,-1)
i_d_pathnum,i_d_seqlen,i_d_batchsize,i_d_dim=input_direct.get_shape()
word_init=tf.zeros(shape=(i_w_seqlen,i_w_batchsize),dtype=tf.int32)
pos_init=tf.zeros(shape=(i_pos_seqlen,i_pos_batchsize),dtype=tf.int32)
parse_init=tf.zeros(s... | direct_init=tf.zeros(shape=(i_d_seqlen,i_d_batchsize,i_d_dim),dtype=tf.float32)
weighted_sum=tf.zeros(shape=(i_w_batchsize,self.LSTM_dim),dtype=tf.float32)
if train_flag:
cell=tf.nn.rnn_cell.DropoutWrapper(LSTMCell(self.LSTM_dim),input_keep_prob=0.7,output_keep_prob=0.7)
... |
gvlproject/python-genomespaceclient | genomespaceclient/__init__.py | Python | mit | 162 | 0 | from .client import GSDataFormat # noqa
from .client import GSFileMeta | data # noqa
from .client impor | t GenomeSpaceClient # noqa
from .shell import main # noqa
|
saymedia/seosuite-dashboard-api | api/admin.py | Python | mit | 187 | 0.005348 | from django.contrib import admin
from api.models import (
CrawlUrls,
CrawlLinks,
)
# Register your models here.
admin.site.register(Craw | lUrls)
admin.site.register(CrawlLi | nks) |
voyagersearch/voyager-py | processing/locale/make_mo_files.py | Python | apache-2.0 | 1,085 | 0.002765 | # (C) Copyright 2014 Voyager Search
#
# 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.
import os
import sys
import glob
def make_mo_fil... | )
try:
sys.path.append(os.path.join(os.path.dirname(sys.executable), "tools", "i18n"))
import msgfmt
for po_file in po_files:
msgfmt.make(po_file, po_file.replace('.po', '.mo'))
except (IOError, ImportError):
pass
if __name__ == '__main__':
make_mo_files()
|
JudoWill/glue | glue/utils/qt/tests/test_qmessagebox_widget.py | Python | bsd-3-clause | 357 | 0 | from .. import QMessageBoxPatched as QMessageBox
from ....qt import get_qapp
from ....external.qt import | QtGu | i
def test_main():
app = get_qapp()
w = QMessageBox(QMessageBox.Critical, "Error", "An error occurred")
w.setDetailedText("Spam")
w.select_all()
w.copy_detailed()
assert app.clipboard().text() == "Spam"
app.quit()
|
googlestadia/renderdoc | util/test/tests/Vulkan/VK_CBuffer_Zoo.py | Python | mit | 31,170 | 0.004588 | import rdtest
import renderdoc as rd
class VK_CBuffer_Zoo(rdtest.TestCase):
def get_capture(self):
return rdtest.run_and_capture("demos_x64", "VK_CBuffer_Zoo", 5)
def check_capture(self):
draw = self.find_draw("Draw")
self.check(draw is not None)
self.controller.SetFrameEven... | 136.0, 137.0, 138.0, 139.0])
# vec4 dummy4;
var_check.check('dummy4')
# | column_major vec2x3 u;
var_check.check('u').cols(3).rows(2).column_major().value([144.0, 148.0, 152.0,
145.0, 149.0, 153.0])
# vec4 dummy5;
var_check.check('dummy5')
# row_major vec3x2 v;
var_check.check('v').co... |
antoinecarme/pyaf | tests/artificial/transf_Difference/trend_MovingMedian/cycle_5/ar_/test_artificial_1024_Difference_MovingMedian_5__20.py | Python | bsd-3-clause | 269 | 0.085502 | import pyaf.Bench.TS_datasets a | s tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "MovingMedian", cycle_length = 5, transform = | "Difference", sigma = 0.0, exog_count = 20, ar_order = 0); |
alexkasko/krakatau-java | krakatau-lib/src/main/resources/Lib/Krakatau/error.py | Python | gpl-3.0 | 429 | 0.002331 | class ClassLoaderError(Exception):
def __init__(self, typen=None, data=""):
self.type = typen
self.data = data
message = u"\n{}: {}".format(typen, data) if typen else unicode(data)
super(ClassLoaderError, self).__init__(message)
class VerificationError(Exception):
def __i | nit__(self, message, data=None):
super(VerificationError | , self).__init__(message)
self.data = data
|
thomasowenmclean/tei_transformer | tests/test_tags.py | Python | gpl-2.0 | 362 | 0.022099 | import unittest
class TestTeiT | ag(unittest.TestCase):
pass
class TestFmtTag(unittest.TestCase):
pass
class TestRendTag(unittest.TestCase):
pass
class TestDeleteMe(unittest.TestCase):
pass
class TestDontTouchMe(unittest.TestCase):
pass
class TestReplaceMeWText(unittest.TestCase):
pass
class TestUnwrapMe(uni | ttest.TestCase):
pass |
windelbouwman/ppci-mirror | ppci/build/buildtasks.py | Python | bsd-2-clause | 7,591 | 0 |
"""
Defines task classes that can compile, link etc..
Task can depend upon one another.
These task are wrappers around the functions provided in the buildfunctions
module
"""
from .tasks import Task, TaskError, register_task
from ..utils.reporting import HtmlReportGenerator, DummyReportGenerator
from .. import api
fr... | Sets a property to a value """
def run(self):
name = self.arguments['name']
value = self.arguments['value']
self.target.project.set_property(name, value)
@register_task
class BuildTask(Task):
""" Builds another build description file (build.xml) """
def run(self):
project =... | utputtingTask(Task):
""" Base task for tasks that create an object file """
def store_object(self, obj):
""" Store the object in the specified file """
output_filename = self.relpath(self.get_argument('output'))
self.ensure_path(output_filename)
with open(output_filename, 'wt', ... |
andrepuschmann/dutycycleviz | dutycycleviz.py | Python | gpl-3.0 | 5,638 | 0.013125 | #!/usr/bin/env python
#
# dutycycleviz.py
#
# Copyright (C) 2013, Andre Puschmann <andre.puschmann@tu-ilmenau.de>
#
# 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 Licens... | THOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABI | LITY 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, see <http://www.gnu.org/licenses/>.
import numpy as np
import numpy as np
import pylab as pl
import scipy.special a... |
akosyakov/intellij-community | python/testData/mover/multiLineSelection_afterDown.py | Python | apache-2.0 | 95 | 0.063158 | class Test | (object):
def q(self):
c = 3
<selection>a = 1
b = 2
<caret>< | /selection> |
facebook/fbthrift | thrift/compiler/test/fixtures/namespace/gen-py3lite/my/namespacing/test/hsmodule/lite_clients.py | Python | apache-2.0 | 3,331 | 0.003903 | #
# Autogenerated by Thrift
#
# DO NOT EDIT
# @generated
#
import typing as _typing
import py3lite_module_root.apache.thrift.metadata.lite_types as _fbthrift_metadata
import folly.i | obuf as _fbthrift_iobuf
from thrift.py3lite.client import (
AsyncClient as _fbthrift_py3lite_AsyncClient,
SyncClient as _fbthrift_py3lite_SyncClient,
Client as _fbthrift_py3lite_Client,
)
import thrift.py3lite.exceptions as _fbthrift_py3lite_exceptions
import thrift.py3lite.types as _fbthrift_py3lite_types
... | le_root.my.namespacing.test.hsmodule.lite_types
import py3lite_module_root.my.namespacing.test.hsmodule.lite_metadata
class HsTestService(_fbthrift_py3lite_Client["HsTestService.Async", "HsTestService.Sync"]):
@staticmethod
def __get_thrift_name__() -> str:
return "hsmodule.HsTestService"
@static... |
clovemfeng/studydemo | python_code/chapter11/page422.py | Python | gpl-2.0 | 1,263 | 0.003959 |
from find_it impo | rt find_closest
fr | om tm2secs2tm import time2secs, secs2time, format_time
def find_nearest_time(look_for, target_data):
what = time2secs(look_for)
where = [time2secs(t) for t in target_data]
res = find_closest(what, where)
return(secs2time(res))
row_data = {}
with open('PaceData.csv') as paces:
column_headings = p... |
AdamWill/anaconda | pyanaconda/ui/gui/spokes/lib/resize.py | Python | gpl-2.0 | 21,784 | 0.002158 | # Disk resizing dialog
#
# Copyright (C) 2012-2013 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed... | ARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public L | icense along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated... |
macosforge/ccs-calendarserver | txdav/xml/rfc6578.py | Python | apache-2.0 | 4,056 | 0.001233 | ##
# Copyright (c) 2009-2017 Apple Inc. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, mod... | EALINGS IN THE
# SOFTWARE.
##
"""
RFC 6578 (Collection Synchronization f | or WebDAV) XML Elements
This module provides XML element definitions for use with WebDAV
Synchronization.
See RFC 6578: http://www.ietf.org/rfc/rfc6578.txt
"""
__all__ = []
from txdav.xml.base import WebDAVElement, WebDAVTextElement, dav_namespace
from txdav.xml.element import registerElement, registerElementClass... |
qvicksilver/ansible | lib/ansible/utils/plugins.py | Python | gpl-3.0 | 8,792 | 0.003071 | # (c) 2012, Daniel Hokka Zakrisson <daniel@hozac.com>
#
# This file i | s 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 later version.
#
# Ansible is distributed in the hope that it will be us... | You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
import os
import os.path
import sys
import glob
import imp
from ansible import constants as C
from ansible import errors
MODULE_CACHE = {}
PATH_CACHE = {}
PLUGIN_PATH_CACHE = {}
_basedi... |
2014c2g5/2014cadp | wsgi/local_data/brython_programs/list1.py | Python | gpl-3.0 | 609 | 0.007678 | 資料 = [1, 2, 3, 4, 5]
'''
program: list1.py
'''
print(資料[:3])
print(資料[2:])
print(資料[1:2])
a = [3, 5, 7, 11, 13]
for x in a:
if x == 7:
print('list contains 7')
break
print(list | (range(10)))
for 索引 in range(-5, 6, 2):
print(索引)
squares = [ x*x for x | in range(0, 11) ]
print(squares)
a = [10, 'sage', 3.14159]
b = a[:]
#list.pop([i]) 取出 list 中索引值為 i 的元素,預設是最後一個
print(b.pop())
print(a)
數列 = [0]*10
print(數列)
'''
delete 用法
'''
a = [1, 2, 3, 4]
print("刪除之前:", a)
del a[:2]
print("刪除之後:", a) |
reinbach/django-machina | machina/apps/forum_member/migrations/0001_initial.py | Python | bsd-3-clause | 1,410 | 0.004255 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
import machina.models.fields
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations ... | erbose_name='Signature', blank=True)),
('posts_count', models.PositiveIntegerField(default=0, verbose_name='Total posts', blank=True)),
('_signature_rendered', models.TextField(null=True, editable=False, blank=True)),
('user', models.OneToOneField(related_name='forum_prof... | options={
'abstract': False,
'verbose_name': 'Forum profile',
'verbose_name_plural': 'Forum profiles',
},
),
]
|
ml-slac/deep-jets | train.py | Python | mit | 2,806 | 0.010335 | import numpy as np
from keras.layers import containers
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, MaxoutDense, Activation
from keras.optimizers import SGD, RMSprop, Adagrad, Adam
from keras.regularizers import l2
from keras.callbacks import EarlyStopping
# import matplotlib.pyp... | elf.model.layers[self.layer_id].params[self.param | _id].get_value()
# # Create the frame and add it to the animation
# img = self.ax.imshow(weights[self.weight_slice], interpolation='nearest')
# self.imgs.append(img)
# def on_train_end(self):
# # Once the training has ended, display the animation
# anim = animati... |
mescobal/geined | geined.py | Python | gpl-3.0 | 11,692 | 0.007216 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Menu principal del sistema GEINED"""
import cgitb ; cgitb.enable()
import cgi
import htm
import subprocess
import pagina
def principal():
"""Menu principal"""
pag = pagina.Pagina("Menu principal", 10)
print(htm.h1("Menú principal"))
print(htm.table(
... | "Usuarios")) +
htm.li(htm.a("ccl.py?accion=listado", "Categorías de clientes")) +
htm.li(htm.a("cem.php?accion=listado", "Categorías de empleados")) +
| htm.li(htm.a("dep.php?accion=listado", "Depósitos")) +
htm.li(htm.a("pro.php?accion=listado", "Proveedores")) +
htm.li(htm.a("upload.php", "Subir archivos")) +
htm.li(htm.a("download.php", "Bajar archivos")) +
htm.li(htm.a("prod.php?accion=listado", "Productos")) +
htm.li(htm.... |
live-clones/dolfin-adjoint | tests_dolfin/hessian_identity_list/hessian_identity_list.py | Python | lgpl-3.0 | 1,279 | 0.003127 | from dolfin import *
from dolfin_adjoint import *
parameters["adjoint"]["cache_factorizations"] = True
mesh = UnitSquareMesh(3, 3)
V = FunctionSpace(mesh, "R", 0)
test = TestFunction(V)
trial = TrialFunction(V)
def main(m):
u = interpolate(Constant(0.1), V, name="Solution")
F = inner(u*u, test)*dx - inner(... | def Jhat(m):
m = m[0] # the control is a list of length | one, so Jhat will have to
# except a list as well
u = main(m)
return assemble(inner(u, u)**3*dx + inner(m, m)*dx)
direction = [interpolate(Constant(0.1), V)]
minconv = taylor_test(Jhat, controls, Jm, dJdm, HJm=HJm,
perturbation_direction=direction)
assert m... |
Rafiot/logbook | scripts/make-release.py | Python | bsd-3-clause | 4,069 | 0.000983 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
make-release
~~~~~~~~~~~~
Helper script that performs a release. Does pretty much everything
automatically for us.
:copyright: (c) 2011 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import sys
import os
import re
from dat... | os.chdir(os.path.join(os.path.dirname(__file__), '..'))
rv = parse_changelog()
if rv is None:
fail('Could not parse changelog')
version, release_date, codename = rv
dev_version = bump_version(version) + '-dev'
info('Releasing %s (codename %s, release date %s)',
version, codena... | _date.date() != date.today():
fail('Release date is not today (%s != %s)' % (release_date.date(), date.today()))
if not git_is_clean():
fail('You have uncommitted changes in git')
set_init_version(version)
set_setup_version(version)
make_git_commit('Bump version number to %s', version)... |
dubourg/openturns | python/test/t_KernelMixture_std.py | Python | gpl-3.0 | 4,057 | 0.000986 | #! /usr/bin/env python
from __future__ import print_function
from openturns import *
TESTPREAMBLE()
RandomGenerator.SetSeed(0)
try:
# Instanciate one distribution object
dimension = 3
meanPoint = NumericalPoint(dimension, 1.0)
meanPoint[0] = 0.5
meanPoint[1] = -0.5
sigma = NumericalPoint(dime... | - 1]))
print("mean=", repr(oneSample.computeMean()))
print("covariance=", repr(oneSample.computeCovariance()))
# Define a point
point = NumericalPoint(distribution.getDimension(), 1.0)
print("Point= ", repr(point))
# Show PDF and CDF of point
eps = 1e-5
# derivative of PDF with regar... | arguments
DDF = distribution.computeDDF(point)
print("ddf =", repr(DDF))
print("ddf (ref)=", repr(distributionRef.computeDDF(point)))
# by the finite difference technique
ddfFD = NumericalPoint(dimension)
for i in range(dimension):
left = NumericalPoint(point)
left[i] += eps
... |
ryanwitt/django-liberace | liberace/systems/debian.py | Python | bsd-2-clause | 554 | 0.00722 | from fabric.api import *
settings_fabric = settings
def identify(env):
if 'linux' in env.uname.lower():
with settings_fabric(warn_only=True):
env.lsb_release = env.lsb_release or run('lsb_release -d').lower()
if 'debian' in env.lsb_release:
return True
def settings(... | uirements(env):
raise NotImplementedError()
| |
prasadtalasila/IRCLogParser | lib/slack/nickTracker.py | Python | gpl-3.0 | 2,925 | 0.003419 | import re
import lib.slack.config as config
import lib.slack.util as util
def nick_tracker(log_dict):
"""
Tracks all nicks and the identifies nicks which point to same user
Args:
log_dict(dictionary): with key as dateTime.date object and value as {"data":datalist,"channel_name":channels name... | logs = day_content["log_data"]
for day_log in day_logs:
# use regex to get the string between <> and appended it to the nicks list
if(util.check_if_msg_line (day_log)):
| m = re.search(r"\<(.*?)\>", day_log)
nick = util.correctLastCharCR(m.group(0)[1:-1])
nicks = nick_append(nick, nicks)
''' Forming list of lists for avoiding nickname duplicacy '''
for line in day_logs:
i... |
ArcherSys/ArcherSys | Lib/test/test_bool.py | Python | mit | 36,233 | 0.004554 | <<<<<<< HEAD
<<<<<<< HEAD
# Test properties of bool promised by PEP 285
import unittest
from test import support
import os
class BoolTest(unittest.TestCase):
def test_subclass(self):
try:
class C(bool):
pass
except TypeError:
pass
else:
... | ual(2+False, 2)
self.assertEqual(2+True, 3)
self.assertEqual(False+False, 0)
self.assertIsNot(False+False, False)
self.assertEqual(False+True, 1)
self.assertIsNot(False+True, True)
self.assertEqual(True+False, 1)
self.assertIsNot(True+False, True)
self.as... | rtEqual(False-False, 0)
self.assertIsNot(False-False, False)
self.assertEqual(True-False, 1)
self.assertIsNot(True-False, True)
self.assertEqual(False-True, -1)
self.assertEqual(True*1, 1)
self.assertEqual(False*1, 0)
self.assertIsNot(False*1, False)
sel... |
tudennis/LeetCode---kamyu104-11-24-2015 | Python/beautiful-arrangement-ii.py | Python | mit | 1,326 | 0 | # Time: O(n)
# Space: O(1)
# Given two integers n and k,
# you need to construct a lis | t which contains n different positive integers
# ranging from 1 to n and obeys the following requirement:
# Suppose this list is [a1, a2, a3, ... , an],
# then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has
# exactly k distinct integers.
#
# If there are multiple | answers, print any of them.
#
# Example 1:
# Input: n = 3, k = 1
# Output: [1, 2, 3]
# Explanation: The [1, 2, 3] has three different positive integers ranging
# from 1 to 3, and the [1, 1] has exactly 1 distinct integer: 1.
#
# Example 2:
# Input: n = 3, k = 2
# Output: [1, 3, 2]
# Explanation: The [1, 3, 2] has thre... |
ivmech/iviny-scope | lib/xlsxwriter/test/comparison/test_chart_axis14.py | Python | gpl-3.0 | 2,805 | 0 | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013, John McNamara, jmcnamara@cpan.org
#
import unittest
import os
from ...workbook import Workbook
from ..helperfunctions import _compare_xlsx_files
class TestCompareXLSXFiles(unittest.TestC... | et1!$A$1:$A$5',
' | values': '=Sheet1!$D$1:$D$5',
})
chart.set_y_axis({'min': 0, 'max': 30})
chart.set_x_axis({'min': 39083, 'max': 39087})
worksheet.insert_chart('E9', chart)
workbook.close()
####################################################
got, exp = _compare_xlsx_files(se... |
99cloud/keystone_register | openstack_dashboard/register/register.py | Python | apache-2.0 | 6,455 | 0.007126 | '''
Created on Nov 2, 2012
@author: maodouzi
'''
import logging
from keystoneclient.v2_0 import client as keystone_client
from novaclient.v1_1 import client as nova_client
from cinderclient.v1 import client as cinder_client
from keystoneclient.exceptions import BadRequest
from openstack_dashboard.local.local_setting... | eteUser()
def _checkRequestArgs(self):
return self._isRequestValid() and (not self._isAccountExist())
def _fetchInfo(self):
| try:
self.tenantList = self.conn.tenants.list()
self.userList = self.conn.users.list()
self.roleList = self.conn.roles.list()
self.tenantDict = {str(item.name):str(item.id) for item in self.tenantList}
self.userDict = {str(item.name):str(item.... |
byung-u/ProjectEuler | Problem_100_199/euler_100.py | Python | mit | 1,335 | 0.004498 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Problem 100
If a box contains twenty-one coloured discs, composed of fifteen blue discs and six red discs, and two discs were taken at random, it can be seen that the probability of taking two blue discs, P(BB) = (15/21)×(14/20) = 1/2.
The next such arrangement, for w... | 414 > L: # 15/21, 85/120 is around 1.414xxxx
print(res)
| break
return
p100()
|
grnet/e-science | orka/setup.py | Python | agpl-3.0 | 676 | 0.028107 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""setup.py: setuptools control."""
import ez_setup
ez_setup.use_setuptools()
from os.path import dirname, abspath, join
from setuptools import | setup
BASE_DIR = join(dirname(abspath(__file__)), 'orka/orka.py')
import orka
requires = ['kamaki','paramiko','requests','PyYAML']
# setup
setup(
name = "orka",
packages = ["orka"],
# starts from this main
entry_points = {
"console_scripts": ['orka = orka.orka:main']
},
version = o... | install_requires = requires
)
|
shirou/ansible | test/units/TestModuleUtilsBasic.py | Python | gpl-3.0 | 12,253 | 0.003101 | import os
import tempfile
import unittest
from nose.tools import raises
from nose.tools import timed
from ansible import errors
from ansible.module_common import ModuleReplacer
from ansible.utils import md5 as utils_md5
TEST_MODULE_DATA = """
from ansible.module_utils.basic import *
def get_module():
return Ans... | try:
| (rc, out, err) = self.module.run_command('echo "foo bar" > %s' % tmp_path, use_unsafe_shell=True)
self.assertEqual(rc, 0)
self.assertTrue(os.path.exists(tmp_path))
md5sum = utils_md5(tmp_path)
self.assertEqual(md5sum, '5ceaa7ed396ccb8e959c02753cb4bd18')
except:
... |
Guidobelix/pyload | module/plugins/hoster/AndroidfilehostCom.py | Python | gpl-3.0 | 2,454 | 0.014262 | # -*- coding: utf-8 -*
#
# Test links:
# https://www.androidfilehost.com/?fid=95916177934518197
import re
from module.plugins.internal.SimpleHoster import SimpleHoster
class AndroidfilehostCom(SimpleHoster):
__name__ = "AndroidfilehostCom"
__type__ = "hoster"
__version__ = "0.05"
__status__ ... | <U>[\w^_]+)</p>'
HASHSUM_PATTERN = r'<h4>(?P<H>.* | ?)</h4>\s*<p><code>(?P<D>.*?)</code></p>'
OFFLINE_PATTERN = r'404 not found'
WAIT_PATTERN = r'users must wait <strong>(\d+) secs'
def setup(self):
self.multiDL = True
self.resume_download = True
self.chunk_limit = 1
def handle_free(self, pyfile):
wait ... |
release-engineering/product-definition-center | pdc/apps/componentbranch/serializers.py | Python | mit | 11,180 | 0.000537 | #
# Copyright (c) 2017 Red Hat
# Licensed under The MIT License (MIT)
# http://opensource.org/licenses/MIT
#
from rest_framework import serializers
from django.conf import settings as django_settings
import re
from datetime import datetime
import six
from pdc.apps.common.fields import ChoiceSlugField
from pdc.apps.co... | lizers.ValidationError({'name': [error_msg]})
return super(SLASerializer, self).update(instance, validated_data)
class SLAToComponentBranchSerializerForComponentBranch(
serializers.ModelSerializer):
"""
A serializer for the SLAToComponentBranch model to be used in the
ComponentBranch seri... | zers.DateField(read_only=True)
class Meta:
model = SLAToComponentBranch
fields = ('id', 'sla', 'eol')
class ComponentBranchSerializer(StrictSerializerMixin,
serializers.ModelSerializer):
"""
A serializer for the ComponentBranch model
"""
name = Bran... |
ack8006/Python-mode-klen | pymode/libs/pylama/lint/extensions.py | Python | lgpl-3.0 | 738 | 0 | """ Load extensions. """
from os import listdir, path as op
CURDIR = op.dirname(__file__)
LINTERS = dict()
PREFIX = 'pylama_'
try:
from importlib import import_module
except ImportError:
from ..libs.importlib import import_module
for p in listdir(CURDIR):
if p.startswith(PREFIX) and op.isdir(op.join(CU... | ttr(module, 'Linter')()
except ImportError:
| continue
try:
from pkg_resources import iter_entry_points
for entry in iter_entry_points('pylama.linter'):
LINTERS[entry.name] = entry.load()()
except ImportError:
pass
|
ricomoss/python-april-2014 | class7/to_battle/script.py | Python | mit | 380 | 0.005263 | #!/ | usr/bin/env python
import os.path
import sys
MODULE_ROOT = os.path.join(os.path.dirname(__file__), '..')
sys.path.insert(0, MODULE_ROOT)
from to_battle.player import Hero, Villain
from to_battle.battle import Battle
if __name__ == '__main__':
player1 = Hero(name='Rico')
player2 = Villain(name='Thanos')
... | layer2)
battle.do_battle()
|
eqrx/mauzr | mauzr/platform/cpython/__init__.py | Python | agpl-3.0 | 5,160 | 0 | """ Bootstrap the mauzr agent on cpython systems. """
import contextlib
import threading
import logging
import _thread
__author__ = "Alexander Sowitzki"
class Core:
""" Manage program components on cpython platforms.
The core can either be started directly by calling :func:`run` or
by using it as a con... | n.
"""
_thread.interrupt_main()
def _setup_config( | self, suit, agent, instance, parser):
from mauzr.platform.cpython.config import Config
self.config = Config(suit, agent, instance, parser)
self.config.parse()
def _setup_logging(self):
""" Setup logging. """
level = self.config.get("log_level", "info").upper()
loggi... |
d-mittal/pystruct | examples/plot_letters.py | Python | bsd-2-clause | 3,493 | 0 | """
===============================
OCR Letter sequence recognition
===============================
This example illustrates the use of a chain CRF for optical character
recognition. The example is taken from Taskar et al "Max-margin markov random
fields".
Each example consists of a handwritten word, that was presegme... | r kernels. This example is more meant to give a
demonstration | of the CRF than to show its superiority.
"""
import numpy as np
import matplotlib.pyplot as plt
from sklearn.svm import LinearSVC
from pystruct.datasets import load_letters
from pystruct.models import ChainCRF
from pystruct.learners import FrankWolfeSSVM
abc = "abcdefghijklmnopqrstuvwxyz"
letters = load_letters()
... |
DailyActie/Surrogate-Model | 01-codes/scikit-learn-master/examples/ensemble/plot_adaboost_regression.py | Python | mit | 1,530 | 0.002614 | """
======================================
Decision Tree Regression with AdaBoost
======================================
A decision tree is boosted using the AdaBoost.R2 [1] algorithm on a 1D
sinusoidal dataset with a small amount of Gaussian noise.
299 boosts (300 decision trees) is compared with a single decision tr... | .linspace(0, 6, 100)[:, np.newaxis]
y = np.sin(X).ravel() + np.sin(6 * X).ravel() + rng.normal(0, 0.1, X.shape[0])
# Fit regression model
regr_1 = DecisionTreeRegressor(max_depth=4)
regr_2 = AdaBoostRegressor(DecisionTreeRegressor(max_depth=4),
n_estimators=300, random_state=rng)
regr_1.fi... | label="n_estimators=1", linewidth=2)
plt.plot(X, y_2, c="r", label="n_estimators=300", linewidth=2)
plt.xlabel("data")
plt.ylabel("target")
plt.title("Boosted Decision Tree Regression")
plt.legend()
plt.show()
|
ProstoKSI/distributed-queue | distributed_queue/tests/test_serializers.py | Python | mit | 556 | 0.005396 | import unittest
from distributed_queue.serializers import BaseSerializer, JsonSerializer
class TestSerializers(unittest.TestCase):
def test_base_serializer(self):
self.assertRaises(NotImplementedError, BaseSerializer.dumps, | {})
self.assertRaises(NotImplementedError, BaseSerializer.loads, "{}")
def test_json_serializer(self | ):
serializer = JsonSerializer
obj = {"a": 1, "b": [1, 2, "3"]}
data = serializer.dumps(obj)
copy_obj = serializer.loads(data)
self.assertEqual(obj, copy_obj)
|
pedohorse/hpaste | python3.7libs/hpaste/hpastecollectionwidget.py | Python | lgpl-3.0 | 12,806 | 0.003904 | import hou
from PySide2.QtCore import Slot, QSortFilterProxyModel, QRegExp, Qt
from PySide2.QtWidgets import QInputDialog, QMessageBox
from . import hpaste
from .hcollections.collectionwidget import CollectionWidget
from .hcollections.collectionbase import CollectionSyncError, CollectionItem
from .hcollections.github... | rint(hpaste.nodesToString(nodes))
self.model().addItemToCollection(collection, name, desc, hpaste.no | desToString(nodes), public, metadata={'nettype': self.__netType})
except CollectionSyncError as e:
QMessageBox.critical(self, 'something went wrong!', 'Server error occured: %s' % str(e))
def _changeAccess(self, index):
item = index.internalPointer()
text, go... |
thobbs/cassandra-dtest | compression_test.py | Python | apache-2.0 | 7,536 | 0.003583 | import os
from assertions import assert_crc_check_chance_equal
from scrub_test import TestHelper
from tools import since
class TestCompression(TestHelper):
def _get_compression_type(self, file):
types = {
'0010': 'NONE',
'789c': 'DEFLATE'
}
with open(file, 'rb') ... | les['start_disabled_compression_table']
self.assertEqual('org.apache.cassandra.io.compress.SnappyCompressor', meta.options['compression']['class'])
self.assertEqual('256', meta.options['compression']['chunk_length_in_kb'])
assert_crc_check_chance_equal(session, "start_disabled_compression_t | able", 0.25)
|
MridulS/BinPy | BinPy/examples/source/Gates/NOT.py | Python | bsd-3-clause | 731 | 0.00684 |
# coding: utf-8
# Examples for NOT class
# In[1]:
# imports
from __future__ import print_function
from Bin | Py.Gates import *
# In[2]:
# Initializing the NOT class
gate = NOT(0)
# Output of the NOT gate
print (gate.output())
# In[3]:
# Input is changed to 0
gate.setInput(1)
# To get the input states
print (gate.getInputStates())
# In[4]:
# New Output of the NOT gate
print (gate.output())
# In[5]:
# Using C... | r conn
gate.setOutput(conn)
# Put this connector as the input to gate1
gate1 = NOT(conn)
# Output of the gate1
print (gate1.output())
# In[6]:
# Information about gate instance
print (gate)
|
josenavas/qiime | scripts/clean_raxml_parsimony_tree.py | Python | gpl-2.0 | 3,356 | 0.001788 | #!/usr/bin/env python
# File created on 10 Nov 2011
from __future__ import division
__author__ = "Jesse Stombaugh"
__copyright__ = "Copyright 2011, The QIIME project"
__credits__ = ["Jesse Stombaugh"]
__license__ = "GPL"
__version__ = "1.9.1-dev"
__maintainer__ = "Jesse Stombaugh"
__email__ = "jesse.stombaugh@colorado... | it(',')
scoring_method = opts.scoring_method
# load tree
tree = DndParser(open(tree_fp, 'U'), constructor=PhyloNode)
# decorate measurements onto tree (either by depth or by num | ber of
# children)
if scoring_method == 'depth':
tree2 = decorate_depth(tree)
elif scoring_method == 'numtips':
tree2 = decorate_numtips(tree)
# get the nodes for the inserted sequences
nodes_dict = get_insert_dict(tree2, set(tips_to_keep))
# remove nodes accordingly
final_... |
bruecksen/isimip | isi_mip/climatemodels/migrations/0047_auto_20170118_1428.py | Python | mit | 45,674 | 0.003416 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-18 13:28
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('climatemodels', '0046_auto_20170117_1034'),
]
operations = [
migrations.Alt... | name='type_of_water_stress',
field=models.TextField(blank=True, default='', help_text='Methods for model calibration and validation', null=True, verbose_name='Type of wat | er stress'),
),
migrations.AlterField(
model_name='agriculture',
name='water_dynamics',
field=models.TextField(blank=True, default='', help_text='Methods for model calibration and validation', null=True, verbose_name='Water dynamics'),
),
migrations.Al... |
zephiro/django-boilerplate | {{cookiecutter.repo_name}}/{{cookiecutter.project_name}}/manage.py | Python | mit | 250 | 0 | #!/usr/bin/env python
import os
import sys
if _ | _name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.project")
from django.core.management import execute_from_command_line
execute_from_command_line | (sys.argv)
|
itsallvoodoo/csci-school | CSCI220/Week 08 - MAR05-09/prog6_7.py | Python | apache-2.0 | 489 | 0.00409 | # prog6_7.py
# This program calculates total wages in a week given | hours works and pay rate
# <Chad Hobbs>
def main(): # Main program
hrs = eval(input("How many hours have been worked this week?: "))
rate = eval(input("What is the pay rate for this employee?: "))
if hrs > 40:
wages = 40 * rate + (hrs - 40) * rate * 1.5
else:
wages = hrs... | nt()
print("The wages for this week is ${0:0.2f}.".format(wages))
main()
|
Kiddinglife/iamhungry | iamhungry/app/views.py | Python | lgpl-3.0 | 3,665 | 0.024557 | """
Definition of views.
"""
from django.shortcuts import render
from django.http import HttpRequest
from django.template import RequestContext
from datetime import datetime |
def home(request):
"""Renders the home page."""
assert isinstance(request, Ht | tpRequest)
return render(request,
'app/index.html',
context_instance = RequestContext(request,
{
'title':'Home Page',
'year':datetime.now().year,
}))
def contact(request):
"""Renders the contact page."""
assert isinstance(request, HttpRequest)
ret... |
asottile/pushmanager | pushmanager/tests/test_template_pushes.py | Python | apache-2.0 | 835 | 0.007186 | import testify as T
from pushmanager.testing.testservlet import TemplateTestCase
class PushesTemplateTest(TemplateTestCase):
authenticated = True
pushes_page = 'pushes.html'
new_push_pag | e = 'new-push.html'
def render_pushes_page(self, page_title='Pushes', pushes=[], pushes_per_page=50, last_push=None):
return self.render_etree(self.pushes_page,
page_title=page_title,
pushes=pushes,
rpp=pushes_per_page,
last_push=last_push
)
def ... | m':
found_form.append(form)
T.assert_equal(len(found_form), 1)
if __name__ == '__main__':
T.run()
|
grahamking/lintswitch | lintswitch/main.py | Python | gpl-3.0 | 4,151 | 0 | """ lintswitch lints your code in the background.
http://github.com/grahamking/lintswitch
"""
import sys
import socket
import logging
import os
import os.path
import argparse
from threading import Thread
try:
# python 3
from queue import Queue
except ImportError:
# python 2
from Queue import Queue
fro... | --httpport',
type=int,
default=8008,
help='Port for web browser interface')
parser.add_argument(
'--pymetrics_warn',
type=int,
default=5,
help='Cyclomatic complexity considered a warning, per function')
parser.add_argument(
'--pymetrics_error',
... | r function')
return parser
def main_loop(listener, work_queue):
"""Wait for connections and process them.
@param listener: a socket.socket, open and listening.
"""
while True:
conn, _ = listener.accept()
data = conn.makefile().read()
conn.close()
work_queue.put(d... |
vadosl/photorganizer | photorganizer/photo/migrations/0001_initial.py | Python | mit | 8,572 | 0.007116 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Album'
db.create_table(u'photo_album', (
(u'i... | ', ['Tag'])
# Adding model 'Image | '
db.create_table(u'photo_image', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('title', self.gf('django.db.models.fields.CharField')(max_length=60, null=True, blank=True)),
('image', self.gf('django.db.models.fields.files.FileField')(max_length=... |
spbguru/repo1 | nupic/support/__init__.py | Python | gpl-3.0 | 27,136 | 0.011829 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | pic.support.fshelpers import makeDirectoryFromAbsolutePath
# Local imports
#############################################################################
def getCallerInfo(depth=2):
"""Utility function to get information about function callers
The information is the tuple (function/method name, filename, class)... | ethod.
depth: how far back in the callstack to go to extract the caller info
"""
f = sys._getframe(depth)
method_name = f.f_code.co_name
filename = f.f_code.co_filename
arg_class = None
args = inspect.getargvalues(f)
if len(args[0]) > 0:
arg_name = args[0][0] # potentially the 'self' arg if its a... |
mypaint/mypaint | gui/drawwindow.py | Python | gpl-2.0 | 34,612 | 0.000751 | # -*- coding: utf-8 -*-
#
# This file is part of MyPaint.
# Copyright (C) 2007-2019 by the MyPaint Development Team.
# Copyright (C) 2007-2014 by Martin Renold <martinxyz@gmx.ch>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published ... | gettext as _
from lib.gettext import C_
logger = logging.getLogger(__name__)
## Module constants
BRUSHPACK_URI = 'https://github.com/mypaint/mypaint/wiki/Brush-Packages'
## Class definitions
class DrawWindow (Gtk.Window):
"""Main drawing window"""
## Class configuration
__gtype_name__ = 'MyPaintDr... |
#: instances. Used by _get_quick_chooser().
_QUICK_CHOOSER_CONSTRUCT_INFO = {
"BrushChooserPopup": (
quickchoice.BrushChooserPopup, [],
),
"ColorChooserPopup": (
quickchoice.ColorChooserPopup, [],
),
"ColorChooserPopupFastSubset": (
qu... |
the-xkcd-community/the-red-spider-project | src/xkcd-search.py | Python | mit | 1,201 | 0.029975 | #!/usr/bin/env python2
# Copyright 2012 Neil Forrester
# Licensed under the Red Spider Project License.
# See the License.txt that shipped with your copy of this software for details.
import re
import argparse
import os
import sys
import codecs
xf = __import__('xkcd-fetch')
if __name__ == "__main__":
# set up comm... | the cache from the file
comics = xf.read_cache()
# search the comics
for num in comics.keys():
if any(map(regex.search, [comics[num].comic_title,
comics[num].title_text,
comics[num].transcript,
com | ics[num].news])):
print num
|
10printhello/Blank-Heroku-Django-App | backoffice/backoffice/apps/pages/urls.py | Python | gpl-2.0 | 217 | 0.009217 | from dja | ngo.conf.urls import patterns, include, url
from apps.pages import views
# See: https://docs.djangoproject.com/en/dev/topics/http/urls/
ur | lpatterns = patterns('',
url(r'^$', views.home, name='home'),
)
|
thomasaarholt/hyperspy | hyperspy/tests/io/test_edax.py | Python | gpl-3.0 | 19,779 | 0.001466 | import gc
import hash | lib
import os
import os.path
import tempfile
import zipfile
import numpy as np
import pytest
import requests
from hyperspy import signals
from hyperspy.io import load
MY_PATH = os.path.dirname(__file__)
ZIPF = os.path.join(MY_PATH, "edax_files.zip")
TMP | _DIR = tempfile.TemporaryDirectory()
TEST_FILES_OK = os.path.isfile(ZIPF)
REASON = ""
SHA256SUM = "e217c71efbd208da4b52e9cf483443f9da2175f2924a96447ed393086fe32008"
# The test files are not included in HyperSpy v1.4 because their file size is 36.5MB
# taking the HyperSpy source distribution file size above PyPI's 60M... |
elyezer/robottelo | tests/foreman/ui/test_oscapcontent.py | Python | gpl-3.0 | 6,070 | 0 | """Tests for Oscapcontent
:Requirement: Oscapcontent
:CaseAutomation: Automated
:CaseLevel: Acceptance
:CaseComponent: UI
:TestType: Functional
:CaseImportance: High
:Upstream: No
"""
import unittest2
from fauxfactory import gen_string
from nailgun import entities
from robottelo.config import settings
from robo... | make_oscapcontent(
session,
name=content_name,
content_path=self.content_path,
content_org=self.org_name,
)
se | lf.assertIsNotNone(
self.oscapcontent.search(content_name))
@skip_if_bug_open('bugzilla', 1289571)
@tier1
def test_negative_create_with_invalid_name(self):
"""Create OpenScap content with negative values
:id: 8ce0e8b4-396a-43cd-8cbe-fb60fcf853b0
:Steps:
... |
abramhindle/UnnaturalCodeFork | python/testdata/launchpad/lib/lp/translations/utilities/kde_po_importer.py | Python | agpl-3.0 | 3,250 | 0.000308 | # Copyright 2009 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""Import module for legacy KDE .po files.
This is an extension of standard gettext PO files.
You can read more about this file format from:
* http://l10n.kde.org/docs/translati... | message.context, message.msgid_singular = (
msgid[len(context_prefix):].split('\n', 1))
self.in | ternal_format = TranslationFileFormat.KDEPO
else:
# Other messages are left as they are parsed by
# GettextPOImporter
pass
return translation_file
|
pypa/warehouse | warehouse/migrations/versions/34b18e18775c_add_last_totp_value_to_user.py | Python | apache-2.0 | 940 | 0.001064 | # 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 Li... | 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.
"""
add last totp value to user
Revision ID: 34b18e18775c
Revises: 0ac2f506ef2e
Create Date: 2019-08-15 21:2... | = "34b18e18775c"
down_revision = "0ac2f506ef2e"
def upgrade():
op.add_column("users", sa.Column("last_totp_value", sa.String(), nullable=True))
def downgrade():
op.drop_column("users", "last_totp_value")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.