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 |
|---|---|---|---|---|---|---|---|---|
caiyunapp/gaia | gaia/environ.py | Python | mit | 182 | 0.005495 | # -*- coding: utf-8 -*-
import os
def get(key):
varname = "PRJ_%s" % key.upper()
if varname in os.envir | on:
return os.environ[varname]
else:
r | eturn None
|
songgc/TF-recomm | svd_train_val.py | Python | apache-2.0 | 3,895 | 0.002824 | import time
from collections import deque
import numpy as np
import tensorflow as tf
from six import next
from tensorflow.core.framework import summary_pb2
import dataio
import ops
np.random.seed(13575)
BATCH_SIZE = 1000
USER_NUM = 6040
ITEM_NUM = 3952
DIM = 15
EPOCH_MAX = 100
DEVICE = "/cpu:0"
def clip(x):
r... | gs.dat", sep="::")
rows = le | n(df)
df = df.iloc[np.random.permutation(rows)].reset_index(drop=True)
split_index = int(rows * 0.9)
df_train = df[0:split_index]
df_test = df[split_index:].reset_index(drop=True)
return df_train, df_test
def svd(train, test):
samples_per_batch = len(train) // BATCH_SIZE
iter_train = data... |
duarten/scylla | dist/common/scripts/scylla_config_get.py | Python | agpl-3.0 | 1,682 | 0.002378 | #!/usr/bin/python2
#
# Copyright 2016 ScyllaDB
#
#
# This file is part of Scylla.
#
# Scylla is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any l... | def get(config, key):
s = open(config).read()
cfg = yaml.load(s)
try:
val = cfg[key]
except KeyError:
print("key | '%s' not found" % key)
sys.exit(1)
if isinstance(val, list):
for v in val:
print("%s" % v)
elif isinstance(val, dict):
for k, v in list(val.items()):
print("%s:%s" % (k, v))
else:
print(val)
def main():
parser = argparse.ArgumentParser(description... |
HydrelioxGitHub/home-assistant | homeassistant/components/zigbee/switch.py | Python | apache-2.0 | 765 | 0 | """Support for Zigbee switches."""
import voluptuous as vol
from homeassistant.components.switch import SwitchDevice
from homeassistant.components.zigbee import (
ZigBeeDigitalOut, ZigBeeDigitalOutConfig, PLATFORM_SCHEMA)
DEPENDENCIES = ['zigbee']
CONF_ON_STATE = 'on_state'
DEFAULT_ON_STATE = 'high'
DEPENDENCIE... | y_info=None):
"""Set up the Zigbee switch platform."""
add_entities([ZigBeeSwitch(hass, ZigBeeDigitalOutConfig(config))])
class ZigBeeSwitch(ZigBeeDigitalOut, SwitchDevice):
"""Representation of a Zigbee Digital Out device."""
| pass
|
wcmitchell/insights-core | insights/parsers/cpuinfo.py | Python | apache-2.0 | 5,851 | 0.000171 | """
CpuInfo - file ``/proc/cpuinfo``
================================
This parser reads the content of the ``/proc/cpuinfo`` file and parses it
into a dictionary of lists, keyed on the left hand column of the cpuinfo
output.
The object also provides properties for the standard information about the
CPU and motherboar... | MHz : 2900.000
cache size : 20480 KB
physical id : 0
siblings : 1
core id : 0
cpu cores : 1
address sizes : 40 bits physical, 48 bits virtual
processor : 1
vendor_id : GenuineIntel
cpu family : 6
model | : 45
model name : Intel(R) Xeon(R) CPU E5-2690 0 @ 2.90GHz
stepping : 2
microcode : 1808
cpu MHz : 2900.000
cache size : 20480 KB
physical id : 2
siblings : 1
core id : 0
cpu cores : 1
address sizes : 40 bits physica... |
davinwang/caffe2 | caffe2/python/operator_test/rebatching_queue_test.py | Python | apache-2.0 | 9,823 | 0.000814 | # Copyright (c) 2016-present, Facebook, 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... | for idx in range(3):
self.assertEquals(workspace.FetchBlob(results[idx]), [1.0])
def test_rebatching_queue_multi_enqueue_dequeue(self):
net = core.Net('net')
workspace.FeedBlob(
"tensors", np.array([x for x in range(10)], np.int32)
)
queue = net.CreateRebatc... | eueRebatchingQueue([queue], 1, num_elements=5),
net.DequeueRebatchingQueue([queue], 1, num_elements=5),
]
workspace.RunNetOnce(net)
npt.assert_array_equal(
workspace.FetchBlob(results[0]), workspace.FetchBlob("tensors")[:5]
)
npt.assert_array_equal(
... |
enthought/traitsgui | enthought/traits/ui/image/image.py | Python | bsd-3-clause | 49,614 | 0.019571 | #------------------------------------------------------------------------------
#
# Copyright (c) 2005, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditions d... | fh.close()
#-------------------------------------------------------------------------------
# Returns the value of a Python symbol loaded from a specified source code
# string:
#-------------------------------------------------------------------------------
def get_python_value ( source, name ):
""" Returns the... | |
danicampora/micropython | tests/extmod/vfs_fat_ramdisk.py | Python | mit | 1,230 | 0.002439 | import sys
import uos
try:
uos.VfsFat
except AttributeError:
print("SKIP")
sys.exit()
class RAMFS:
SEC_SIZE = 512
def __init__(self, blocks):
self.data = bytearray(blocks * self.SEC_SIZE)
def readblocks(self, n, buf):
#print("readblocks(%s, %x(%d))" % (n, id(bu | f), len(buf)))
for i in range(len(buf)):
buf[i] = self.data[n * self.SEC_SIZE + i]
def writeblocks(self, n, buf):
#print("writeblocks(%s, %x)" % (n, id(buf)))
for i in range(len(buf)):
self.data[n * self.SEC_SIZE + i] = buf[i]
def ioctl(self, op, arg):
#... | en(self.data) // self.SEC_SIZE
if op == 5: # BP_IOCTL_SEC_SIZE
return self.SEC_SIZE
try:
bdev = RAMFS(48)
except MemoryError:
print("SKIP")
sys.exit()
uos.VfsFat.mkfs(bdev)
assert b"FOO_FILETXT" not in bdev.data
assert b"hello!" not in bdev.data
vfs = uos.VfsFat(bdev, "/ramdisk")
... |
Xiaomi2008/Caffe_3D_FF | python/detect.py | Python | bsd-2-clause | 5,423 | 0.001291 | #!/usr/bin/env python
"""
detector.py is an out-of-the-box windowed detector
callable from the command line.
By default it configures and runs the Caffe reference ImageNet model.
Note that this model was trained for image classification and not detection,
and finetuning for detection can be expected to improve ... | t to collect in input window."
)
args = parser.parse_args()
channel_swap = [int(s) for s in args.channel_swap.split(',')]
# Make detector | .
detector = caffe.Detector(args.model_def, args.pretrained_model,
gpu=args.gpu, mean_file=args.mean_file,
input_scale=args.input_scale, channel_swap=channel_swap,
context_pad=args.context_pad)
if args.gpu:
print 'GPU mode'
# Load input.
t = time.t... |
3DP-Unlimited/3DP-Printrun | printrun/gviz.py | Python | gpl-3.0 | 21,353 | 0.007961 | # This file is part of the Printrun suite.
#
# Printrun 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.
#
# Printrun is distributed in ... | Bitmap(), shortHelp = _("Reset view"), longHelp = '')
vbox.Add(self.toolbar, 0, border = 5)
| panel.SetSizer(vbox)
hbox.Add(panel, 1, flag = wx.EXPAND)
self.layerslider = wx.Slider(hpanel, style = wx.SL_VERTICAL | wx.SL_AUTOTICKS | wx.SL_LEFT | wx.SL_INVERSE)
self.layerslider.Bind(wx.EVT_SCROLL, self.process_slider)
hbox.Add(self.layerslider, 0, border = 5, flag = wx.LEFT... |
leihaha/Django-By-Example_demo | bookmarks/images/views.py | Python | gpl-2.0 | 1,464 | 0.003415 | from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .forms import ImageCreateForm
from .models import Image
# Create your views here.
@login_required
def image_create(request):
"""
View for creatin... |
# assign current user to the item
new_item.user = request.user
new_item.save()
messages.success(request, 'Image added successfully')
# redirect to new created item detail view
return redirect(new_item.get_absolute_url())
else:
# build ... | marklet via GET
form = ImageCreateForm(data=request.GET)
return render(request, 'images/image/create.html', {'section': 'images',
'form': form})
def image_detail(request, id, slug):
image = get_object_or_404(Image, id=id, slug=slug)
return re... |
SauloAislan/ironic | ironic/api/controllers/v1/utils.py | Python | apache-2.0 | 20,567 | 0 | # Copyright 2013 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | tes.VERBS['abort']: versio | ns.MINOR_13_ABORT_VERB,
states.VERBS['clean']: versions.MINOR_15_MANUAL_CLEAN,
states.VERBS['adopt']: versions.MINOR_17_ADOPT_VERB,
}
V31_FIELDS = [
'boot_interface',
'console_interface',
'deploy_interface',
'inspect_interface',
'management_interface',
'power_interface',
'raid_inter... |
harry-7/Plinth | plinth/modules/snapshot/__init__.py | Python | agpl-3.0 | 1,992 | 0 | #
# This file is part of Plinth.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distribute... | FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""
Plinth module to manage filesystem snapshots.
"""
from django.utils.trans... |
name = _('Storage Snapshots')
description = [
_('Snapshots allows creating and managing filesystem snapshots. These can '
'be used to roll back the system to a previously known good state in '
'case of unwanted changes to the system.'),
_('Automatic snapshots are taken every hour, day, month and ... |
smallyear/linuxLearn | salt/salt/states/grafana.py | Python | apache-2.0 | 12,608 | 0 | # -*- coding: utf-8 -*-
'''
Manage Grafana Dashboards
This module uses ``elasticsearch``, which can be installed via package, or pip.
You can specify elasticsearch hosts directly to the module, or you can use an
elasticsearch profile via pillars:
.. code-block:: yaml
mygrafanaprofile:
hosts:
- es1... | managed:
grafana.dashboard_present:
- name: myservice
- dashboard_from_pillar: default
- rows_from_pillar:
- systemhealth
- requests
# Passing hosts in
Ensure myservice dashboard is managed:
grafana.dashboard_present:
- name: myservice
... | itable: true
height: 150px
title: System Health
panels:
- aliasColors: {}
id: 200000
annotate:
enable: false
bars: false
datasource: null
editable: true... |
shacknetisp/vepybot | plugins/redeclipse/restatsdb.py | Python | mit | 3,324 | 0.000301 | # -*- coding: utf-8 -*-
import bot
from lib import timeutils
bot.reload(timeutils)
class Module(bot.Module):
index = "restatsdb"
def register(self):
self.addcommand(self.main, 'get',
'Query a statsdb-interface API.'
' Actions: toprace <map>, game <id>,... | ' % args.getstr('query')
return "%s by %s" % (
timeutils.durstr(json['toprace']['time'] / 1000,
dec=True, full=True).strip(),
("%s playing as %s" % (
| json['toprace']['gameplayer']['handle'],
json['toprace']['gameplayer']['name'])
if json['toprace']['gameplayer']['handle']
else
"<no auth> playing as %s" % (
json['toprace']['gameplayer']['name']))
)
def actiontotals(self,... |
pxmkuruc/usd-qt | pxr/usdQtEditors/hierarchyEditor.py | Python | apache-2.0 | 10,079 | 0.000099 | #
# Copyright 2017 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. T... | eBlock():
prims = s | elf._GetSelectedPrims()
for prim in prims:
prim.SetActive(True)
def DeactivateSelection(self):
with Sdf.ChangeBlock():
prims = self._GetSelectedPrims()
for prim in prims:
prim.SetActive(False)
def ClearActiveForSelection(self):
... |
rapidpro/ureport | ureport/contacts/migrations/0021_auto_20190926_1554.py | Python | agpl-3.0 | 619 | 0 | # Generated by Djan | go 2.2.5 on 2019-09-26 15:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("contacts", "0020_install_triggers")]
operations = [
migrations.AlterField(
model_name="contact",
name="gender",
field=mod | els.CharField(
blank=True,
choices=[("M", "Male"), ("F", "Female"), ("O", "Other")],
help_text="Gender of the contact",
max_length=1,
null=True,
verbose_name="Gender",
),
)
]
|
pudo/regenesis | regenesis/views/catalog.py | Python | mit | 819 | 0.001221 | from flask import Blueprint, render_template
from regenesis.core import app, engine, get_cata | log
from regenesis.views.util import dimension_type_text
from regenesis.database import statistic_table, dimension_table
blueprint = Blueprint('catalog', __name__)
@blueprint.route('/<catalog>/index.html')
def view(catalog):
catalog = get_catalog(catalog)
statistics = statistic_table.find(order_by='title_de'... | (dimension['measure_type'])
dimensions.append(dimension)
return render_template('catalog/index.html',
catalog=catalog,
statistics=statistics,
dimensions=dimensions)
|
Cal-CS-61A-Staff/ok-client | client/sources/common/models.py | Python | apache-2.0 | 2,352 | 0.002551 | """Models for serialization of tests."""
from client.sources.common import core
class Test(core.Serializable):
name = core.String()
points = core.Float()
partner = core.String(optional=True)
def run(self, env):
"""Subclasses should override this method to run tests.
NOTE: env is inte... | -- function; computes the hash code of a given string.
"""
raise NotImplementedError
def unlock(self, unique_id_prefix, case_id, interact):
"""Subclasses should override this method for unlocking a test case.
It is the responsibility of the the subclass to make any changes to the
... | d to False.
PARAMETERS:
unique_id_prefix -- string; an identifier for this Case, for purposes of
analytics.
case_id -- string; an identifier for this Case, for purposes of
analytics.
interact -- function; handles u... |
coteyr/home-assistant | homeassistant/components/graphite.py | Python | mit | 5,000 | 0 | """
homeassistant.components.graphite
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Component that records all events and state changes and feeds the data to
a graphite installation.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/graphite/
"""
import logging
import... | 'queuing event!')
def _send_to_graphite(self, data):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10)
sock.connect((self._host, self._port))
sock.sendall(data.encode('ascii'))
sock.send('\n'.encode('ascii'))
sock.close()
... | hings['state'] = state.state_as_number(new_state)
except ValueError:
pass
lines = ['%s.%s.%s %f %i' % (self._prefix,
entity_id, key.replace(' ', '_'),
value, now)
for key, value in things.items()
... |
cathyyul/sumo-0.18 | tools/route/route2alts.py | Python | gpl-3.0 | 3,601 | 0.008331 | #!/usr/bin/env python
"""
@file route2alts.py
@author Daniel Krajzewicz
@author Michael Behrisch
@date 11.09.2009
@version $Id: route2alts.py 14425 2013-08-16 20:11:47Z behrisch $
Counts possible routes for all depart/arrival edges.
Builds route alternatives assigning the so determined probabilities to use a r... | <routeDistribution last="0">\n')
route = attrs["edges"]
edges = route.split(" ")
| od = ( edges[0], edges[-1] )
self._out.write(' <route cost="1" probability="' + str(self._stats._odRouteProbs[od][route]) + '" edges="' + route + '"/>\n')
for r in self._stats._odRouteProbs[od]:
if r==route:
continue
else:
... |
cjaymes/pyscap | src/scap/model/cpe_lang_2_3/CPEFactRefType.py | Python | gpl-3.0 | 952 | 0.00105 | # Copyright 2016 Casey Jaymes
# This file is part of PySCAP.
#
# PySCAP 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.
#
# PySCAP is ... | 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 PySCAP. If not, see <http://www.gnu.org/licenses/>.
import logging
from scap.model.cpe_lang_2_3.FactRefType import Fact... |
skuschel/postpic | doc/source/conf.py | Python | gpl-3.0 | 6,594 | 0.002123 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# postpic documentation build configuration file, created by
# sphinx-quickstart on Tue Nov 21 16:26:48 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# au... | help_basename = 'postpicdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'let | terpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source st... |
pulilab/rapidpro | temba/airtime/models.py | Python | agpl-3.0 | 10,395 | 0.003271 | from __future__ import unicode_literals
import hashlib
import json
import requests
import six
import time
from django.conf import settings
from django.db import models
from smartmin.models import SmartModel
from temba.channels.models import Channel
from temba.contacts.models import Contact, TEL_SCHEME
from temba.orgs... | if not isinstance(skuid_list, list):
| skuid_list = [skuid_list]
local_info_value_list = content_json.get('local_info_value_list', [])
if not isinstance(local_info_value_list, list):
local_info_value_list = [local_info_value_list]
product_local_value_map = dict(zip([float(elt) for elt in lo... |
jahuth/convis | convis/retina_virtualretina.py | Python | gpl-3.0 | 30,950 | 0.010501 | """
This module is a compatibility layer between the Virtual Retina configurations and behaviour and the python implementation.
"""
import xml.etree.ElementTree as ET
import collections
import copy
from future.utils import iteritems as _iteritems
def dict_recursive_update(d, u):
for k, v in _iteritems(u):
... | ,
'scaling-factor-outside-fovea__inv-deg': 1.0
},
'outer-plexiform-layers': [
{
'l | inear-version': {
'center-sigma__deg': 0.05,
'surround-sigma__deg': 0.15,
'center-tau__sec': 0.01,
'center-n__uint': 0,
'surround-tau__sec': 0.004,
'opl-amplification': 10,
... |
zouyapeng/instance_monitor_server | contact/models.py | Python | apache-2.0 | 562 | 0 | #!/usr/bin/env python |
# -*- coding: utf8 -*-
from __future__ import unicode_literals
from django.db import models
class Contact(models.Model):
step_user = models.CharField(max_length=128)
username = models.CharField(max_length=128)
action_time = models.CharField(max_length=32, blank=True, null=True)
tel = models.CharFiel... | rue)
def __unicode__(self):
return self.username
|
OpenPathView/batchPanoMaker | opv_import/model/camera_set_partition.py | Python | gpl-3.0 | 1,341 | 0 | # coding: utf-8
# Copyright (C) 2017 Open Path View, Maison Du Libre
# 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.
# ... | uted 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 sho | uld have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
# Contributors: Benjamin BERNARD <benjamin.bernard@openpathview.fr>
# Email: team@openpathview.fr
# Description: Camera Set Partition, represent a partition of ImagesSets.
from typing impo... |
PanDAWMS/panda-jedi | pandajedi/jediorder/JobThrottler.py | Python | apache-2.0 | 1,110 | 0.007207 | from pandajedi.jedicore.FactoryBase import FactoryBase
from pandajedi.jediconfig import jedi_config
# logger
from pandacommon.pandalogger.PandaLogger import PandaLogger
logger = PandaLogger().getLogger(__name__.split('.')[-1])
# factory class for throttling
class JobThrottler (FactoryBase):
# constructor
de... | rottled(self, vo, sourceLabel, cloudName, workQueue, resourceType):
impl = self.getImpl(vo, sourceLabel)
retVal = impl.toBeThrottled(vo, sourceLabel, cloudName, workQueue, resourceType)
# retrieve min priority and max number of jobs from concrete class
self.minPriority = impl.minPriority... | nderNqLimit
return retVal
# check throttle level
def mergeThrottled(self, vo, sourceLabel, thrLevel):
impl = self.getImpl(vo, sourceLabel)
return impl.mergeThrottled(thrLevel)
|
OstapHEP/ostap | ostap/utils/utils.py | Python | bsd-3-clause | 57,489 | 0.031626 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# =============================================================================
## @file
# Module with some simple but useful utilities for
# - timing
# - memory
# - profiling
# - ...
# @author Vanya BELYAEV Ivan.Belyaev@itep.ru
# @date 2013-02-10
#
# =====... |
## show on screen
stat = pstats.Stats( self._profile ).sort_stats( 'cumulative' )
stat.print_stats()
del self._profile
# =============================================================================
## Very simple profiler, based on cProfile module
# @see ht... |
def profiler( name = '' ) :
"""Very simple profiler, based on cProfile module
- see https://docs.python.org/2/library/profile.html
with profiler() :
#
# ... some code here ...
#
"""
return Profiler ( name )
# ===========================================... |
zstackio/zstack-woodpecker | integrationtest/vm/simulator/iam2/test_iam2_project_vpc_cascade_delete.py | Python | apache-2.0 | 8,266 | 0.015364 |
'''
@auther:fangxiao
'''
import apibinding.api_actions as api_actions
import zstackwoodpecker.test_util as test_uti | l
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.operations.iam2_oper | ations as iam2_ops
import zstackwoodpecker.operations.affinitygroup_operations as ag_ops
import zstackwoodpecker.operations.resource_operations as res_ops
import zstackwoodpecker.operations.vxlan_operations as vxlan_ops
import zstackwoodpecker.operations.net_operations as net_ops
import zstackwoodpecker.operations.acco... |
erdc/proteus | proteus/tests/surface_tension/rising_bubble_rans3p/twp_navier_stokes_n.py | Python | mit | 1,998 | 0.023023 | from __future__ import absolute_import
from proteus import *
try:
from .twp_navier_stokes_p import *
from .risingBubble import *
except:
from twp_navier_stokes_p import *
from risingBubble import *
if timeDiscretization=='vbdf':
timeIntegration = VBDF
timeOrder=2
stepController = Min_dt_cfl... | _atol_res
atol_u = {0:time_tol,1:time_tol}
rtol_u = {0:time_tol,1:time_tol}
else:
timeIntegration = BackwardEuler_cfl
st | epController = Min_dt_cfl_controller
if nd==2:
femSpaces = {0:basis,
1:basis}
else:
femSpaces = {0:basis,
1:basis,
2:basis}
massLumping = False
numericalFluxType = None
conservativeFlux = None
numericalFluxType = RANS3PF.NumericalFlux
subgridError = RANS3PF.Subgri... |
ZachGoldberg/gupnp-python | test/gupnp.py | Python | gpl-3.0 | 1,115 | 0.004484 | from gi.repository import GLib, GUPnP, GSSDP, GObject, libsoup
from gupnp_device_tests import device_available
from gupnp_control_point_tests import test_control_point
from gupnp_service_proxy_tests import device_available_service_test
# Note: glib.thread_init() doesn't work here, have to use the gobject call
GObject.... | b.main_context_default()
test_control_point()
ctx = GUPnP.Context(interface="eth0")
# Bind to eth0 in the maincontext on any port
cp = GUPnP.ControlPoint().new(ctx, "upnp:rootdevice")
# Use glib style .connect() as a callback on the controlpoi | nt to listen for new devices
cp.connect("device-proxy-available", device_available)
cp.connect("device-proxy-available", device_available_service_test)
# "Tell the Control Point to Start Searching"
GSSDP.ResourceBrowser.set_active(cp, True)
# Enter the main loop which begins the work and facilitates callbacks
GObject... |
unclesaam/Social-Network-Harvester | SocialNetworkHarvester/snh/migrations/0001_migrate1.py | Python | bsd-3-clause | 40,915 | 0.008628 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
"Write your forwards methods here."
# Note: Don't use "from appname.models imp... | ax_length': '255', 'nul | l': 'True'}),
'pmk_id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'screenname': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}),
'status': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}),
... |
ticklemepierce/ghostpy | ghostpy/_compiler.py | Python | lgpl-3.0 | 45,996 | 0.002392 | #
# Copyright (c) 2015 Will Bond, Mjumbe Wawatu Ukweli, 2012 Canonical Ltd
#
# This program 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, version 3 only.
#
# This program is distributed in the hope th... | [<compile>:t] ] => builder.add_invertedblock(symbol, arguments, t)
partial ::= ["partial" <anything>:symbol [<arg>*:arguments]] => builder.add_partial(symbol, arguments)
path ::= [ | "path" [<pathseg>:segment]] => ("simple", segment)
| [ "path" [<pathseg>+:segments] ] => ("complex", segments)
complexarg ::= [ "path" [<pathseg>+:segments] ] => ([u"resolve(context, '" + u"', '".join(segments) + u"')"], segments)
| [ "subexpr" ["path" <pathseg>:name] [<arg>*:arguments] ] => u'resolve_subexpr(he... |
erinspace/rivannastreamwatch_api | rivannastreamwatch/settings.py | Python | mit | 3,277 | 0.001221 | """
Django settings for rivannastreamwatch project.
Generated by 'django-admin startproject' using Django 1.11.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
... | cs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDA... | .password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics... |
arrti/proxypool | proxypool/errors.py | Python | apache-2.0 | 501 | 0.003992 |
class ProxyPoolError(Exception):
"""proxypool error base"""
class CrawlerRuleImplementionError(ProxyPoolError):
def __str__(self):
return 'crawler rule required "start_url", "ip_xpath" and "port_xpath".'
class CrawlerRuleBaseInstantiateError(ProxyPoolError):
def __str__(self):
return ... | ptyError(ProxyPoolError):
def __str__(self):
return 'the prox | y pool was empty in a long time.'
|
amenonsen/ansible | lib/ansible/modules/network/eos/eos_l3_interfaces.py | Python | gpl-3.0 | 7,195 | 0.001668 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2019 Red Hat
# GNU General Public License v3.0+
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#############################################
# WARNING #
#############################################
#
# This file is au... | returned: always
type: list
sample: >
The configuration returned will always be in the same format
of the parameters above.
after:
description: The resulting configuration model invocation.
returned: when changed
type: list
sample: >
The configuration returned will alw | ays be in the same format
of the parameters above.
commands:
description: The set of commands pushed to the remote device.
returned: always
type: list
sample: ['interface Ethernet2', 'ip address 192.0.2.12/24']
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.eos... |
dannyjacobs/PRISim | main/consolidate_HERA_CST_beams.py | Python | mit | 2,436 | 0.002874 | import numpy as NP
import healpy as HP
from astropy.io import fits
import glob
rootdir = '/data3/t_nithyanandan/project_HERA/'
beams_dir = 'power_patterns/CST/mdl03/'
prefix = 'X4Y2H_490_'
suffix = '.hmap'
pols = ['X']
colnum = 0
outdata = []
schemes = []
nsides = []
npixs = []
frequencies = []
for pol in pols:
f... | (npixs[pi]-1, ' | Last pixel # (0 based)')
hdulist += [hdu]
hdulist += [fits.ImageHDU(frequencies[pi], name='FREQS_{0}'.format(pol))]
outhdu = fits.HDUList(hdulist)
outhdu.writeto(outfile, clobber=True)
|
IhToN/DAW1-PRG | Facturacion/Collections/Bills.py | Python | apache-2.0 | 1,808 | 0.001106 | import time
from Facturacion.Objects.Bill import Bill, ItemLine
from Facturacion.Controllers.ControlDB import BillsController
from Facturacion.Collections.Vendors import Vendors
from Facturacion.Collections.Clients import Clients
from Facturacion.Collections.Items import Items
class Bills:
facturas = {}
contr... | ]] = Bill(bill[0], Vendors.vendedores[bill[1]], Clients.clientes[bill[2]], bill[3])
cls.load_items(bill[0])
@classmethod
def load_items(cls, cod_factura):
factura = cls.facturas[cod_factura]
for item in cls.controller.get_items(cod_factura):
factura.add_item(ItemLine(fac... | Items.articulos[item[0]], item[1]))
@classmethod
def get_max_code(cls):
if not cls.facturas:
return 1
return max(cls.facturas, key=int) + 1
@classmethod
def items_to_il(cls, cod_factura, dict_articulos):
il_list = []
for item, cant in dict_articulos.items()... |
srijannnd/Login-and-Register-App-in-Django | simplesocial/groups/migrations/0001_initial.py | Python | mit | 1,868 | 0.003212 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-21 12:06
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migratio... | eateModel(
name='Group | Member',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='memberships', to='groups.Group')),
('user', models.Forei... |
rlowrance/mlpack | module_logistic.py | Python | mit | 1,237 | 0 | ' | ''module for logistic loss for binary classification to +1 or -1'''
import numpy as np
import unitte | st
import pdb
import math
def logistic():
'''logistic error'''
def output(predicted, expected):
'''expected is +1 or -1'''
return math.log(1 + math.exp(-predicted * expected))
def gradient(predicted, expected):
'''gradient wrt predicted'''
raise NotImplementedError('gradie... |
sp1rs/cookiecutter | tests/test_generate_file.py | Python | bsd-3-clause | 2,271 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_generate_file
------------------
Tests formerly known from a unittest residing in test_generate.py named
TestGenerateFile.test_generate_file
TestGenerateFile.test_generate_file_verbose_template_syntax_error
"""
from __future__ import unicode_literals
import os
i... | context={'syntax_error': 'syntax_error'},
env=env
)
except TemplateSyntaxError as exception:
assert str(exception) == expected_msg
except Exception as exception:
pytest.fail('Unexpected exception t | hrown: {0}'.format(exception))
else:
pytest.fail('TemplateSyntaxError not thrown')
|
juanchodepisa/sbtk | SBTK_League_Helper/test3.py | Python | mit | 3,732 | 0.044483 | # shading = {
# 0: " ",
# 1: "░",
# 2: "▒",
# 3: "▓",
# 4: "█"}
# intro_string = ''' __ __ _ _ _
# \ \ / /__| |__ ___ _ __ ___ | |_ ___(_)
# \ \/\/ / -_) / _/ _ \ ' \/ -_) | _/ _ \_
# \_/\_/\___|_\__\___/_|_|_\___... | ▄██ ███▄▄██▄ | ██ ██ | ║ │
# │ ║ ──███▄ ▀███─{ ██████ }── ║ │
# │ ║ ▀██▀▀███ ██▀ | ██ ██ | ║ │
# │ ║ ▀█▄ | ▄█▀ \ ██████▀ / ║ │
# │ ║ `▀▀███▀▀´ `=.___,=´ ║ │
# │ ║ │ │ ║ │
# │ ║ ,=´"""`=. ,▄▄███▄▄. ║ │
# │ ║ / ██ \ ▄██ █████▄ ║ │
# │ ║ ... |
hanbox/spider_template | spider_template/scrapy_redis/dupefilter.py | Python | mit | 3,992 | 0.000501 | import logging
import time
from scrapy.dupefilters import BaseDupeFilter
from scrapy.utils.request import request_fingerprint
from . import defaults
from .connection import get_redis_from_settings
logger = logging.getLogger(__name__)
# TODO: Rename class to RedisDupeFilter.
class RFPDupeFilter(BaseDupeFilter):
... |
----------
crawler : scrapy.crawler.Crawler
Returns
-------
RFPDupeFilter
Instance of RFPDupeFilter.
"""
ret | urn cls.from_settings(crawler.settings)
def request_seen(self, request):
"""Returns True if request was already seen.
Parameters
----------
request : scrapy.http.Request
Returns
-------
bool
"""
fp = self.request_fingerprint(request)
... |
roomai/RoomAI | roomai/models/texasholdem/TexasholdemA3C.py | Python | mit | 1,770 | 0.00678 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author : SiFaXie
# @Date : 2018/12/23
# @Email : sifaxie@tencent.com
# @File : TexasholdemA3C.py
# @Desc :
import multiprocessing
import os
import threading
import numpy as np
import tensorflow as tf
import shutil
import roomai
from roomai.models.algorithms... | 3CPlayer(state_spec, n_a)
a3c_player.load_model('./checkpoint','TexasHoldemModel')
randomp_pleyer = RandomPlayer()
players = [a3c_player, randomp_pleye | r]
env = TexasHoldemEnv()
for i in range(100):
scores = TexasHoldemEnv.compete_silent(env, players)
print(scores)
if __name__ =='__main__':
# texasholdema3c_train = TexasholdemA3C_Train()
TexasholdemA3C_Predict() |
adhoc-dev/odoo-argentina | l10n_ar_account_withholding/models/res_company.py | Python | agpl-3.0 | 9,290 | 0.000324 | from odoo import models, fields, api, _
# import odoo.tools as tools
try:
from pyafipws.iibb import IIBB
except ImportError:
IIBB = None
# from pyafipws.padron import PadronAFIP
from odoo.exceptions import UserError
import logging
import json
import requests
# from dateutil.relativedelta import relativedelta
_l... | ', 'Regímenes Generales')],
string='Padron AGIP',
default='regimenes_generales',
)
agip_alicuota_no_sincripto_retencion = fields.Float(
'Agip: Alicuota no inscripto retención',
)
agip_alicuota_no_sincripto_percepcion = fields.Float(
'Agip: Alicuota no inscripto percepción... | at(
'Arba: Alicuota no inscripto retención',
)
arba_alicuota_no_sincripto_percepcion = fields.Float(
'Arba: Alicuota no inscripto percepción',
)
cdba_alicuota_no_sincripto_retencion = fields.Float(
'Rentas Córdoba: Alícuota no inscripto retención'
)
cdba_alicuota_no_sincr... |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_07_01/operations/_load_balancer_network_interfaces_operations.py | Python | mit | 5,718 | 0.004197 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | tp_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpRes | ponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancer... |
halcy/Mastodon.py | tests/test_instance.py | Python | mit | 1,396 | 0.012178 | import pytest
from mastodon.Mastodon import MastodonVersionError
@pytest.mark.vcr()
def test_instance(api):
instance = api.instance()
assert isinstance(instance, dict) # hehe, instance is instance
expected_keys = set(('description', 'email', 'title', 'uri', 'version', 'urls'))
assert set(instance.k... | assert len(activity) > 0
assert "statuses" in activity[0]
assert "logins" in activity[0]
assert "week" in activity[0]
@pytest.mark.vcr()
def test_instance_peers(api):
assert len(api.instance_peers()) == 0
@pytest.mark.vcr()
de | f test_low_version(api_low_version):
with pytest.raises(MastodonVersionError):
instance = api_low_version.instance()
@pytest.mark.vcr()
def test_emoji(api):
assert len(api.custom_emojis()) == 0
@pytest.mark.vcr()
def test_health(api):
assert api.instance_health() == True
@pytest.mark.vcr(... |
open-synergy/opnsynid-l10n-indonesia | l10n_id_djbc_kb_lap_common/reports/lap_kb_mutasi_common.py | Python | agpl-3.0 | 8,054 | 0 | # -*- coding: utf-8 -*-
# Copyright 2018 OpenSynergy Indonesia
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from openerp import models, fields, api
from openerp import tools
class LapKbMutasiCommon(models.AbstractModel):
_name = "l10n_id.djbc_kb_lap_mutasi_common"
_description = "Common Mo... | ory_id != %s OR
a.inventory_id IS NULL)
""" % (adjustment)
return str_where
@api.multi
def _qty_join(self):
self.ensure_one()
pass
@api.multi
def _qty_select(self):
self.ensure_one()
str_select = """
| SELECT
a.product_qty AS qty
"""
return str_select
@api.multi
def _compute_qty(self):
date_start = self._context.get("date_start", False)
date_end = self._context.get("date_end", False)
obj_inv_line = self.env["stock.inventory.line"]
obj_inv = sel... |
BrainTech/openbci | obci/configs/settings.py | Python | gpl-3.0 | 1,839 | 0.006525 | import os
from ConfigParser import SafeConfigParser
addrs = os.environ.get('MULTIPLEXER_ADDRESSES', '').split(',')
addr_tuples = []
if addrs:
for addr in addrs:
addr = addr.split(':')
if len(addr) == 2:
addr_tuples.append((addr[0], int(addr[1])))
MULTIPLEXER_ADDRESSES = addr_tuples if ... | rser = SafeConfigParser()
parser.read('/etc/default/ope | nbci')
app = parser.get('diodes', 'appliance')
except:
app = 'dummy'
return app
def module_abs_path():
"""This method returns absolute path to directory containing a module
that imported and fired the method.
Eg. having module /x/y/z/ugm/ugm.py with:
ugm.py:
... |
motorialab/sicurskiweb | deploy/gunicorn.conf.py | Python | gpl-3.0 | 189 | 0 | from __futu | re__ import unicode_literals
import os
bind = "127.0.0.1:%(gunicorn_port)s"
workers = (os.sysconf("SC_NPROCESSORS_ONLN") * 2) + 1
loglevel = "error"
proc_name = "%( | proj_name)s"
|
hfp/libxsmm | samples/deeplearning/sparse_training/dlrm/split_sgd.py | Python | bsd-3-clause | 3,392 | 0.002948 | import torch
from torch.optim.optimizer import Optimizer, required
_available = False
try:
from pcl_embedding_bag import bf16_update
_available = True
except ImportError as e:
#print(e)
pass
def is_available():
return _available
class SplitSGD(Optimizer):
r"""Implements low precision stochast... | _state = self.state[p]
if 'low_bits' not in param_state:
buf = param_state['low_bits'] = torch.zeros_like(p.data, dtype=torch.short)
else:
buf = param_state['low_bits']
# if weight_decay != 0:
# d... | decay, p.data)
# if momentum != 0:
# param_state = self.state[p]
# if 'momentum_buffer' not in param_state:
# buf = param_state['momentum_buffer'] = torch.clone(d_p).detach()
# else:
# buf = param... |
changecong/wikisplit | wikisplit.py | Python | mit | 11,476 | 0.008975 | # -*- coding: utf-8 -*-
######################################################################
## Filename: wikisplit.py
## Copyright: 2014, Zhicong Chen
## Version:
## Author: Zhicong Chen <zhicong.chen@changecong.com>
## Created at: Fri Feb 21 23:21:17 2014
## Modified at: Mon Mar 3 16:3... |
# check if all flieds contains
| if not self.__book.has_key('author'):
# try to get info form the brief introduction
brief_intro = self.__first_paragraph(self.__content)
authors = self.__get_authors_from_content(brief_intro)
self.__book['author'] = authors
if not self.__book.has_k... |
ShaolongHu/lpts | site-packages/pychart/line_plot.py | Python | gpl-2.0 | 6,684 | 0.007481 | #
# Copyright (C) 2000-2005 by Yasushi Saito (yasushi.saito@gmail.com)
#
# Jockey 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, or (at your option) any
# later version.
#
# Jockey is distr... | styles round-robin. <<line_style>>"),
'tick_mark': (tick_mark.T, None, pychart_util.tick_mark_desc),
'error_bar': (error_bar.T, None,
'The style of the error bar. <<error_bar>>'),
}
class T(chart_object.T):
__doc__ = line_plot_doc.doc
keys = _keys
def check_ | integrity(self):
assert chart_object.T.check_integrity(self)
##AUTOMATICALLY GENERATED
##END AUTOMATICALLY GENERATED
def get_data_range(self, which):
if which == 'X':
return pychart_util.get_data_range(self.data, self.xcol)
else:
return pychart_util.get_data... |
jgeewax/parinx | parinx/utils.py | Python | apache-2.0 | 9,290 | 0.000108 | # -*- coding:utf-8 -*-
import datetime
try:
import simplejson as json
except ImportError:
import json
class DateTimeJsonEncoder(json.JSONEncoder):
"""
JSONEncoder subclass that knows how to encode date/time.
"""
def default(self, obj):
if isinstance(obj, datetime.datetime):
... | od from dict/iterable E and F.
If E is a dict instance, does: for k in E: od[k] = E[k]
If E has a .keys() method, does: for k in E.keys(): od[k] = E[k]
Or if E is an iterable of items, does: for k, v in E: od[k] = v
In either case, this is followe | d by: for k, v in F.items(): od[k] = v
'''
if len(args) > 2:
raise TypeError('update() takes at most 2 positional '
'arguments (%d given)' % (len(args),))
elif not args:
raise TypeError('update() takes at least 1 argument (0 given)')
... |
tpherndon/asyncwebbench | aiohttp/aiohttp_python3.py | Python | bsd-3-clause | 985 | 0.00203 | import asyncio
from aiohttp import web
# pypy does not have ujson
try:
import ujson as json
except ImportError:
import json
@asyncio.coroutine
def handle(request):
data = {}
keys = ["key%s" % i for i in range(1, 11)]
for key in keys:
data[key] = request.GET.get(key, "")
assert isi... | ncode('utf-8'), content_type='application/json; charset=utf-8')
@asyncio.coroutine
def init(loop):
app = web.Application(loop=loop)
app.router.add_route('GET', '/', handle)
srv = yield from loop.create_server(app.make_handler(),
'127.0.0.1', 7000)
print("Server... | KeyboardInterrupt:
pass
|
stormi/tsunami | src/secondaires/navigation/commandes/voile/border.py | Python | bsd-3-clause | 4,041 | 0.002736 | # -*-coding:Utf-8 -*
# Copyright (c) 2010 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# r... | on = 5
personnage << "Vous bordez {}.".format(voile.nom)
personnage.salle.envoyer("{{}} borde {}.".format(
voile.nom), personnage)
else:
| personnage << "|err|Cette voile ne peut être bordée " \
"davantage.|ff|"
|
jeffery9/mixprint_addons | ineco_thai_account/invoice.py | Python | agpl-3.0 | 38,150 | 0.008519 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-Today INECO LTD,. PART. (<http://www.ineco.co.th>).
#
# This program is free software: you can redistribute it and/or modify
# it under the... | use the parent for the journal entries
#because you want to invoice 'Agrolait, accounting department' but the journal items are for 'Agrolait'
part = inv.partner_id
if part.parent_id and not part.is_company:
part = part.parent_id
return part
def onchange_payment_term_d... |
if not date_invoice:
date_invoice = time.strftime('%Y-%m-%d')
if not payment_term_id:
return {'value':{'date_due': date_invoice}} #To make sure the invoice has a due date when no payment term
pterm_list = self.pool.get('account.payment.term').compute(cr, uid, pa... |
drewp/tahoe-lafs | src/allmydata/immutable/layout.py | Python | gpl-2.0 | 20,826 | 0.002305 | import struct
from zope.interface import implements
from twisted.internet import defer
from allmydata.interfaces import IStorageBucketWriter, IStorageBucketReader, \
FileTooLargeError, HASH_SIZE
from allmydata.util import mathutil, idlib, observer, pipeline
from allmydata.util.assertutil import precondition
from a... | hes
each share_hash is written as a two-byte (big-endian) hashnum
followed by the 32-byte SHA-256 hash. We store only the hashes
necessary to validate the share hash root
? : start of uri_extension_length (four-byte big-endian value)
? : start of uri_extension
"""
"""
v2 shares: these use 8-by... | Footnote 1 below.
0x14: offset of data (=00 00 00 00 00 00 00 44)
0x1c: offset of plaintext_hash_tree UNUSED
0x24: offset of crypttext_hash_tree
0x2c: offset of block_hashes
0x34: offset of share_hashes
0x3c: offset of uri_extension_length + uri_extension
0x44: start of data
: rest of share is the same as v1, abov... |
felipenaselva/felipe.repository | script.module.resolveurl/lib/resolveurl/plugins/ok.py | Python | gpl-2.0 | 2,491 | 0.004416 | """
OK resolveurl XBMC Addon
Copyright (C) 2016 Seberoth
Version 0.0.2
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... | []
for entry in vids['urls']:
quality = self.__replaceQuality(entry['name'])
sources.append((quality, entry['url']))
try: sources.sort(key=lambda x: int(x[0]), reverse=True)
| except: pass
source = helpers.pick_source(sources)
source = source.encode('utf-8') + helpers.append_headers(self.header)
return source
def __replaceQuality(self, qual):
return self.qual_map.get(qual.lower(), '000')
def __get_Metadata(self, media_id):
url = "http... |
arximboldi/jagsat | src/core/error.py | Python | gpl-3.0 | 1,072 | 0.005597 | #
# Copyright (C) 2009, 2010 JAGSAT Development Team (see below)
#
# This file is part of JAGSAT.
#
# JAGSAT 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 ... | py of the GNU General Public License
# along with this program. If not, se | e <http://www.gnu.org/licenses/>.
#
# JAGSAT Development Team is:
# - Juan Pedro Bolivar Puente
# - Alberto Villegas Erce
# - Guillem Medina
# - Sarah Lindstrom
# - Aksel Junkkila
# - Thomas Forss
#
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from base.error import *... |
Ziemin/telepathy-gabble | tests/twisted/tubes/test-socks5-muc.py | Python | lgpl-2.1 | 2,964 | 0.004386 | """Check if SOCKS5 relays are disabled in muc"""
import os
if os.name != 'posix':
# skipped on non-Unix for now, because it uses a Unix socket
raise SystemExit(77)
import dbus
from servicetest import call_async, EventPattern, EventProtocolClientFactory
from gabbletest import acknowledge_iq, make_muc_presenc... | parameters = tube.addElement((None, 'parameters'))
stream.send(presence)
def new_chan_predicate(e):
pa | th, props = e.args[0][0]
return props[cs.CHANNEL_TYPE] == cs.CHANNEL_TYPE_STREAM_TUBE
e = q.expect('dbus-signal', signal='NewChannels',
predicate=new_chan_predicate)
channels = e.args[0]
assert len(channels) == 1
path, props = channels[0]
assert props[cs.CHANNEL_TYPE] == cs... |
kajgan/stbgui | Navigation.py | Python | gpl-2.0 | 12,831 | 0.023381 | from enigma import eServiceCenter, eServiceReference, eTimer, pNavigation, getBestPlayableServiceReference, iPlayableService, eActionMap, setPreferredTuner, eStreamServer
from Components.ParentalControl import parentalControl
from Components.SystemInfo import SystemInfo
from Components.config import config, configfile
... | s None:
self.stopService()
return 0
from Components.ServiceEventTracker import InfoBarCount
InfoBarInstance = InfoBarCount == 1 and InfoBar.instance
if not checkParentalControl or parentalControl.isServicePlayable(ref, boundFunction(self.playService, checkParentalControl=False, forceRestart=forceRestart, ad... | ayingServiceReference or eServiceReference()
playref = getBestPlayableServiceReference(ref, oldref)
print "playref", playref
if playref and oldref and playref == oldref and not forceRestart:
print "ignore request to play already running service(2)"
return 1
if not playref:
alternativeref ... |
RaoUmer/distarray | distarray/localapi/tests/__init__.py | Python | bsd-3-clause | 316 | 0 | # encoding: utf-8
# ---------------------------------------------------------------------------
# Copyright (C) 2008-2014, IPython Development Team and Enthou | ght, Inc.
# Distrib | uted under the terms of the BSD License. See COPYING.rst.
# ---------------------------------------------------------------------------
|
windskyer/weibo | setup.py | Python | apache-2.0 | 484 | 0 | #!/usr/bin/env python
# author zwei
# email suifeng20@hotmail.com
# THIS FILE IS MANAGED BY THE GLOBAL REQUIREMENTS REPO - DO NOT EDIT
import setuptools
# In python < 2.7.4, a lazy loading of package `pbr` will break
# setuptools if some other modules registered functions in `atexit`.
# solution f | rom: http://bugs.python.org/issue15881#msg170215
try:
import multiprocessing # noqa
except ImportError:
p | ass
setuptools.setup(
setup_requires=['pbr>=1.8'],
pbr=True)
|
robertsj/poropy | pyqtgraph/widgets/ValueLabel.py | Python | mit | 2,623 | 0.010294 | from pyqtgraph.Qt import QtCore, QtGui
from pyqtgraph.ptime import time
import pyqtgraph as pg
__all__ = ['ValueLabel']
class ValueLabel(QtGui.QLabel):
"""
QLabel specifically for displaying numerical values.
Extends QLabel adding some extra functionality:
- displaying units with si prefix
... | for v in self.values]) / float(len(self.val | ues))
def paintEvent(self, ev):
self.setText(self.generateText())
return QtGui.QLabel.paintEvent(self, ev)
def generateText(self):
if len(self.values) == 0:
return ''
avg = self.averageValue()
val = self.values[-1][1]
if self... |
ortutay/23andme-phenotypes-hackathon | my_app/my_app/migrations/0006_phenotype_user.py | Python | mit | 689 | 0.001451 | # -*- coding: utf-8 -*-
# Generated by Dj | ango 1.11.1 on 2017-05-26 15:47
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('... | migrations.AddField(
model_name='phenotype',
name='user',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
preserve_default=False,
),
]
|
NMTHydro/Recharge | utils/prism_precip_checker.py | Python | apache-2.0 | 7,611 | 0.003547 | # ===============================================================================
# Copyright 2018 gabe-parrish
#
# 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/licen... | n(p_list))
date_dict["{}".format(key)] = p_list
print "DATE DICT", date_dict
return date_dict
def raster_reader(date_dict):
"""
:param date_dict: key is date in ISO format. Value is a list of paths to tiff files of Prism precip images prior
to the date.
:return: a dictionary where ... | teritems():
arr_list = []
for file in value:
with rasterio.open(file) as raster:
arr = raster.read(1)
arr_list.append(arr)
raster_dict["{}".format(key)] = (arr_list, value)
return raster_dict
def format_outputter(raster_dict):
"""
Forma... |
vmalloc/json_rest | setup.py | Python | bsd-3-clause | 918 | 0.003268 | import os
import platform
import itertools
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), "json_rest", "__version__.py")) as version_file:
exec(version_file.read())
_INSTALL_REQUIREMENTS = ["python-cjson", "pyforge", "sentinels"]
if platform.python_version() < '2.7':... | QUIREMENTS.append('unittest2')
setup(name="json_rest",
classifiers = [
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Programming Language :: Python :: 2.7",
],
description="Utility for REST/J... | version=__version__,
packages=find_packages(exclude=["tests"]),
install_requires=_INSTALL_REQUIREMENTS,
scripts=[],
)
|
walter-trueplus/training | fixing_issues_view/models/models.py | Python | gpl-3.0 | 133 | 0.015038 | # - | *- coding: utf-8 -*-
from odoo import models, fields, api
class fixing_issues_view(models.Model):
_inherit = 'project.iss | ue' |
messagebird/python-rest-api | messagebird/hlr.py | Python | bsd-2-clause | 749 | 0 | from messagebird.base | import Base
class HLR(Base):
def __init__(self):
self.id = None
self.href = None
self.msisdn = None
self.network = None
self | .reference = None
self.status = None
self.details = None
self._createdDatetime = None
self._statusDatetime = None
@property
def createdDatetime(self):
return self._createdDatetime
@createdDatetime.setter
def createdDatetime(self, value):
self._createdDat... |
DominikDitoIvosevic/Uni | AI/lab1/searchAgents.py | Python | mit | 24,561 | 0.006922 | # searchAgents.py
# | ---------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attributio... | @cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
"""
This file contains all of the agents that can be selected to control Pacman. To
select an agent, use the '-p' option when running pacman.py. Arguments can be
passed to your agent usin... |
rvs/gpdb | src/test/tinc/tincrepo/mpp/gpdb/tests/storage/vacuum/mpp24011/test_mpp24011.py | Python | apache-2.0 | 2,465 | 0.002028 | """
Copyright (C) 2004-2015 Pivotal Software, Inc. All rights reserved.
This program and the accompanying materials are made available under
the terms of the 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
... |
@gucs gp_create_table_random_default_distribution=off
@product_version gpdb: [4.2.8.1-4.2], [4.3.3-]
'''
def setUp(self):
self.filereputil = Filerepe2e_Util()
def tearDown(self):
self.filereputil.inject_fault(f='repair_frag_end', y='reset', seg_id=2)
def test_mpp24011(self):
... | ("""
drop table if exists mpp24011;
create table mpp24011(
a int,
b int,
c text
) distributed by (a);
insert into mpp24011
select 1, i, repeat('x', 255-42) from generate_series(1, 32 * 4 * 3)i;
create unique in... |
ct-23/home-assistant | tests/components/automation/test_init.py | Python | apache-2.0 | 25,931 | 0 | """The tests for the automation component."""
import asyncio
from datetime import timedelta
import unittest
from unittest.mock import patch
from homeassistant.core import State, CoreState
from homeassistant.setup import setup_component, async_setup_component
import homeassistant.components.automation as automation
fro... | utomation.DOMAIN, {
automation.DOMAIN: {
'trigger': [
{
'platform': 'event',
'event_type': 'test_event',
},
],
'condition': {
'condition': 'state',
... | xisting',
'state': 'beer',
},
'action': {
'service': 'test.automation',
}
}
})
self.hass.bus.fire('test_event')
self.hass.block_till_done()
assert len(self.calls) == 0
self.hass.... |
AisinoPythonTeam/PythonAiniso | ic_crawler/gsgj_phone/gsgj_phone/spiders/gsgj_phone_spider.py | Python | apache-2.0 | 3,486 | 0.005472 | # -*- coding:utf-8 -*-
import re
import time
import json
import string
import hashlib
from scrapy import log
from scrapy.spider import Spider
from scrapy.http import Request, FormRequest
from bson.objectid import ObjectId
from gsgj_phone import settings
from gsgj_phone.util.time_handler import *
from gsgj_phone.items... | , formdata=query_item['detail_formdata'], headers=settings.DEFAULT_HEADERS, callback=self.parse_detail, errback=self.parse_err)
def parse_detail(self, response):
log.msg('_____________code: %s' % response.body, level=log.ERROR)
| item = response.meta.get('item', None)
res_json = json.loads(response.body)
log.msg('%s' % response.body, level=log.WARNING)
if not res_json:
self.parse_err('')
return
self.json_parse.detail_parse(item, res_json)
for k in self.data['json_data']['retData'... |
creasyw/IMTAphy | documentation/doctools/tags/0.4.3/sphinx/roles.py | Python | gpl-2.0 | 8,698 | 0.004254 | # -*- coding: utf-8 -*-
"""
sphinx.roles
~~~~~~~~~~~~
Handlers for additional ReST roles.
:copyright: 2007-2008 by Georg Brandl.
:license: BSD.
"""
import re
from docutils import nodes, utils
from docutils.parsers.rst import roles
from sphinx import addnodes
ws_re = re.compile(r'\s+')
caption_... | , 'environment variable; %s' % text,
targetid, text)
indexnode['entries'] = [('single', text, targetid, text),
('single', 'environment variable; %s' % text,
| targetid, text)]
xref_nodes = xfileref_role(typ, rawtext, etext, lineno, inliner,
options, content)[0]
return [indexnode, targetnode] + xref_nodes, []
elif typ == 'pep':
env.note_index_entry('single', 'Python Enhancement Proposals!PEP %s' % text... |
mafik/pargen | pargen.py | Python | agpl-3.0 | 2,144 | 0.010758 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
from __future__ import print_function
import argparse
import random
import math
import model
import utils
import gen
default_paraphrase = u"Niestety, psy czasem się mylą. Może ich zgubić choćby zapach palącego papierosy."
parser = argparse.ArgumentParser(description='... | = 20
def semantic_distance(x, y):
a = set(x.split())
b = set(y.split())
common = a & b
if len(common) == 0:
return 0.0
c = float(len(common))
S = 0.5 * math.log(len(a) / c, 2) + 0.5 * math.log(len(b) / c, 2)
if S < 1.0:
return S * scale
return math.exp(-3 * S) * scale
start_sentence = args.par... | ntic distance", old_similarity)
generator = gen.SentenceGenerator(args)
generator.favorize(start_sentence.split(), args.favorize_alpha)
with utils.ModelSession(args) as model_session:
session = model_session.session
for i in range(100):
T = 0.9 ** (i/ 100. * 10)
removed_chars = int(math.ceil(len(sentence) ... |
baffelli/pyperator | pyperator/__init__.py | Python | mit | 222 | 0.004505 | from pyperator.decorators import inport, outport, component, run_once
from pyperator.nodes import Component
from pyperator.DAG import Multigraph
from | pyperator.utils import InputPort, OutputPort
import | pyperator.components |
babyliynfg/cross | tools/project-creator/Python2.6.6/Lib/bsddb/test/test_thread.py | Python | mit | 16,484 | 0.009282 | """TestCases for multi-threaded access to a DB.
"""
import os
import sys
import time
import errno
from random import random
DASH = '-'
try:
WindowsError
except NameError:
class WindowsError(Exception):
pass
import unittest
from test_all import db, dbutils, test_support, verbose, ha... | get_new_environment_path, get_new_database_path
if have_threads :
from threading import Thread
import sys
if sys.version_info[0] < 3 :
from threading import currentThread
else :
from threading import current_thread as currentThread
#-----------------------------------------... | ThreadedTestCase(unittest.TestCase):
dbtype = db.DB_UNKNOWN # must be set in derived class
dbopenflags = 0
dbsetflags = 0
envflags = 0
import sys
if sys.version_info[:3] < (2, 4, 0):
def assertTrue(self, expr, msg=None):
self.failUnless(expr,msg=msg)
... |
mvaled/sentry | src/sentry/signals.py | Python | bsd-3-clause | 4,787 | 0.002507 | from __future__ import absolute_import
import logging
from django.dispatch.dispatcher import NO_RECEIVERS, Signal
class BetterSignal(Signal):
def connect(self, receiver=None, **kwargs):
"""
Support decorator syntax:
>>> @signal.connect(sender=type)
>>> def my_receiver(**kwargs):... | g_args | =["organization"])
alert_rule_created = BetterSignal(providing_args=["project", "rule", "user"])
repo_linked = BetterSignal(providing_args=["repo", "user"])
release_created = BetterSignal(providing_args=["release"])
release_commits_updated = BetterSignal(
providing_args=["release", "removed_commit_ids", "added_comm... |
pjuhanak/vm-starter | vm.py | Python | gpl-3.0 | 3,827 | 0.012804 | #!/usr/bin/python
"""
VM starter - start your virtual hosts based on config file
------------------ | --------------------------------------------------------------
@author Petr Juhanak, http://www.hackerlab.cz
@release 1.0, 20130808
@licence GPLv3 http:://www.gnu.org/licenses/gpl-3.0.html
--------------------------------------------------------------------------------
"""
import re
import sys
import os.path... | '1','i','I','s','S']
VBOX_MANAGE = 'C:\Program Files\Oracle\VirtualBox\VBoxManage.exe'
if os.name == 'nt':
vbox_manage = os.path.normpath('"'+VBOX_MANAGE+'"')
# functions
def show_banner():
print "VM starter 1.0 - Author Petr Juhanak | http://www.hackerlab.cz (GPLv3)"
print ""
def report_error(message)... |
jtrobec/pants | src/python/pants/backend/jvm/tasks/jvm_compile/analysis_parser.py | Python | apache-2.0 | 5,221 | 0.009385 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed 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 os
import re
... | """An efficient parser of just the binary, source and external deps sections.
Returns a dict of src -> iterable of deps, where each item in deps is either a binary dep,
source dep or external dep, i.e., either a source file, a class file or a jar file.
All paths are relative.
"""
raise NotImpl... | e form '<num> items' and returns <num> as an int."""
matchobj = self._num_items_re.match(line)
if not matchobj:
raise ParseError('Expected: "<num> items". Found: "{0}"'.format(line))
return int(matchobj.group(1))
def rebase_from_path(self, infile_path, outfile_path, old_base, new_base, java_home=No... |
angeltogaita/linuxkernel | scripts/applications/rss.py | Python | bsd-3-clause | 1,849 | 0.031909 | #!/usr/bin/env python
# rq/64k - 2010/2011
# http://code.google.com/p/rsspy/
# imports
import os
import sys as s
import unicodedata
# check if feedparser module is installed
try: import feedparser
except ImportError:
import webbrowser
print "This script requires feedparser."
webbrowser.open("http://code.google.com... | tts"
os.system(festivalcommand)
print
# pretty obvious what this does | , huh?
def main():
# if no arguments, print usage.
if (s.argv[2:] == []):
usage()
url = str(s.argv[1])
# headlines length must be a integer.
try: hl = int(s.argv[2])
except ValueError: usage()
# feed://* is not allowed, use http://* instead.
if (url.startswith("feed://") == True):
error("feed:// not suppo... |
rec/echomesh | code/python/external/pi3d/__init__.py | Python | mit | 1,492 | 0.00067 | from __future__ import absolute_import, division, print_function, unicode_literals
"""
Allows the use of:
import pi3d
to drag in most of the important classes of pi3d.
"""
from echomesh.util import Log
from pi3d.constants import *
from pi3d import Display
from pi3d.Camera import Camera
from pi3d.Keyboard import ... | evationMap import ElevationMap
from pi3d.shape.Extrude import Extrude
from pi3d.shape.Helix import Helix
from pi3d.shape.Lathe import Lathe
from pi3d.shape.MergeShape import MergeShape
from pi3d.shape.Model import Model
from pi3d.shape.Plane import Plane
from pi3d.shape.Sphere import Sphere
from pi3d.shape.TCone import... | String
from pi3d.util.Defocus import Defocus
from pi3d.util.Font import Font
from pi3d.util.Screenshot import screenshot
from pi3d.util.Ttffont import Ttffont
|
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-2.7/Lib/test/test_ntpath.py | Python | mit | 8,404 | 0.000833 | import ntpath
import os
from test.test_support import TestFailed
from test import test_support, test_genericpath
import unittest
def tester(fn, wantResult):
fn = fn.replace("\\", "\\\\")
gotResult = eval(fn)
if wantResult != gotResult:
raise TestFailed, "%s should return: %s but returned: %s" \
... | h.splitext(".ext")', ('.ext', ''))
tester('ntpath.splitext("\\foo.ext\\foo")', ('\\foo.ext\\foo', ''))
tester('ntpath.splitext("foo.ext\\")', ('foo.ext\\', ''))
test | er('ntpath.splitext("")', ('', ''))
tester('ntpath.splitext("foo.bar.ext")', ('foo.bar', '.ext'))
tester('ntpath.splitext("xx/foo.bar.ext")', ('xx/foo.bar', '.ext'))
tester('ntpath.splitext("xx\\foo.bar.ext")', ('xx\\foo.bar', '.ext'))
tester('ntpath.splitext("c:a/b\\c.d")', ('c:a/b\\c',... |
ghchinoy/tensorflow | tensorflow/tools/compatibility/testdata/test_file_v1_12.py | Python | apache-2.0 | 3,449 | 0.004639 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | uage governing permissions and
# limitations under the License.
# =============================== | ===============================================
"""Tests for tf upgrader."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from tensorflow.python.framework import test_util
from tensorflow.python.platform import test as test_lib
c... |
harmslab/epistasis | epistasis/models/linear/elastic_net.py | Python | unlicense | 3,836 | 0.000261 | import numpy as np
from sklearn.linear_model import ElasticNet
from ..base import BaseModel, use_sklearn
from ..utils import arghandler
# Suppress an annoying error from scikit-learn
import warnings
warnings.filterwarnings(action="ignore", module="scipy",
message="^internal gelsd")
@use_sklea... | return n
@arghandler
def fit(self, X=None, y=None, **kwargs):
# If a threshold exists in the data, pre-classify genotypes
X = np.asfortranarray(X)
self = super(self.__class__, self).fit(X, y)
# Link coefs to epistasis values.
self.epistasis.values = np.reshape(se | lf.coef_, (-1,))
return self
def fit_transform(self, X=None, y=None, **kwargs):
return self.fit(X=X, y=y, **kwargs)
@arghandler
def predict(self, X=None):
X = np.asfortranarray(X)
return super(self.__class__, self).predict(X)
@arghandler
def predict_transform(self,... |
jnsebgosselin/WHAT | gwhat/projet/tests/test_project.py | Python | gpl-3.0 | 10,455 | 0 | # -*- coding: utf-8 -*-
# Copyright © 2014-2018 GWHAT Project Contributors
# https://github.com/jnsebgosselin/gwhat
#
# This file is part of GWHAT (Ground-Water Hydrograph Analysis Toolbox).
# Licensed under the terms of the GNU General Public License.
# ---- Standard library imports
import os
import os.path as osp
... | oading an invalid project when no backup exists.
"""
# Create an invalid project file.
os.makedirs(osp.dirname(projectpath))
with open(projectpath, 'w') as f:
f.write('empty file')
assert osp.exists(projectpath)
mock_qmsgbox = mocker.patch.object(QMessageBox, 'exec_')
mock_qmsgbox.r... | == 1
assert result is False
assert projmanager.projet is None
def test_load_corrupt_project_continue(projmanager, mocker, projectfile):
"""
Test loading a corrupt project when no backup exists and click to
load it anyway.
"""
assert osp.exists(projectfile)
assert not osp.exists(projec... |
whiterabbitengine/fifeplusplus | engine/python/fife/extensions/pychan/exceptions.py | Python | lgpl-2.1 | 1,894 | 0.016895 | # -*- coding: utf-8 -*-
# ####################################################################
# Copyright (C) 2005-2013 by the FIFE team
# http://www.fifengine.net
# This file is part of FIFE.
#
# FIFE is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General ... |
Exception raised during the run time - for example caused by a missing name attribute in a XML file.
"""
pass
class GuiXMLError(PyChanException):
"""
An error that occured during parsing an XML file.
"""
class ParserError(PyChanException):
"""
An error that occured during parsing an at | tribute.
"""
class PrivateFunctionalityError(RuntimeError):
"""
Exception raised if private attributes/functions are used.
"""
class StopTreeWalking(StopIteration):
"""
Internal exception used to abort iteration over the widget tree.
"""
|
LibreTime/libretime | api/libretime_api/models/playout.py | Python | agpl-3.0 | 2,080 | 0 | from django.db import models
from .files import File
class ListenerCount(models.Model):
timestamp = models.ForeignKey("Timestamp", models.DO_NOTHING)
mount_name = models.ForeignKey("MountName", models.DO_NOTHING)
listener_count = models.IntegerField()
class Meta:
managed = False
db_t... | table = "cc_live_log"
class PlayoutHistory(models.Model):
file = models.ForeignKey(File, models.DO_NOTHING, blank=True, null=True)
starts = models.DateTimeField()
ends = models.DateTimeField(blank=True, null=True)
instance = models.ForeignKey(
"ShowInstance", models.DO_NOTHING, blank=True, nul... | managed = False
db_table = "cc_playout_history"
class PlayoutHistoryMetadata(models.Model):
history = models.ForeignKey(PlayoutHistory, models.DO_NOTHING)
key = models.CharField(max_length=128)
value = models.CharField(max_length=128)
class Meta:
managed = False
db_table = "c... |
FredLoney/nipype | nipype/interfaces/io.py | Python | bsd-3-clause | 58,935 | 0.000916 | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
""" Set of interfaces that allow interaction with data. Currently
available interfaces are:
DataSource: Generic nifti to named Nifti interface
DataSink: Generic named output from interfaces to ... | desc='store output in parametrized structure')
strip_dir = Directory(desc='path to strip out of filename')
substitutions = InputMultiPath(traits.Tuple(traits.Str, traits.Str),
desc=('List of 2-tuples reflec | ting string '
'to substitute and string to replace '
'it with'))
regexp_substitutions = InputMultiPath(traits.Tuple(traits.Str, traits.Str),
desc=('List of 2-tuples reflecting a pair '
... |
simvisage/oricreate | docs/howtos/ex03_cp_factories/miura_ori_factory.py | Python | gpl-3.0 | 596 | 0.001678 | r'''
This example demonstrates the crease pattern factory usage
for MiuraOri crease pattern.
This crease pattern contains quadrilateral facet | s.
A quadrilateral facet is assembled out of two triangles
connected with a no-fold-line.
'''
def create_cp():
# begin
from oricreate.api import MiuraOriCPFactory
cp_factory = MiuraOriCPFactory()
| cp = cp_factory.formed_object
print('Nodes of facets enumerated counter clock-wise\n', cp.F_N)
print('Lines of facets enumerated counter clock-wise\n', cp.F_L)
# end
return cp
if __name__ == '__main__':
create_cp()
|
DavidToroczkai/Game-Theory-Experiments-in-Python | elfarol/Elfarol.py | Python | gpl-3.0 | 2,400 | 0.049583 | import random
import sys
class adaptableClass:
chance = 0
def __init__(self):
self.chance = random.randint(1, 10)/10
def increase(self):
if self.chance != 1.0:
self.chance = (self.chance * 10 + 1) / 10
def decrease(self):
if self.chance != 0.1:
self.chance = (self.chance * 10 - 1) / 10
def initgen(... | e:
nodict[current] = 1
return godict, nodict
def humanreadable(godict, nodict, popsize, iterations, go, point):
if len(go) < point:
status = "Going to the El Farol"
else:
status = "Staying at home"
sort = sorted(set(list(godict. | keys()) + list(nodict.keys())))
print("Iteration ", iterations, ":", sep = "")
print(status, "was the better choice.")
print("Chance", " ", "Go", " ", "No go", " ", "Total", sep = "")
for s in sort:
gofreq = float(godict.get(s, 0))/popsize * 100
nofreq = float(nodict.get(s, 0))/popsize * 100
allfreq = (float(... |
lifemapper/core | LmCommon/common/lm_xml.py | Python | gpl-3.0 | 14,471 | 0.000069 | """Module containing Lifemapper XML utilities
Note: Mainly wraps elementTree functionality to fit Lifemapper needs
"""
from types import (BuiltinFunctionType, BuiltinMethodType, FunctionType,
LambdaType, MethodType)
from LmCommon.common.attribute_object import LmAttList, LmAttObj
import xml.etree.E... | serialize_xml
# .............................................................................
def _get_element_qname(namespace, tag):
"""Assembles a QName obje | ct from a namespace and tag
Args:
namespace: The namespace to use for the QName.
tag: The tag of the QName.
Note:
* If namespace is -1, the default namespace (specified by
__DEFAULT_NAMESPACE__) will be used.
* If namespace is None, the QName will not have a namespa... |
rightscale/cloud-init | cloudinit/sources/DataSourceCloudStack.py | Python | gpl-3.0 | 9,871 | 0 | # vi: ts=4 expandtab
#
# Copyright (C) 2012 Canonical Ltd.
# Copyright (C) 2012 Cosmin Luta
# Copyright (C) 2012 Yahoo! Inc.
# Copyright (C) 2012 Gerard Dethier
# Copyright (C) 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Cosmin Luta <q4break@gmail.com>
# Author: Scott Moser <scott.mo... | f):
mcfg = self.ds_cfg
if not mcfg:
mcfg = {}
(max_wait, timeout) = self._get_url_settings()
urls = [uhelp.combine_url(self.metadata_address,
'latest/meta-data/instance-id')]
start_time = time.time()
url = uhelp.wait_for_url... | LOG.debug("Using metadata source: '%s'", url)
else:
LOG.critical(("Giving up on waiting for the metadata from %s"
" after %s seconds"),
urls, int(time.time() - start_time))
return bool(url)
def get_config_obj(self):
return ... |
rayidghani/CharBucks | app/views.py | Python | mit | 214 | 0.009346 | # views.py
from flask import render_template
from app import app
@app.route('/')
def index():
return render_template("index.html")
@app.route('/about')
def about | ():
return render_ | template("about.html")
|
aelkikhia/pyduels27 | epicduels/rules/board_rules.py | Python | apache-2.0 | 7,465 | 0 |
from math import fabs
from epicduels.content import game_state as GS
def square_state(board, pos):
return board['board'][pos['x']][pos['y']]
def is_diagonal(origin, target):
"""
Verify if points are diagonal
"""
return fabs(origin['x'] - target['x']) == fabs(origin['y'] - target['y'])
# verif... | return _is_parallel_clear_x_axis(board, origin, target)
else:
# when y is the pivot
return _is_parallel_clear_y_axis(board, origin, target)
# Verify if the diagonal path between two squares is not obstructed.
def is_diagonal_clear(board, orig | in, target):
"""
Verify if there is a clear diagonal path between two points
"""
x = -1
y = -1
end = int(fabs(origin['x'] - target['x']) - 1)
# set modifiers for x and y coordinate traversal
if origin['x'] < target['x']:
x = 1
if origin['y'] < target['y']:
y = 1
... |
codelucas/facebook-context | backend-flask/shell.py | Python | apache-2.0 | 366 | 0.005464 | #!/usr/bin/env python2.7
"""
/shell.py will allow you to get a console and enter com | mands
within your flask environment.
"""
import os
import sys
import readline
from pprint import pprint
from flask im | port *
sys.path.insert(0, '/home/lucas/www/text2img.lucasou.com/text2img-env/text2img/backend-flask')
from backend import *
os.environ['PYTHONINSPECT'] = 'True'
|
ClearCorp/account-financial-tools | account_multicompany_usability/__openerp__.py | Python | agpl-3.0 | 1,507 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar)
# All Rights Reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Pu... | tails.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Account Multicompany Usability',
'version': '8.0.1.2.0',
... | r': 'ADHOC SA',
'website': 'www.adhoc.com.ar',
'license': 'AGPL-3',
'depends': [
'account',
],
'data': [
'views/res_company_property_view.xml',
'views/res_company_view.xml',
'views/res_partner_view.xml',
'views/product_view.xml',
'security/security.xml... |
rit-sailing/website | files/models.py | Python | mit | 1,637 | 0.032987 | from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.template.defaultfilters import slugify
from main.models import TeamMember
from django.db import models
import re
class Folder(models.Model):
name = models.CharField(max_length=20)
parent = models.ForeignKey('self',... | nt = instance.parent
while(current != None):
path = "/" + current.slug + path
current = current.parent
return 'files' + path + filename
class File(models.Model):
name = models.CharField(max_length=20)
content = models.FileField(upload_to=file_pa | th)
description = models.CharField(max_length=100, blank=True)
publish_date = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
uploaded_by = models.ForeignKey(TeamMember)
parent = models.ForeignKey(Folder, null=True, blank=True)
slug = models.SlugField()
def get_path(se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.