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 |
|---|---|---|---|---|---|---|---|---|
adieu/authentic2 | authentic2/migrations/0006_auto__chg_field_user_username__chg_field_user_email.py | Python | agpl-3.0 | 266 | 0 | # -*- codi | ng: utf-8 -*-
from south.db import db
from south.v2 import SchemaMigration
class Migration(SchemaMigr | ation):
def forwards(self, orm):
pass
def backwards(self, orm):
pass
models = {
}
complete_apps = ['authentic2']
|
cristhro/Machine-Learning | ejercicio 5/flaskApp/flaskApp.py | Python | gpl-3.0 | 6,023 | 0.01926 | from flask import Flask, jsonify, request, render_template, make_response
from datetime import datetime
from elasticsearch import Elasticsearch
es = Elasticsearch()
app = Flask(__name__)
@app.route('/')
def hello_world():
return render_template(
'index.html'
)
@app.route('/buscar', methods = ["POST"... | itle)s" % hit["_source"])
return resultado
def realizar_busqueda_3(buscado):
bodyQuery = {
"query": {
"regexp":{
"Title": buscado +".*"
}
},
"highlight": {
"fields": {
"Title": {},
"Plot": {"fragment_size": 300, "number_of_fragments": 3},
... | este ejemplo
"require_field_match": False
}
}
res = es.search(index="prueba-index", body= bodyQuery)
print("Got %d Hits:" % res['hits']['total'])
resultado = []
for hit in res['hits']['hits']:
resultado.append(hit['highlight'])
return resultado
def realizar_busqueda_4(b... |
endlisnis/weather-records | maxtemp.py | Python | gpl-3.0 | 3,298 | 0.010309 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
import time, posix, daily
data = daily.load("ottawa")
class FloatValue():
__slots__ = ()
def __init__(self, field):
self.fieldIndex = field.index
def __call__(self, fields):
r = fields[self.fieldIndex]
... | return self(one) < self(two)
def findBest(proc):
bv = None
date = None
#
for year in data:
yd = data[year]
for month in yd:
md = yd[month]
for day in md:
f = md[day]
if bv == None or proc.better(f, bv):
bv ... | def histogram(proc):
hist = {}
#
for year in data:
yd = data[year]
for month in yd:
md = yd[month]
for day in md:
f = proc(md[day])
if f != None:
if f not in hist:
hist[f] = 0
... |
awslabs/sockeye | sockeye_contrib/benchmark/benchmark_to_output.py | Python | apache-2.0 | 1,162 | 0 | #!/usr/bin/env python
# Copyright 2021 Amazon.com, Inc. or its affiliates. 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. A copy of the License
# is located at
#
# http:/ | /aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied. See the License for the specific language governing
# permissions and limitations under the License.
import sys
from... | entry = dict(field.split('=', 1) for field in fields)
yield entry
def get_output_from_benchmark_output(input_stream) -> Iterator[str]:
for entry in read_benchmark_handler_output(input_stream):
yield entry['output']
def main():
for output in get_output_from_benchmark_output(sys.stdin):
... |
prman-pixar/RenderManForBlender | rfb_utils/camera_utils.py | Python | mit | 2,235 | 0.004474 | from bpy_extras.view3d_utils import location_3d_to_region_2d
def render_get_resolution_(r):
xres = int(r.resolution_x * r.resolution_percentage * 0.01)
yres = int(r.resolution_y * r.resolution_percentage * 0.01)
return xres, yres
def render_get_aspect_(r, camera=None, x=-1, y=-1):
if x != -1 and y... | == 'VERTICAL' or fit == 'AUTO' and yratio > xratio:
aspectratio = yratio / xratio
xaspect = 1.0
yaspect = aspectratio
else:
aspectratio = xaspect = | yaspect = 1.0
return xaspect, yaspect, aspectratio
def get_viewport_cam_borders(ob, render, region, region_data, scene):
# Code reference:
# https://blender.stackexchange.com/questions/6377/coordinates-of-corners-of-camera-view-border
cam = ob.data
frame = cam.view_frame(scene=scene)
# move fr... |
Fougere87/unsec | unsec/algorithm/__init__.py | Python | unlicense | 202 | 0.00495 | from unsec.algorithm | .algo import Algo
from unsec.algorithm.hierarchical_algo import HierarchicalAlgo
from unsec.algorithm.skmean_algo import SKMeanAlgo
from unsec.algor | ithm.kmean_algo import KMeanAlgo
|
fabioz/Pydev | plugins/org.python.pydev.core/pysrc/_pydevd_bundle/pydevd_bytecode_utils.py | Python | epl-1.0 | 25,462 | 0.001885 | """
Bytecode analysing utils. Originally added for using in smart step into.
Note: not importable from Python 2.
"""
import sys
if sys.version_info[0] < 3:
raise ImportError('This module is only compatible with Python 3.')
from _pydev_bundle import pydev_log
from types import CodeType
from _pydevd_frame_eval.ven... | those as if they didn't change the stack.
STRICT_MODE = False
DEBUG = False
_BINARY_OPS = set([opname for opname in dis.opname if opname.startswith('BINARY_')])
_BINARY_OP_MAP = {
'BINARY_POWER': '__pow__',
'BINARY | _MULTIPLY': '__mul__',
'BINARY_MATRIX_MULTIPLY': '__matmul__',
'BINARY_FLOOR_DIVIDE': '__floordiv__',
'BINARY_TRUE_DIVIDE': '__div__',
'BINARY_MODULO': '__mod__',
'BINARY_ADD': '__add__',
'BINARY_SUBTRACT': '__sub__',
'BINARY_LSHIFT': '__lshift__',
'BINARY_RSHIFT': '__rshift__',
'BIN... |
Shir0kamii/py3status | py3status/modules/mpd_status.py | Python | bsd-3-clause | 8,004 | 0.00025 | # coding: utf-8
"""
Display information from mpd.
Configuration parameters:
cache_timeout = how often we refresh this module in seconds (2s default)
color = enable coloring output (default False)
color_pause = custom pause color (default i3status color degraded)
color_play = custom play color (default ... | ubret, subfound = parse_template(instr, value_getter, found)
if found:
pass
elif subfound:
ret.append(''.join(subret))
found = True
else:
return '', False
elif char == '&':
subret, subfound = parse_te... | ound:
subret = ''.join(subret)
ret.append(subret)
else:
return '', False
else:
ret.append(char)
ret = ''.join(ret)
return ret, found
def song_attr(song, attr):
def parse_mtime(date_str):
return datetime.datetime.strpt... |
Micronaet/micronaet-script | DropboxWebsite/dropbox.py | Python | agpl-3.0 | 4,978 | 0.010848 | ###############################################################################
#
# Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the ... | ----------------------------------------
def get_modify_date(fullname):
''' Return modify da | te for file
'''
modify_date = datetime.fromtimestamp(
os.stat(fullname).st_mtime).strftime('%Y-%m-%d')
return modify_date
# -----------------------------------------------------------------------------
# ODOO operation:
# -------------------------------------------... |
flingone/frameworks_base_cmds_remoted | libs/boost/tools/build/test/module_actions.py | Python | apache-2.0 | 2,354 | 0.000425 | #!/usr/bin/python
# Copyright 2003 Dave Abrahams
# Copyright 2006 Rene Rivera
# Copyright 2003 Vladimir Prus
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
# Demonstration that module variables have the ... | t1",
"A.act t1: X1-t1 ",
"B.act t1",
"B.act t1: X1-t1 X2-B ",
"act t1",
"act t1: X1-t1 X2-global X3-global ",
"A.act t2",
"A.act t2: X1-A X2-t2 ",
"B.act t2",
"B.act t2: X2-t2 ",
"act t2",
"act t2: X1-global X2-t2 X3-global ",
| "A.act t3",
"A.act t3: X1-A X3-t3 ",
"B.act t3",
"B.act t3: X2-B X3-t3 ",
"act t3",
"act t3: X1-global X2-global X3-t3 ",
"...updated 3 targets...",
""]
# Accommodate for the fact that on Unixes, a call to 'echo 1 2 3 '
# produces '1 2 3' (note the spacing).
if os.name !... |
Orav/kbengine | kbe/src/lib/python/Tools/scripts/rgrep.py | Python | lgpl-3.0 | 1,542 | 0 | #! /usr/bin/env python3
"""Reverse grep.
Usage: rgrep [-i] pattern file
"""
import sys
import re
import getopt
def main():
bufsize = 64 * 1024
reflags = 0
opts, args = getopt.getopt(sys.argv[1:], "i")
for o, a in opts:
if o == '-i':
reflags = reflags | re.IGNOR... | as msg:
usage("can't open %r: %s" % (filename, msg), 1)
f.seek(0, 2)
pos = f.tell()
leftover = None
while pos > 0:
size = min(pos, bufsize)
pos = pos - size
f.seek(pos)
buffer = f.read(size)
lines = buffer.split("\n")
del buffer
... | if not lines[-1]:
del lines[-1]
else:
lines[-1] = lines[-1] + leftover
if pos > 0:
leftover = lines[0]
del lines[0]
else:
leftover = None
for line in reversed(lines):
if prog.search(line):
... |
tectronics/pipal | face.py | Python | gpl-3.0 | 34 | 0.029412 | #!/usr/bin/env python3
i | mport | cv2 |
Adarnof/allianceauth | allianceauth/srp/auth_hooks.py | Python | gpl-2.0 | 699 | 0 | from allianceauth.services.hooks import MenuItemHook, UrlHook
from allianceauth import | hooks
from . import urls
class SrpMenu(MenuItemHook):
def __init__(self):
MenuItemHook.__init__(self, 'Ship Replacement',
'fa fa-money | fa-fw',
'srp:management',
navactive=['srp:'])
def render(self, request):
if request.user.has_perm('srp.access_srp'):
return MenuItemHook.render(self, request)
return ''
@hooks.register('menu_item_hook')
def register_menu():
... |
neherlab/treetime | treetime/seq_utils.py | Python | mit | 14,020 | 0.013623 | import numpy as np
from Bio import Seq, SeqRecord
alphabet_synonyms = {'nuc':'nuc', 'nucleotide':'nuc', 'aa':'aa', 'aminoacid':'aa',
'nuc_nogap':'nuc_nogap', 'nucleotide_nogap':'nuc_nogap',
'aa_nogap':'aa_nogap', 'aminoacid_nogap':'aa_nogap',
'DNA':'nuc',... | 'N': np.array([1, 1, 1, 1, 1], dtype='float'),
'X': np.array([1, 1, 1, 1, 1], dtype='float'),
'R': np.array([1, 0, 1, 0, 0], dtype='float'),
'Y': np.array([0, 1, 0, 1, 0], dtype='float'),
'S': np.array([0, 1, 1, 0, 0], dtype='float'),
'W': np.array([1, 0, 0, 1, 0], dtype='float'),
'K': np.arr... | 1, 0], dtype='float'),
'H': np.array([1, 1, 0, 1, 0], dtype='float'),
'B': np.array([0, 1, 1, 1, 0], dtype='float'),
'V': np.array([1, 1, 1, 0, 0], dtype='float')
},
'nuc_nogap':{
'A': np.array([1, 0, 0, 0], dtype='float'),
'C': np.array([0, 1, 0, 0], dtype='float'),
'G': np.array([0, 0, 1... |
jpf/ftp-to-s3 | server.py | Python | mit | 3,319 | 0.000603 | import hashlib
import os
import threading
from Queue import Queue
import requests
from boto.s3.connection import S3Connection
from boto.s3.key import Key
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer
from konfig import Konfig
konf ... | print "Worker online"
while True:
print "Worker waiting for job ... %s" % str(job_queue.qsize() | )
filename = job_queue.get()
print "Worker got job: %s, qsize: %s" % (
filename,
str(job_queue.qsize()))
process_file(filename)
# time.sleep(1)
job_queue.task_done()
print "Task done, qsize: %s" % str(job_queue.qsize... |
iulian787/spack | var/spack/repos/builtin/packages/alquimia/package.py | Python | lgpl-2.1 | 2,700 | 0.00037 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Alquimia(CMakePackage):
"""Alquimia is an interface that exposes the capabilities
of m... | aintainers = ['smolins', 'balay']
version('develop')
version('xsdk-0.6.0', commit='9a0aedd3a927d4d5e837f8fd18b74ad5a78c3821')
version('xsdk-0.5.0', commit='8397c3b00a09534c5473ff3ab21f0e32bb159380')
version('xsdk-0.4.0', commit='2edad6733106142d014bb6e6a73c2b21d5e3cf2d')
version('xsdk-0.3.0', tag='... | ', tag='xsdk-0.2.0')
variant('shared', default=True,
description='Enables the build of shared libraries')
depends_on('mpi')
depends_on('hdf5')
depends_on('pflotran@xsdk-0.6.0', when='@xsdk-0.6.0')
depends_on('pflotran@xsdk-0.5.0', when='@xsdk-0.5.0')
depends_on('pflotran@xsdk-0.4.0... |
wangyum/tensorflow | tensorflow/python/tools/saved_model_cli_test.py | Python | apache-2.0 | 15,971 | 0.00288 | # Copyright 2017 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... | ers import local_cli_wrapper
from tensorflow.python.platform import test
from tensorflow.python.tools import saved_model_cli
SAVED_MODEL_PATH = ('cc/saved_model/testdata/half_plus_two/00000123')
@contextlib.co | ntextmanager
def captured_output():
new_out, new_err = StringIO(), StringIO()
old_out, old_err = sys.stdout, sys.stderr
try:
sys.stdout, sys.stderr = new_out, new_err
yield sys.stdout, sys.stderr
finally:
sys.stdout, sys.stderr = old_out, old_err
class SavedModelCLITestCase(test.TestCase):
def ... |
comic/comic-django | app/grandchallenge/retina_api/mixins.py | Python | apache-2.0 | 1,522 | 0 | from django.conf import settings
from django.contrib.auth.mixins import AccessMixin
from rest_framework import permissions
def is_in_retina_graders_group(user):
"""
Checks if the user is in the retina graders group
:param user: Django User model
:return: true/false
"""
return user.groups.filte... | se
""" |
return user.groups.filter(name=settings.RETINA_ADMINS_GROUP_NAME).exists()
def is_in_retina_group(user):
"""
Checks if the user is in the retina graders or retina admins group
:param user: Django User model
:return: true/false
"""
return is_in_retina_graders_group(user) or is_in_retina_ad... |
thefirstwind/s3qloss | src/s3ql/backends/common.py | Python | gpl-3.0 | 38,276 | 0.003919 | '''
common.py - this file is part of S3QL (http://s3ql.googlecode.com)
Copyright (C) 2008-2009 Nikolaus Rath <Nikolaus@rath.org>
This program can be distributed under the terms of the GNU GPLv3.
'''
from __future__ import division, print_function, absolute_import
from ..common import QuietError, BUFSIZE
from abc imp... | a temporary error (as defined by
`is_temp_failure`) occurs during opening, closing or execution of *fn*, the operation is
retried.
'''
with self.open_read(key) as fh:
return fn(fh)
@retry
def perform_write(self, fn, key, metadata=None, is_compressed=False):
'... | ta using *fn*, retry on temporary failure
Open object for writing, call `fn(fh)` and close object. If a temporary error (as defined by
`is_temp_failure`) occurs during opening, closing or execution of *fn*, the operation is
retried.
'''
with self.open_write(key, metadat... |
laserson/luigi | test/import_test.py | Python | apache-2.0 | 1,296 | 0 | # -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# Licensed under the Apache License, Version 2.0 (the "License") | ;
# you may not use this file except in compliance with the License.
# You may obt | ain 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 spe... |
hxp2k6/https-github.com-stamparm-maltrail | trails/feeds/badips.py | Python | mit | 636 | 0.001572 | #!/usr/bin/env python
"""
Copyright (c) 2014-2015 Miroslav Stampar (@stamparm)
See the file 'LICENSE' for copying pe | rmission
"""
from core.common import retrieve_content
__url__ = "https://www.badips.com/get/list/any/2?age=7d"
__check__ = ".1"
__info__ = "attacker"
__reference__ = "badips.com"
def fetch():
retval = {}
content = retrieve_content(__url__)
if __check__ in content:
for line in content.split('\n')... | __)
return retval
|
WorldViews/Spirals | play/tweet.py | Python | mit | 6,221 | 0.003376 | from flask import Flask, request, redirect, url_for, session, flash, g, \
render_template
from flask_oauth import OAuth
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
# configuration
#DA... | requ | est.url))
status = request.form['tweet']
if not status:
return redirect(url_for('index'))
resp = twitter.post('statuses/update.json', data={
'status': status
})
if resp.status == 403:
flash('Your tweet was too long.')
elif resp.status == 401:
flash('Authoriz... |
pf4d/dolfin-adjoint | dolfin_adjoint/adjglobals.py | Python | lgpl-3.0 | 3,298 | 0.005458 | import coeffstore
import expressions
import caching
import libadjoint
from dolfin_adjoint import backend
if backend.__name__ == "dolfin":
import lusolver
# Create the adjointer, the central object that records the forward solve
# as it happens.
adjointer = libadjoint.Adjointer()
mem_checkpoints = set()
disk_check... | ish()
# A dictionary that saves the functionspaces of all checkpoint variables that have been saved to disk
checkpoint_fs = {}
function_names = s | et()
def adj_check_checkpoints():
adjointer.check_checkpoints()
def adj_reset_cache():
if backend.parameters["adjoint"]["debug_cache"]:
backend.info_blue("Resetting solver cache")
caching.assembled_fwd_forms.clear()
caching.assembled_adj_forms.clear()
caching.lu_solvers.clear()
cachin... |
lduarte1991/edx-platform | lms/djangoapps/verify_student/services.py | Python | agpl-3.0 | 1,283 | 0.001559 | """
Implementation of "reverification" service to communicate with Reverification XBlock
"""
import logging
from django.core.urlresolvers import reverse
from student.models import User
from .models import SoftwareSecurePhotoVerification
log = logging.getLogger(__name__)
class VerificationService(object):
"""... | user_id)
# TODO: provide a photo verification abstraction so that this
# isn't hard-coded to use Software Secure.
return SoftwareSecurePhotoVerification.user_status(use | r)
def reverify_url(self):
"""
Returns the URL for a user to verify themselves.
"""
return reverse('verify_student_reverify')
|
pylayers/pylayers | pylayers/util/project.py | Python | mit | 10,692 | 0.020675 | #-*- coding:Utf-8 -*-
from __future__ import print_function
"""
.. curentmodule:: pylayers.util.project
.. autosummary::
"""
import numpy as np
import os
import sys
import shutil
import pkgutil
import pdb
import seaborn as sns
import logging
class PyLayers(object):
""" Generic PyLayers Meta Class
"""
# ... | os.mkdir(basename)
#
# write file project.conf
#
fd = open(os.path.join(basename,'project.conf'),'w')
fd.close()
#for nm in pstruc.keys():
for nm,nv in pstruc.items():
dirname = os.path.join(basename , pstruc[nm])
if not 'win' in sys.platform: |
spl = nv.split('/') # never again a variable called sp
else:
spl = nv.split('\\') # never again a variable called sp
if len(spl)>1:
if not os.path.isdir(os.path.join(basename ,spl[0])):
os.mkdir(os.path.join(basename ,spl[0]))
os.mkdir(os.path.join(basename,nv))
... |
HarmeetDhillon/Socket-Programming | Client.py | Python | gpl-2.0 | 561 | 0.026738 | from so | cket import *
import sys
clientSocket = socket(AF_INET, SOCK_STREAM) #creates socket
server_address = ('127.0.0.1', 80)#create connection at this given port
print >>sys.stderr, 'CONNECTING TO %s AT PORT %s' % server_address
clientSocket.connect(server_address)#connect to server at given address
filename=raw_input(... | file
clientSocket.close() #close the connection
|
amaas-fintech/amaas-core-sdk-python | tests/unit/monitor/item.py | Python | apache-2.0 | 1,147 | 0.003487 | from __future__ import absolute_import, division, print_function, unicode_literals
import copy
import json
import unittest
from amaascore.monitor.item import Item
from amaascore.tools.generate_monitor_item import generate_item
class ItemTest(unittest.TestCase):
def setUp(self):
self.longMessage = True ... | em_id)
# If item_json is valid JSON, this will run without serialisation errors
item_json_id = json.loads(json.dum | ps(item_json, ensure_ascii=False)).get('item_id')
self.assertEqual(item_json_id, self.item_id)
if __name__ == '__main__':
unittest.main()
|
arnomoonens/DeepRL | yarll/functionapproximation/tile_coding.py | Python | mit | 2,943 | 0.005097 | # -*- coding: utf8 -*-
from typing import List, Tuple
import numpy as np
from yarll.functionapproximation.function_approximator import FunctionApproximator
class TileCoding(FunctionApproximator):
"""Map states to tiles"""
def __init__(self, x_low, x_high, y_low, y_high, n_tilings: int, n_y_tiles: int, n_x_ti... | elf.y_low = y_low
se | lf.y_high = y_high
self.n_x_tiles = n_x_tiles
self.n_y_tiles = n_y_tiles
self.n_tilings = n_tilings
self.n_actions = n_actions
if self.n_x_tiles % 1 != 0 or self.n_x_tiles <= 0:
raise TypeError("Number of x tiles must be a positive natural number instead of {}".forma... |
gizela/gizela | gizela/data/PointListSimple.py | Python | gpl-3.0 | 2,885 | 0.020104 | # gizela
#
# Copyright (C) 2010 Michal Seidl, Tomas Kubin
# Author: Tomas Kubin <tomas.kubin@fsv.cvut.cz>
# URL: <http://slon.fsv.cvut.cz/gizela>
#
# $Id: PointListSimple.py 68 2010-08-19 09:42:00Z tomaskubin $
'''
class for list of points without finding by id and without duplicity handling
'''
from gizela.ut... | n([point.make_table_row() for point in self._list]) +\
self._list[0].make_footer()
def __str__(self):
return self.make_table()
if __name__ = | = "__main__":
from gizela.data.PointCart import PointCart
c1 = PointCart(id="C",x=1,y=2,z=3)
c2 = PointCart(id="B",x=4,y=5,z=6)
#pd=PointList(textTable=c1.get_text_table())
# setting text table accoridng to PointCart instance
pd=PointListSimple(textTable=TextTable([("ID","%2s"),(... |
huggingface/pytorch-transformers | tests/test_modeling_wav2vec2.py | Python | apache-2.0 | 23,117 | 0.002855 | # coding=utf-8
# Copyright 2021 The HuggingFace Inc. team. 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 r... | range(len(input_le | ngths)):
input_values[i, input_lengths[i] :] = 0.0
attention_mask[i, input_lengths[i] :] = 0.0
batch_outputs = model(input_values, attention_mask=attention_mask).last_hidden_state
for i in range(input_values.shape[0]):
input_slice = input_values[i : i + 1, : input_l... |
thauser/pnc-cli | test/integration/test_buildconfigsetrecords_api.py | Python | apache-2.0 | 1,504 | 0.00266 | import pytest
__author__ = 'thauser'
from pnc_cli.swagger_client.apis import BuildconfigsetrecordsApi
from test import testutils
import pnc_cli.user_config as uc
bcsr_api = None
@pytest.fixture(scope='function', autouse=True)
def init_api():
global bcsr_api
bcsr_api = BuildconfigsetrecordsApi(uc.user.get_ap... | cords', id=None)
def test_get_build_records_invalid_param():
testutils.assert_raises_typeerror(bcsr_api, 'get_build_records', id=1)
@pytest.mark.xpass(reason='none of the default record sets contain build records, and there is no api to add them.')
def test_g | et_build_records():
records = bcsr_api.get_build_records(id=1, page_index=0, page_size=1000000, sort='', q='').content
assert records is None
|
chen2aaron/SnirteneCodes | StarterLearningPython/208-namespaces-2.py | Python | gpl-2.0 | 303 | 0.0033 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Created by xixijun
# Date: 15-5-7
# Blog: morningchen.com
def outer_foo():
a = 10
def inner_foo():
| global a
a = 20
print "inne | r_foo: a=", a
# inner_foo()
print "outer_foo: a=", a
a = 30
outer_foo()
print "a=", a
|
kgorman/WMG_speed | app/app.py | Python | mit | 5,559 | 0.004317 | #!/usr/bin/env python
from flask import Flask
from flask import render_template
import pandas as pd
import numpy as np
import datetime as datetime
app = Flask(__name__)
if not app.debug:
import logging
file_handler = logging.FileHandler('error.log')
file_handler.setLevel(logging.WARNING)
app.logger.a... | np.max)['peak_speed']
keys = mean_speed.index.get_values()
mean_speed_l = [str(i) for i in list(mean_speed.get_values())]
max_speed_l = | [str(i) for i in list(max_speed.get_values())]
keys_l = [str(i) for i in list(keys)]
mean_speed_str = ','.join(mean_speed_l)
max_speed_str = ','.join(max_speed_l)
keys_str = ",".join(keys_l)
return [keys_str, mean_speed_str, max_speed_str]
def get_speed_by_day(df):
grouped = df.sort(['weekd... |
RazerM/logbook | logbook/ticketing.py | Python | bsd-3-clause | 19,231 | 0.000312 | # -*- coding: utf-8 -*-
"""
logbook.ticketing
~~~~~~~~~~~~~~~~~
Implements long handlers that write to remote data stores and assign
each logging message a ticket id.
:copyright: (c) 2010 by Armin Ronacher, Georg Brandl.
:license: BSD, see LICENSE for more details.
"""
from time import time
im... | e database for a ticket."""
raise NotImplementedError()
class SQLAlchemyBackend(BackendBase):
"""Implements a backend that is writing into a database SQLAlchemy can
interface.
This backend takes some additional options:
`table_prefix`
an optional table prefix for | all tables created by
the logbook ticketing handler.
`metadata`
an optional SQLAlchemy metadata object for the table creation.
`autocreate_tables`
can be set to `False` to disable the automatic
creation of the logbook tables.
"""
def setup_backend(self):
from ... |
openstack/ironic | ironic/objects/__init__.py | Python | apache-2.0 | 1,737 | 0 | # Copyright 2013 IBM Corp.
#
# 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 agree... | for it to be registered by services that may
| # need to receive it via RPC.
__import__('ironic.objects.allocation')
__import__('ironic.objects.bios')
__import__('ironic.objects.chassis')
__import__('ironic.objects.conductor')
__import__('ironic.objects.deploy_template')
__import__('ironic.objects.deployment')
__import__('ironic.obje... |
gregbdunn/aws-ec2rescue-linux | tools/moduletests/unit/test_selinuxpermissive.py | Python | apache-2.0 | 8,783 | 0.004213 | # Copyright 2016-2020 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
#
# or in the "license" f... | ct=(True, False))
| @mock.patch("moduletests.src.selinuxpermissive.os.path.isfile", return_value=True)
@mock.patch("moduletests.src.selinuxpermissive.backup", return_value=True)
@mock.patch("moduletests.src.selinuxpermissive.fix", return_value=True)
def test_run_success_fixed(self, fix_mock, backup_mock, isfile_mock, detect_m... |
gilch/drython | drython/expression.py | Python | apache-2.0 | 13,683 | 0.000292 | # Copyright 2016 Matthew Egan Odendahl
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | rgs)
# enset = unstar(set)
def enset(*args):
"""
returns args as a set
>>> enset(1, 2, 3) == {1, 2, 3}
True
"""
return set(args)
# efset = unstar(frozenset)
def efs | et(*args):
"""
return args as a frozenset
>>> efset(1, 2, 3) == frozenset([1, 2, 3])
True
"""
return frozenset(args)
def edict(*args, **kwargs):
"""
pairs args and makes a dictionary with them
>>> edict(1, 2)
{1: 2}
>>> edict(1, 2, 3, 4, 5, 6)[3]
4
>>> edict(1, 2,... |
DistributedComponents/verdi-aggregation | extraction/aggregation-dynamic/script/client.py | Python | bsd-2-clause | 2,030 | 0.002463 | import socket
import re
import uuid
from struct import pack, unpack
from select import select
def poll(sock, timeout):
return sock in select([sock], [], [], timeout)[0]
class SendError(Exception):
pass
class ReceiveError(Exception):
pass
class Client(object):
re_aggregate_response = re.compile(r'Agg... | e.compile(r'LevelResponse[^0-9-]+([0-9]+|-)')
def __init__(self | , host, port, sock=None):
if not sock:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((host, port))
else:
self.sock = sock
def send_msg(self, msg):
n = self.sock.send(pack("<I", len(msg)))
if n < 4:
rai... |
EDRN/labcas-backend | workflows/src/main/resources/rnaseq/pges/rnaseq-task1.py | Python | apache-2.0 | 2,942 | 0.009857 | # python script to execute RNA Sequence Pipeline Task #1
# usage: python rnaseq-pipeline-task1.py --num_threads <num_threads> --gene_transcript_file <gene_transcript_file> --genome_index <genome_index >
# --data_dir <data_dir> --output_dir <output_dir> --sample_id <sample_id>
# e... | task1.py --num_threads 24 --gene_transcript_file genes.gtf --genome_index genome
# --data_dir /data/EDRN --output_dir thout --sample_id ERR164503
import argparse
import os
INPUT_FILE_EXTENSIONS = ['.sra','.fastq','.gtf','.fa','.bt2']
if __name__ == '__main__':
# par... | ce Pipeline Task #1")
parser.add_argument('--num_threads', dest='num_threads', type=int, help="Number of THreads", default=1)
parser.add_argument('--gene_transcript_file', dest='gene_transcript_file', type=str, help="Gene Transcript File", default=None)
parser.add_argument('--genome_index', dest='genome_ind... |
MakingMexico/web_page | makingmx/settings/base.py | Python | gpl-3.0 | 3,343 | 0.001197 | """
Django settings for makingmx project.
Generated by 'django-admin startproject' using Django 1.10.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import o... | },
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https | ://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = 'staticfiles'
STATICFILES_DIRS = (
... |
shantanu69/pygame-physics | PyParticleSystem/PyParticles/utils.py | Python | mit | 330 | 0.027273 | import math
def add_vectors(vector1, vector2):
#Note the vectors are tuple (angle, magnitude)
x = math.sin(vector | 1[0]) * vector1[1] + math.sin(vector2[0]) * vector2[1]
y = math.cos(vector1[0]) * vector1[1] + math.cos(vector2[0]) * vector2[1]
mag = math.hypot(x, y)
angle = (math.pi/2) - math.atan2(y, x)
return (angle, ma | g) |
CatherineH/adolphus | adolphus/yamlparser.py | Python | gpl-3.0 | 13,944 | 0.002438 | """\
YAML parser module.
@author: Aaron Mavrinac
@organization: University of Windsor
@contact: mavrin1@uwindsor.ca
@license: GPL-3
"""
import os
import yaml
from math import pi
import pkg_resources
from itertools import chain
from .robot import Robot
from .solid import Solid
from .laser import RangeModel
from .cov... | .
@rtype: C{list}
"""
path = self._path
if isinstance(robot, str):
robot_file = self._external_path(path, robot)
robot = yaml.load(open(robot_file, 'r'))
path = os.path.split(robot_file) | [0]
links = robot['links']
print links
for link in links:
link['offset'] = self._parse_pose(link['offset'])
link['triangles'] = self._parse_triangles(link, path)
return links
def _parse_model(self, model, modeltype):
"""\
Parse a multi-camera ... |
rochacbruno/flasgger | tests/test_examples.py | Python | mit | 2,399 | 0 | # coding: utf-8
from flex.core import validate
from flex import load as validate_fully
def test_validate_example_specs(test_data):
"""
This test is generated by conftest.py
for each app in examples app and `test_data` param is:
mod, client, specs_data, opts = test_data
mod: examples.example_name... | ecs, before it was renamed to OpenAPI.
validate_fully(spec)
else:
# OpenAPI specs are not yet supported by flex, so we should fall
# back to a fairly simple structural validation.
validate(spec)
def test_required_at | tributes(test_data):
"""
This test is generated by conftest.py
for each app in examples app and `test_data` param is:
mod, client, specs_data, opts = test_data
mod: examples.example_name (the test module)
client: Flask app test client
specs_data: {'url': {swag_specs}} for every spec in app... |
sanyi/awsutils | examples/tornado-sqs.py | Python | mit | 536 | 0.01306 |
import tornado.ioloop
#!! this example requires the file /test/setting.py with the folowing constants is created
from awsutils.tornado.sqsclient import SQSCl | ient
from test.settings import access_key, secret_key
sqsclient = SQSClient(endpoint='sqs.us-east-1.amazonaws.com', access_key=access_key, secret_key=secret_key, | secure=False)
def renderResult(data):
print("message received", data)
sqsclient.sendMessage(callback=renderResult, qName="test", messageBody="this is a test message")
tornado.ioloop.IOLoop.instance().start() |
Hellseher/ProjectEuler | src/pe_python/pe_050_problem.py | Python | gpl-2.0 | 2,384 | 0 | #! /usr/bin/env python
# _*_ coding: UTF-8 _*_
# File : 50-problem.py
# Created : Sat 11 Apr 2015 20:57:18
# Last Modified : Sat 18 Apr 2015 22:21:45
# Maintainer : sh | arlatan, <sharlatanus@gmail.com>
# Title : CONSECUTIVE PRIME SUM
# License : Same as Python (GPL)
# Credits : https://projecteuler.net/
#
# -=:[ Description ]:=-
# The prime 41, can be written as the sum of six consecutive primes:
# 41 = 2 + 3 + 5 + 7 + 11 + 13
# This is the longest sum of conse... | primes below one-thousand that
# adds to a prime, contains 21 terms, and is equal to 953.
# Which prime, below one-million, can be written as the sum of the most
# consecutive primes?
from termcolor import colored
import sys
import time
import math
INIT_TIME = time.time()
def isprime(num):
search_lim = int(m... |
pvanhorn/openthread | tests/scripts/thread-cert/Cert_6_6_02_KeyIncrementRollOver.py | Python | bsd-3-clause | 3,389 | 0.000885 | #!/usr/bin/env python
#
# Copyright (c) 2016, The OpenThread Authors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# ... | des[ED].enable_whitelist()
self.nodes[ED].set_key_switch_guardtime(0)
def tearDown(self):
for node in list(self.nodes.values()):
node.stop()
del self.nodes
del self.simulator
def test(self):
self.nodes[LEADER].start()
self.simulator.go(5)
sel... | self.simulator.go(5)
self.assertEqual(self.nodes[ED].get_state(), 'child')
addrs = self.nodes[ED].get_addrs()
for addr in addrs:
self.assertTrue(self.nodes[LEADER].ping(addr))
key_sequence_counter = self.nodes[LEADER].get_key_sequence_counter()
self.nodes[LEADE... |
domofwk/domofwk-docs | source/formations/flask/fabfile.py | Python | gpl-2.0 | 122 | 0.008197 | from fabric.api import local
def html():
local('hovercraft -t ./sixfeetup_hovercraft formation_flask.rst ./bui | ld/')
| |
alexforencich/python-ivi | ivi/rigol/rigolDS1000Z.py | Python | mit | 2,014 | 0.001986 | """
Python Interchangeable Virtual Instrument Library
Copyright (c) 2017 Alex Forencich
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 righ... | RANTIES 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 DEALIN... | e driver"
def __init__(self, *args, **kwargs):
self.__dict__.setdefault('_instrument_id', '')
super(rigolDS1000Z, self).__init__(*args, **kwargs)
self._analog_channel_count = 4
self._digital_channel_count = 16
self._bandwidth = 100e6
self._bandwidth_limit = {'20M':... |
zidik/Thermal_Camera | PC software/cmdparser.py | Python | mit | 1,830 | 0.003825 | import threading
import time
import queue
import logging
class CmdParser(threading.Thread):
"""
Thread that parses incoming messages
and executes functions accordingly
"""
def __init__(self, rx, thermal_data):
threading.Thread.__init__(self)
self.rx = rx
self.thermal_data... | e(True):
parsed = self.parse()
# if there was nothing to do - sleep a bit..
if not parsed:
time.sleep(0.01)
finally:
logging.error("Parser thread stopped")
def par | se(self):
"""
Fetches a new message from queue and tries to parse it
returns boolean - true if message was successfully parsed
"""
try:
message = self.rx.get_nowait()
except queue.Empty:
# Nothing to parse
return False
parsed = ... |
cbgaindia/parsers | state_budget/sikkim/sikkim_budget_csv_generator.py | Python | mit | 4,866 | 0.007398 | import argparse
import csv
import glob
import logging
from logging.config import fileConfig
import os
import re
import sys
import xlrd
fileConfig('parsers/logging_config.ini')
logger = logging.getLogger()
reload(sys)
sys.setdefaultencoding('utf-8')
FILE_REGEX = "Demand|Budget at a glance|Receipt"
BUDGET_START_SLUG = "... | dget_files
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Generates CSV files for Sikkim Budget(from XLSX & XLS Documents)")
parser.add_argument("input_dir", help="In | put directory for budget documents")
args = parser.parse_args()
if not args.input_dir:
logger.error("Please input directory to begin CSV extraction")
else:
obj = SikkimBudgetCSVGenerator()
obj.process_budget_files(args.input_dir)
|
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractEmergencyExitsReleaseBlog.py | Python | bsd-3-clause | 226 | 0.026549 | def extractEmergencyExitsReleaseBlog(item):
"""
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title | '])
if not (chp or vol or frag) or 'preview' in item['title'].l | ower():
return None
return False
|
samedder/azure-cli | src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/custom.py | Python | mit | 108,353 | 0.004125 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | .create_or_update(
resource_group_name=parsed_id[0],
vm_name=parsed_id[1],
parameters=instance, raw=no_wait)
if lro_operation:
return lro_operation(poller)
return LongRunningOperation()(poller)
def _parse_rg_name(strid):
'''From an ID, extract the contained (resource group... | return (parts['resource_group'], parts['name'])
# Use the same name by portal, so people can update from both cli and portal
# (VM doesn't allow multiple handlers for the same extension)
_ACCESS_EXT_HANDLER_NAME = 'enablevmaccess'
_LINUX_ACCESS_EXT = 'VMAccessForLinux'
_WINDOWS_ACCESS_EXT = 'VMAccessAgent'
_LINUX_D... |
Chilledheart/chromium | tools/telemetry/telemetry/internal/platform/profiler/vtune_profiler.py | Python | bsd-3-clause | 5,290 | 0.008885 | # Copyright 2013 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.
import logging
import os
import subprocess
import sys
import tempfile
from telemetry.core import exceptions
from telemetry.internal.platform import profiler... | renderer = False
for pid, output_file in process_output_file_map.iteritems():
if 'renderer' in output_file:
has_renderer = True
break
for pid, output_file in process_output_file_map.iteritems():
if has_renderer:
if not 'renderer' in output_file:
continue
elif... | ss_profilers.append(
_SingleProcessVTuneProfiler(pid, output_file, browser_backend,
platform_backend))
@classmethod
def name(cls):
return 'vtune'
@classmethod
def is_supported(cls, browser_type):
if sys.platform != 'linux2':
return False
if bro... |
nomad-mystic/nomadmystic | fileSystem/school-projects/development/softwaredesignandcomputerlogiccis122/cis122lab3/python/Lab3.py | Python | mit | 18,030 | 0.00416 | # File = Lab3.py
# Programmer = Keith Murphy
# date created = 2-5-2015
# date Modified = 2-9-2015
__author__ = 'pather'
# Hello Mark,
# This is my first a stab at the Lab3 assignment. Everything tested well logically ans tried to fallow pseudocode
# specs closely. Let me know if I can make any improvements. Thanks... | ar_population_100
# Module welcome_message()
# Display String Welcome Message
# End module
def welcome_message():
print('Welcome to the future continental population calculator!!')
# Module try_again()
# Call main()
# End Module
def try_again():
main()
# Function choose_continent()
# Declare Stri | ng name_of_continent
# Declare Real years_in_the_future
#
# Display string 'The six populated continents are...'
# Display 'Please type the name of the continent...'
# Input name_of_continent
# Display String 'please type 50 or 100 years from now...'
# Input years_in_the_future
#
# If name of the continen... |
sixninetynine/pex | pex/pex_info.py | Python | apache-2.0 | 9,898 | 0.011619 | # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, print_function
import json
import os
import warnings
from collections import namedtuple
from .common import open_zip
from .compatibility import st... | lied_env.PEX_SCRIPT,
'zip_safe': zip_safe,
'inherit_path': supplied_env.PEX_INHERIT_PATH,
'ignore_errors': supplied_env.PEX_IGNORE_ERRORS,
'always_write_cache': supplied_env.PEX_ALWAYS_CACHE,
}
# Filter out empty entries not explicitly set in | the environment.
return cls(info=dict((k, v) for (k, v) in pex_info.items() if v is not None))
@classmethod
def _parse_requirement_tuple(cls, requirement_tuple):
if isinstance(requirement_tuple, (tuple, list)):
if len(requirement_tuple) != 3:
raise ValueError('Malformed PEX requirement: %r' ... |
graywizardx/slacksocket | slacksocket/webclient.py | Python | mit | 1,363 | 0.000734 | import logging
import requests
import slacksocket.errors as errors
log = logging.getLogger('slacksocket')
class WebClient(requests.Session):
""" Minimal client for connecting to Slack web API """
def __init__(self, token):
self._token = token
super(Web | Client, self).__init__()
def get(self, url, method='GET', max_attempts=3, **params):
if max_attempts == 0:
raise errors.SlackAPIError('Max retries exceeded')
elif max_attempts < 0:
message = 'Expected max_attemp | ts >= 0, got {0}'\
.format(max_attempts)
raise ValueError(message)
params['token'] = self._token
res = self.request(method, url, params=params)
try:
res.raise_for_status()
except requests.exceptions.HTTPError as e:
raise errors.SlackA... |
skywind3000/collection | script/pocketsnes_cht.py | Python | mit | 8,764 | 0.007188 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#======================================================================
#
# pocketsnes_cht.py -
#
# Created by skywind on 2020/06/17
# Last Modified: 2020/06/17 20:26:39
#
#======================================================================
from __future__ im... | break
if space == 0:
if line == 'cheat':
index += 1
avail = True
else:
avail = False
elif avail:
text = line.strip('\r\n\t ')
... | if index not in cheats:
cheats[index] = {}
if text == 'enable':
cheats[index]['enable'] = True
elif ':' in text:
key, _, val = text.partition(':')
key = key.st... |
mrshu/err | tests/repo_manager_tests.py | Python | gpl-3.0 | 4,299 | 0.002559 | import tempfile
import shutil
import os
import pytest
from errbot import repo_manager
from errbot.storage.memory import MemoryStoragePlugin
assets = os.path.join(os.path.dirname(__file__), 'assets')
@pytest.fixture
def plugdir_and_storage(request):
plugins_dir = tempfile.mkdtemp()
storage_plugin = MemorySt... | , 'repos', 'doh.json'),))
manager.index_update()
assert repo_manager.REPO_INDEX not in manager
def test_tokenization():
e = {
"python": "2+",
"repo": "https://github.com/name/err-reponame1",
"path": "/plugin1.plug",
"avatar_url": "https://avatars.githubuserc... | ent.com/u/588833?v=3",
"name": "PluginName1",
"documentation": "docs1"
}
words = {'https',
'com',
'name',
'err',
'docs1',
'reponame1',
'plug',
'2',
'plugin1',
'avatars... |
martijnvermaat/rpclib | src/rpclib/test/test_service.py | Python | lgpl-2.1 | 8,487 | 0.003064 | #!/usr/bin/env python
#
# rpclib - Copyright (C) Rpclib contributors.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later ... | vice"
street = String
city = String
zip = Integer
since = DateTime
laditude = Float
longitude = Float
class Person(ComplexModel):
__namespace__ = "T | estService"
name = String
birthdate = DateTime
age = Integer
addresses = Array(Address)
titles = Array(String)
class Request(ComplexModel):
__namespace__ = "TestService"
param1 = String
param2 = Integer
class Response(ComplexModel):
__namespace__ = "TestService"
param1 = Flo... |
jawilson/home-assistant | homeassistant/components/tellduslive/entry.py | Python | apache-2.0 | 4,213 | 0 | """Base Entity for all TelldusLive entities."""
from datetime import datetime
import logging
from tellduslive import BATTERY_LOW, BATTERY_OK, BATTERY_UNKNOWN
from homeassistant.const import (
ATTR_BATTERY_LEVEL,
ATTR_MANUFACTURER,
ATTR_MODEL,
ATTR_VIA_DEVICE,
DEVICE_DEFAULT_NAME,
)
from homeassist... | entity import DeviceInfo, Entity
from .const import SIGNAL_UPDATE_ENTITY
_LOGGER = logging.getLogger(__name__)
ATTR_LAST_UPDATED = "time_last_updated"
class TelldusLiveEntity(Entity):
"""Base class for all Telldus Live entities."""
def __init__(self, client, device_id):
"""Initialize the entity.""... | _added_to_hass(self):
"""Call when entity is added to hass."""
_LOGGER.debug("Created device %s", self)
self._async_unsub_dispatcher_connect = async_dispatcher_connect(
self.hass, SIGNAL_UPDATE_ENTITY, self._update_callback
)
async def async_will_remove_from_hass(self):
... |
Ziqi-Li/bknqgis | numpy/numpy/core/tests/test_multiarray.py | Python | gpl-2.0 | 259,483 | 0.000748 | from __future__ import division, absolute_import, print_function
import collections
import tempfile
import sys
import shutil
import warnings
import operator
import io
import itertools
import functools
import ctypes
import os
import gc
from contextlib import contextmanager
if sys.version_info[0] >= 3:
import builti... | ="C", align=None):
"""Alloc | ate a new ndarray with aligned memory."""
dtype = np.dtype(dtype)
if dtype == np.dtype(object):
# Can't do this, fall back to standard allocation (which
# should always be sufficiently aligned)
if align is not None:
raise ValueError("object array alignment not supported")
... |
homeworkprod/byceps | tests/unit/services/shop/cart/test_cart_repr.py | Python | bsd-3-clause | 1,558 | 0 | """
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from decimal import Decimal
from byceps.database import ge | nerate_uuid
from byceps.services.shop.article.transfer.models import (
Article,
ArticleNumber,
ArticleID,
ArticleNumber,
Arti | cleType,
)
from byceps.services.shop.cart.models import Cart
from byceps.services.shop.shop.transfer.models import ShopID
def test_cart_empty_repr():
cart = Cart()
assert repr(cart) == '<Cart(0 items)>'
def test_cart_filled_repr():
article1 = create_article(
ArticleNumber('a-001'), 'Article #1',... |
amit-bansil/netsci | robocompviz/trueskill/trueskillhelpers.py | Python | mit | 5,897 | 0.001357 | # -*- coding: utf-8 -*-
from __future__ import with_statement
from contextlib import contextmanager
import functools
import inspect
import logging
import trueskill
from trueskill.backends import available_backends
from trueskill.factorgraph import (Variable, Factor, PriorFactor,
Like... | methods[0] = method
elif m | ethod in ('up', 'down'):
methods[1] = method
break
factor = frame[0].f_locals['self']
before = Gaussian(pi=self.pi, tau=self.tau)
# helpers for logging
logs = []
l = logs.append
bullet = lambda changed: colored(' * ', 'red') if changed else... |
ProjetPP/PPP-CAS | ppp_cas/calchasLex.py | Python | mit | 876 | 0.026256 | import ply.lex as lex
tokens = (
'NUMBER',
'PLUS',
'MINUS',
'TIMES',
'DIVIDE',
'LPAREN',
'RPAREN',
'COMMA',
'ID',
'EXCL',
'POW',
'DTIMES',
'MOD',
'EQ',
'APOSTROPHE',
'AND',
'OR',
'NOT',
)
t_DTIMES = r'\*\*'
t_PLUS = r'\+'
t_MINUS =... | = r'!'
t_POW = r'\^'
t_MOD = r'%'
t_EQ = r'='
t_APOSTROPHE = r'\''
t_AND = r'&'
t_OR = r'\|'
t_NOT = r'~'
def t_NUMBER(t):
r"""([0-9]*\.[0-9]+|[0-9]+)"""
return t
def t_ID(t):
r"""[a-zA-Z_][a-zA-Z0-9_]*"""
return t
def t_newline(t):
r"""\n+"... | lue)
t_ignore = ' \t'
def t_error(t):
t.lexer.skip(1)
calchasLexer = lex.lex()
|
Informatorio/Sis_LegajosV2 | courses/migrations/0003_course_usuario.py | Python | gpl-3.0 | 692 | 0.001445 | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-12-05 20:53
from __future__ import unicode_literals
from django.conf import set | tings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('courses', '0002_auto_20161204_2330'),
]
operations = [
migrations.Ad | dField(
model_name='course',
name='usuario',
field=models.OneToOneField(default='', on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
preserve_default=False,
),
]
|
Mog333/DeepRL | network/DeepQNetwork.py | Python | mit | 7,211 | 0.012342 | """
Author: Robert Post
Based on code from Nathan Sprague
from: https://github.com/spragunr/deep_q_rl
"""
import DeepNetworks
import lasagne
import numpy as np
import theano
import theano.tensor as T
import cPickle
import imp
class DeepQNetwork(object):
def __init__(self, batchSize, numFrames, inputHeight, inputW... | lf.discountRate ** self.kReturnLength) * T.max(nextQValues, axis = 1, keepdims = True)
targetDifference = target - qValues[T.arange(self.batchSize), actions.reshape((-1,))].reshape((-1, 1))
quadraticPart = T.minimum(abs(targetDifference), self.clipDelta)
linea | rPart = abs(targetDifference) - quadraticPart
# if self.clipDelta > 0:
# targetDifference = targetDifference.clip(-1.0 * self.clipDelta, self.clipDelta)
if self.batchAccumulator == "sum":
# loss = T.sum(targetDifference ** 2)
loss = T.sum(0.5 * quadraticPart ** 2 + ... |
alexm92/sentry | tests/sentry/api/serializers/test_group.py | Python | bsd-3-clause | 3,998 | 0 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from datetime import timedelta
from django.utils import timezone
from mock import patch
from sentry.api.serializers | import serialize
from sentry.models import (
GroupResolution, GroupResolutionStatus, GroupSnooze, GroupSubscription,
GroupStatus, Release
)
from sentry.testutils import TestCase
class GroupSerializerTest(TestCase):
def test_is_ignored_with_expired_snooze(self):
now = timezone.now().replace(microse... | )
GroupSnooze.objects.create(
group=group,
until=now - timedelta(minutes=1),
)
result = serialize(group, user)
assert result['status'] == 'unresolved'
assert result['statusDetails'] == {}
def test_is_ignored_with_valid_snooze(self):
now = tim... |
sumeetsk/NEXT-1 | next/apps/test_utils.py | Python | apache-2.0 | 5,270 | 0.007211 | """
This file is to provide a unifed testing framework for NEXT.
"""
import requests
import os
import json
import time
import numpy as np
HOSTNAME = os.environ.get('NEXT_BACKEND_GLOBAL_HOST', 'localhost') \
+ ':' + os.environ.get('NEXT_BACKEND_GLOBAL_PORT', '8000')
def initExp(initExp_args_dict, assert_20... | esponse = requests.get(url)
print "GET experiment response =",response.text, response.status_code
if assert_200: assert response.status_code is 200
initExp_response_dict = json.loads(response.text)
return initExp_response_dict
def forma | t_times(getQuery_times, processAnswer_times, total_pulls,
participant_uid):
processAnswer_times.sort()
getQuery_times.sort()
return_str = '%s \n\t getQuery\t : %f (5), %f (50), %f (95)\n\t processAnswer\t : %f (5), %f (50), %f (95)\n' % (participant_uid,getQuery_... |
colloquium/spacewalk | backend/server/test/unit-test/rhnSQL/test_executemany.py | Python | gpl-2.0 | 1,833 | 0.007092 | #!/usr/bin/python
# Copyright (c) 2005--2010 Red Hat, Inc.
#
#
#
# $Id$
raise Exception("""
This test is no more valid; see the bug
https://bugzilla.redhat.com/show_bug.cgi?id=423351
""")
import os
import unittest
from spacewalk.server import rhn | SQL
DB = 'rhnuser/rhnuser@webdev'
class ExecutemanyTest(unittest.TestCase):
def setUp(self):
self.table_name = "misatest_%d" % os.getpid()
rhnSQL.initDB(DB)
self._cleanup()
rhnSQL.execute("create table %s (id int, val varchar2(10))" %
self.table_name)
def _cl... | SQL.execute("drop table %s" % self.table_name)
except rhnSQL.SQLStatementPrepareError:
pass
def tearDown(self):
self._cleanup()
rhnSQL.commit()
def test_executemany(self):
"""
Tests the case of passing an integer as a value into a VARCHAR2 ... |
research-team/NEUCOGAR | NEST/cube/noradrenaline/scripts-2/keys.py | Python | gpl-2.0 | 700 | 0.017143 | # Keys for connection type
GABA = 0
Glu = 1
ACh = 2
NA_ex = 3
NA_in = 4
DA_ex = 3
DA_in = 4
# Keys for synapse models
model = 0
basic_weight = 1
# Keys for parts dictionary
k_outer = 'Outer ID'
k_outer_ids = 'Outer children IDs'
k_inner = 'Inner ID'
k_inner_ids = 'Inner children IDs'
k_name = 'Name'
k_NN = 'N... | el = 'Model'
# Synapse models
glu_synapse = 'glu_synapse'
gaba_syna | pse = 'gaba_synapse'
ach_synapse = 'ach_synapse'
nora_synapse_ex = 'nora_synapse_ex'
nora_synapse_in = 'nora_synapse_in'
gen_static_syn = 'noise_conn'
#########dopa
dopa_synapse_ex = 'dopa_synapse_ex'
dopa_synapse_in = 'dopa_synapse_in' |
mfnch/pyrtist | pyrtist/examples/arcs.py | Python | lgpl-2.1 | 1,134 | 0.005291 | #!PYRTIST:VERSION:0:0:1
from pyrtist.lib2d import Point, Tri
#!PYRTIST:REFPOINTS:BEGIN
bbox1 = Point(0, 50); bbox2 = Point(100, 0)
p1 = Point(25.7575757576, 30.3787878788)
p2 = Point(19.814314022, 27.0345941837)
p3 = Point(27.7318108704, 19.2297513487)
p4 = Point(47.8787878788, 18.4090909091)
p5 = Point(67.7272727273, ... | 48484848)
#!PYRTIST:REFPOINTS:END
# Example showing how to draw arcs and compute their bounding box.
from pyrtist.lib2d import *
w = Window()
w << BBox(bbox1, bbox2)
# Define three arcs.
arc1 = Arc(Through(p1, p2, p3), Close.no)
arc2 = Arc(Through(p4, p5, p6), Color.red, StrokeStyle(1, Color.blue, Cap.round))
arc3 = ... | = BBox(arc3)
w << Stroke(0.2, Color.red, Rectangle(*bb))
# Find the point in the middle of arc1 using 0.5 as an index.
w << Circle(Color(0, 0.5, 0), 1, arc1[0.5])
gui(w)
|
MoiTux/pyramid-request-log | pyramid_request_log/config.py | Python | mit | 1,497 | 0 | from __future__ import absolute_import
import logging
import re
from pyramid.settings import aslist
from . import request_log
log = logging.getLogger(__name__)
def includeme(config):
settings = config.registry.settings
config.scan('pyramid_request_log.request_log')
if 'pyramid_request_log.pattern' i... | log.info('Pyramid-Request-Log will ignore routes: %s',
unlog_route)
re_compile = re.compile('({})'.format(')|('.join(unlog_route)))
request_log.unlog_route = re_compile
key = 'pyramid_request_log.authenticated_id'
if key in settings:
request_log.authentica... | |
drix00/pymcxray | pymcxray/Simulation.py | Python | apache-2.0 | 58,934 | 0.003954 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
.. py:currentmodule:: pymcxray.Simulation
.. moduleauthor:: Hendrix Demers <hendrix.demers@mail.mcgill.ca>
MCXRay simulation parameters.
"""
###############################################################################
# Copyright 2017 Hendrix Demers
#
# Licensed ... | eAlloyThinFilm2(elements, filmThickness_nm):
specimen = Specimen.Specimen()
specimen.numberRegions = 2
# Region 0
region = Region.Region()
region.numberElements = 0
region.regionType = RegionTyp | e.REGION_TYPE_BOX
parameters = [-10000000000.0, 10000000000.0, -10000000000.0, 10000000000.0, 0.0, 20000000000.0]
region.regionDimensions = RegionDimensions.RegionDimensionsBox(parameters)
specimen.regions.append(region)
# Region 1
region = Region.Region()
region.numberElements = len(elements)
... |
RasaHQ/rasa_core | rasa/core/tracker_store.py | Python | apache-2.0 | 13,497 | 0 | import itertools
import json
import logging
import pickle
# noinspection PyPep8Naming
from typing import Iterator, KeysView, List, Optional, Text
from rasa.core.actions.action import ACTION_LISTEN_NAME
from rasa.core.broker import EventChannel
from rasa.core.domain import Domain
from rasa.core.trackers import (
Ac... | def find_tracker_store(domain, store=None, event_broker=None):
if store is None or store.type is None:
return InMemoryTrackerStore(domain, event_broker=event_broker)
elif store.type == 'redis':
return RedisTrackerStore(domain=domain,
host=sto... | return MongoTrackerStore(domain=domain,
host=store.url,
event_broker=event_broker,
**store.kwargs)
elif store.type.lower() == 'sql':
return SQLTrackerStore(domain=domain,
... |
airekans/paxosim | simulator.py | Python | mit | 10,270 | 0.001071 | import sys
import importlib
import inspect
class Process(object):
def __init__(self):
pass
def process(self, _in):
pass
def get_id(self):
return self._id
class Simulator(object):
def __init__(self, processes, links, commands):
self._cur_time = 0
self... | , self._cur_time)
if output:
self.sent_output(proc_id, output)
skip_round_num -= 1
if skip_round_num <= 0:
round_num = self.process_command()
if round_num is None:
break
else:
... | es[proc_id]) > 0:
return self._input_queues[proc_id][0]
else:
return {}
def sent_output(self, process_id, output):
for target_process, msg in output.iteritems():
try:
distance = self._links[(process_id, target_process)]
except KeyError... |
CIRALabs/DSAP | manage.py | Python | mit | 249 | 0.004016 | #!/usr/bin/env python
import os
import sys
if | __name__ == "__main__":
| os.environ.setdefault("DJANGO_SETTINGS_MODULE", "src.web.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
tgbugs/hypush | test/memex/util/markdown_test.py | Python | mit | 3,893 | 0.001798 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pytest
from hyputils.memex.util import markdown
class TestRender(object):
def t | est_it_renders_markdown(self):
actual = markdown.render("_emphasis_ **bold**")
assert "<p><em>emphasis</em> <strong>bold</strong></p>\n" == actual
def test_it_ignores_math_block(self):
actual = markdown.render("$$1 + 1 = 2$$")
assert "<p>$$1 + 1 = 2$$</p>\n" == actual
def test_... | r \(1 + 1 = 2\)")
assert "<p>Foobar \\(1 + 1 = 2\\)</p>\n" == actual
def test_it_sanitizes_the_output(self, markdown_render, sanitize):
markdown.render("foobar")
sanitize.assert_called_once_with(markdown_render.return_value)
@pytest.fixture
def markdown_render(self, patch):
... |
tensorflow/tensorflow | tensorflow/python/estimator/canned/prediction_keys.py | Python | apache-2.0 | 1,219 | 0.001641 | # 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... | ting, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =========================== | ===================================================
"""prediction_keys python module.
Importing from tensorflow.python.estimator is unsupported
and will soon break!
"""
# pylint: disable=unused-import,g-bad-import-order,g-import-not-at-top,wildcard-import
from tensorflow_estimator.python.estimator.canned import predi... |
kirbyj/vPhon | rules.py | Python | gpl-3.0 | 11,430 | 0.084898 | #rules.py
#coding: utf-8
onsets = { 'b' : 'ɓ',
'c' : 'k',
'ch' : 'c',
'd' : 'j',
'đ' : 'ɗ',
'g' : 'ɣ',
'gh' : 'ɣ',
'gi' : 'z',
'h' : 'h',
'k' : 'k',
'kh' : 'x',
'l' : 'l',
... | 'ɨə', 'ữa' : 'ɨə', 'ựa' : 'ɨə',
'ươ' : 'ɨə', 'ướ' : 'ɨə', 'ườ' : 'ɨə', 'ưở' : 'ɨə', 'ưỡ' : 'ɨə', 'ượ' : 'ɨə',
'yê' : 'iə', 'yế' : 'iə', 'yề' : 'iə', 'yể' : 'iə', 'yễ' : 'iə', 'yệ' : 'iə',
'uơ' : 'uə', 'uở' : 'uə', 'uờ': 'uə', 'uở' : 'uə', 'uỡ' : 'uə', 'uợ' : 'uə'
}
offglides = { ... |
'ay' : 'aj', 'áy' : 'aj', 'ày' : 'aj', 'ảy' : 'aj', 'ãy' : 'aj', 'ạy' : 'aj',
'ao' : 'aːw', 'áo' : 'aːw', 'ào' : 'aːw', 'ảo' : 'aːw', 'ão' : 'aːw', 'ạo' : 'aːw',
'au' : 'aw', 'áu' : 'aw', 'àu' : 'aw', 'ảu' : 'aw', 'ãu' : 'aw', 'ạu' : 'aw',
'ây' : 'əj', 'ấ... |
dirmeier/dataframe | dataframe/callable.py | Python | gpl-3.0 | 1,564 | 0.001279 | # dataframe: a data-frame implementation using method piping
#
# Copyright (C) 2016 Simon Dirmeier
#
# This file is part of dataframe.
#
# dataframe 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 versi... | : whenever you want to use ``modify`` or ``aggregate`` you need to
wri | te a class that extends ``Callable`` and overwrite ``__call__``.
``__call__`` has to return a scalar or list, depending if you want to
aggregate columns or modify. So a class that modifies a column returns
list, while a class that aggregates returns a scalar.
"""
def __call__(self, *args):
... |
mastizada/kuma | vendor/packages/ipython/IPython/Magic.py | Python | mpl-2.0 | 135,645 | 0.005964 | # -*- coding: utf-8 -*-
"""Magic functions for InteractiveShell.
"""
#*****************************************************************************
# Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
# Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
#
# Distributed under the terms of th... | import tempfile
import time
import cPickle as pickle
import textwrap
from cStringIO import StringIO
from getopt import getopt,GetoptError
from pprint import ppri | nt, pformat
# cProfile was added in Python2.5
try:
import cProfile as profile
import pstats
except ImportError:
# profile isn't bundled by default in Debian for license reasons
try:
import profile,pstats
except ImportError:
profile = pstats = None
# Homebrewed
import IPython
from I... |
Tendrl/commons | tendrl/commons/flows/import_cluster/__init__.py | Python | lgpl-2.1 | 5,760 | 0.000174 | import etcd
import json
import re
import sys
import traceback
from tendrl.commons import flows
from tendrl.commons.flows.exceptions import FlowExecutionFailedError
from tendrl.commons.objects import AtomExecutionFailedError
from tendrl.commons.utils import etcd_utils
class ImportCluster(flows.BaseFlow):
def __i... | for entry in _clusters.leaves:
_cluster = NS.tendrl.objects.Cluster(
integration_id=entry.key.split('/')[-1]
).load()
if _clus | ter.short_name and short_name and \
_cluster.is_managed == 'yes' and \
_cluster.short_name == short_name.strip().lower():
raise FlowExecutionFailedError(
"Cluster with name: %s already exists" % short_name
)
... |
gjover/Lima_subtree | python/__init__.py | Python | gpl-3.0 | 2,173 | 0.016107 | ############################################################################
# This file is part of LImA, a Library for Image Acquisition
#
# Copyright (C) : 2009-2011
# European Synchrotron Radiation Facility
# BP 220, Greno | ble 38043
# FRANCE
#
# This is free s | oftware; 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 software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY;... |
foursquare/pants | tests/python/pants_test/cache/test_artifact.py | Python | apache-2.0 | 2,540 | 0.015354 | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import unittest
from pants.cache.artifact import DirectoryArtifact, TarballArt... | :
with temporary_dir() as tmpdir:
artifact_root = os.path.join(tmpdir, 'artifacts')
artifact_dir = os.path.join(tmpdir, 'cache')
safe_mkdir(artifact_di | r)
artifact = DirectoryArtifact(artifact_root, artifact_dir)
self.assertTrue(artifact.exists())
def test_does_not_exist_when_dir_missing(self):
with temporary_dir() as tmpdir:
artifact_root = os.path.join(tmpdir, 'artifacts')
artifact_dir = os.path.join(tmpdir, 'cache')
artifact ... |
DGA-MI-SSI/YaCo | deps/swig-3.0.7/Examples/python/std_map/runme.py | Python | gpl-3.0 | 1,089 | 0 | # file: runme.py
import example
pmap = example.pymap()
pmap["hi"] = 1
pmap["hello"] = 2
dmap = {}
dmap["hello"] = 1.0
dmap["hi"] = 2.0
print dmap.items()
print dmap.keys()
print dmap.values()
print dmap
hmap = example. | halfd | (dmap)
dmap = hmap
print dmap
for i in dmap.iterkeys():
print "key", i
for i in dmap.itervalues():
print "val", i
for k, v in dmap.iteritems():
print "item", k, v
dmap = example.DoubleMap()
dmap["hello"] = 1.0
dmap["hi"] = 2.0
for i in dmap.iterkeys():
print "key", i
for i in dmap.itervalues():
... |
alejandro-mc/trees | testWeightedSPR.py | Python | mit | 4,022 | 0.021631 | #randSPRwalk.py
#writes random SPR walks to files
#calls GTP on each SPR random walk file to get
#the ditances between each tree and the first tree of the sequence
#the results are written to csv files with lines delimited by \t
import tree_utils as tu
import w_tree_utils as wtu
import os
import sys
import numpy as np
... | refix__ = 'U' + __prefix__
#take a single size or a range of sizes
if ":" in sys.argv[2]:
size_start, size_end = map(lambda x: int(x),sys.argv[2].split(':'))
else:
size_start = int(sys.argv[2])
size_end = size_start + 1
size_range = range(size_start,size_end)
... |
#take a single seed or a range of seeds
if ":" in sys.argv[5]:
seed_start,seed_end = map(lambda x: int(x),sys.argv[5].split(':'))
else:
seed_start = int(sys.argv[5])
seed_end = seed_start + 1
seed_range = range(seed_start,seed_end)
#set pid property before calli... |
dparaujo/projeto | app_administrativo/usuario/forms.py | Python | gpl-3.0 | 1,398 | 0.046662 | # -*- coding: utf-8 -*-
from django import forms
from app_academico.curso.models import *
from app_academico.turno.models import TblAcademicoTurno
class UsuarioModelForm(forms.ModelForm):
# def __init__(self, *args, **kwargs):
# super(CursoModelForm, self).__init__(*args, **kwargs)
descricao = forms.CharField(
... | TblAcademicoCurso
fields = | ('descricao','quant_vaga','turno','pre_requisito', 'ativo') |
sigvef/elma | docs/conf.py | Python | mit | 365 | 0 | import sys
import os
sys.path.insert(0, os.path.abspath('..'))
extensions = ['sphinx.ext.autodoc', 'sphinxcontrib.napoleon']
source_suffix = '.rst'
ma | ster_doc = 'index'
project = u'Elma Python Library'
copyright = u'2015, Elma Library Contributors'
exclude_patterns = ['_build']
pygments_style = 'sphinx'
todo_include_todos = False
html_theme | = 'sphinx_rtd_theme'
|
kubevirt/client-python | test/test_k8s_io_apimachinery_pkg_apis_meta_v1_root_paths.py | Python | apache-2.0 | 1,105 | 0.002715 | # coding: utf-8
"""
KubeVirt API
This is KubeVirt API an add-on for Kubernetes.
OpenAPI spec version: 1.0.0
Contact: kubevirt-dev@googlegroups.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
import unittest
i... | aths unit test stubs """
def setUp(self):
pass
def tearDown(self):
pass
def testK8sIoApimachineryPkgApisMetaV1RootPaths(self):
"""
Test K8sIoApimachineryPkgApisMetaV1RootPaths
| """
# FIXME: construct object with mandatory attributes with example values
#model = kubevirt.models.k8s_io_apimachinery_pkg_apis_meta_v1_root_paths.K8sIoApimachineryPkgApisMetaV1RootPaths()
pass
if __name__ == '__main__':
unittest.main()
|
mgax/zechat | migrations/versions/52ceb70dfec2_message.py | Python | mit | 1,158 | 0.002591 | revision = '52ceb70dfec2'
down_revision = None
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
op.create_table(
'message',
sa.Column('id', postgresql.UUID(), nullable=False),
sa.Column('sender', sa.String() | , nullable=False),
sa.Column('recipient', sa.String(), nullable=False),
sa.Column('hash', sa.String(), nullable=False),
sa.Column('payload', sa.String(), nullable=False),
sa.PrimaryKeyConstraint('id'),
)
op.create_index(
op.f('ix_message_sender'),
'message',
... | lse,
)
op.create_index(
op.f('ix_message_recipient'),
'message',
['recipient'],
unique=False,
)
op.create_index(
op.f('ix_message_hash'),
'message',
['hash'],
unique=False,
)
def downgrade():
op.drop_index(op.f('ix_message_hash'... |
ThunderGemios10/Corpse-Party-2U-Script-Editor | eboot_patch.py | Python | gpl-3.0 | 25,393 | 0.039601 | # -*- coding: utf-8 -*-
################################################################################
### Copyright © 2012-2013 BlackDragonHunt
### Copyright © 2012-2013 /a/nonymous scanlations
###
### This file is part of the Super Duper Script Editor.
###
### The Super Duper Script Editor is free software: you c... | rean", u"Traditional Chinese", u"Simplified Chinese"]
LANGUAGES = [u"日本語", u"English", u"Français", u"Español", u"Deutsch", u"Italiano", u"Nederlands", u"Português", u"Русский", u"한국어", u"繁體中文", u"简体中文"]
LANG_CFG_ID = "sys_menu_lang"
CLT_CFG_ID = "custom_clt"
EBOOT_PATCHES = [
{NAME: "Extend EBOOT", ENABLED: True... | ORIG: ConstBitStream(hex = "0x0300"), PATCH: ConstBitStream(hex = "0x0400")},
{POS: 0x00000054, ORIG: ConstBitStream(hex = "0x0100000040CB200080CA20000000000028E40000842A2E000600000040000000"), PATCH: ConstBitStream(hex = "0x0100000040CB200020F54E000000000000200100002001000700000010000000")},
{POS: 0x00000... |
jmptrader/dirigible-spreadsheet | dirigible/fts/tests/test_2774_ExportCSV.py | Python | mit | 7,349 | 0.003402 | # Copyright (c) 2010 Resolver Systems Ltd.
# All Rights Reserved
#
from __future__ import with_statement
from os import path
import urllib2
from urlparse import urljoin
from functionaltest import FunctionalTest, PAGE_LOAD_TIMEOUT
class Test_2774_ExportCSV(FunctionalTest):
def test_can_export_csv(self):
... | stream.in | fo()['Content-Disposition'],
'attachment; filename=%s.csv' % (sheet_name,)
)
expected_file_name = path.join(
path.dirname(__file__),
"test_data", "expected_unicode_csv.csv"
)
with open(expected_file_name) as expected_file:
self... |
DoubleNegativeVisualEffects/gaffer | python/GafferTest/ExecutableOpHolderTest.py | Python | bsd-3-clause | 5,467 | 0.049387 | ##########################################################################
#
# Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Red... | .assertEqual( n2Requirements[1].node, n2b )
self.assertEqual( n2Requirements[1].context, c )
t1 = Gaffer.ExecutableNode.Task(n2a,c)
t2 = Gaffer.ExecutableNode.Task(n2b,c)
self.assertEqual( n2Requirements[0], t1 )
self.assertEqual( n2Requirements[1], t2 )
self.assertEqual( len(set(n2.executionRequirements(c)... | n1.executionRequirements(c), [ Gaffer.ExecutableNode.Task(n2,c) ] )
def testSerialise( self ) :
s = Gaffer.ScriptNode()
s["n"] = Gaffer.ExecutableOpHolder()
opSpec = GafferTest.ParameterisedHolderTest.classSpecification( "primitive/renameVariables", "IECORE_OP_PATHS" )[:-1]
s["n"].setOp( *opSpec )
... |
danrg/RGT-tool | src/RGT/XML/SVG/clipPathNode.py | Python | mit | 3,223 | 0.003413 | from RGT.XML.SVG.basicSvgNode import BasicSvgNode
from RGT.XML.SVG.Attribs.conditionalProcessingAttributes import ConditionalProcessingAttributes
from RGT.XML.SVG.Attribs.presentationAttributes import PresentationAttributes
from RGT.XML.SVG.Attribs.classAttribute import ClassAttribute
from RGT.XML.SVG.Attribs.style... | if data is not None:
if data not in allowedValues:
values = ''
for val | ue in allowedValues:
values += value + ', '
values = values[0: len(values) - 2]
raise ValueError('Value not allowed, only ' + values + 'are allowed')
else:
self._setNodeAttribute(self.ATTRIBUTE_EXTERNAL_RESOURCES_REQUIRED, data)
... |
Alignak-monitoring-contrib/alignak-app | test/test_all_items.py | Python | agpl-3.0 | 12,482 | 0.000801 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2018:
# Matthieu Estrada, ttamalfor@gmail.com
#
# This file is part of (AlignakApp).
#
# (AlignakApp) is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Sof... | tate_id': 4,
'passive_checks_enabled': False,
'active_checks_enabled': True
},
'service%d' % i
)
service_list.append(service)
def test_item_ | model(self):
"""Create ItemModel"""
under_test = Item()
under_test.create('_id', {'ls_state': 'DOWN'}, 'name')
self.assertTrue('_id' == under_test.item_id)
self.assertTrue('ls_state' in under_test.data)
self.assertTrue('DOWN' == under_test.data['ls_state'])
sel... |
jaggu303619/asylum | openerp/addons/mail/wizard/invite.py | Python | agpl-3.0 | 4,418 | 0.004301 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2012-Today OpenERP SA (<http://www.openerp.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms o... | t wizard.message == '<br>': # when deleting the message, cleditor keeps a <br>
# add signature
user_id = self.pool.get | ("res.users").read(cr, uid, [uid], fields=["signature"], context=context)[0]
signature = user_id and user_id["signature"] or ''
if signature:
wizard.message = tools.append_content_to_html(wizard.message, signature, plaintext=True, container_tag='div')
... |
psusloparov/sneeze | pocket_change/pocket_change/rest/components/jira_extensions.py | Python | apache-2.0 | 5,279 | 0.007388 | from pocket_change.rest.util import Preserializer, JiraRelatedResource
from pocket_change.rest.components import kaichu
from flask import g, request, current_app
from pocket_change import sqlalchemy_db
from flask.ext.restful import Resource
from flask.ext.restful.reqparse import RequestParser
from flask.ext.login impor... | {'message' : 'Invalid token.'}, 400
if password:
user = PocketChangeUser(None, username, password)
if user.is_authenticated():
User = sqlalchemy_db.models['User']
try:
db_user = (sqlalchem... | me, password=password)
sqlalchemy_db.session.add(db_user)
sqlalchemy_db.session.commit()
user.token = db_user.get_new_token(current_app.secret_key[:16],
expires=timedelta(hours=6),
... |
nicememory/pie | pyglet/pyglet/input/__init__.py | Python | apache-2.0 | 7,513 | 0.001863 | # ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistribu... | NCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWA... | blet and USB HID device support.
This module provides a unified interface to almost any input device, besides
the regular mouse and keyboard support provided by
:py:class:`~pyglet.window.Window`. At the lowest
level, :py:func:`get_devices` can be used to retrieve a list of all supported
devices, including joysticks, ... |
Alwnikrotikz/kegbot | pykeg/src/pykeg/core/migrations/0047_add_system_stats.py | Python | gpl-2.0 | 26,712 | 0.007637 | # 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 'SystemStats'
db.create_table('core_systemstats', (
('date', self.gf('djang... | , {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'T | rue', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Per... |
luoguizhou/gooderp_addons | core/models/res_company.py | Python | agpl-3.0 | 2,323 | 0.003017 | # -*- coding: utf-8 -*-
from odoo import api, fields, models, tools
from odoo.exceptions import UserError
import os
from odoo.tools import misc
import re
# 成本计算方法,已实现 先入先出
CORE_COST_METHOD = [('average', u'全月一次加权平均法'),
('std',u'定额成本'),
('fifo', u'先进先出法'),
]
... | ck_email(self):
''' 验证 email 合法性 '''
if self.email:
| res = re.match('^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$', self.email)
if not res:
raise UserError(u'请检查邮箱格式是否正确: %s' % self.email)
start_date = fields.Date(u'启用日期',
required=True,
default=lambda self: fields.Date.co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.