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 |
|---|---|---|---|---|---|---|---|---|
cga-harvard/cga-worldmap | geonode/contrib/dataverse_styles/style_layer_maker.py | Python | gpl-3.0 | 12,317 | 0.004871 | """
Given Style Rules, create an SLD in XML format add it to a layer
"""
if __name__=='__main__':
import os, sys
DJANGO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(DJANGO_ROOT)
os.environ['DJANGO_SETTINGS_MODULE'] = 'geonode.settings'
import logging
import os
from... | if response is None or not response.status == 200:
self.add_err_msg('Failed to set new style as the default')
return False
# (3) Set the new style as the default for the layer
# Send a PUT to the catalog to set the default sty | le
json_str = """{"layer":{"defaultStyle":{"name":"%s"},"styles":{},"enabled":true}}""" % formatted_sld_object.sld_name
geoserver_json_url = self.get_set_default_style_url(self.layer_name)
if geoserver_json_url is None:
self.add_err_msg('Failed to format the url to set new style for ... |
mattvonrocketstein/smash | smashlib/ipy3x/core/page.py | Python | mit | 12,350 | 0.001053 | # encoding: utf-8
"""
Paging capabilities for IPython.core
Authors:
* Brian Granger
* Fernando Perez
Notes
-----
For now this uses ipapi, so it can't be in IPython.utils. If we can get
rid of that dependency, we could move it there.
-----
"""
#----------------------------------------------------------------------... | needed: the screen size in rows/columns
return screen_lines_real
# print '***Screen size:',screen_lines_real,'lines x',\
# screen_cols,'col | umns.' # dbg
def page(strng, start=0, screen_lines=0, pager_cmd=None):
"""Display a string, piping through a pager after a certain length.
strng can be a mime-bundle dict, supplying multiple representations,
keyed by mime-type.
The screen_lines parameter specifies the number of *usable* lines of you... |
fizyk/pyramid_decoy | src/pyramid_decoy/__init__.py | Python | mit | 1,031 | 0 | # Copyright (c) 2014 by pyramid_decoy authors and contributors
# <see AUTHORS file>
#
# This module is part of pyramid_decoy and is released under
# the MIT License (MIT): http://opensource.org/licenses/MIT
"""Main decoy module."""
__version__ = "0.2.0"
SETTINGS_PREFIX = "decoy"
def includeme(configurator):
"""... | gurator object
"""
configurator.registry["decoy"] = get_decoy_settings(
configurator.get_settings()
)
configurator.add_route("decoy", pattern="/*p")
configurator.add_view("pyramid_decoy.views.decoy", route_name="decoy | ")
def get_decoy_settings(settings):
"""
Extract decoy settings out of all.
:param dict settings: pyramid app settings
:returns: decoy settings
:rtype: dict
"""
return {
k.split(".", 1)[-1]: v
for k, v in settings.items()
if k[: len(SETTINGS_PREFIX)] == SETTINGS_PR... |
googlefonts/gfregression | Lib/gfregression/gf_families_ignore_camelcase.py | Python | apache-2.0 | 936 | 0.002137 | from utils import secret
import requests
import re |
import json
import os
def gf_families_ignore_camelcase():
"""Find family names in the GF collection which cannot be derived by
splitting the filename using a camelcase function e.g
VT323, PTSans.
If these filenames are split, they will be V T 323 and P T Sans."""
families = {}
api_u | rl = 'https://www.googleapis.com/webfonts/v1/webfonts?key={}'.format(
secret('GF_API_KEY')
)
r = requests.get(api_url)
for item in r.json()["items"]:
if re.search(r"[A-Z]{2}", item['family']):
families[item["family"].replace(" ", "")] = item["family"]
return families
def ma... |
hipnusleo/laserjet | resource/pypi/cffi-1.9.1/demo/gmp_build.py | Python | apache-2.0 | 733 | 0.001364 | import cffi
#
# This is only a | demo based on the GMP library.
# There is a rather more complete (but perhaps outdated) version available at:
# http://bazaar.launchpad.net/~tolot-solar-empire/+junk/gmpy_cffi/files
#
ffibuilde | r = cffi.FFI()
ffibuilder.cdef("""
typedef struct { ...; } MP_INT;
typedef MP_INT mpz_t[1];
int mpz_init_set_str (MP_INT *dest_integer, char *src_cstring, int base);
void mpz_add (MP_INT *sum, MP_INT *addend1, MP_INT *addend2);
char * mpz_get_str (char *string, int base, MP_INT *integer)... |
pandeyravi15/SGMBL | script/revcomp.py | Python | gpl-3.0 | 576 | 0.064236 | import sys
inFile = open(sys.argv[1],'r')
nuc = {'A':'T','T':'A','G':'C','C':'G','K':'M','M':'K','R':'Y' | ,'Y':'R','S':'W','W':'W','B':'V','V':'B','H':'G','D':'C','X':'N','N':'N'}
def revComp(seq):
rev = ''
for i in range(len(seq) - 1,-1,-1):
rev += nuc[seq[i]]
return rev
header = ''
seq = ''
for line in inFile:
if line[0] == ">":
if header != '':
print header
prin... | pper())
|
vmassuchetto/dnstorm | dnstorm/app/context_processors.py | Python | gpl-2.0 | 1,367 | 0.003658 | from django.contrib.auth.forms import AuthenticationForm
from django.core.urlresolvers import reverse
from actstream.models import user_stream
from dnstorm.app import DNSTORM_URL
from dnstorm.app.utils import get_option
from dnstorm.app.models import Problem, Idea
from dnstorm.app.utils import get_option
def base(re... | not context.get('site_title', None):
context['site_title'] = '%s | %s' % (
get_option('site_title'), get_option('site_description'))
context['site_url'] = get_option('site_url')
context['login_form'] = AuthenticationForm()
context['login_url'] = reverse('login') + '?next | =' + request.build_absolute_uri() if 'next' not in request.GET else ''
context['logout_url'] = reverse('logout') + '?next=' + request.build_absolute_uri() if 'next' not in request.GET else ''
# Checks
context['is_update'] = 'update' in request.resolver_match.url_name
# Activity
context['user_activ... |
theoriginalgri/django-mssql | sqlserver_ado/compiler.py | Python | mit | 10,087 | 0.002776 | from __future__ import absolute_import, unicode_literals
try:
from itertools import zip_longest
except ImportError:
from itertools import izip_longest as zip_longest
import django
from django.db.models.sql import compiler
import re
NEEDS_AGGREGATES_FIX = django.VERSION[:2] < (1, 7)
# query_clas... | if meta.has_auto_field:
if hasattr(self.query, 'fields'):
# django 1.4 replaced columns with fields
fields = self.query.fields
auto_field = meta | .auto_field
else:
# < django 1.4
fields = self.query.columns
auto_field = meta.auto_field.db_column or meta.auto_field.column
auto_in_fields = auto_field in fields
quoted_table = self.connection.ops.quote_name(meta.db_table)
... |
PetePriority/home-assistant | homeassistant/components/isy994/fan.py | Python | apache-2.0 | 3,213 | 0 | """
Support for ISY994 fans.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/fan.isy994/
"""
import logging
from typing import Callable
from homeassistant.components.fan import (FanEntity, DOMAIN, SPEED_OFF,
SPEE... | evice(ISYDevice, FanEntity):
"""Representation of an ISY994 fan device."""
@property
def speed(self) -> str:
"""Return the current speed."""
return VALUE_TO_STATE.get(self.value)
@property
def is_on(self) -> bool:
"""Get if the fan is on."""
return self.value != 0
... | """Send the set speed command to the ISY994 fan device."""
self._node.on(val=STATE_TO_VALUE.get(speed, 255))
def turn_on(self, speed: str = None, **kwargs) -> None:
"""Send the turn on command to the ISY994 fan device."""
self.set_speed(speed)
def turn_off(self, **kwargs) -> None:
... |
eneldoserrata/marcos_openerp | addons/purchase/purchase.py | Python | agpl-3.0 | 67,788 | 0.007612 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | in self.pool.get('purchase.order.line').browse(cr, uid, ids, context=c | ontext):
result[line.order_id.id] = True
return result.keys()
def _invoiced(self, cursor, user, ids, name, arg, context=None):
res = {}
for purchase in self.browse(cursor, user, ids, context=context):
invoiced = False
if purchase.invoiced_rate == 100.00:
... |
mfem/PyMFEM | mfem/_par/sparsemat.py | Python | bsd-3-clause | 42,261 | 0.004023 | # This file was automatically generated by SWIG (http://www.swig.org).
# Version 4.0.2
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info < (2, 7, 0):
raise Runtime... | return _sparsemat.SparseMatrix_Clear(self)
Clear = _swig_new_instance_method(_sparsemat.SparseMatrix_Clear)
def ClearGPUSparse(self):
r"""ClearGPUSparse(SparseMatrix self)"""
return _sparsemat.SparseMatrix_ClearGPUSparse(self)
ClearGPUSparse = _swig_new_instance_method(_sparsemat.SparseMa... | Sparse(self)
ClearCuSparse = _swig_new_instance_method(_sparsemat.SparseMatrix_ClearCuSparse)
def Empty(self):
r"""Empty(SparseMatrix self) -> bool"""
return _sparsemat.SparseMatrix_Empty(self)
Empty = _swig_new_instance_method(_sparsemat.SparseMatrix_Empty)
def GetI(self, *args):
... |
scottrice/Ice | tests/managed_rom_archive_tests.py | Python | mit | 2,688 | 0.005952 |
import json
from mockito import *
import os
import shutil
import tempfile
import unittest
from ice.history import ManagedROMArchive
class ManagedROMArchiveTests(unittest.TestCase):
def setUp(self):
self.tempdir = tempfile.mkdtemp()
self.temppath = os.path.join(self.tempdir, "tempfile")
self.mock_user =... | elf.assertNotEqual(archive.previous_managed_ids(self.mock_user), new_ids)
archive.set_managed_ids(self.mock_user, ["1234567890"])
self.a | ssertEqual(archive.previous_managed_ids(self.mock_user), new_ids)
def test_creating_new_archive_after_set_managed_ids_uses_new_ids(self):
archive = ManagedROMArchive(self.temppath)
new_ids = ["1234567890"]
self.assertNotEqual(archive.previous_managed_ids(self.mock_user), new_ids)
archive.set_managed... |
dpgoetz/swift | swift/common/middleware/keystoneauth.py | Python | apache-2.0 | 25,905 | 0.000116 | # Copyright 2012 OpenStack Foundation
#
# 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... | eware to your pipeline::
[pipeline:main]
pipeline = catch_errors cache authtoken keystoneauth proxy-server
Make sure you have the authtoken middleware before the
keystoneauth middleware.
The authtoken middleware will take care of validating the user and
keystoneauth will authorize acc... | you can either
install it by copying the file directly in your python path or by
installing keystonemiddleware.
If support is required for unvalidated users (as with anonymous
access) or for formpost/staticweb/tempurl middleware, authtoken will
need to be configured with ``delay_auth_decision`` se... |
jarjun/EmergencyTextToVoiceCall | app/forms.py | Python | mit | 204 | 0.009804 | from f | lask.ext.wtf import Form
from wtforms import TextAreaField
from wtforms.validators import DataRequired
class Reques | tForm(Form):
inputText = TextAreaField('inputText', validators=[DataRequired()])
|
garinh/cs | docs/support/docutils/languages/de.py | Python | lgpl-2.1 | 1,814 | 0 | # Authors: David Goodger; Gunnar Schwant
# Contact: goodger@users.sourceforge.net
# Revision: $Revision: 21817 $
# Date: $Date: 2005-07-21 13:39:57 -0700 (Thu, 21 Jul 2005) $
# Copyright: This module has been | placed in the public domain.
# New language mappings are welcome. Before doing a new translation, please
# read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be
# translate | d for each language: one in docutils/languages, the other in
# docutils/parsers/rst/languages.
"""
German language mappings for language-dependent features of Docutils.
"""
__docformat__ = 'reStructuredText'
labels = {
'author': 'Autor',
'authors': 'Autoren',
'organization': 'Organisation',
'address'... |
salessandri/programming-contests | project-euler/problem076.py | Python | gpl-3.0 | 1,376 | 0.00218 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
########################################################################
# Solves problem 76 from projectEuler.net.
# Finds the number of different ways that 100 can be written as sum of
# 2 positive integers.
# Copyright (C) 2010 Santiago Alessandri
#
# This p... | Public License as published by
# the Free Software Foundation, | either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more ... |
moradin/renderdoc | util/test/tests/D3D11/D3D11_Texture_Zoo.py | Python | mit | 457 | 0.002188 | import rdtest
class D3D11_Texture_Zoo(rdtest.TestCase):
| slow_test = True
demos_test_name = 'D3D11_Texture_Zoo'
def __init__(self):
rdtest.TestCase.__init__(self)
self.zoo_helper = rdtest.Texture_Zoo()
def check_capture(self):
# This takes ownership of the controller | and shuts it down when it's finished
self.zoo_helper.check_capture(self.capture_filename, self.controller)
self.controller = None
|
ptr-yudai/JokenPC | server/JPC.py | Python | mit | 11,068 | 0.006781 | # coding: utf-8
from geventwebsocket.handler import WebSocketHandler
from gevent import pywsgi, sleep
import json
import MySQLdb
class JPC:
#
# 初期化
#
def __init__(self, filepath_config):
import hashlib
# 設定ファイルをロード
fp = open(filepath_config, 'r')
config = json.load(fp)
... |
# 解答数をインクリメント
cursor.execute("UPDATE problem SET solved=solved+1 WHERE id={id};".format(id=self.record['id']))
# 解答ユーザーを更新
cursor.execute("UPDATE problem SET solved_user='{user}' WHERE id={id};".format(user=self.user, id=self.record['id']))
# 解答時間を更新
cursor.execute("UPDA... | .commit()
return
#
# 新規要求を処理
#
def handle(self, env, response):
self.ws = env['wsgi.websocket']
print("[INFO] 新しい要求を受信しました。")
# 要求を取得
self.packet = self.ws.receive()
if not self.analyse_packet(): return
# 問題を取得
self.get_problem()
#... |
AlanCoding/tower-cli | tests/test_cli_action.py | Python | apache-2.0 | 2,582 | 0 | # Copyright 2015, Ansible, Inc.
# Luke Sneeringer <lsneeringer@ansible.com>
#
# 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 requi... | def test_dash_dash_help(self):
"""Establish that no_args_is_help causes the help to be printed,
and an exit.
"""
# Create a command with which to test.
@click.command(no_args_is_help=True, cls=ActionSubcommand)
@click.argument('parrot')
def foo(parrot):
... | h that this command sends help if called with nothing.
result = self.runner.invoke(foo)
self.assertIn('--help', result.output)
self.assertIn('Show this message and exit.\n', result.output)
def test_categorize_options(self):
"""Establish that options in help text are correctly catego... |
dbcls/dbcls-galaxy | lib/galaxy/datatypes/sniff.py | Python | mit | 9,773 | 0.014734 | """
File format detector
"""
import logging, sys, os, csv, tempfile, shutil, re, zipfile
import registry
from galaxy import util
log = logging.getLogger(__name__)
def get_test_fname(fname):
"""Returns test data filename"""
path, name = os.path.split(__file__)
full_path = os.path.join(path, 'test',... | st_fname('test_tab1.tabular')
>>> is_column_based(fname, sep=' ', skip=0)
False
>>> fname = get_test_fname('test_tab1.tabular')
>>> is_column_based(fname)
True
"""
headers = get_hea | ders( fname, sep, is_multi_byte=is_multi_byte )
count = 0
if not headers:
return False
for hdr in headers[skip:]:
if hdr and hdr[0] and not hdr[0].startswith('#'):
if len(hdr) > 1:
count = len(hdr)
break
if count < 2:
return False
for h... |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_09_01/operations/_virtual_router_peerings_operations.py | Python | mit | 22,524 | 0.004972 | # 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 ... | alizer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def _delete_initial(
self,
resource_group_name, # type: str
virtual_router_name, # type: str
peering_name, # type: str
**kwar... | Error, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-09-01"
accept = "application/json"
# Construct URL
url = self._delete_initial.metadata['url'] # type: ignore
path_format_arguments = {... |
a5kin/hecate | xentica/core/color_effects.py | Python | mit | 4,034 | 0 | """
The collection of decorators for the ``color()`` method, each CA model
should have.
The method should be decorated by one of the classes below, otherwise
the correct model behavior will not be guaranteed.
All decorators are get the ``(red, green, blue)`` tuple from
``color()`` method, then process it to create so... | ADE_OUT);
new_b = max(min(new_b, old_col.z + FADE_IN),
old_col.z - FADE_OUT);
"""
ret | urn super().__call__()
|
rescale/django-money | djmoney/settings.py | Python | bsd-3-clause | 987 | 0.001013 | # -*- coding: utf-8 -*-
import operator
from django.conf import settings
from moneyed import CURRENCIES, DEFAULT_CURRENCY, DEFAULT_CURRENCY_CODE
# The default currency, you can define this in your project's settings module
# This has to be a currency object imported from moneyed
DEFAULT_CURRENCY = getattr(settings,... | RENCY_CHOICES = [(code, CURRENCIES[code].name) for code in PROJECT_CURRENCIES]
else:
CURRENCY_CHOICES = [(c.code, c.name) for i, c in CURRENCIES.items() if
c.code | != DEFAULT_CURRENCY_CODE]
CURRENCY_CHOICES.sort(key=operator.itemgetter(1, 0))
DECIMAL_PLACES = getattr(settings, 'CURRENCY_DECIMAL_PLACES', 2)
|
antonszilasi/honeybeex | honeybeex/honeybee/radiance/command/gensky.py | Python | gpl-3.0 | 5,946 | 0.001177 | # coding=utf-8
from _commandbase import RadianceCommand
from ..datatype import RadiancePath, RadianceTuple
from ..parameters.gensky import GenskyParameters
import os
class Gensky(RadianceCommand):
u"""
gensky - Generate an annual Perez sky matrix from a weather tape.
The attributes for this class and th... | s for month, day and hour.
genskyParameters: Radiance parameters for gensky. If None Default
parameters will be set. You can use self.genskyParameters to view,
add or remove the parameters before executing the command.
Usage:
from honeybee.radiance.parameters.gensky import ... | ate and modify genskyParameters. In this case a sunny with no sun
# will be generated.
gnskyParam = GenSkyParameters()
gnskyParam.sunnySkyNoSun = True
# create the gensky Command.
gnsky = GenSky(monthDayHour=(1,1,11), genskyParameters=gnskyParam,
outputName = r'd:/sunnyW... |
openstack/keystone | keystone/common/policies/domain.py | Python | apache-2.0 | 3,937 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# | http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# 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 permis... | es import base
DEPRECATED_REASON = (
"The domain API is now aware of system scope and default roles."
)
deprecated_list_domains = policy.DeprecatedRule(
name=base.IDENTITY % 'list_domains',
check_str=base.RULE_ADMIN_REQUIRED,
deprecated_reason=DEPRECATED_REASON,
deprecated_since=versionutils.depre... |
hdm-dt-fb/rvt_model_services | process_model.py | Python | mit | 14,344 | 0.00251 | """ process_model.py
Usage:
process_model.py <command> <project_code> <full_model_path> [options]
Arguments:
command action to be run on model, like: qc, audit or dwf
currently available: qc, audit, dwf
project_code unique project code consis... | ]
if viewer:
viewer = "/viewer"
comma_concat_arg | s = ",".join([f"{k}={v}" for k, v in args.items()])
print(col.bold_blue(f"+process model job control started with command: {command}"))
print(col.bold_orange(f"-detected following root path:"))
print(f" {rms_paths.root}")
format_json = {"sort_keys": True, "indent": 4, "separators": (',', ': ')}
hashes_db = Tin... |
pepsipepsi/nodebox_opengl_python3 | examples/04-text/02-style.py | Python | bsd-3-clause | 687 | 0.039301 | import os, sys
sys.path.insert(0, os.pat | h.join("..",".."))
from nodebox.graphics.context import *
from nodebox.graphics import *
txt = Text("So long!\nThanks for all the fish.",
font = "Droid S | erif",
fontsize = 20,
fontweight = BOLD,
lineheight = 1.2,
fill = color(0.25))
# Text.style() can be used to style individual characters in the text.
# It takes a start index, a stop index, and optional styling parameters:
txt.style(9, len(txt), fontsize=txt.fontsize/2, fontweight=NORMAL)
de... |
UManPychron/pychron | pychron/processing/ratios/ratio_editor.py | Python | apache-2.0 | 4,353 | 0.003446 | # ===============================================================================
# Copyright 2014 Jake Ross
#
# 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... | intercept_ratio = nominal_value(niso.uvalue / diso.uvalue)
def plot_ratio(self, g, niso, diso):
niso.time_zero_offset = self.time_zero_offset
diso.time_zero_offset = self.time_zero_offset
fd = {'filter_outliers': True, 'std_devs': 2, 'iterations': 1}
niso.filter_outliers_dict = f | d
diso.filter_outliers_dict = fd
niso.dirty = True
diso.dirty = True
g.new_plot()
g.set_x_limits(min_=0, max_=100)
g.set_y_title(niso.name)
_,_,nl = g.new_series(niso.offset_xs, niso.ys, filter_outliers_dict=fd)
g.new_plot()
g.set_y_title(diso.na... |
hqpr/findyour3d | config/settings/local.py | Python | mit | 1,853 | 0.001079 | """
Local settings
- Run in Debug mode
- Use console backend for emails
- Add Django Debug Toolbar
- Add django-extensions as app
"""
from .base import * # noqa
# DEBUG
# ------------------------------------------------------------------------------
DEBUG = env.bool('DJANGO_DEBUG', default=True)
TEMPLATES[0]['OPT... | -------------------------------------
INTERNAL_IPS = ['127.0.0.1', '10.0.2.2', ]
DEBUG_TOOLBAR_CONFIG = {
'DISABLE_PANELS': [
'debug_toolbar.panels.redirects.RedirectsPanel',
| ],
'SHOW_TEMPLATE_CONTEXT': True,
}
# django-extensions
# ------------------------------------------------------------------------------
INSTALLED_APPS += ['django_extensions', ]
# TESTING
# ------------------------------------------------------------------------------
TEST_RUNNER = 'django.test.runner.Discove... |
Alberto-Beralix/Beralix | i386-squashfs-root/usr/lib/pymodules/python2.7/gwibber/microblog/urlshorter/zima.py | Python | gpl-3.0 | 56 | 0.017857 | / | usr/share/pyshared/gwibber/microblog/urlshorte | r/zima.py |
fandemonium/code | parsers/img_oid_to_ncbi_from_html.py | Python | mit | 234 | 0.004274 | import sys
import re
for lines in open(sys.argv[1], "rU"):
line = lines.strip()
lexemes = re.split(".out:", line) |
oid = lexemes[0].split(".")[1]
ncbi = re.split("val=|'", lexemes[1])[2]
print oid + " \t" + nc | bi
|
xuru/pyvisdk | pyvisdk/do/cluster_destroyed_event.py | Python | mit | 1,147 | 0.00959 |
import logging
from pyvisdk.except | ions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def ClusterDestroyedEvent(vim, *args, **kwargs):
'''This event records when a | cluster is destroyed.'''
obj = vim.client.factory.create('ns0:ClusterDestroyedEvent')
# do some validation checking...
if (len(args) + len(kwargs)) < 4:
raise IndexError('Expected at least 5 arguments got: %d' % len(args))
required = [ 'chainId', 'createdTime', 'key', 'userName' ]
op... |
napalm-automation/napalm-yang | napalm_yang/models/openconfig/interfaces/interface/subinterfaces/subinterface/ipv4/unnumbered/interface_ref/__init__.py | Python | apache-2.0 | 9,237 | 0.001191 | # -*- coding: utf-8 -*-
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClassType
from pyangbind.lib.yangtypes import TypedListType
from pyangbind.lib.yangtypes import YANGBool
from pyangbind.lib.yangtypes import YANGListTy... | if load is None:
setmethod(getattr(args[0], e))
else:
setmethod(geta | ttr(args[0], e), load=load)
def _path(self):
if hasattr(self, "_parent"):
return self._parent._path() + [self._yang_name]
else:
return [
"interfaces",
"interface",
"subinterfaces",
"subinterface",
... |
casep/Molido | sdate.py | Python | gpl-2.0 | 350 | 0.002857 | #!/usr/bin/env python
""" Calculate the Julian Date """
import time
import math
t = time.time()
""" Technically, we should be adding 2440587.5,
however, since we are trying to s | tick to the stardate
concept, we add only 40587.5"""
jd = (t / 86400.0 + 40587.5)
# Use the idea that 10 Julian days is eq | ual to 1 stardate
print "%05.2f" % jd
|
li282886931/apistore | robot/robot/news/eladies_sina_com_cn.py | Python | gpl-2.0 | 2,757 | 0.005261 | # -*- coding: utf-8 -*-
import sys
import time
import json
import datetime
import scrapy
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request
import robot
from robot.items import RobotItem
from robot.models.base import Base
from robot.settings import logger
class EladiedSinaComCnItem(RobotIt... | .url))
hxs = HtmlXPathSelector(response)
l = [
# 视觉大片
{'id': 'SI_Scroll_2_Cont', 'cl': 'photograph_gallery'},
# 八卦
{'id': 'SI_Scroll_3_Cont', 'cl': 'gossip'},
# 服饰搭配
| {'id': 'SI_Scroll_4_Cont', 'cl': 'style'},
# 美体瘦身
{'id': 'SI_Scroll_5_Cont', 'cl': 'body'},
# 彩妆美发
{'id': 'SI_Scroll_6_Cont', 'cl': 'beauty'},
]
for d in l:
sites = hxs.select('//div[@id="%s"]/div/div/a/@href' % d['id']).extract()
... |
AutorestCI/azure-sdk-for-python | azure-mgmt-compute/azure/mgmt/compute/v2017_03_30/operations/availability_sets_operations.py | Python | mit | 17,248 | 0.002609 | # 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 ... | eration_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: AvailabilitySet or Client | RawResponse if raw=true
:rtype: ~azure.mgmt.compute.v2017_03_30.models.AvailabilitySet or
~msrest.pipeline.ClientRawResponse
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
# Construct URL
url = '/subscriptions/{subscriptionId}/resourceGroups/{r... |
laowantong/mocodo | mocodo/tests/__init__.py | Python | mit | 33 | 0 | from __fu | ture__ import division
| |
iandennismiller/gthnk | src/gthnk/server.py | Python | mit | 1,615 | 0.000619 | # -*- coding: utf-8 -*-
# gthn | k (c) Ian Dennis Miller
import os |
import flask
import logging
from flaskext.markdown import Markdown
from mdx_linkify.mdx_linkify import LinkifyExtension
from mdx_journal import JournalExtension
from . import db, login_manager, bcrypt
from .models.day import Day
from .models.entry import Entry
from .models.page import Page
from .models.user import ... |
Richard-Mathie/cassandra_benchmark | vendor/github.com/datastax/python-driver/tests/integration/cqlengine/columns/test_validation.py | Python | apache-2.0 | 21,274 | 0.001081 | # Copyright 2013-2016 DataStax, 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 writi... | fic language governing permissions and
# limitations under the License.
try:
import unittest2 as unittest
except ImportError:
import unittest # noqa
import sys
from datetime import datetime, timedelta, date, tzinfo
from decimal import Decimal as D
from uuid import uuid4, uuid1
from cassandra import InvalidR... | e.columns import Text
from cassandra.cqlengine.columns import Integer
from cassandra.cqlengine.columns import BigInt
from cassandra.cqlengine.columns import VarInt
from cassandra.cqlengine.columns import DateTime
from cassandra.cqlengine.columns import Date
from cassandra.cqlengine.columns import UUID
from cassandra.cq... |
khertan/ownNotes | python/webdav/acp/Privilege.py | Python | gpl-3.0 | 4,423 | 0.007009 | # Copyright 2008 German Aerospace Center (DLR)
#
# 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... |
"""
| __privileges = list()
def __init__(self, privilege=None, domroot=None):
"""
Constructor should be called with either no parameters (create blank Privilege),
one parameter (a DOM tree or privilege name to initialize it directly).
@param domroot: A DOM tr... |
domin1101/malmo-challenge | malmopy/version.py | Python | mit | 1,232 | 0.007305 | # Copyright (c) 2017 Microsoft Corporation.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publis... | THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE | , ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ===================================================================================================================
VERSION = '0.1.0'
|
marcos-sb/quick-openstacked-hadoop | Alba/albaproject/mapred/models.py | Python | apache-2.0 | 2,416 | 0.009934 | from django.db import models
from django.contrib.auth.models import User
from albaproject.settings import MEDIA_ROOT
import pdb
def _upload_to_generic(prefix_path=None, instance=None, field=None, filename=None):
#pdb.set_trace()
if not instance.pk: # generate DB PK if not present
instance... | _upload_to_generic(None, self, 'mapred', filename)
def output_dest(self, filename):
return _upload_to_generic(None, self, 'output', filename)
def output_path(self):
return _upload_to_generic(MEDIA_ROOT, self, 'output', None)
user = models.ForeignKey(User)
file_inp... | nput_dest, null=True)
mapred_job = models.FileField(upload_to=mapred_dest, null=True)
fully_qualified_job_impl_class = models.CharField(max_length=200, null=True)
file_output = models.FileField(upload_to=output_dest, null=True)
submission_date = models.DateTimeField(auto_now_add=True)
class Server(mod... |
jbalogh/zamboni | apps/search/forms.py | Python | bsd-3-clause | 11,040 | 0.000815 | import collections
from django import forms
from django.forms.util import ErrorDict
from tower import ugettext as _, ugettext_lazy as _lazy
import amo
from amo import helpers
from applications.models import AppVersion
sort_by = (
('', _lazy(u'Keyword Match')),
('updated', _lazy(u'Updated', 'advanced_search_... | cat = forms.ChoiceField(choices=search_groups, required=False)
# This gets replaced by a <select> with js.
lver = forms.ChoiceField(
label=_(u'{0} Version').format(unicode(current_app.pretty)),
choices=get_app_versions(current_app), required=False)
appver = fo... | r t in amo.ADDON_SEARCH_TYPES],
required=False, coerce=int, empty_value=amo.ADDON_ANY)
pid = forms.TypedChoiceField(label=_('Platform'),
choices=[(p[0], p[1].name) for p in amo.PLATFORMS.iteritems()
if p[1] != amo.PLATFORM_ANY], required=False,
... |
rajul/tvb-framework | tvb/config/logger/cluster_handler.py | Python | gpl-2.0 | 3,331 | 0.006304 | # -*- coding: utf-8 -*-
#
#
# TheVirtualBrain-Framework Package. This package holds all Data Management, and
# Web-UI helpful to run brain-simulations. To use it, you also need do download
# TheVirtualBrain-Scientific Package (for simulators). See content of the
# documentation-folder for more details. See also http:/... | ile where code from Web application will be stored
WEB_LOG_FILE = "web_application.log"
# Name of the file where to write logs from the code executed on cluster nodes
CLUSTER_NODES_LOG_FILE = "operations_executions.log"
# Size of the buffer which store log entries in memory
# in number of lines
... | ', interval=1, backupCount=0):
"""
Constructor for logging formatter.
"""
# Formatting string
format_str = '%(asctime)s - %(levelname)s'
if TvbProfile.current.cluster.IN_OPERATION_EXECUTION_PROCESS:
log_file = self.CLUSTER_NODES_LOG_FILE
if TvbProf... |
chrisboo/pyhistogram | examples/plot_simple_1D_hist_example.py | Python | gpl-3.0 | 478 | 0 | """
===============================================
Demonstration for filling a histogram in a loop
===============================================
A simple, one dimensional histogram is filled in a loop with random
values. The result is than plotted with the build in plot com | mand.
"""
from pyhistogram import Hist
import numpy as np
import matplotlib.pyplot as plt
h = Hist(20, -5, 5)
sampl | e = np.random.normal(size=500)
for v in sample:
h.fill(v)
h.plot()
plt.show()
|
opennode/nodeconductor-assembly-waldur | src/waldur_rancher/management/commands/sync_users.py | Python | mit | 986 | 0.004057 | import logging
from django.core.management.base import BaseCommand
from waldur_rancher.utils import SyncUser
logger = logging.getLogger(__name__)
class Command(BaseCommand):
h | elp = """Sync users from Waldur to Rancher."""
def handle(self, *args, **options):
def print_message(count, action, name='user'):
| if count == 1:
self.stdout.write(
self.style.SUCCESS('%s %s has been %s.' % (count, name, action))
)
else:
self.stdout.write(
self.style.SUCCESS('%s %ss have been %s.' % (count, name, action))
)
... |
didrocks/cupstream2distro | cupstream2distro/utils.py | Python | gpl-3.0 | 904 | 0 | # -*- coding: utf-8 -*-
# Copyright (C) 2013 Canonical
#
# Authors:
# Didier Roche
#
# This program is free software; you can redistribute it and/or modify it under
# the terms o | f the GNU General Public License as published by the Free Software
# Foundation; version 3.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty | of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-130... |
linky00/pythonthegathering | test.py | Python | mit | 209 | 0.009569 | from pythonthegathering import ManaPool, spell
pool = ManaPoo | l()
@spell('WBB')
def boop(x):
p | rint(x)
pool.tap('plains').tap('swamp').tap('swamp')
boop('boop', mana_pool=pool, mana_pay={'W': 1, 'B': 2})
|
robertdown/atlas_docs | atlas_doc/migrations/0008_auto_20170828_0043.py | Python | gpl-3.0 | 461 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-28 04:43
fr | om __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('atlas_doc', '0007_page_version'),
]
opera | tions = [
migrations.AlterField(
model_name='collection',
name='prev_rev',
field=models.UUIDField(blank=True, null=True),
),
]
|
droundy/deft | papers/hughes-saft/figs/density_calc.py | Python | gpl-2.0 | 986 | 0.004057 | #!/usr/bin/env python
import math
fin = open('figs/single-rod-in-water.dat', 'r')
fout = open('figs/single-rods-calculated-density.dat', 'w')
kB = 3.16681539628059e-6 # This is Boltzmann's constant in Hartree/Kelvin
first = 1
nm = 18.8972613
for line in fin:
| current = str(line)
pieces = current.split('\t')
if first:
r2 = float(pieces[0])/2*nm
E2 = float(pieces[1])
first = 0
else:
if ((float(pieces[0])/2*nm - r2) > 0.25):
r1 = r2
r2 = float(pieces[0])/2*nm
E1 = E2
E2 = float(piece... | actually it's energy per unit length!
length = 1 # arbitrary
r = (r1 + r2)/2
dEdR = (E2-E1)/(r2-r1)*length
area = 2*math.pi*r*length
force = dEdR
pressure = force/area
kT = kB*298 # about this
ncontact = pressure/kT
... |
jennywoites/MUSSA | MUSSA_Flask/app/API_Rest/Services/AlumnoServices/EncuestaAlumnoService.py | Python | gpl-3.0 | 6,276 | 0.002709 | from flask_user import login_required
from app.API_Rest.Services.BaseService import BaseService
from app.models.generadorJSON.respuestas_encuestas_generadorJSON import generarJSON_encuesta_alumno
from app.models.respuestas_encuesta_models import EncuestaAlumno, RespuestaEncuestaTematica, RespuestaEncuestaTags
from app.... |
if not parametros_son_validos:
self.logg_error(msj)
return {'Error': msj}, codigo
encuesta = EncuestaAlumno.query.get(idEncuestaAlumno)
encuesta.finalizada = finaliza | da
db.session.commit()
materiaAlumno = MateriasAlumno.query.get(encuesta.materia_alumno_id)
self.agregarPalabrasClavesALasMaterias(encuesta, materiaAlumno.materia_id)
self.agregarTematicasALasMaterias(encuesta, materiaAlumno.materia_id)
self.actualizar_puntaje_y_cantidad_encues... |
margulies/surfdist | nipype/surfdist_nipype.py | Python | mit | 8,586 | 0.02737 | #!/usr/bin/env python
from nipype.interfaces.io import FreeSurferSource, DataSink
from nipype.interfaces.utility import IdentityInterface
from nipype import Workflow, Node, MapNode, JoinNode, Function
import nibabel as nib
import numpy as np
import os
import surfdist as sd
import csv
def trimming(itemz, phrase):
it... | e
def create_surfdist_workflow(subjects_dir,
subject_list,
| sources,
target,
hemi,
atlas,
labs,
name):
sd = Workflow(name=name)
# Run a separate tree for each template, hemisphere and source structure
infosource = No... |
eunchong/build | third_party/twisted_10_2/twisted/protocols/ftp.py | Python | bsd-3-clause | 93,283 | 0.002969 | # -*- test-case-name: twisted.test.test_ftp -*-
# Copyright (c) 2001-2010 Twisted Matrix Laboratories.
# See LICENSE for details.
"""
An FTP protocol implementation
@author: Itamar Shtull-Trauring
@author: Jp Calderone
@author: Andrew Bennetts
"""
# System Imports
import os
import time
import re
import operator
impo... | OME_MSG = "220.2"
SVC_CLOSING_CTRL_CNX = "221"
GOODBYE_MSG = "221"
DATA_CNX_OPEN_NO_XFR_IN_PROGRESS = "225"
CLOSING_DATA_CNX = "226"
TXFR_COMPLETE_OK = "226"
ENTERING_PASV_MODE ... | ED_IN_PROCEED = "230.1" # v1 of code 230
GUEST_LOGGED_IN_PROCEED = "230.2" # v2 of code 230
REQ_FILE_ACTN_COMPLETED_OK = "250"
PWD_REPLY = "257.1"
MKD_REPLY = "257.2"
USR_NAME_OK_NEED_PASS ... |
coolharsh55/hdd-indexer | setup.py | Python | mit | 8,480 | 0 | """Setup for HDD-indexer
This module provides the setup for ``hdd-indexer`` by downloading its
`dependencies`, creating the `database`, createing a sampel `user`.
Usage:
$ python setup.py
Dependencies:
The dependencies are installed with pip.
$ pip install -r requirements.txt
Database:
The d... | py', 'migrate']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
for line in p.stdout:
print line,
p.wait()
if p.returncode:
print 'ERROR! ERROR! ERROR!'
return
SETUP_STATUS['database_migrate'] = True
pickle_setup(SETUP_STATUS)
raw_input("Press Enter to continue...")... | ser
cls()
print "Now that it's done, let's create a user for you!"
print '----------------------'
print "username: user"
print "password: pass"
print '----------------------'
print "You ready?"
raw_input("Press Enter to continue...")
# load django's settings
os.environ.setdefault... |
dayatz/taiga-back | taiga/celery.py | Python | agpl-3.0 | 1,321 | 0.000758 | # -*- coding: utf-8 -*-
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
# This program is free software: you can r... | undation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILIT | Y or FITNESS 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/>.
import os
from celery import Celery
os.environ.setdefault('DJANGO_... |
mrgloom/menpofit | menpofit/modelinstance.py | Python | bsd-3-clause | 11,665 | 0.000171 | import numpy as np
from menpo.base import Targetable, Vectorizable
from menpo.model import MeanInstanceLinearModel
from menpofit.differentiable import DP
def similarity_2d_instance_model(shape):
r"""
A MeanInstanceLinearModel that encodes all possible 2D similarity
transforms of a 2D shape (of n_points).... | nsform`
:type: int
"""
return self.global_transform.n_parameters
@property
def global_parameters(self):
| r"""
The parameters for the global transform.
:type: (`n_global_parameters`,) ndarray
"""
return self.global_transform.as_vector()
def _new_target_from_state(self):
r"""
Return the appropriate target for the model weights provided,
accounting for the effect ... |
mattsch/Sickbeard | sickbeard/tvcache.py | Python | gpl-3.0 | 1,097 | 0.012762 | import time
import datetime
import sqlite3
import urllib
import gzip
import urllib2
import StringIO
import sickbeard
from sickbeard import db
from sickbeard import logger
from sickbeard.common import *
class TVCache():
def __init__(self, providerName):
self.providerName = pr... |
return db.DBConnection("cache.db")
def _clearCache(self):
myDB = self._getDB()
myDB.action("DELETE FROM "+self.providerName+" WHERE 1")
def updateCache(self):
print "This should be overridden by implementing classes"
... | f searchCache(self, show, season, episode, quality=ANY):
myDB = self._getDB()
sql = "SELECT * FROM "+self.providerName+" WHERE tvdbid = "+str(show.tvdbid)+ \
" AND season = "+str(season)+" AND episode = "+str(episode)
if quality != ANY:
sql +=... |
ekohl/ganeti | lib/opcodes.py | Python | gpl-2.0 | 47,432 | 0.005081 | #
#
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
... | _CheckFileStorage)
def _CheckStorageType(storage_type):
"""Ensure a given storage type is valid.
"""
if storage_type not in constants.VALID_STORAGE_TYPES:
raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
| errors.ECODE_INVAL)
if storage_type == constants.ST_FILE:
RequireFileStorage()
return True
#: Storage type parameter
_PStorageType = ("storage_type", ht.NoDefault, _CheckStorageType,
"Storage type")
class _AutoOpParamSlots(type):
"""Meta class for opcode definitions.
""... |
galaxy-iuc/parsec | parsec/commands/workflows/run_workflow.py | Python | apache-2.0 | 4,029 | 0.001986 | import click
from parsec.cli import pass_context, json_loads
from parsec.decorators import custom_exception, json_output
@click.command('run_workflow')
@click.argument("workflow_id", type=str)
@click.option(
"--dataset_map",
help="A mapping of workflow inputs to datasets. The datasets source can be a LibraryD... | y.",
type=str
)
@click.option(
"--history_name",
help="Create a new history with the given name to store the workflow output. If both ``history_id`` and ``hist | ory_name`` are provided, ``history_name`` is ignored. If neither is specified, a new 'Unnamed history' is created.",
type=str
)
@click.option(
"--import_inputs_to_history",
help="If ``True``, used workflow inputs will be imported into the history. If ``False``, only workflow outputs will be visible in the g... |
AXAz0r/apex-sigma-core | sigma/modules/minigames/racing/nodes/race_storage.py | Python | gpl-3.0 | 1,238 | 0 | import copy
import secrets
races = {}
colors = {
'🐶': 0xccd6dd,
'🐱': 0xffcb4e,
'🐭': 0x99aab5,
'🐰': 0x99aab5,
'🐙': 0x9266cc,
'🐠': 0xffcc4d,
'🦊': 0xf4900c,
'🦀': 0xbe1931,
'🐸': 0x77b255,
'🐧': 0xf5f8fa
}
names = {
'🐶': 'dog',
'🐱': ' | cat',
'🐭': 'mouse',
'🐰': 'rabbit',
'🐙': 'octopus',
'🐠': 'fish',
'🦊': 'fox',
'🦀': 'crab',
'🐸': 'frog',
'🐧': 'penguin'
}
participant_icons = ['🐶', '🐱', '🐭', '🐰', '🐙', '🐠', '🦊', '🦀', '🐸', '🐧']
def make_race(channel_id, buyin):
icon_copy = copy.deepcopy(participant_ic... | s)
race_data = {
'icons': icon_copy,
'users': [],
'buyin': buyin
}
races.update({channel_id: race_data})
def add_participant(channel_id, user):
race = races[channel_id]
icons = race['icons']
users = race['users']
usr_icon = secrets.choice(icons)
icons.remove(usr... |
andrewisakov/taximaster_x | router/main.py | Python | unlicense | 572 | 0 | #!/usr/bin/python3
import tornado.ioloop
import tornado.options
import tornado.httpserver
fr | om routes import routes_setup
import settings
clients = []
if __name__ == '__main__':
tornado.options.parse_command_line()
tornado.options.define('log_file_max_size', default=str(10*1024*1024))
tornado.options.define('log_file_prefix', default='router.log')
app = tornado.web.Application(routes_setup... | ttp_server.listen(settings.PORT)
tornado.ioloop.IOLoop.current().start()
|
ujdhesa/unisubs | apps/statistic/migrations/0001_initial.py | Python | agpl-3.0 | 10,707 | 0.008219 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'EmailShareStatistic'
db.create_table('statistic_emailsharestatistic', (
('... | ,
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.CustomUser'], null=True, blank=True)),
))
db.send_create_signal('statistic', ['EmailShare | Statistic'])
# Adding model 'TweeterShareStatistic'
db.create_table('statistic_tweetersharestatistic', (
('created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
... |
facebookresearch/Detectron | detectron/datasets/cityscapes_json_dataset_evaluator.py | Python | apache-2.0 | 3,355 | 0 | # Copyright (c) 2017-present, Facebook, In | c.
#
# 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 und... | S,
# 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.
##############################################################################
"""Functions for evaluating results on Cityscapes."""
from... |
zstackorg/zstack-woodpecker | integrationtest/vm/hybrid/test_add_iz.py | Python | apache-2.0 | 623 | 0.004815 | '''
New Integration Test for hybrid.
@author: Quarkonics
'''
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_lib as test_lib
im | port zstackwoodpecker.test_state as test_state
test_obj_dict = test_state.TestStateDict()
test_stub = test_lib.lib_get_test_stub()
hybrid = test_stub.HybridObject()
def test():
hybrid.add_datacenter_iz()
hybrid.del_iz()
test_util.test_pass('Add Delete Identity Zone Test Success')
#Will be call... | test().
def error_cleanup():
global test_obj_dict
test_lib.lib_error_cleanup(test_obj_dict)
|
nickpascucci/Robot-Arm | software/desktop/brazo/brazo_lib/preferences.py | Python | mit | 3,116 | 0.007702 | # -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
### BEGIN LICENSE
# This file is in the public domain
### END LICENSE
"""Provides a shared preferences dictionary"""
from desktopcouch.records.server import CouchDatabase
from desktopcouch.records.record import Record
import gtk
import gobject... | gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
'loaded' : (gobject.SIGNAL_RUN_LAST,
gobject.TYPE_NONE, (gobject.TYPE_PYOBJ | ECT,))}
publisher = Publisher()
self.emit = publisher.emit
self.connect = publisher.connect
def db_connect(self):
'''connect to couchdb
create if necessary'''
# logging.basicConfig will be called now
self._database = CouchDatabase(self._db... |
Pasotaku/Anime-Feud-Survey-Backend | Old Python Code/settings_db_init.py | Python | mit | 617 | 0.001621 | import sqlite3
import os
def init():
"""
Creates and initializes settings database.
Doesn't do anything if | the file already exists. Remove the local copy to recreate the database.
"""
if not os.path.isfile("settings.sqlite"):
app_db_connection = sqlite3.connect('settings.sqlite')
app_db = app_db_connection.cursor()
app_db.execute("CREATE TABLE oauth (site, rate_remaining, rate_reset)")
... | onnection.close()
if __name__ == "__main__":
init()
|
dan-git/outdoor_bot | src/outdoor_bot/msg/_mainTargetsCommand_msg.py | Python | bsd-2-clause | 4,588 | 0.017873 | """autogenerated by genpy from outdoor_bot/mainTargetsCommand_msg.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class mainTargetsCommand_msg(genpy.Message):
_md5sum = "b1faa92c8dffb7694c609d94e4e2d116"
_type = "outdoor_bot/mainTargetsCommand_ms... | param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwds:
super(mainTargetsCommand_msg, self).__init__(*args, **kwds)
#message fields cannot be None, assign default values for t... | if self.zoomDigcamZoom is None:
self.zoomDigcamZoom = 0
if self.homeDigcamZoom is None:
self.homeDigcamZoom = 0
if self.approxRange is None:
self.approxRange = 0.
if self.firstTarget is None:
self.firstTarget = False
else:
self.cameraName = 0
self.r... |
jamesthechamp/zamboni | mkt/operators/helpers.py | Python | bsd-3-clause | 360 | 0 | imp | ort jinja2
from jingo import register
from tower import ugettext_lazy as _lazy
from mkt.site.helpers import page_title
@register.function
@jinja2.contextfunction
def operators_page_title(context, title=None):
section = _lazy('Operator Dashboard')
title = u'%s | %s' % (title, section) if title else section
... | tle)
|
malaonline/Server | server/app/migrations/0186_change_user_group.py | Python | mit | 7,213 | 0.000161 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
group_and_permission = [
("超级管理员", [], ['all']),
("运营部", ['Can change teacher'],
[
# 待上架, 已上架老师, 老师编辑
'teachers_unpublished',
'teachers_published',
'teachers_unpublished_e... | # 课程列表, 投诉, 考勤
'school_timeslot',
# 中心设置, 编辑
'schools',
'staff_school',
# 订单查看, 申请退费
'orders_review',
'orders_action',
# 奖学金设置, 领用列表
'coupon_config',
'coupons_list',
]),
("财务主管", [],
[
# 教师银行卡查询
... | kcard_list',
# 订单查看, 申请退费, 审核
'orders_review',
'orders_refund',
'orders_action',
# 老师收入列表, 收入明细, 提现审核
'teachers_income_list',
'teachers_income_detail',
'teachers_withdrawal_list',
# 奖学金, 领用列表
'coupons_list',
# 校区收入记录(财务)
... |
rgeorgi/intent | intent/tests/instance_construction_tests.py | Python | mit | 718 | 0.009749 | from unittest import TestCase
from intent.igt.rgxigt import RGIgt
class ConstructIGTTests(TestCase):
def setUp(self):
self.lines = [{'text':'This is a test','tag':'L'},
{'text':'blah blah blah blah','tag':'G'}]
def test_add_raw_lines(self):
| inst = RGIgt(id='i1')
inst.add_raw_tier(self.lines)
self.assertEqual(len(inst.raw_tier()), 2)
def test_add_clean_lines(self):
inst = RGIgt(id='i1')
inst.add_clean_tier(self.lines)
self.assertEqual(len(inst.clean_tier()), 2)
def test_add_norm_lines(self):
inst ... | inst.add_clean_tier(self.lines)
self.assertEqual(len(inst.clean_tier()), 2) |
xesscorp/KiCost | kicost/distributors/__init__.py | Python | mit | 3,347 | 0.000299 | # -*- coding: utf-8 -*-
# MIT license
#
# Copyright (C) 2018 by XESS Corporation / Hildo Guillardi Júnior
#
# 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 with... | get_dist_name_from_label(label):
''' Returns the internal distributor name for a provided label. '''
return distributor_class.label2name.get(label.lower())
def set_distributors_logger(logger):
''' Sets the logger used by the class '''
distributor_class.logger = logger
def set_distributors_progress(c... | d to indicate progress '''
distributor_class.progress = cls
def set_api_options(api, **kwargs):
''' Configure an API (by name) '''
distributor_class.set_api_options(api, **kwargs)
def set_api_status(api, enabled):
''' Enable/Disable a particular API '''
distributor_class.set_api_status(api, enab... |
Linaro/squad | test/test_code_quality.py | Python | agpl-3.0 | 285 | 0 | import subprocess
import shutil
from unittest import TestCase
if shutil.which('flake8'):
class TestCodeQualit | y(TestCase):
def test_flake8(self):
self.assertEqual(0, subprocess.call( | 'flake8'))
else:
print("I: skipping flake8 test (flake8 not available)")
|
matthewkenzie/gammacombo | scripts/plotModuleExample.py | Python | gpl-3.0 | 1,823 | 0.044981 | #!/usr/bin/env python
import ROOT as r
def setTextBoxAttributes(text, color, font):
text.SetTextColor(color)
text.SetTextAlign(13)
text.SetTextSize(0.04)
text.SetTextFont(font)
def | dress(canv, colors):
# need this to keep the objects alive
objs = []
vub_inc = r.TLatex(0.16,0.655,"V_{ub} inclusive")
vub_inc.SetNDC()
vub_inc.Draw("same")
objs.append(vub_inc)
vcb_inc = r.TLatex(0.68,0.72,"V_{cb} inclusive")
vcb_inc.SetNDC()
vcb_inc.SetTextAngle(90)
vcb_inc.Draw("same")
obj... | 0.72,"V_{cb} exclusive")
vcb_excl.SetNDC()
vcb_excl.SetTextAngle(90)
vcb_excl.Draw("same")
objs.append(vcb_excl)
vub_vcb_lhcb = r.TLatex(0.17,0.29,"V_{ub}/V_{cb} LHCb")
vub_vcb_lhcb.SetNDC()
vub_vcb_lhcb.SetTextAngle(8)
vub_vcb_lhcb.Draw("same")
objs.append(vub_vcb_lhcb)
indirect = r.TLatex(0.17,0... |
smurfix/HomEvenT | test/mod_path.py | Python | gpl-3.0 | 1,386 | 0.025271 | #!/usr/bin/python
# -*- coding: utf-8 -*-
##
## Copyright © 2007-2012, Matthias Urlichs <matthias@urlichs.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 License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public Lice... | mport load_module
from homevent.statement import main_words
from test import run
input = """\
block:
if exists path "..":
log DEBUG Yes
else:
log DEBUG No1
if exists path "...":
log DEBUG No2
else:
log DEBUG Yes
if exists directory "..":
log DEBUG Yes
else:
log DEBUG No3
if exists directory "README"... |
emanuelcovaci/TLT | blog/contact/forms.py | Python | agpl-3.0 | 1,487 | 0.000672 | from django.core.validators import validate_email
from django import forms
from captcha.fields import ReCaptchaField
from .models import ContactUs
class CreateContact(forms.ModelForm):
captcha = ReCaptchaField()
class Meta:
model = ContactUs
fields = '__all__'
widgets = {
... | ed_data['email']
if validate_email(email):
raise forms.ValidationError("Adresa de email nu e valida")
return email
def clean_last_name(self):
last_name = self.cleaned_data['last_name']
| if not last_name.isalpha():
raise forms.ValidationError("Introdu un nume corect")
return last_name
def clean_message(self):
message = self.cleaned_data['message']
if len(message) < 50:
raise forms.ValidationError(
"Mesajul tau e prea scurt!"
... |
DCOD-OpenSource/django-simple-help | simple_help/admin.py | Python | mit | 1,108 | 0.000903 | # -*- coding: utf-8 -*-
# django-simple-help
# simple_help/admin.py
from __future__ import unicode_literals
from django.contrib import admin
try: # add modeltranslation
from modeltranslation.translator import translator
from modeltranslation.admin import TabbedDjangoJqueryTranslationAdmin
except ImportErro... | translator.register(PageHelp, PageHelpTranslationOptions)
# registering admi | n custom classes
admin.site.register(PageHelp, PageHelpAdmin)
|
iem-projects/WILMAmix | WILMA/net/resolv.py | Python | gpl-2.0 | 2,201 | 0.011369 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright © 2013, IOhannes m zmölnig, IEM
# This file is part of WILMix
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of th... | ill 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 WILMix. If not, see <http://www.gnu.org/licen... | e: prefer IPv6 addresses (if there are none, the function might still return IPv4)
# IPv6=false: prefer IPv4 addresses (if there are none, the function might still return IPv6)
# IPv6=None: first available address returned
info=QHostInfo()
adr=info.fromName(hostname).addresses()
if not adr: return None
... |
morenopc/edx-platform | lms/djangoapps/courseware/tests/test_views.py | Python | agpl-3.0 | 21,213 | 0.002641 | # coding=UTF-8
"""
Tests courseware views.py
"""
import unittest
from datetime import datetime
from mock import MagicMock, patch
from pytz import UTC
from django.test import TestCase
from django.http import Http404
from django.test.utils import override_settings
from django.contrib.auth.models import User, AnonymousU... | (Http404, views.redirect_to_course_position,
mock_module)
def test_registered_for_course(self):
self.assertFalse(views.registered_for_co | urse('Basketweaving', None))
mock_user = MagicMock()
mock_user.is_authenticated.return_value = False
self.assertFalse(views.registered_for_course('dummy', mock_user))
mock_course = MagicMock()
mock_course.id = self.course_key
self.assertTrue(views.registered_for_course(mo... |
dmulholland/ivy | ivy/ext/ivy_jinja.py | Python | unlicense | 1,779 | 0.000562 | # ------------------------------------------------------------------------------
# This extension adds support for Jinja templates.
# ------------------------------------------------------------------------------
impor | t sys
from ivy import hooks, site, templates
try:
import jinja2
except ImportError:
jinja2 = None
# Stores an initialized Jinja environment instance.
env = None
# The jinja2 package is an optional dependency.
if jinja2:
# Initialize our Jinja environment on the 'init' event hook.
@hooks.register('... | settings = {
'loader': jinja2.FileSystemLoader(site.theme('templates'))
}
# Check the site's config file for any custom settings.
settings.update(site.config.get('jinja', {}))
# Initialize an Environment instance.
global env
env = jinja2.Environment(*... |
algochecker/algochecker-web | webapp/forms.py | Python | mit | 6,858 | 0.001896 | from django import forms
from django.forms import Form, ModelForm
from django.utils import timezone
from webapp.models import Task, TaskGroup, TaskGroupSet
from webapp.validators import validate_package
from webapp.widgets import CustomSplitDateTimeWidget
class TaskGroupForm(ModelForm):
class Meta:
model... |
)
class CopyTaskGroup(Form):
name = forms.CharField(
label='New name',
widget=forms.TextInput(attrs={'placeholder': 'New name'}),
required=True
)
description = form | s.CharField(
label='Description',
widget=forms.Textarea(attrs={'placeholder': 'Type in new description (optional)'}),
required=False
)
class TaskGroupSetForm(ModelForm):
class Meta:
model = TaskGroupSet
fields = '__all__'
exclude = ['task_group']
labels ... |
Brocade-OpenSource/OpenStack-DNRM-Neutron | neutron/db/migration/alembic_migrations/versions/1d76643bcec4_nvp_netbinding.py | Python | apache-2.0 | 2,023 | 0.001483 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2013 OpenStack Foundation
#
# 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... | governing permissions and limitations
# under | the License.
#
"""nvp_netbinding
Revision ID: 1d76643bcec4
Revises: 3cb5d900c5de
Create Date: 2013-01-15 07:36:10.024346
"""
# revision identifiers, used by Alembic.
revision = '1d76643bcec4'
down_revision = '3cb5d900c5de'
# Change to ['*'] if this migration applies to all plugins
migration_for_plugins = [
'n... |
tsmrachel/remo | remo/dashboard/admin.py | Python | bsd-3-clause | 835 | 0 | from django.contrib import admin
from django.utils.encoding import smart_text
from import_export.admin import ExportMixin
from remo.dashboard.models import ActionItem
def encode_action_item_names(modeladmin, request, queryset):
for obj in queryset:
ActionItem.objects.filter(pk=obj.id).update(name=smart_... | tem
list_display = ('__unicode__', 'user', 'due_date', 'created_on',
'priority', 'updated_on', 'object_id',)
search_fields = ['user__first_name', 'user__last_ | name',
'user__userprofile__display_name', 'name']
actions = [encode_action_item_names]
admin.site.register(ActionItem, ActionItemAdmin)
|
geminy/aidear | oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/build/android/play_services/preprocess.py | Python | gpl-3.0 | 9,974 | 0.008823 | #!/usr/bin/env python
#
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''Prepares the Google Play services split client libraries before usage by
Chrome's build system.
We need to preprocess Google Play... | args.out_dir,
args.config_file,
args.is_extracted_repo)
def ProcessGooglePlayServices(repo, out_dir, config_path, is_extracted_repo):
config = utils.ConfigParser(config_path)
tmp_root = tempfile.mkdtemp()
try:
tmp_paths = ... | mpDir(tmp_root)
if is_extracted_repo:
_ImportFromExtractedRepo(config, tmp_paths, repo)
else:
_ImportFromAars(config, tmp_paths, repo)
_GenerateCombinedJar(tmp_paths)
_ProcessResources(config, tmp_paths, repo)
_BuildOutput(config, tmp_paths, out_dir)
finally:
shutil.rmtree(tmp_ro... |
coreboot/chrome-ec | extra/cr50_rma_open/cr50_rma_open.py | Python | bsd-3-clause | 26,490 | 0.000227 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2018 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Used to access the cr50 console and handle RMA Open
"""Open cr50 using RMA authentication.
Run RMA Open ... | cant communicate with any of the consoles.
Try Running cr50_rma_open again. If it still fails unplug the ccd cable
for 5 seconds and plug it back in.
"""
DEBUG_TOO_MANY_USB_DEVICES = """
DEBUG SELECT USB:
More than one cr50 usb device was found. Disconnect all but one device
or use the -s option with the correct usb ... | _BOARD_ID = """
DEBUG ERASED BOARD ID:
If you are using a prePVT device run
/usr/share/cros/cr50-set-board-id.sh proto
If you are running a MP device, please talk to someone.
"""
DEBUG_AUTHCODE_MISMATCH = """
DEBUG AUTHCODE MISMATCH:
- Check the URL matches the one generated by the last cr50_rma_open
run.
... |
vfilimonov/pydatastream | pydatastream/pydatastream.py | Python | mit | 32,857 | 0.002404 | """ pydatastream main module
(c) Vladimir Filimonov, 2013 - 2021
"""
import warnings
import json
import math
from functools import wraps
import requests
import pandas as pd
###############################################################################
_URL = 'https://product.datastream.com/dswsclient/V1/DSServic... | #######################################################
def _convert_date(date):
""" Convert date to YYYY-MM-DD """
if date is None:
return ''
if isinstance(date, str) and (date.upper() == 'BDATE'):
return 'BDATE'
return pd.Timestamp(date).strftime('%Y-%m-%d')
def _parse | _dates(dates):
""" Parse dates
Example:
/Date(1565817068486) -> 2019-08-14T21:11:08.486000000
/Date(1565568000000+0000) -> 2019-08-12T00:00:00.000000000
"""
if dates is None:
return None
if isinstance(dates, str):
return pd.Timestamp(_parse_dates([d... |
renqianluo/DLT2T | DLT2T/utils/registry_test.py | Python | apache-2.0 | 7,045 | 0.008375 | # coding=utf-8
# Copyright 2017 The DLT2T Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | MyDefaultModality(modality.Modality):
pass
| self.assertTrue(registry.symbol_modality() is MyDefaultModality)
def testList(self):
@registry.register_symbol_modality
class MySymbolModality(modality.Modality):
pass
@registry.register_audio_modality
class MyAudioModality(modality.Modality):
pass
@registry.register_image_modal... |
matheusmonte/PythonScripts | Salario078.py | Python | mit | 62 | 0.016129 | salario | = float(raw_input())
print( | salario + (salario * 0.78)) |
TechJournalist/stackalytics | tests/unit/test_web_utils.py | Python | apache-2.0 | 3,954 | 0.000506 | # Copyright (c) 2013 Mirantis 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 writi... | net/cinder/+spec/'
'super-driver" class="ext_link">super-driver</a>' + '\n' +
'Change-Id: <a href="https://review.openstack.org/#q,'
'Ie49ccd2138905e17 | 8843b375a9b16c3fe572d1db,n,z" class="ext_link">'
'Ie49ccd2138905e178843b375a9b16c3fe572d1db</a>')
observed = web.make_commit_message(record)
self.assertEqual(expected, observed,
'Commit message should be processed correctly')
@mock.patch('dashboard.web.get_vau... |
decvalts/landlab | landlab/components/stream_power/stream_power.py | Python | mit | 17,514 | 0.010049 | from __future__ import print_function
import numpy as np
from landlab import ModelParameterDictionary
from landlab.core.model_parameter_dictionary import MissingKeyError, ParameterValueError
from landlab.field.scalar_data_fields import FieldError
from landlab.grid.base import BAD_INDEX_VALUE
class StreamPowerEroder(... | s=None,
W_if_used=None, Q_if_used=None, K_if_used=None):
"""
A simple, explicit implementation of a stream power algorithm.
*grid* & *dt* are the grid object and timestep (floa | t) respectively.
*node_elevs* is the elevations on the grid, either a field string or
n |
DTOcean/dtocean-core | example_data/fixed_tidal_fixed_layout_10_scenario.py | Python | gpl-3.0 | 31,371 | 0.008288 | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 09 10:39:38 2015
@author: 108630
"""
import os
import numpy as np
import pandas as pd
from scipy.stats import multivariate_normal, norm
from dtocean_core.utils.moorings import get_moorings_tables
# Note that the electrical folder in the test_data directory should be
#... |
ny = len(y)
# Bathymetry
X, Y = np.meshgrid(x,y)
Z = np.zeros(X.shape) - 50.
depths = Z.T[:, :, np.newaxis]
sediments = np.chararray((nx,ny,1), itemsize=20)
sediments[:] = "loose sand"
strata = {"values": {'depth': depths,
'sediment': sediments},
"coords": [x, y, | ["layer 1"]]}
# Soil characteristics
max_temp = 10.
max_soil_res = 10.
target_burial_depth = 10
# Polygons
lease_area = [(startx, starty),
(endx, starty),
(endx, endy),
(startx, endy)]
#nogo_areas = [np.array([[50., 50.],[60., 50.],[60., 60.],[50., 60.]])]
nog... |
openstack/neutron-lib | neutron_lib/api/definitions/segment.py | Python | apache-2.0 | 4,049 | 0 | # Copyright (c) 2016 Hewlett Packard Enterprise Development Company, L.P.
#
# 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
#
# ... | nstants.ATTR_NOT_SPECIFIED,
'convert_to': converters.convert_to_ | int,
'is_sort_key': True,
'is_visible': True
},
'name': {
'allow_post': True,
'allow_put': True,
'default': constants.ATTR_NOT_SPECIFIED,
'validate': {
'type:string_or_none': NAME_LEN
},
'is_f... |
wtsnjp/nlp100 | chap07/k67.py | Python | unlicense | 290 | 0.006897 | #
# usage: python k67.py {alias}
#
import sys
import pymongo
def find_aliases(alias):
cn = pymongo.MongoClient().MusicBrainz.artist
return [a for a in cn.find({'aliases.name': alias})]
if __name__ == '__main__':
n = sys | .argv | [1]
for a in find_aliases(n):
print(a)
|
barseghyanartur/django-currencies | currencies/context_processors.py | Python | bsd-3-clause | 450 | 0 | from currencies.models import Currency
def currencies(request):
currencies = Currency.objects.active()
if not request.session.get('currency'):
try:
currency = Currency.objects.get(is_default__exact=True)
| except Currency.DoesNotExist:
currency = None
request.session['currency'] = currency
return {
'CURRENCIES': currencies,
'CURRENCY': request.session['cur | rency']
}
|
annoviko/pyclustering | pyclustering/cluster/ema.py | Python | gpl-3.0 | 28,795 | 0.010662 | """!
@brief Cluster analysis algorithm: Expectation-Maximization Algorithm for Gaussian Mixture Model.
@details Implementation based on paper @cite article::ema::1.
@authors Andrei Novikov (pyclustering@yandex.ru)
@date 2014-2020
@copyright BSD-3-Clause
"""
import numpy
import random
from pycluster... | alize_random()
raise NameError("Unknown type of EM algorithm initialization is specified.")
def __calculate_initial_clusters(self, centers):
"""!
@brief Calculate Euclidean distance to each point from the each cluster.
@brief Nearest points are captured by accordi... | d clusters as list of clusters. Each cluster contains indexes of objects from data.
"""
clusters = [[] for _ in range(len(centers))]
for index_point in range(len(self.__sample)):
index_optim, dist_optim = -1, 0.0
for index in range(... |
mikekap/batchy | tests/batch_tests.py | Python | apache-2.0 | 4,519 | 0.002213 | import itertools
from batchy.runloop import coro_return, runloop_coroutine
from batchy.batch_coroutine import batch_coroutine, class_batch_coroutine
from . import BaseTestCase
CALL_COUNT = 0
@batch_coroutine()
def increment(arg_lists):
def increment_single(n):
return n + 1
global CALL_COUNT
CAL... | ss_batch_coroutine(0)
def run(self, _):
self.run_call_count += 1
yield
@class_batch_coroutine(0)
def throw(self, _):
self.throw_count += 1
raise ValueError()
yield # pylint: disable-msg=W0101
@class_batch_coroutine(2)
def throw_sooner(self, _):
self... | ValueError()
yield # pylint: disable-msg=W0101
def reset(self):
self.get_call_count = self.set_call_count = self.run_call_count = self.throw_count = 0
class BatchTests(BaseTestCase):
def setup(self):
global CALL_COUNT
CALL_COUNT = 0
def test_simple_batch(self):
@r... |
FabienPean/sofa | applications/plugins/BulletCollisionDetection/examples/PrimitiveCreation.py | Python | lgpl-2.1 | 9,475 | 0.054142 | import Sofa
import random
from cmath import *
############################################################################################
# this is a PythonScriptController example script
############################################################################################
###################################... | node.createObject('MechanicalObject',name='rigidDOF',template='Rigid',position=str(x)+' '+str(y)+' '+str(z)+' 0 0 0 1',velocity='0 0 '+str(falling_speed)+' 0 0 0 1')
mass = node.createObject('UniformMass',name='mass',totalMass=1)
node.createObject('TCapsuleModel',template='Rigid',name='capsule_model',radii=str(radi... | ight))
return 0
def createBulletCapsule(parentNode,name,x,y,z,*args):
node = parentNode.createChild(name)
radius=0
if len(args)==0:
radius = random.uniform(1,3)
else:
radius = args[0]
if len(args) <= 1:
height = random.uniform(1,3)
else:
height = args[1]
meca = node.createObject('MechanicalObject'... |
skarphed/skarphed | core/lib/database.py | Python | agpl-3.0 | 15,700 | 0.008153 | #!/usr/bin/python
#-*- coding: utf-8 -*-
###########################################################
# © 2011 Daniel 'grindhold' Brendle and Team
#
# This file is part of Skarphed.
#
# Skarphed is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public License
# as ... | ct(self):
"""
The class actua | lly connects to the database and stores the
connection in _connection
"""
if None in (self._user, self._ip, self._dbname, self._password):
raise DatabaseException(DatabaseException.get_msg(1))
#TODO: Globally Definable DB-Path
try:
self._connection = ... |
empowerhack/HealthMate | healthmate/services/admin.py | Python | mit | 530 | 0 | """Admin functionality for services."""
from django.contrib import admin
from django.contrib.admin import site
from leaflet.admin import LeafletGeoAdmin
from .models import Service, ServiceImage
class | ServiceImageInline(admin.TabularInline):
"""The inline for service images."""
model = ServiceImage
extra = 3
ordering = ("order",)
class ServiceAdm | in(LeafletGeoAdmin, admin.ModelAdmin):
"""The class for the service admin."""
inlines = [ServiceImageInline]
site.register(Service, ServiceAdmin)
|
oceanobservatories/mi-instrument | mi/dataset/parser/test/test_nutnr_m_glider.py | Python | bsd-2-clause | 7,448 | 0.003894 | """
@package mi.dataset.parser.test
@file mi/dataset/parser/test/test_nutnr_m_glider.py
@author Emily Hahn
@brief A test parser for the nutnr series m instrument through a glider
"""
import os
from nose.plugins.attrib import attr
from mi.core.exceptions import SampleException, ConfigurationException, DatasetParserExce... | verConfigKeys.PARTICLE_CLASS: 'NutnrMDataParticle'
}
def test_simple(self):
"""
Test a simple case that we can par | se a single message
"""
with open(os.path.join(RESOURCE_PATH, 'single.mrg'), 'rU') as file_handle:
parser = GliderParser(self.config, file_handle, self.exception_callback)
particles = parser.get_records(1)
self.assert_particles(particles, "single.yml", RESOURCE_PATH... |
muscatmat/vmi-event-naive-detector | scripts/check_creds.py | Python | mit | 972 | 0.012346 | #!/usr/bin/python
# Import System Required Paths
import sys
sys.path.append('/usr/local/src/volatility-master')
# Import Volalatility
import volatility.conf as conf
import volatility.registry as registry
registry.PluginImporter()
config = conf.ConfObject()
import volatility.commands as commands
import volatility.addr... | try.register_global_options(config, addrspace.BaseAddressS | pace)
config.parse_options()
config.PROFILE="LinuxDebian31604x64"
config.LOCATION = "vmi://debian-hvm"
# Other imports
import time
# Retrieve check creds plugin
import volatility.plugins.linux.check_creds as fopPlugin
fopData = fopPlugin.linux_check_creds(config)
invalid_fop_start_time = time.time()
for msg in fopDa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.