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 |
|---|---|---|---|---|---|---|---|---|
lcpt/xc | python_modules/materials/steel_base.py | Python | gpl-3.0 | 838 | 0.020311 | # -*- coding: utf-8 -*-
from __future__ import division
''' Base classes and function for structural steel.'''
__author__= "Ana Ortega (AO_O) and Luis C. Pérez Tato (LCPT) | "
__copyright__= "Copyright 2015, AO_O and LCPT"
__license__= "GPL"
__version__= "3.0"
__email__= " ana.Ortega.Ort@gmail.com, l.pereztato@gmail.com"
import math
from materials import typical_materials
from miscUtils import LogMe | ssages as lmsg
class BasicSteel(typical_materials.BasicElasticMaterial):
'''Base class for structural steels.
:ivar fy: Yield stress.
:ivar fu: ultimate stress.
:ivar gammaM: partial factor for cross-section resistance.
'''
def __init__(self, E, nu, fy, fu, gammaM):
super(BasicSteel,self).__in... |
8ldesign/DataFeedsTester | setup.py | Python | mit | 318 | 0.006289 | __author__ = 'Krishna Mudragada'
from setuptools import setup
setup(name='DataFeedsTester',
version='0.1',
descriptio | n='Test your Data feeds for validity',
url='http://github.com/mudragada/DataFeeds',
author='Krishna Mudragada',
license='MIT',
| install_requires = ['logging', 're'])
|
luoguizhou/gooderp_addons | finance/tests/test_report.py | Python | agpl-3.0 | 15,946 | 0.000266 | # -*- coding: utf-8 -*-
from odoo.tests.common import TransactionCase
from odoo.exceptions import UserError
from odoo.addons.finance.report.report import ActionReportPickingWrapped
class TestReport(TransactionCase):
def setUp(self):
super(TestReport, self).setUp()
# 审核2015年12月和2016年1月的会计凭证
... | zard = self.env['create.vouchers.summary.wizard'].create(
{'period_begin_id': self.period_201512.id,
'period_end_id': self.period_201512.id,
'subject_name_id': self.env.ref('finance.account_cash').id,
'subject_name_end_id': self.env.ref('finance.account_bank').id,
... | self.period_201512, self.env.ref('finance.account_bank'))
def test_view_detail_voucher(self):
'''在明细账上查看凭证明细按钮'''
report = self.env['create.vouchers.summary.wizard'].create(
{'period_begin_id': self.period_id,
'period_end_id': self.period_id,
'subject_nam... |
wwitzel3/awx | awx/main/tests/functional/commands/test_expire_sessions.py | Python | apache-2.0 | 2,664 | 0.002252 | # Python
import pytest
import string
import random
# Django
from django.utils import timezone
from django.test import Client
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.sessions.models import Session
from django.core.management.base import CommandError
# AWX
from a... | pass')
dylan = User.objects.create_user('dylan', 'dylan@email.com', 'word')
client_0 = Client()
client_1 = Client | ()
client_0.force_login(charlie, backend=settings.AUTHENTICATION_BACKENDS[0])
client_1.force_login(dylan, backend=settings.AUTHENTICATION_BACKENDS[0])
return charlie, dylan
@staticmethod
def run_command(username=None):
command_obj = Command()
command_obj.handle(user=user... |
south-coast-science/scs_core | src/scs_core/aqcsv/connector/datum_mapping.py | Python | mit | 6,655 | 0.003907 | """
Created on 11 Mar 2019
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
example document:
{"topic": "particulates", "species": "pm1", "site-code": null}
"""
from collections import OrderedDict
from scs_core.aqcsv.conf.airnow_site_conf import AirNowSiteConf
from scs_core.aqcsv.connector.source_mapping... | _code=rec.as_json(),
parameter_code=parameter_code,
duration=duration,
frequency=0,
value=self.value(datum),
unit_code=mapping.unit_code,
qc_code=mapping.qc_code,
| poc=poc,
lat=lat,
lon=lon,
gis_datum=gis_datum,
elev=elev,
method_code=mapping.method_code,
mpc_code=mapping.mpc_code,
mpc_value=mapping.mpc_value)
return record
# -----------------------------------------------... |
cavaunpeu/vanilla-neural-nets | vanilla_neural_nets/neural_network/network.py | Python | mit | 3,546 | 0.005358 | import numpy as np
from vanilla_neural_nets.neural_network.training_batch_generator import MiniBatchGenerator
from vanilla_neural_nets.neural_network.optimization_algorithm import GradientDescent
from vanilla_neural_nets.neural_network.loss_function import MeanSquaredError
from vanilla_neural_nets.neural_network.activ... | vation_function_class
self.output_layer_activation_function_class = output_layer_activation_function_class or activation_function_class
self.optimization_algorithm_class = optimiz | ation_algorithm_class
self.learning_rate = learning_rate
self.n_epochs = n_epochs
self.training_batch_size = training_batch_size
self.holdout_data = holdout_data
self.random_number_generator = np.random.RandomState(random_state)
self.parameters = NetworkLayersCollection(
... |
alexandrul-ci/robotframework | utest/writer/test_rowsplitter.py | Python | apache-2.0 | 5,821 | 0.000687 | import unittest
from robot.writer.rowsplitter import RowSplitter
from robot.utils.asserts import assert_equal
class TestRowSplitter(unittest.TestCase):
def _test(self, data, expected, cols=3, table_type='settings'):
splitter = RowSplitter(cols=cols)
actual = list(splitter.split(data, table_type)... | [['1.1', '1.2', '1.3', '${EMPTY}'],
['...', '2.1', '2.2', '${EMPTY}'],
['...', '3.1', '', '${EMPTY}']], c | ols=4)
def test_splitting_inside_comment(self):
self._test(['Kw', 'Arg', '#Comment in', 'many cells'],
[['Kw', 'Arg', '#Comment in'],
['...', '# many cells']])
self._test(['Kw', 'Arg', '# Comment', 'in', 'very', 'many', 'cells', '!'],
[['Kw'... |
JiaminXuan/leetcode-python | symmetric_tree/solution.py | Python | bsd-2-clause | 891 | 0 | # De | finition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a boolean
def isSymmetric(self, root):
if root is None:
return True
... | t)
return False
def _isSymmetric(self, left, right):
if left is None and right is None:
return True
if left is not None and right is not None:
return (left.val == right.val and
self._isSymmetric(left.left, right.right) and
self... |
vicgc/bitcurator | dfxml/python/iverify.py | Python | gpl-3.0 | 1,718 | 0.013388 | #!/usr/bin/python
"""Reads an fiwalk XML file and reports how many of the files are still in the image..."""
import hashlib, os.path, fiwalk, sys
present = []
not_present = []
def process_fi(fi):
print "process file",fi.filename()
if fi.filesize()==0: return
try:
if fi.file_present():
... | print "Present in image:"
print "================="
print "\n".join([fi.filename() for fi in present])
print "\n"
print "Not Present or altered in image:"
print "============== | ======="
for fi in not_present:
print fi.filename()
|
izadorozhna/tempest | tempest/services/network/resources.py | Python | apache-2.0 | 5,754 | 0 | # Copyright 2013 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2... | bleFloatingIp, self).update(**result['floatingip'])
def __repr__(self):
return '<%s addr="%s">' % (self.__class__.__name__,
self.floating_ip_address)
def __str__(self):
return '<"FloatingIP" addr="%s" id="%s">' % (self.floating_ip_address,
... | :
def delete(self):
self.client.delete_port(self.id)
class DeletableSecurityGroup(DeletableResource):
def delete(self):
self.client.delete_security_group(self.id)
class DeletableSecurityGroupRule(DeletableResource):
def __repr__(self):
return '<%s id="%s">' % (self.__class__._... |
nils-werner/xbmc-somafm | default.py | Python | gpl-2.0 | 1,907 | 0.009439 | import os,sys,urllib2
|
import xbmcplugin,xbmcgui
import xml.etree.ElementTree as ET
__addon__ = "SomaFM"
__addonid__ = "plugin.audio.somafm"
__version__ = "0.0.2"
def log(msg):
print "[PLUGIN] '%s (%s)' " % (__addon__, __version__) + str(msg)
log("Initialized!")
log(sys.argv)
rootURL = "http://somafm.com/"
#pluginPat... | e):
headers = {}
headers['User-Agent'] = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3'
if withReferrer:
headers['Referrer'] = withReferrer
return headers
def getHTMLFor(url, withData=None, withReferrer=None):
url = rootURL + url
log(... |
codeforamerica/mdc-feedback | feedback_test/unit/util.py | Python | mit | 402 | 0.004975 | # -*- coding: utf-8 -*-
# See:
# https://github.com/c | odeforamerica/pittsburgh-purchasing-suite/blob/master/purchasing_test/unit/util.py
import datetime
from feedback.user.models import User
def create_a_user(email= | 'foo@foo.com'):
return User(email=email, first_name='foo', last_name='foo')
def insert_a_user(email='foo@foo.com'):
user = create_a_user(email)
user.save()
return user
|
nakato/smashcache | smashcache/cache/cache.py | Python | apache-2.0 | 7,314 | 0.001094 | # Copyright (c) 2015 Sachi King
#
# 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... | nd == self.objects[uri].object_size:
content_length = self.objects[uri].object_size
else:
# Sigh, so because 0 is "send first byte" and there are 20 bytes
# we're sending bytes 0-19. If we tell chrome we are sending
# 0-20, that's 21 bytes and chro | me freaks and sends a load of RST
#
# Todo: Look into how I handle send bytes and try to make this
# less of a case-by-case modification to headers. It's confusing
headers.extend([('Content-Range', ("bytes %s-%s/%s" %
(start, end-1, self.object... |
duedil-ltd/portainer | portainer/app/__init__.py | Python | mit | 504 | 0 | """
"""
import argparse
parser = argparse.ArgumentParser(
prog="portainer",
fromfile_prefix_chars="@"
)
subparsers = parser.add_subparsers()
def subcommand(name, callback=None):
"""A decorator for main functions to add themselves as subcommands."""
def decorator(fn):
subparser = subparser... | )
subparser.set_defaults(_fn=fn, _name=name, _parser=subparser)
if callback:
callb | ack(subparser)
return fn
return decorator
|
flysmoke/ijizhang | ijizhang_prj/accounts/forms.py | Python | mit | 2,097 | 0.026818 | #coding=utf-8
from djan | go import forms
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
# Register your models here.
class RegisterForm(forms.Form):
username=forms.CharField(label=_(u"昵称"),max_length=20,widget=forms.TextInput(attrs={'size': 20,'class':"form-control"}))
email=forms... | rField(label=_(u"密码"),max_length=20,widget=forms.PasswordInput(attrs={'size': 20,'class':"form-control"}))
re_password=forms.CharField(label=_(u"重复密码"),max_length=20,widget=forms.PasswordInput(attrs={'size': 20,'class':"form-control"}))
def clean_username(self):
'''验证重复昵称'''
users = User.object... |
zhangf911/common | edition/block_holder.py | Python | mit | 6,717 | 0.001191 | from biicode.common.model.cells import SimpleCell
from biicode.common.model.dependency_set import DependencySet
from biicode.common.model.brl.block_name import BlockName
from biicode.common.model.symbolic.block_version_table import BlockVersionTable
from biicode.common.model.blob import Blob
from biicode.common.model.r... | except KeyError:
content = None
try:
self._config = BiiConfig(content)
except ConfigurationFileError as e:
raise ConfigurationFileError('%s/biicode.conf: Line | %s'
% (self.block_name, str(e)))
return self._config
@property
def mains(self):
return self.config.mains
@property
def tests(self):
return self.config.tests
@property
def data(self):
return self.config.data
@pro... |
ant0nisk/pyUniBraille | tests/test_all.py | Python | gpl-3.0 | 1,366 | 0.000732 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Includes all the test modules from this directory
a | nd runs the tests.
LICENSE:
Braille Grade 2 Translation in Pyth | on
Copyright (C) 2016 Antonis Katzourakis
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 progra... |
bfontaine/term2048 | tests/test_keypress.py | Python | mit | 2,726 | 0 | # -*- coding: UTF-8 -*-
import sys
import platform
if platform.python_version() < '3.0':
from StringIO import StringIO
else:
from io import StringIO
if platform.python_version() < '2.7':
import unittest2 as unittest
else:
import unittest |
try:
import termios as _termios
except ImportError:
_termios = None
import helpers
from term2048 import keypress as kp
keypress = kp._getRealModule()
fno = sys.stdin.fileno()
class FakeStdin(StringIO):
def fileno(self):
return fno
class TestKeypress(unittest.TestCase):
def _pushChars(se... | )
def _pushArrowKey(self, code):
"""helper. Add an arrow special key in the fake stdin"""
self._pushChars(27, 91, code)
def setUp(self):
self.stdin = sys.stdin
sys.stdin = FakeStdin()
def tearDown(self):
sys.stdin = self.stdin
def test_getKey_read_stdin(self):... |
Code4SA/censusreporter | api/controller/census.py | Python | mit | 37,032 | 0.001323 | from collections import OrderedDict
from sqlalchemy import func
from api.models import get_model_from_fields
from api.models.tables import get_datatable, get_table_id
from api.utils import get_session, add_metadata
from api.controller.geography import get_geography
from .utils import (collapse_categories, calculate_... | OLD_INCOME_RECODE['R 76 401 - R 153 800'] = 'R75k - R150k'
HOUSEHOLD_INCOME_RECODE['R 153 801 - R 307 600'] = 'R150k - R300k'
HOUSEHOLD_INCOME_RECODE['R 307 601 - R 614 400'] = 'R300k - R60 | 0k'
HOUSEHOLD_INCOME_RECODE['R 614 001 - R 1 228 800'] = 'R600k - R1.2M'
HOUSEHOLD_INCOME_RECODE['R 1 228 801 - R 2 457 600'] = 'R1.2M - R2.5M'
HOUSEHOLD_INCOME_RECODE['R 2 457 601 or more'] = 'Over R2.5M'
HOUSEHOLD_INCOME_ESTIMATE = {}
HOUSEHOLD_INCOME_ESTIMATE['R0'] = 0
HOUSEHOLD_INCOME_ESTIMATE['Under R4800'] = 240... |
sgrogan/freecad-extras-eaglepcb2 | command/PCBglue.py | Python | lgpl-2.1 | 11,805 | 0.006438 | # -*- coding: utf8 -*-
#****************************************************************************
#* *
#* Printed Circuit Board Workbench for FreeCAD PCB *
#* Flexible Printed Circuit Board Workbench for FreeCAD FP... | dShape
from command.PCBgroups import createGroup_Glue
#***********************************************************************
#* GUI
#***********************************************************************
class createGlueGui(QtGui.QWidget):
def __init__(self, parent=None):
Qt... | self.form = self
self.form.setWindowTitle(u"Create glue path")
self.form.setWindowIcon(QtGui.QIcon(":/data/img/gluePath.png"))
#
self.height = QtGui.QDoubleSpinBox(self)
self.height.setSingleStep(0.1)
self.height.setValue(1)
self.height.setRange(0.1, 1000)
... |
CenterForOpenScience/mfr-code-pygments | setup.py | Python | mit | 2,143 | 0.000933 | # -*- coding: utf-8 -*-
import re
import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run... | _pygments',
version=__version__,
install_requires=[
'mfr==0.1.0',
| 'Pygments',
],
description='code_pygments support for mfr',
long_description=read("README.rst"),
author='Center for Open Science',
author_email='contact@cos.io',
url='https://github.com/CenterForOpenScience/mfr_code_pygments',
packages=find_packages(exclude=("test*", 'previewer')),
... |
haddocking/powerfit | powerfit/powerfitter.py | Python | apache-2.0 | 22,830 | 0.002453 | from __future__ import absolute_import, division
from sys import stdout
from os import remove
from os.path import join, abspath, isdir
import os.path
from time import time, sleep
from multiprocessing import RawValue, Lock, Process, cpu_count
from string import Template
import numpy as np
from numpy.fft import irfftn ... | processes[n].join()
self._combine()
@staticmethod
def _run_correlator_instance(target, template, | mask, rotations, laplace,
counter, jobid, queues, directory):
correlator = CPUCorrelator(target.array, laplace=laplace)
correlator.template = template.array
correlator.mask = mask.array
correlator.rotations = rotations
correlator._counter = counter
correlator... |
srottem/indy-sdk | samples/python/setup.py | Python | apache-2.0 | 398 | 0.002513 | from d | istutils.core import setup
setup(
name='python-indy-sdk-sample',
version='0.0.1',
url='https://github.com/hyperledger/indy-sdk',
license='MIT/Apache-2.0',
author='Artem Ivanov',
author_email= | 'artem.ivanov@dsr-company.com',
description='This is the sample of usage python wrapper for Hyperledger Indy SDK.',
install_requires=['python3-indy==1.8.1-dev-1039']
)
|
bleepbloop/Pivy | examples/Mentor/10.7.PickFilterManip.py | Python | isc | 6,102 | 0.004753 | #!/usr/bin/env python
###
# Copyright (c) 2002-2007 Systems in Motion
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS I... | olor(0, 1, 0)))
scene.addChild(myText("e", 2, SbColor(0, 1, 1)))
scene.addChild(myText("n", 3, SbColor(1, 0, 0)))
# Open Inventor is two words!
scene.addChild(myText("I", 5, SbColor(1, 0, 1)))
scene.addChild(myText("n", 6, SbColor(1, 1, 0)))
scene.addChild(myText("v", 7, SbColor(1, 1, 1)))
... | ext("t", 10, SbColor(0, 1, 1)))
scene.addChild(myText("o", 11, SbColor(1, 0, 0)))
scene.addChild(myText("r", 12, SbColor(1, 0, 1)))
return scene
def main():
# Initialization
mainWindow = SoGui.init(sys.argv[0])
# Create a scene graph. Use the toggle selection policy.
sel = SoSelect... |
mauriziofilippone/deep_gp_random_features | code/losses/mean_sq_error.py | Python | apache-2.0 | 959 | 0.013556 | ## Copyright 2016 Kurt Cutajar, Edwin V. Bonilla, Pietro Michiardi, Maurizio Filippone
##
## 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... | icense.
impo | rt numpy as np
from . import loss
class RootMeanSqError(loss.Loss):
def __init__(self, dout):
loss.Loss.__init__(self,dout)
def eval(self, ytrue, ypred):
error_rate = np.sqrt(np.mean(np.square(ytrue - ypred)))
return error_rate
def get_name(self):
return "RMSE"
|
thingsinjars/electron | script/upload.py | Python | mit | 7,675 | 0.010945 | #!/usr/bin/env python
import argparse
import errno
import os
import subprocess
import sys
import tempfile
from lib.config import PLATFORM, get_target_arch, get_chromedriver_version, \
get_platform_key
from lib.util import atom_gyp, execute, get_atom_shell_version, parse_version, \
... | d the index.json.
execute([sys.executable,
os.path.join(SOURCE_ROOT, 'script', 'upload-index-json.py')])
# Press the publish button.
publish_release(github, release['id'])
# Do not upload other files when passed "-p".
return
# Upload atom-shell with GitHub Releases API.
upload_at... | E))
if PLATFORM == 'darwin':
upload_atom_shell(github, release, os.path.join(DIST_DIR, DSYM_NAME))
# Upload chromedriver and mksnapshot for minor version update.
if parse_version(args.version)[2] == '0':
chromedriver = 'chromedriver-{0}-{1}-{2}.zip'.format(
get_chromedriver_version(), get_platfor... |
DevWright/RedBoxPyBot | RoboClient/python/KeyPressMap.py | Python | gpl-3.0 | 550 | 0.005455 | class KeyPressMap:
def __init__(self):
self.__keymap = {}
def keyDown(self, key):
self.__keymap[key] = True
def keyUp(self, key):
self.__keymap[key] = False
def isPressed(self, key):
result = self.__keymap.get(key)
if result == None:
return... | print(s | elf.__keymap)
KEYS = KeyPressMap()
|
seanli9jan/tensorflow | tensorflow/python/data/experimental/ops/map_defun.py | Python | apache-2.0 | 2,667 | 0.004124 | # 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... | n an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Experimental API for optimizing `tf.da... | ."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import gen_dataset_ops
def map_defun(fn, elems, output_dtypes, output_shapes):... |
fgaTactics/tecprog2017.1 | gameEngine/Scene.py | Python | gpl-3.0 | 306 | 0 | import pygame
# This class creates the scene basic structure
class Scene(object):
def __init__(self, name="DE | FAULT", ID=0):
self.name = name
self.ID = ID
def update(self, events):
pass
def load(self):
| pass
def draw(self, screen, groups):
pass
|
euccastro/icbink | entry_point.py | Python | mit | 248 | 0.008065 | from rpython.rlib import | jit
import interpret
import parse
import kernel_type as kt
def entry_point(argv):
jit.set_param(None, "trace_limit", 20000)
interpr | et.run(argv)
return 0
def target(driver, args):
return entry_point, None
|
AllMyChanges/allmychanges.com | allmychanges/management/commands/migrate_downloaders.py | Python | bsd-2-clause | 6,481 | 0.000926 | # coding: utf-8
import os
import shutil
from django.core.management.base import BaseCommand
from django.conf import settings
from twiggy_goodies.threading import log
from twiggy_goodies.django import LogMixin
from allmychanges.downloaders import guess_downloaders
from allmychanges.models import (
Changelog)
from... | ize=len(changelogs)):
| if ch.id not in migrated:
status = migrate(ch)
migrated[ch.id] = status
if idx % 10:
save_state()
except:
log.trace().error('Error during migration')
pass
save_state()
|
cshzc/X1Tool | src/server/apps/x1tool.py | Python | gpl-2.0 | 1,304 | 0.002301 | #!/usr/bin/env python
# coding:utf-8
import hashlib
import logging
from x1category import X1Category
TOOL_PREFIX = 'X1Tool'
class X1Tool(object):
'appid:6376477c731a89e3280657eb88422645f2d1e2a684541222e21371f3110110d2'
DEFAULT_METADATA = {'name': "X1Tool", 'author': "admin", 'comments': "default", 'template':... | return hashlib.sha224(cls.__name__).hexdigest()
except Exception, e:
logging.error('Fail to get appid: %s' % e)
return "0000000000"
def run(self, args):
return args
def metadata(self, attr_key=None, attr_value=None):
try:
if attr_key is None:
... | etadata[attr_key]
except Exception, e:
logging.error('Fail to set attr: %s(%s)' % (attr_key, e))
if __name__ == '__main__':
app = X1Tool()
print app.appid()
print app.metadata()
|
rpgplanet/django-postman | postman/views.py | Python | bsd-3-clause | 12,521 | 0.00591 | import datetime
import urlparse
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db.models import Q
from django.http import Http404
from dja... | e_name, {
'pm_messages' | : msgs, # avoid 'messages', already used by contrib.messages
'by_conversation': option is None,
'by_message': option == OPTION_MESSAGES,
'by_conversation_url': reverse(view_name),
'by_message_url': reverse(view_name, args=[OPTION_MESSAGES]),
'current_url': request.get_full_pat... |
Spacecraft-Code/SPELL | drivers/standalone/src/constants.py | Python | lgpl-3.0 | 1,170 | 0.018803 | ###################################################################################
## MODULE : constants
## DATE : Mar 18, 2011
## PROJECT : SPELL
## DESCRIPTION: Constants definition
## --------------------------------------------------------------------------------
##
## Copyright (C) 2008, 2015 SES E... | nd/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 o | f the License, or
## (at your option) any later version.
##
## This software 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 shou... |
Kunalpod/codewars | mexican_wave.py | Python | mit | 255 | 0.031373 | #Kunal Gautam
#Codewars : @Kunalpod |
#Problem name: Mexican Wave
#Problem level: 6 kyu
def wave(str):
li=[]
for i in range(len(str)):
x=list(str)
x[i]=x | [i].upper()
li.append(''.join(x))
return [x for x in li if x!=str]
|
google-research/google-research | cache_replacement/policy_learning/cache_model/metric.py | Python | apache-2.0 | 7,155 | 0.004193 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | FloatTensor): batch of probability distributions
over cache lines of shape (batch_size, num_cache_lines), each
corre | sponding to a cache access. In each distribution, the lines are
ordered from top-1 to top-num_cache_lines.
eviction_mask (torch.ByteTensor): of shape (batch_size), where
eviction_mask[i] = True if the i-th cache access results in an eviction.
The metric value is tracked for two populations... |
jicksy/oneanddone_test | vendor-local/lib/python/jingo_minify/__init__.py | Python | mpl-2.0 | 70 | 0 | VE | RSION = (0, 6, 0)
__version__ = '.'.join((str(x) for x in VERSIO | N))
|
rbpiccinini/codes | eigendrake/scripts/heterogeneous/case01/temporal_case01.py | Python | gpl-3.0 | 7,529 | 0.007704 |
import firedrake as fd
import numpy as np
from slepc4py import SLEPc
from firedrake.petsc import PETSc
import scipy.io as sp
import pandas as pd
import matplotlib.pyplot as plt
def coords2ijk(x, y, z, Delta, data_array):
i = np.floor(x / Delta[0]).astype(int)
j = np.floor(y / Delta[1]).astype(int)
k = np... | .assign(u_0)
u_n.rename('Pressure')
# Compute volume
vol = fd.Function(V).assign(fd.Constant(1.0))
vol = fd | .assemble(vol*fd.dx)
# Write properties
fd.File('spe10_case01_u0.pvd').write(u_n, Kx, Ky, Kz, phi)
outfile = fd.File("spe10_case01.pvd")
outfile.write(u_n)
# Compute transmissibility with harmonic interpolation of K to facets
Tx_facet = fd.conditional(fd.gt(fd.avg(Tx), 0.0), Tx('+')*Tx('-') / fd.avg(Tx), 0.0)
Ty_face... |
Tayamarn/socorro | socorro/external/postgresql/models.py | Python | mpl-2.0 | 55,980 | 0.000804 | #! /usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
SQLAlchemy models for Socorro
"""
from __future__ import unicode_literals
from sqlalchemy im... | return 'product_info_change'
def bind_processor(self, dialect):
def process(value):
| return value
return process
def result_processor(self, dialect, coltype):
def process(value):
return value
return process
def __repr__(self):
return 'product_info_change'
class release_enum(types.UserDefinedType):
name = 'release_enum'
def get_... |
r-alex-hall/fontDevTools | scripts/admin/addCurrentPathToSyspath.py | Python | gpl-3.0 | 373 | 0.010724 | # DESCRIPTION
# Adds the path of whichever directory you | call this script from to the PATH (temporarily, or for as long as you have the terminal open) as Python sees it.
# USAGE
# Run through a Python interpreter, without any parameter:
# pyth | on /path/to_this_script/addCurrentPathToSyspath.py
# CODE
import os
currpath=os.getcwd()
import sys
sys.path.append(currpath) |
gmkou/MusicPi | test/test_init.py | Python | mit | 374 | 0.016043 | # -*- coding: utf-8 -*-
from unittest import TestCase
import os
from nose.tools import with_setup, raises
fifo = "/tmp/mplayercontrol.fifo"
class FifoTestCase(TestCase):
def setUp(self):
| print 'before test'
def tearDown(se | lf):
print 'after test'
def fifo_test(self):
exist = os.path.exists(fifo)
assert exist
|
wikilinks/nel | nel/process/tag.py | Python | mit | 6,517 | 0.003836 | #!/usr/bin/env python
import os
import sys
import re
import string
from itertools import izip
from time import time
from bisect import bisect_left
from subprocess import Popen, PIPE
from cStringIO import StringIO
import spacy
from .process import Process
from ..model import recognition
from ..doc import Mention, Cha... | # - therefore we need to slice up the text into chunks of at most max_size
# - however, we can't slice between sentences or tokens without hurting the tagger accuracy
# - stanford doesn't return offsets, so we must keep tokens we sen | d and tags returned aligned
if tokens:
acc = 0
token_offsets = []
character_to_token_offset = {0:-1}
for i, t in enumerate(tokens):
acc += len(t) + 1
token_offsets.append(acc)
character_to_token_offset[acc] = i
... |
maxime-beck/compassion-modules | thankyou_letters/tests/__init__.py | Python | agpl-3.0 | 440 | 0 | # -*- coding: utf-8 -*-
########################### | ###################################################
#
# Copyright (C) 2018 Compassion CH (http://www.comp | assion.ch)
# Releasing children from poverty in Jesus' name
# @author: Nicolas Badoux <n.badoux@hotmail.com>
# The licence is in the file __manifest__.py
#
##############################################################################
from . import test_thankyou_letters
|
channelcat/sanic | tests/test_touchup.py | Python | mit | 528 | 0 | import logging
from sanic.signals import RESERVED_NAMESPACES
from sanic.touchup import TouchUp
def test_touchup_methods(app):
assert | len(TouchUp._registry) == 9
async def test_ode_removes_dispatch_events(app, caplog):
with caplog.at_level(logging.DEBUG, logger="sanic.root"):
await app._startup()
logs = caplog.record_tuples
for signal in RESERVED_NAMESPACES["http"]:
assert (
"sanic.root",
loggin... | al}",
) in logs
|
jvalinsky/Kumquat | app/forms.py | Python | mit | 1,886 | 0.012725 | from flask.ext.wtf import Form
from wtforms import StringField, BooleanField, SelectField, PasswordField, TextField, FileField
from wtforms.fields.html5 import DateField
from wtforms.validators import DataRequired
class LoginForm(Form):
username = StringField('username', validators=[DataRequired()])
password ... | description', validators=[DataRequired()])
duedate = DateField('due date', validators=[DataRequired()])
karma = SelectField(u'karma', choices=[('none', ''), | (5,'small'), (10,'medium'), (30,'large'),(50,'huge')])
# class PicForm(Form):
name = StringField('name', validators=[DataRequired()])
pic = FileField('pic', validators=[DataRequired()]) |
ArcaniteSolutions/truffe2 | truffe2/units/migrations/0004_auto__add_accreditation.py | Python | bsd-2-clause | 8,999 | 0.008445 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Accreditation'
db.create_table(u'units_accreditation', (
... | 'to': u"orm['units.Unit']"}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['users.TruffeUser']"}),
'validation_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'})
},
u'units.role': {
| 'Meta': {'object_name': 'Role'},
'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
... |
zenden2k/qBittorrent | src/searchengine/nova/engines/kickasstorrents.py | Python | gpl-2.0 | 3,172 | 0.003468 | #VERSION: 1.28
#AUTHORS: Christophe Dumez (chris@qbittorrent.org)
#CONTRIBUTORS: Diego de las Heras (diegodelasheras@gmail.com)
# 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... |
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUS... | THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from novaprinter import prettyPrinter
from helpers import retrieve_url, download_file
import json
class kickasstorrents(object):
url = 'https://kat.cr'
name = 'Kickass Torrents'
supported_categories = {'all': '', 'movies': 'Mo... |
ccpgames/eve-metrics | web2py/gluon/contrib/pysimplesoap/client.py | Python | mit | 36,225 | 0.007564 | #!/usr/bin/env python
# -*- coding: latin-1 -*-
# 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; either version 3, or (at your option) any later
# version.
#
# This program is distr... | der support
self.__headers | = {} # general headers
self.__call_headers = None # OrderedDict to be marshalled for RPC Call
# check if the Certification Authority Cert is a string and store it
if cacert and cacert.startswith("-----BEGIN CERTIFICATE-----"):
fd, filename = tempfile.mkstemp()... |
MrLeeh/flaskhab | app/core/__init__.py | Python | mit | 94 | 0.010638 | from flask import Blueprint, url_f | or
core = Bl | ueprint('core', __name__)
from . import filters
|
pSCANNER/USC-source-code | hqmf2sqlserver/tests_postgres/create_test_key.py | Python | apache-2.0 | 432 | 0.020833 | #!/usr/bin/python
DEFAULT_DBURL="postgresql+psycopg2:///cqm"
DEFAULT_SOURCE_SCHEMA="results"
DEFAULT_KEY | _SCHEMA="expected"
import sys
from TestKey import TestKey
if __name__ == '__main__':
measures = sys.argv[1:]
dburl=DEFAULT_DBURL
source_schema=DEFAULT_SOURCE_SCHEMA
key_schema=DEFAULT_KEY_SCHEMA
tk = | TestKey(dburl, key_schema)
for m in measures:
tk.make_key_table(m, source_schema)
|
kynikos/outspline | src/outspline/extensions/copypaste_api.py | Python | gpl-3.0 | 2,260 | 0.000885 | # Outspline - A highly modular and extensible outliner.
# Copyright (C) 2011 Dario Giovannetti <dev@dariogiovannetti.net>
#
# This file is part of Outspline.
#
# Outspline 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 F... | ceived a copy of the GNU General Public Li | cense
# along with Outspline. If not, see <http://www.gnu.org/licenses/>.
import outspline.core_api as core_api
import copypaste
from copypaste import queries
def copy_items(filename, citems):
return copypaste.copy_items(filename, citems)
def paste_items_as_children(filename, baseid, description='Paste as ch... |
hryamzik/ansible | lib/ansible/modules/cloud/google/gcp_compute_target_pool.py | Python | gpl-3.0 | 15,890 | 0.003713 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Google
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# ----------------------------------------------------------------------------
#
# *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
#
... | - NONE: Connections from
the same client IP may go to any instance in the pool.'
- "- CLIENT_IP: Connections from the same client IP will go to the same instance
in the pool while that instance remains healthy."
- "- CLIENT_IP_PROTO: Connections from the same clie... | the same instance in the pool while that instance remains healthy."
returned: success
type: str
region:
description:
- A reference to Region resource.
returned: success
type: str
'''
############################################# |
CSD-Public/stonix | src/stonix_resources/ui_dylan_pyqt5_main_listview.py | Python | gpl-2.0 | 25,596 | 0.004845 | ###############################################################################
# #
# Copyright 2019. Triad National Security, LLC. All rights reserved. #
# This program was produced under U.S. Government contract 89233218CNA000001 #
... | cy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred)
sizePolicy.setHorizontalStr | etch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.button_frame.sizePolicy().hasHeightForWidth())
self.button_frame.setSizePolicy(sizePolicy)
self.button_frame.setLayoutDirection(QtCore.Qt.LeftToRight)
self.button_frame.setFrameShape(QtGui.QFrame.NoFrame)
... |
AlexStarov/Shop | applications/mycalendar/managers.py | Python | apache-2.0 | 914 | 0.00224 | # -*- coding: utf-8 -*-
from django.db import models
from datetime import datetime
__author__ = 'AlexStarov'
class Manager(models.Manager):
def location_date_time_gte_today(self):
aaa = self.location_date_time.filter(date_start__gte=datetime.today(), )
print(self, )
print(aaa, )
... | _at')
def first_level(self):
return self.published().filter(parent__isnull=1, )
# # Закрепленные в рубриках
# def rubric_locked(self, rubric=None):
# qs = self.published()
# if rubric:
# try:
# return qs.get(rubric_locked=1, rubric=rubric)
# except... | rubric_locked=1, first_locked=0)
# return qs
|
jamesiter/jimauth | models/user.py | Python | gpl-3.0 | 11,723 | 0.002579 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import jimit as ji
from mysql.connector import errorcode, errors
from database import Database as db
from filter import FilterFieldType, Filter
__author__ = 'James Iter'
__date__ = '16/6/8'
__contact__ = 'james.iter.cn@gmail.com'
__copyright__ = '(c) 2016 b... | -cn'], ': ', e.msg])
raise ji.PreviewingError(json.dumps(ret, ensure_ascii=False))
finally:
cursor.close()
cnx.close()
def delete(self):
if not self.exist():
ret = dict()
ret['state'] = ji.Common.exchange_state(40401)
ret['... | lf.id.__str__()])
raise ji.PreviewingError(json.dumps(ret, ensure_ascii=False))
sql_stmt = ("DELETE FROM user WHERE id = %(id)s")
cnx = db.cnxpool.get_connection()
cursor = cnx.cursor(dictionary=True, buffered=True)
try:
cursor.execute(sql_stmt, self.__dict__)
... |
2ndy/RaspIM | usr/share/pyshared/debian/changelog.py | Python | gpl-2.0 | 23,472 | 0.006518 | # changelog.py -- Python module for Debian changelogs
# Copyright (C) 2006-7 James Westby <jw+debian@jameswestby.net>
# Copyright (C) 2008 Canonical Ltd.
#
# 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 Fo... |
if self._changes is None:
self._changes = [change]
else:
#Bit of trickery to keep the formatting nicer with a blank
#line at the end if there is one
changes = self._changes
| changes.reverse()
added = False
for i in range(len(changes)):
m = blankline.match(changes[i])
if m is None:
changes.insert(i, change)
added = True
break
changes.reverse()
... |
rajalokan/nova | nova/tests/unit/fake_notifier.py | Python | apache-2.0 | 4,395 | 0.000455 | # Copyright 2013 Red Hat, 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 agre... | payload = self._serializer.serialize_entity(ctxt, p | ayload)
# NOTE(sileht): simulate the kombu serializer
# this permit to raise an exception if something have not
# been serialized correctly
jsonutils.to_primitive(payload)
# NOTE(melwitt): Try to serialize the context, as the rpc would.
# An exception will ... |
warefab/scratch-n-sketch | python/draw_arcs_tft.py | Python | mit | 1,415 | 0.012721 | """
*
* Scratch_n_sketch scripting
* Text screen saver
*
"""
from libs.board import *
#init
board = scratch_n_sketch()
#connect board
board.conne | ct()
#initialize colors
board.backGroundColor(0, 0, 0)
board.penColor(255, 0, 255)
board.textBackColor(0, 0, 0)
#rotate display by 180
board.rotateDisplay(board.rotate_0)
board.setFont(Font.terminal)
#xp = yp = 100
deg = 0
e = 310
pi = 22/7
r = 25
lf = 0
for i in range(3):
deg = 0
if i == 0:
| board.penColor(255, 0, 255)
xp = 110
yp = 50
e = 150
elif i == 1:
board.penColor(255, 255, 0)
xp = 110
yp = 120
e = 230
r = 35
elif i == 2:
board.penColor(0, 255, 255)
xp = 110
yp = 240
e = 345
r = 60
... |
SublimeGit/SublimeGit | sgit/stash.py | Python | mit | 3,127 | 0.000959 | # coding: utf-8
import time
import sublime
from sublime_plugin import WindowCommand
from .util import noop
from .cmd import GitCmd
from .helpers import GitStashHelper, GitStatusHelper, GitErrorHelper
class GitStashWindowCmd(GitCmd, GitStashHelper, GitErrorHelper):
def pop_or_apply_from_panel(self, action):
... | run(self):
repo = self.get_repo()
if not repo:
| return
snapshot = time.strftime("Snapshot at %Y-%m-%d %H:%M:%S")
self.git(['stash', 'save', '--', snapshot], cwd=repo)
self.git(['stash', 'apply', '-q', 'stash@{0}'], cwd=repo)
self.window.run_command('git_status', {'refresh_only': True})
class GitStashPopCommand(WindowCommand, ... |
DmZ/ajenti | ajenti/ui/classes.py | Python | lgpl-3.0 | 5,994 | 0.003337 | import random
from lxml import etree
from ajenti.utils import fix_unicode
class Element(etree.ElementBase):
def __init__(self, tag, *args, **kwargs):
etree.ElementBase.__init__(self)
self.tag = tag
self.set('id', str(random.randint(1,9000*9000)))
self._init(*args, **kwargs)
... | Element):
if e.tag == 'treecontainer':
self.append(e)
elif e.tag == 'treecontainernode':
self.append(e)
else:
| self.append(UI.TreeContainerNode(e))
class TabControl(Element):
def __init__(self, *args, **kwargs):
Element.__init__(self, 'tabcontrol', **kwargs)
self.vnt = UI.TabHeaderNode(id=self['id'])
self.vnc = UI.Container()
self.append(UI.VConta... |
rven/odoo | odoo/addons/test_apikeys/__manifest__.py | Python | agpl-3.0 | 229 | 0 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Tests flow of API keys',
'category': 'Tools',
| 'depends': ['web_tour'],
'data': ['views/asset | s.xml'],
}
|
wateraccounting/wa | Collect/ETmonitor/Ew_monthly.py | Python | apache-2.0 | 803 | 0.017435 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 03 09:37:33 2018
@author: tih
"""
import os
import sys
from DataAccess import DownloadData
def main(Dir, Startdate='', Enddate='', latlim=[-60, 70], lonlim=[-180, 180], Waitbar = 1):
"""
This function downloads monthly ETmonitor data
Keyword arguments:
... | Download monthly ETmonitor Ew data for the period %s till %s' %(Startdate, Enddate)
Type = "ew"
# Download data
DownloadData(Dir, Startdate, Enddate, latlim, lonlim, Type, Waitbar)
|
if __name__ == '__main__':
main(sys.argv) |
praekelt/nurseconnect | nurseconnect/templatetags/nurseconnect_tags.py | Python | bsd-2-clause | 2,516 | 0 | import calendar
from django.template import Library
from molo.core.templatetags.core_tags import load_sections
from molo.profiles.models import UserProfilesSettings
from nurseconn | ect.utils import get_survey_results_for_user
r | egister = Library()
@register.filter('fieldtype')
def fieldtype(field):
return field.field.widget.__class__.__name__
@register.inclusion_tag("core/tags/footerlink.html", takes_context=True)
def footer_link(context, id):
request = context["request"]
locale = context.get("locale_code")
terms = UserPr... |
pfe-asr-2014/tsp-mooc-agent | app/agent.py | Python | mit | 390 | 0.007692 | from logger import Logger
from docker import Client
import signal
import sys
import yaml
def signal_term_handler(signal, frame):
print 'terminating...'
sys.exi | t(0)
signal.signal(signal.SIGTERM, signal_term_handler)
with open("agent.yml", 'r | ') as ymlfile:
cfg = yaml.load(ymlfile)
client = Client(base_url='unix://var/run/docker.sock')
Logger(client).read_logs(cfg['filter'])
|
infobloxopen/neutron | neutron/openstack/common/middleware/request_id.py | Python | apache-2.0 | 1,027 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | EADER_REQUEST_ID = 'x-open | stack-request-id'
@versionutils.deprecated(as_of=versionutils.deprecated.KILO,
in_favor_of='oslo.middleware.RequestId')
class RequestIdMiddleware(request_id.RequestId):
pass
|
wlan0/cattle | tests/integration/cattletest/core/test_allocation.py | Python | apache-2.0 | 17,207 | 0 | from common_fixtures import * # NOQA
from test_shared_volumes import add_storage_pool
def test_inactive_agent(super_client, new_context):
host = super_client.reload(new_context.host)
agent = host.agent()
c = new_context.create_container()
assert c.state == 'running'
agent = super_client.wait_su... | = cl | ient.wait_success(
client.create_container(imageUuid=image_uuid,
requestedHostId=host1.id,
ports=['8081:81/tcp']))
containers.append(c)
# try to deploy another container with same public port + protocol
c2 = cli... |
hjanime/VisTrails | vistrails/tests/utils.py | Python | bsd-3-clause | 13,151 | 0.002281 | ###############################################################################
##
## Copyright (C) 2014-2015, New York University.
## Copyright (C) 2011-2014, NYU-Poly.
## Copyright (C) 2006-2011, University of Utah.
## All rights reserved.
## Contact: contact@vistrails.org
##
## This file is part of VisTrails.
##
## ... | ngPackage:
if not enable_pkg:
raise
enable_package(identifier)
pkg = pm.get_package(identifier)
for func_name, params in functions:
param_list = []
for j, (param_type, param_val) in enumerate(params):
param_list.append(... | tion_list.append(ModuleFunction(name=func_name,
parameters=param_list))
name = name.rsplit('|', 1)
if len(name) == 2:
namespace, name = name
else:
namespace = None
name, = name
module = Module(name=name,
... |
appcito/automation-tool | instancelist-cli.py | Python | mit | 163 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
package documentati | on
"""
from Automation.instancelist import main |
if __name__ == '__main__':
main()
|
jonDel/pyrarcr | old/pyrarcr-0.2.py | Python | mit | 2,210 | 0.039819 | #!/usr/bin/env python3
##### ##### ##### ##### #### ####
# # # # # # # # # # #### #### # # #
##### #### ##### ##### ##### # # # # ####
# # # # # # # # # # # # #
# # # # # # # # #### # #### # ####
#finds the password of a desired ... | ]==".rar":
print("Trying:",k)
kf=os.popen("unrar t -y -p%s %s 2>&1|grep 'All OK'"%(k,rf))
tryn+=1
for rkf in kf.readlines():
if rkf=="All OK\n":
print("Found password:",repr(k))
print("Tried combination count:",tryn)
print("It took",round(time.time()-start,3),"seconds")
prin... | time.sleep(2)
sys.exit(1)
elif rf[-4:]==".zip" or rf[-3:]==".7z":
print("Trying:",k)
kf=os.popen("7za t -p%s %s 2>&1|grep 'Everything is Ok'"%(k,rf))
tryn+=1
for rkf in kf.readlines():
if rkf=="Everything is Ok\n":
print("Found password:",repr(k))
print("Tried combination coun... |
circuitar/Nanoshield_Termopar | extras/docs/conf.py | Python | mit | 867 | 0.005767 | import sys
import os
import shlex
import subprocess
read_the_docs_build = os.environ.get('READTHEDOCS', None) == 'True'
if read_the_docs_build:
subprocess.call('doxygen', shell=True)
extensions = ['breathe']
breathe_projects = { 'Nanoshield_Termopar': 'xml' }
breathe_default_project = "Nanoshield_Termopar"
templ... | = '.rst'
master_doc = 'index'
project = u'Nanoshield_Termopar'
copyright = u'2015, Nanoshield_Termopar'
author = u'Nanoshield_Termopar'
version = '1.0'
release = '1.0'
language = None
exclude_patterns = ['_build']
pygments_style = 'sphinx'
todo_include_todos = False
html_static_path = ['_static']
htmlhelp_basename = 'N... | anoshield\_Termopar Documentation',
u'Nanoshield\_Termopar', 'manual'),
]
|
googleapis/python-dialogflow-cx | samples/generated_samples/dialogflow_v3_generated_agents_export_agent_async.py | Python | apache-2.0 | 1,539 | 0.00065 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may | obtain a copy o | f 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 la... |
ClaudiaSaxer/PlasoScaffolder | src/plasoscaffolder/bll/mappings/parser_init_mapping.py | Python | apache-2.0 | 1,234 | 0.004862 | # -*- coding: utf-8 -*-
"""Class representing the mapper for the parser init files."""
from plasoscaffolder.bll.mappings import base_mapping_helper
from plasoscaffolder.bll.mappings import base_sqliteplugin_mapping
from plasoscaffolder.model import init_data_model
class ParserInitMapping(
base_sqliteplugin_mappin... | ng the init mapper class.
Args:
mapping_helper (base_mapping_helper.BaseMappingHelper): the helper class
for the mapping
"""
super().__init__()
self._helper = mapping_helper
def GetRenderedTemplate(
self,
data: init_data_model.InitDataModel) -> str:
"""Retrieves the p... | tDataModel): the data for init file
Returns:
str: the rendered template
"""
context = {'plugin_name': data.plugin_name,
'is_create_template': data.is_create_template}
rendered = self._helper.RenderTemplate(
self._PARSER_INIT_TEMPLATE, context)
return rendered
|
webisteme/punkmoney | tracker/utils/graph.py | Python | mit | 1,913 | 0.019341 | #!/usr/bin/python
"""
PunkMoney 0.2 :: graph.py
Calculates karma as PageRank in the thank-you graph.
"""
# Create a graph
import networkx as nx
from networkx.exception import NetworkXError
from mysql import Connection
from pprint import pprint
import math
import operator
class Karma(Connection):
| def __init__(self):
self.DG = nx.DiGraph()
self.setupLogging()
self.connectDB()
# Get graph data
def populate(self):
sql = "SELECT * FROM tracker_events WHERE type = 1"
values = self.getRows(sql)
for v in values:
self.DG.add_... | def recalculate(self):
authorities = nx.hits(self.DG)[1]
# Convert to log scale
authorities_log = {}
for user,value in authorities.items():
v = value * 10**30
if value > 0:
v = math.log(v)
... |
connor-cash/nesonomics | unused/HexManager.py | Python | gpl-3.0 | 785 | 0.014013 | class HexManager:
def __init__(self, world):
self.world = world
def promp | tAssignHex(self):
hexid = raw_input("Hex id to assign");
networkid = raw_input("Network id to assing this hex");
targethex = self.world.getHexByID(hexid)
targetNetwork = self.world.getNetwork(networkid)
shouldContinue = False
if (targetNetwork.hasOwner() & & (targethex.ge... | = raw_input("Requested action assigns hex to a different player, proceed?(y/n)")
if (shouldContinue):
self.world.assignHexToNetwork(targethex, targetNetwork)
print "hex assigned"
else:
print "action aborted"
def promptSetHex():
pass
|
axbaretto/beam | sdks/python/.tox/docs/lib/python2.7/site-packages/sphinx/environment/managers/indexentries.py | Python | apache-2.0 | 7,329 | 0.000819 | # -*- coding: utf-8 -*-
"""
sphinx.environment.managers.indexentries
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Index entries manager for sphinx.environment.
:copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
import bisect
import un... | d)) in iteritems(v[1]))
if v[2] is None:
# now calculate the key
letter = unicodedata.normalize('NFD', k[0])[0].upper()
if letter in letters:
return letter
else:
# get all other symbols under one heading
... | ]
return [(key_, list(group))
for (key_, group) in groupby(newlist, keyfunc2)]
|
tysonholub/twilio-python | tests/integration/api/v2010/account/usage/record/test_this_month.py | Python | mit | 5,379 | 0.003532 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class ThisMonthTestCase(Integra... | ode",
"count": "0",
"count_ | unit": "messages",
"description": "Short Code Inbound SMS",
"end_date": "2015-09-04",
"price": "0",
"price_unit": "usd",
"start_date": "2015-09-01",
"subresource_uris": {
... |
puttarajubr/commcare-hq | corehq/ex-submodules/casexml/apps/case/views.py | Python | bsd-3-clause | 201 | 0.00995 |
def reference_case_attachment_view(request, domain, case_id, attachment_id):
raise NotImplemented("This | view is to be overrided by the s | pecific implementations for retrieving case attachments")
|
linovia/microinvoices | microinvoices/invoices/serializers.py | Python | mit | 281 | 0 | from rest_framework | import serializers
from . import models
class | Invoice(serializers.ModelSerializer):
class Meta:
model = models.Invoice
fields = (
'id', 'name', 'additional_infos', 'owner',
'creation_date', 'update_date',
)
|
drufat/dec | doc/plot/cheb/basis_forms_2d.py | Python | gpl-3.0 | 1,285 | 0.009339 | import numpy as np
from dec.grid2 import Grid_2D, basis_fn
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
g = Grid_2D.periodic(7, 7)
X = np.linspace(g.gx.xmin, g.gx.xmax, 100)
Y = np.linspace(g.gy.xmin, g.gy.xmax, 100)
X, Y = np.meshgrid(X, Y)
B = basis_fn(g.gx.dec.B, g.gy.dec.B)
fig = plt.fi... | ig = plt.figure()
ax = fig.gca(projection='3d')
for i, j, c in [(0, 0, 'r'),
(2, 2, 'g'),
(4, 4, 'b')]:
Z = B[2, True](i, j)(X,Y)
ax.plot_surface(X, Y, Z, rstride=3, cstride=3, color=c, alpha=0.4)
fig = plt.figure()
ax = fig.gca(projection='3d')
for i, j, c in [(0, 0, 'r'),
... | urface(X, Y, Z, rstride=3, cstride=3, color=c, alpha=0.4)
plt.show()
|
VeryLonelyCocks/shiva | shiva/commands/telegram/selectel.py | Python | gpl-3.0 | 8,541 | 0.002487 | import io
import os
class Selectel:
def __init__(self, core):
self.core = core
self.telegram = core.telegram.BOT
self.commands = {
'auth': self.storage_auth,
'containers': self.send_container_list,
'select_container': self.select_container,
... | share_button = [[{
'text': '',
'url': 'https://t.me/share/url?url={}'.format(link)
}]]
if link:
self.telegram.send_message(link, chat_id=chat['id'], reply_markup={'inline_keyboard': share_button})
else:
self.telegram.send_message('К сожале... | te = self.core.states.get(chat['id']) or {}
container = state.get('container')
if not container:
self.telegram.send_message('Пожалуйста, выберите контейнер. \n'
'Список доступных контейнеров — /containers')
return
files = self.sdk.... |
telminov/sw-django-division-perm | division_perm/forms.py | Python | mit | 10,182 | 0.00307 | # coding: utf-8
from django import forms
from django.conf import settings
from django.contrib.auth import password_validation
from django.contrib.auth.models import User
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
from django.core import validators
from . import models
clas... | tance.encrypted_secret_key:
secret_key = self.instance.get_secret_key()
self.fields['secret_ke | y'].help_text = secret_key
def clean(self):
cleaned_data = super().clean()
can_external = cleaned_data.get('can_external')
secret_key = cleaned_data.get('secret_key')
if can_external and not (self.instance.encrypted_secret_key or secret_key):
err_msg = 'Для внешних вызов... |
ddico/odoo | addons/l10n_ch/report/__init__.py | Python | agpl-3.0 | 52 | 0.019231 | # -*- coding:utf-8 - | *-
from . import swis | sqr_report |
sid-kap/pants | src/python/pants/backend/jvm/tasks/jvm_compile/java/java_compile.py | Python | apache-2.0 | 7,482 | 0.006683 | # 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
from pant... | jvm_options=jvm_options,
args=args,
workunit_name='jmake',
workunit_labels=[WorkUnitLabel.COMPILER])
if result:
default_message = 'Unexpected error - | JMake returned {}'.format(result)
raise TaskError(_JMAKE_ERROR_CODES.get(result, default_message))
|
tardis-sn/tardis | tardis/montecarlo/montecarlo_numba/calculate_distances.py | Python | bsd-3-clause | 3,846 | 0.00078 | import math
from numba import njit
from tardis.montecarlo.montecarlo_numba import (
njit_dict_no_parallel,
)
import tardis.montecarlo.montecarlo_numba.numba_config as nc
from tardis.montecarlo.montecarlo_numba.numba_config import (
C_SPEED_OF_LIGHT,
MISS_DISTANCE,
SIGMA_THOMSON,
CLOSE_LINE_THRESH... | e distance to 0.
if abs(nu_diff / nu) < CLOSE_LINE_THRESHOLD:
nu_diff = 0.0
if nu_diff >= 0:
distance = (nu_diff / nu) * C_SPEED_OF_LIGHT * time_explosion
else:
raise MonteCarloException(
"nu difference is less than 0.0"
)
if nc.ENABLE_FULL_RELATIVITY:
... | no_parallel)
def calculate_distance_line_full_relativity(
nu_line, nu, time_explosion, r_packet
):
# distance = - mu * r + (ct - nu_r * nu_r * sqrt(ct * ct - (1 + r * r * (1 - mu * mu) * (1 + pow(nu_r, -2))))) / (1 + nu_r * nu_r);
nu_r = nu_line / nu
ct = C_SPEED_OF_LIGHT * time_explosion
distance =... |
savioabuga/phoenix | phoenix/dashboard/views.py | Python | bsd-3-clause | 614 | 0.001629 | from django.views.generic import TemplateView
from django.shortcuts import render_to_response
from django.template import RequestContext
from braces.views import LoginRequiredMixin
class DashboardView(LoginRequiredMixin, TemplateView):
template_name = 'dashboard.html'
def get(self, *args, **kwargs):
... | s):
context_data = super(DashboardView, self).get_context_data(**kwargs)
co | ntext_data['number_livestock'] = None
return context_data
|
ourway/vixenserver | controllers/appadmin.py | Python | gpl-3.0 | 14,439 | 0.002563 | # -*- coding: utf-8 -*-
# ##########################################################
# ## make sure administrator is on localhost
# ###########################################################
import os
import socket
import datetime
import copy
import gluon.contenttype
import gluon.fileutils
# ## critical --- make a ... | =IS_NOT_EMPTY(error_message=T("Cannot be empty")))), TR(T('Update:'),
INPUT(_name='update_check', _type='checkbox',
value=False), INPUT(_style='width:400px',
_name='update_fields', _value=request.vars.update_fields
or '')), TR(T('Delete:') | , INPUT(_name='delete_check',
_class='delete', _type='checkbox', value=False), ''),
TR('', '', INPUT(_type='submit', _value='submit'))),
_action=URL(r=request, args=request.args))
if request.vars.csvfile != None:
try:
import_csv(db[request.vars.tab... |
josdaza/deep-toolbox | PyTorch/LogisticClassifier.py | Python | mit | 2,935 | 0.006814 | import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
# Datos de Prueba
data = [("me gusta comer en la cafeteria".split(), "SPANISH"),
("Give it to me".split(), "ENGLISH"),
("No creo que sea una buena idea".split(), "SPANISH"),
... | 00):
for instance, label in data:
model.zero_grad()
bow_vec = autograd.Variable(make_bow_vector(instance, word_to_ix))
| target = autograd.Variable(make_target(label, label_to_ix))
log_probs = model(bow_vec)
loss = loss_function(log_probs, target)
loss.backward()
optimizer.step()
return model
def test_model(model,test_data):
for instance, label in test_data:
bow_... |
SonRiab/infotool | portal/views.py | Python | gpl-2.0 | 744 | 0 | """
Copyright (C) 2014 Rene Jablonsk | i
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; version 2
of the License.
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... |
yuxiang-zhou/MarketAnalysor | MADjangoProject/market/admin.py | Python | mit | 1,065 | 0.006573 | from django.contrib import admin
from django.contrib.auth.models import User
from .models import Stock, StockHistory, StockSelection, SectorHistory, StockNews
class C | ommonAdmin(admin.ModelAdmin):
date_hierarchy = 'pub_date'
class SectorAdmin(CommonAdmin):
list_display = ('Symbol', 'Sector', 'pub_date')
search_fields = ['Symbol', 'Sector']
class StockAd | min(CommonAdmin):
list_display = ('Symbol', 'Name','MarketCap', 'Catagory', 'pub_date')
search_fields = ['Symbol']
class StockRelativeAdmin(CommonAdmin):
def stock_info(obj):
return '{}, {}, {}, {}'.format(
obj.stock.Symbol,
obj.stock.Name,
obj.stock.MarketCap,
... |
puttarajubr/commcare-hq | corehq/apps/es/cases.py | Python | bsd-3-clause | 777 | 0 | from .es_query import HQESQuery
from . import filters
class CaseES(HQESQuery):
index = 'cases'
@property
def builtin_filters(self):
re | turn [
opened_range,
closed_range,
is_closed,
case_type,
owner,
] + super(CaseES, self).builtin_filters
def opened_range(gt=None, gte=None, lt=None, lte=None):
return filters.date_range('opened_on', gt, gte, lt, lte)
def closed_range(gt=None, g... | ):
return filters.term('closed', closed)
def case_type(type_):
return filters.term('type.exact', type_)
def owner(owner_id):
return filters.term('owner_id', owner_id)
|
perfsonar/pscheduler | pscheduler-tool-iperf2/iperf2/iperf2_parser.py | Python | apache-2.0 | 9,825 | 0.011094 | import re
import pscheduler
import pprint
logger = pscheduler.Log(quiet=True)
# A whole bunch of pattern matching against the output of the "iperf" tool
# client output. Builds up an object of interesting bits from it.
def parse_output(lines):
results = {}
results['succeeded'] = True
seen_header = False
... | nterval_streams,
"summary": summary_stream
}
if interval == "summary":
summary_interval = finalized
else:
intervals.append(finalized)
logger.debug(intervals)
# sort according to start interval
intervals.sort(key = lambda x: x['summary']['start'... | lts["summary"] = summary_interval
return results
if __name__ == "__main__":
# Test a "regular" output
test_output = """
------------------------------------------------------------
Client connecting to 10.0.2.15, TCP port 5001
TCP window size: 19800 Byte (default)
-------------------------------------... |
Thomasvdw/ProgProject | Data/zipcode/zip_to_county_incts.py | Python | mit | 1,853 | 0.026983 | # -*- coding: utf-8 -*-
"""
Created on Wed May 27 20:06:01 2015
@author: Thomas
"""
# Python standard library imports
import csv
SOLAR_CSV = "C:\Users\Thomas\Documents\GitHub\ProgProject\PVdata\SolarRadiation\solar_by_zip.csv"
OUTPUT_CSV = "C:\Users\Thomas\Documents\GitHub\ProgProject\PVdata\SolarRadiation\solar_by_... | t 'second part..' + row[0]
zipcode[row[5]] = row[0]
incits = {}
retu | rn incits, zipcode, radiation
if __name__ == '__main__':
incits, zipcode, radiation = main()
with open(INCITS_CSV, 'r') as csvfile:
reader = csv.reader(csvfile, delimiter = ",")
next(csvfile)
for row in reader:
print 'third part..' + row[0]
... |
team-vigir/flexbe_behavior_engine | flexbe_testing/src/flexbe_testing/tester.py | Python | bsd-3-clause | 7,123 | 0.002948 | #!/usr/bin/env python
import rosunit
import unittest
import re
from flexbe_core.core.user_data import UserData
from .logger import Logger
from .test_interface import TestInterface
from .test_context import TestContext, LaunchContext
from .data_provider import DataProvider
class Tester(object):
def __init__(sel... | onfig needs to be a dictionary but is:\n\t%s' % str(config))
assert 'path' in config
assert 'class' in config or 'name' in config
assert 'outcome' in config or config.get('import_only', False)
# ROSUNIT interface
def perform_rostest(self, test_pkg):
TestCase = type(test_pkg + '... | nittest.TestCase,), self._tests)
rosunit.unitrun(test_pkg, test_pkg + '_flexbe_tests', TestCase)
def _test_output(self, value, expected):
def _test_call(test_self):
test_self.assertEqual(value, expected, "Output value %s does not match expected %s" % (value, expected))
return _t... |
stormi/tsunami | src/secondaires/navigation/equipage/ordres/deplacer.py | Python | bsd-3-clause | 2,490 | 0.001209 | # -*-coding:Utf-8 -*
# Copyright (c) 2012 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
# lis... | # may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, I | NCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREM... |
iekadou/django-pjaxr | django_pjaxr/test_settings.py | Python | mit | 4,024 | 0.001988 | # Django settings for testproject project.
import os
PROJECT_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DEBUG_PROPAGATE_EXCEPTIONS = True
ALLOWED_HOSTS = ['*']
ADMINS = ()
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.back... | ngo.template.loaders.app_directories.Lo | ader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROO... |
hchiam/cognateLanguage | miniExamples/germalkorswa/createList.py | Python | mit | 10,267 | 0.008279 | from collections import OrderedDict
import re
#------------------------
# shared variables:
#------------------------
words = OrderedDict()
outputFilename = 'output.txt'
filename1 = 'data.txt'
allophones = {
'aeiou' : 'a',
'bp' : 'b',
'cjsz' : 'z',
'dt' : 'd',
'fv' : 'v',
'gkq' : 'g',
'... | o initial vowel
words[lang] = word[1:]
#if lang != 'Chi': # get first, simplified syllable
words[lang] = simpNonChiWordMaker(words[lang])
#eli | f lang == 'Chi':
#words[lang] = simpChiWordMaker(words[lang])
print (word)
#removeHForHin(word,lang)
wordsInitSyllables = words.copy()
# the words with allophonic spelling:
for language in words:
if language != 'Eng':
words[language] = respellWi... |
InfiniTower/Omni | networking/web.py | Python | gpl-2.0 | 240 | 0.016667 | import rss |
class WebConnector:
def __init__(self):
self.rss_feed = rss.FeedReader()
def get_news(self, source):
return self.rss_feed.get_news(source)
def get_joke(self):
return self.rss_feed.get_jok | e()
|
aubzen/sheltermanager | src/wordprocessor.py | Python | gpl-3.0 | 41,766 | 0.008619 | #!/usr/bin/python
import additional
import animal
import configuration
import dbfs
import financial
import html
import log
import medical
import person
import users
import utils
from i18n import _, format_currency_no_symbol, now, python2display, yes_no
from sitedefs import BASE_URL
def org_tags(dbo, username):
""... | bo.locale, now(dbo.timezone)),
"USERNAME" : username,
"USERREALNAME" : realname,
"USEREMAILADDRESS" : email
}
return tags
def additional_yesno(l, af):
"""
Returns the yes/no value for an additi | onal field. If it has a LOOKUPVALUES
set, we use the value the user set.
"""
if af["LOOKUPVALUES"] is not None and af["LOOKUPVALUES"] != "":
values = af["LOOKUPVALUES"].split("|")
for v in values:
if af["VALUE"] is None:
if v.strip().startswith("0"):
... |
doganmeh/quranfal | quranfal/migrations/0003_auto_20160608_2056.py | Python | mit | 1,430 | 0.003497 | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-06-08 20:56
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('quran', '0009_word_utextmin'),
('quranfal', '0002_auto... | model_name='useraya',
name='list',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='quranfal.List'),
),
migrations.AlterField(
model_name='userword',
name='list',
field=models.ForeignKey(on_delete=django.db.model... | ManyField(through='quranfal.UserAya', to='quran.Aya'),
),
migrations.AddField(
model_name='list',
name='words',
field=models.ManyToManyField(through='quranfal.UserWord', to='quran.DistinctWord'),
),
]
|
cosbynator/NPSGD | npsgd/standalone_task.py | Python | bsd-3-clause | 1,821 | 0.006041 | # Author: Thomas Dimson [tdimson@gmail.com]
# Date: January 2011
# For distribution details, see LICENSE
"""Module containing abstract base class for standalone models."""
import os
import logging
import subprocess
from model_task import ModelTask
from config import config
class StandaloneError(RuntimeError): pass
c... | """Abstract base task for standalone models.
This class is meant to be the superclass of the user's various
standalone models. These will generally compiled models, but can includ | e
anything that needs to be launched in a subprocess
"""
abstractModel = "StandaloneTask"
executable = "ls"
def executableParameters(self):
"""Returns parameters to the underlying executable as a Python list."""
return [
"-al",
"*"
]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.