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 |
|---|---|---|---|---|---|---|---|---|
MrgInfo/PiCam | upload.py | Python | gpl-2.0 | 5,086 | 0.000984 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Dropbox upload daemon.
"""
from fnmatch import fnmatch
from operator import itemgetter
from os import listdir, path, mknod, stat
from time import strptime, sleep, time
from dropbox.client import DropboxClient, DropboxOAuth2FlowNoRedirect
from dropbox.rest import ... | return None
return [
{
'file': m['path'],
'modified': strptime(m['modified'], '%a, %d %b %Y %H:%M:%S %z'),
'size': m['bytes']
}
for m in metadata['contents']
if not m['is_dir']
]
def _upload(sel... | nt: DropboxClient):
""" Upload new files from directory.
"""
now = time()
for filename in listdir(self.directory):
if fnmatch(filename, '*.upl'):
continue
local_name = '/' + filename
full_name = path.join(self.directory, filename)
... |
ecederstrand/exchangelib | exchangelib/services/find_item.py | Python | bsd-2-clause | 4,353 | 0.002068 | from ..errors import InvalidEnumValue
from ..folders.base import BaseFolder
from ..items import ID_ONLY, ITEM_TRAVERSAL_CHOICES, SHAPE_CHOICES, Item
from ..util import MNS, TNS, create_element, set_xml_value
from .common import EWSPagingService, folder_ids_element, shape_element
class FindItem(EWSPagingService):
... | raise InvalidEnumValue("depth", depth, ITEM_TRAVERSAL_CHOICES | )
self.additional_fields = additional_fields
self.shape = shape
return self._elems_to_objs(
self._paged_call(
payload_func=self.get_payload,
max_items=max_items,
folders=folders,
**dict(
additional_fi... |
smartboyathome/Wonderland-Engine | tests/CheshireCatTests/test_team_checks_manual.py | Python | agpl-3.0 | 3,635 | 0.002476 | '''
Copyright (c) 2012 Alexander Abbott
This file is part of the Cheshire Cyber Defense Scoring Engine (henceforth
referred to as Cheshire).
Cheshire 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... | cific_manual_check_for_specific_team_with_params(self):
self.login_user('admin', 'admin')
query_data = {
"failure": "assured"
}
result_data = {
"type": "IllegalParameter",
"reason": "Parameters are not allowed for this interface."
}
res... | , data=json.dumps(query_data))
print result.data
assert result.status_code == 403
assert json.loads(result.data) == result_data |
gltn/stdm | stdm/third_party/sqlalchemy/orm/exc.py | Python | gpl-2.0 | 6,616 | 0 | # orm/exc.py
# Copyright (C) 2005-2020 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""SQLAlchemy ORM exceptions."""
from .. import exc as sa_exc
from .. import util
NO_ST... | pected mappings not present."""
class ObjectDereferencedError(sa_exc.SQLAlchemyError):
"""An operation cannot complete due to an object being garbage
collected.
"""
class DetachedInstanceError(sa_exc.SQLAlchemyError):
"""An attempt to access unloaded attributes on a
mapped instance that is deta... | """An mapping operation was requested for an unknown instance."""
@util.dependencies("sqlalchemy.orm.base")
def __init__(self, base, obj, msg=None):
if not msg:
try:
base.class_mapper(type(obj))
name = _safe_cls_name(type(obj))
msg = (
... |
bloyl/mne-python | mne/io/eximia/eximia.py | Python | bsd-3-clause | 3,000 | 0 | # Authors: Eric Larson <larson.eric.d@gmail.com>
# Federico Raimondo <federaimondo@gmail.com>
#
# License: BSD-3-Clause
import os.path as op
from ..base import BaseRaw
from ..utils import _read_segments_file, _file_size
from ..meas_info import create_info
from ...utils import logger, verbose, warn, fill_doc,... | --
raw : instance of RawEximia
A Raw object containing eXimia data.
See Also
--------
mne.io.Raw : Documentation of attribute and methods.
"""
return RawEximia(fname, preload, verbose)
@fill_doc
class RawEximia(BaseRaw):
"""Raw object from an Eximia EEG file.
Parameters
-... | e).
%(preload)s
%(verbose)s
See Also
--------
mne.io.Raw : Documentation of attribute and methods.
"""
@verbose
def __init__(self, fname, preload=False, verbose=None):
fname = _check_fname(fname, 'read', True, 'fname')
data_name = op.basename(fname)
logger.info(... |
bitbyt3r/musicserver | start.py | Python | gpl-2.0 | 459 | 0.006536 | #!/usr/bin/python
import xmlrpc.client
from time import sleep
def remoteCall(func, *args):
try:
| ret = func(*args)
return ret
except xmlrpc.client.Fault as e:
print(e)
server = xmlrpc.client.ServerProxy("https://localhost:8080", allow_none=True)
sid = remoteCall(server.login, "dj", "abc123")
print(remoteCall(server.getfoo, sid))
sleep(3)
print(remoteCall(server.ge | tfoo, sid))
sleep(6)
print(remoteCall(server.getfoo, sid))
|
Gawen/pytun | pytun.py | Python | mit | 6,392 | 0.006414 | """ pytun
pytun is a tiny piece of code which gives you the ability to create and
manage tun/tap tunnels on Linux (for now).
"""
__author__ = "Gawen Arab"
__copyright__ = "Copyright 2012, Gawen Arab"
__credits__ = ["Gawen Arab", "Ben Lapid"]
__license__ = "MIT"
__version__ = "1.0.1"
__maintainer__ = "Gawen Arab"
__e... | if e.errno == 1:
logger.error("Cannot open a %s tunnel because the operation is not permitted." % (self.mode_name.upper(), ))
raise self.NotPermitted()
raise
self.name = ret[:16].strip("\x00")
logger.info("Tunnel '%s' opened." % (self.name, ))
def clos... | return
logger.debug("Closing tunnel '%s'..." % (self.name or "", ))
# Close tun.ko file
os.close(self.fd)
self.fd = None
logger.info("Tunnel '%s' closed." % (self.name or "", ))
def send(self, buf):
""" Send the buffer 'buf'. """
os.w... |
mdmintz/SeleniumBase | seleniumbase/translate/italian.py | Python | mit | 21,139 | 0 | # Italian / Italiano - Translations - Python 3 Only!
from seleniumbase import BaseCase
from seleniumbase import MasterQA
class CasoDiProva(BaseCase):
def __init__(self, *args, **kwargs):
super(CasoDiProva, self).__init__(*args, **kwargs)
self._language = "Italian"
def apri(self, *args, **kwa... | self.js_click(*args, **kwargs)
def js_aggiornare_testo(self, *args, **kwargs):
# js_update_text(selector, text)
return self.js_update_text(*args, **kwargs)
def js_digitare(self, *args, **kwargs) | :
# js_type(selector, text)
return self.js_type(*args, **kwargs)
def controlla_html(self, *args, **kwargs):
# inspect_html()
return self.inspect_html(*args, **kwargs)
def salva_screenshot(self, *args, **kwargs):
# save_screenshot(name)
return self.save_screensho... |
boundary/pulse-api-cli | tests/unit/boundary/metric_create_batch_test.py | Python | apache-2.0 | 2,094 | 0.001433 | #!/usr/bin/env python
#
# Copyright 2015 BMC Software, 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 applicab... | aw or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# | limitations under the License.
#
from unittest import TestCase
import os
import json
from boundary import MetricCreateBatch
from boundary import MetricDelete
from metric_test import MetricTest
from boundary import MetricExport
from cli_test import CLITest
from cli_runner import CLIRunner
class MetricCreateBatchTes... |
csiu/promi2 | code/promi2.py | Python | mit | 8,709 | 0.006889 | #!/usr/bin/env python
# Author: csiu
# Created: 2015-02-02
import argparse
from ConfigParser import SafeConfigParser
import sys
import os
from utils import get_value_from_keycolonvalue_list, ensure_dir, random_string
import features
import mirna_proximity
import correlation
import gff_unify_features
import promirna
i... | ensure_dir(outdir_mprox, False)
gff_mirnaprox = os.path.join(outdir_mprox, 'features_mirnaprox.gff')
gff_mirna = cparser.get('mirbase','gff2')
mirna_proximity.main(gff_cage, gff_mirna, gff_mirnaprox)
## merge extracted features (gff_unify_features.py)
gff_features = os.... | |
bmaia/rext | core/updater.py | Python | gpl-3.0 | 3,055 | 0.008191 | #This file is part of REXT
#updater.py - script that handles updating of REXT and it's components
#Author: Ján Trenčanský
#License: GNU GPL v3
import subprocess
import time
import re
import os
import interface.utils
import core.globals
from interface.messages import print_blue
#Pull REXT from git repo
def update_re... | if regex.search(line) is not None:
line = "".join(line.split("\t"))
line = line.split("(")
oui = line[0].replace(" ", "")
company = line[1].split(")")[1]
company = company.replace("\n", "")
if com... | company = "Private"
try:
cursor.execute("INSERT INTO oui (oui, name) VALUES (?, ?)", [oui, company])
connection.commit()
except Exception as e:
#CONRAD CORP. and CERN + ROYAL MELBOURNE INST ... |
infobloxopen/infoblox-netmri | infoblox_netmri/api/broker/v3_8_0/job_handler_broker.py | Python | apache-2.0 | 46,467 | 0.001894 | from ..broker import Broker
class JobHandlerBroker(Broker):
controller = "job_handlers"
def index(self, **kwargs):
"""Lists the available job handlers. Any of the inputs listed may be be used to narrow the list; other inputs will be ignored. Of the various ways to query lists, using this method is mo... | ion is available for created_at.
:type created_at: Array of String
| ``api version min:`` 2.6
| ``api ve | rsion max:`` None
| ``required:`` False
| ``default:`` None
:param created_by: No description is available for created_by.
:type created_by: Array of String
| ``api version min:`` 2.6
| ``api version max:`` None
| ``required:``... |
thysol/CS4098 | backend/peos_notify.py | Python | gpl-2.0 | 701 | 0.011412 | #!/usr/bin/python
import os
import re
import sys
import json
import urllib
import socket
import subprocess
import cgi, cgitb
from os import listdir
from os.path | import isfile, join
#http://178.62.51.54:13930/event=CREATE&login_name=henrik&pathway_name=test_commit.pml
def peos_notify(patient_id):
EXECUTION_PATH = "../peos/os/kernel/"
#Error constants
ERROR_USER_NOT_EXIST = 1
ERROR_SCRIPT_FAIL = 2
os.chdir(os.path.dirname(os.path.realpath(__file__)))... | = subprocess.Popen(["./peos", "-l", str(patient_id), "-u" ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate()
return output, error
|
fangxingli/hue | desktop/libs/notebook/src/notebook/models.py | Python | apache-2.0 | 6,176 | 0.009067 | #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... | else:
escaped_field = smart_unicode(field, errors='replace') # Prevent error when gettin | g back non utf8 like charset=iso-8859-1
if not nulls_only:
escaped_field = escape(escaped_field).replace(' ', ' ')
escaped_row.append(escaped_field)
data.append(escaped_row)
return data
def make_notebook(name='Browse', description='', editor_type='hive', statement='', status='ready... |
AlexLitvino/i8080_simulator | microprocessor/register_pair.py | Python | apache-2.0 | 189 | 0 | class RegisterPair:
def __init__(self, name, register_high, reg | ister_low):
self.name = name
self.register_high = register_high
self.register_low = | register_low
|
AnanseGroup/map-of-innovation | mapofinnovation/controllers/uifunc.py | Python | mit | 2,555 | 0.019178 | import logging |
import json
import redis
import sys
import urllib
import os
from urlparse import urlparse
from pylons import request, response, session, tmpl_context as c, url
from pylons.d | ecorators import jsonify
from pylons.controllers.util import abort, redirect
from mapofinnovation.lib.base import BaseController, render
log = logging.getLogger(__name__)
class UifuncController(BaseController):
def index(self):
# Return a rendered front page template
markers = []
indices ... |
amiraliakbari/sharif-mabani-python | by-session/ta-922/j6/a1.py | Python | mit | 136 | 0.014706 | def b():
print("hooora!")
dic1 = {1: 2, 1: 4}
for i in dic | 1.items():
if 'a' = | = i:
b()
else:
break
print ":(" |
stonewell/pymterm | pymterm/cap/unknown_cap.py | Python | mit | 443 | 0.004515 | import logging
def handle(term, context, cap_turple):
cap_name, increase_params = cap_turple
if hasattr(term, cap_name):
if increase_params:
for idx in range(len(con | text.params)):
context.params[idx] -= 1 if context.params[idx] != 0 else 0
getattr(term, cap_name)(context)
else:
| logging.error('No module named:{}, params:{}'.format(cap_name, context.params))
|
Saethlin/astrotools | photometry.py | Python | mit | 5,356 | 0.020724 | #!/usr/bin/env python
import numpy as np
from astropy.io import fits
import scipy.ndimage
import scipy.fftpack
import scipy.optimize
def getcentroid(coordinates, values):
"""
Image centroid from image points im that match with a 2-d array pos, which
contains the locations of each point in an all-positive... | = np.zeros(laplace.shape[0])
col_buffer = np.zeros(laplace.sha | pe[1][None,:])
above = np.vstack((laplace[1:],row_buffer[:]))
below = np.vstack((row_buffer[:,:],laplace[:-1]))
right = np.hstack((laplace[1:],row_buffer[:,:]))
stars = stars & (laplace < above) & (laplace < below) & (laplace < right) & (laplace < left)
#Pick a sky value
sky = np.median(im)
... |
veltzer/pdmt | pdmt/plugins/nodes/operations/debinstaller.py | Python | gpl-3.0 | 1,546 | 0.001294 | import pdmt.api
import pdmt.config
import pdmt.utils.subproc
'''
This module handles publishing and unpublishing a deb package from an apt repository
Mark Veltzer <mark@veltzer.net>
'''
class Operation(object):
def __init__(self):
super().__init__(
'debinstaller',
'install th... | dmt.config.ns_apt.p_component])
args.extend(['remove', pdmt.config.ns_apt.p_codename, NAME])
pdmt.utils.subproc.check_call(args)
def command(name): |
args = []
if pdmt.config.ns_apt.p_sudo:
args.append('sudo')
args.append('reprepro')
args.append(name)
pdmt.utils.subproc.check_call(args)
def makerepo():
pass
def dumpunreferenced():
command('dumpunreferenced')
def deleteunreferenced():... |
denys-duchier/Scolar | config/softs/jaxml-3.01/test/test.py | Python | gpl-2.0 | 9,215 | 0.007162 | #! /usr/bin/env python
# Test program for jaxml
#
# (C) Jerome Alet <alet@librelogiciel.com> 2000
# You're welcome to redistribute this software under the
# terms of the GNU General Public Licence version 2.0
# or, at your option, any higher version.
#
# You can read the complete GNU GPL in the file COPYING
# which sho... | to be able to exit from <select> ... </select>
page._push()
page.select(name="choice", size="1")
page.option("Choice number 1")
page.option("Choice number 2")
page.option("Choice number 3", selected="selected")
# exit from <sel | ect> ... </select>
page._pop()
page.h3("Second part of the Form")
page._br()
page._textinput(name="dumbstring", size="50")
page._submit()
page._reset()
# here we exit from the <form> ... </form>
page._pop()
page._text("here we should be outside of the form")
page._text("and there we should be one the same line visua... |
bitesofcode/xqt | xqt/wrappers/pyside.py | Python | lgpl-3.0 | 9,830 | 0.007121 | """ Sets up the Qt environment to work with various Python Qt wrappers """
# define authorship information
__authors__ = ['Eric Hulser']
__author__ = ','.join(__authors__)
__credits__ = []
__copyright__ = 'Copyright (c) 2012, Projex Software'
__license__ = 'LGPL'
# main... | exsoftware.com'
# requires at least the QtCore module
import PySide
import logging
import re
import sys
import xml.parsers.expat
from PySide import QtCore, QtGui, QtUiTools
from xml.etree import ElementT | ree
from ..lazyload import lazy_import
log = logging.getLogger(__name__)
class XThreadNone(object):
"""
PySide cannot handle emitting None across threads without crashing.
This variable can be used in place of None.
:usage |class A(QtCore.QObject):
| valueChang... |
manqala/erpnext | erpnext/schools/doctype/student_batch_name/test_student_batch_name.py | Python | gpl-3.0 | 300 | 0.006667 | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe | Technologies Pvt. Ltd. and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest
# test_records = frappe.get_test_records('Student Batch Name')
class TestStudentBatchName(unitt | est.TestCase):
pass
|
hajicj/safire | safire/learning/learners/__init__.py | Python | gpl-3.0 | 50 | 0.02 | from .base_sgd_ | learner import BaseSGD | Learner
|
tiagoprn/experiments | pyramid_basics/request_response/tutorial/views.py | Python | mit | 669 | 0.001495 | from pyramid.httpexceptions import HTTPFound
from pyramid.response import Response
from pyramid.view import (
view_config,
view_defaults
)
@view_defaults(renderer='home.p | t')
class TutorialViews:
def __init__(self, request):
self.request = request
@view_config(route_name='home')
def home(self): # Here we redirect to the p | lain route below
return HTTPFound(location='/plain')
@view_config(route_name='plain')
def plain(self):
name = self.request.params.get('name', 'No Name Provided')
body = 'URL %s with name: %s' % (self.request.url, name)
return Response(content_type='text/plain', body=body)
|
japeq/blackbeltsorvihero | create-pack.py | Python | lgpl-2.1 | 689 | 0.033382 | #!/usr/bin/env python
import os
pack = open('BlackBeltSorviHero.dat', 'w')
length = 0
offset = 0
for i in [1, 2]:
leng | th = 0
for fname in os.listdir('data'):
f = open('data/' + fname)
f.seek(0, 2)
size = f.tell()
f.close()
length += len("%s %d %d\n" % (fname, offset, size))
offset += size
offset = length + 4
for fname in | os.listdir('data'):
f = open('data/' + fname)
f.seek(0, 2)
size = f.tell()
f.close()
pack.write("%s %d %d\n" % (fname, offset, size))
offset += size
pack.write("END\n")
for fname in os.listdir('data'):
f = open('data/' + fname)
while True:
s = f.read(4096)
if not s:
break
pack.write(s)
size = f.tell... |
pombredanne/sparkey-python | test/binary_test.py | Python | apache-2.0 | 2,128 | 0 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2012-2013 | 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 obtain a copy of the License at
#
# http://www.apache.org/licenses | /LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under th... |
ladybug-analysis-tools/ladybug-core | ladybug/climatezone.py | Python | gpl-3.0 | 3,407 | 0.002935 | # coding=utf-8
"""Functions for computing climate classifications/zones from weather data."""
from __future__ import division
from .datacollection import HourlyContinuousCollection
def ashrae_climate_zone(dry_bulb_temperature, annual_precipitation=None):
"""Estimate the ASHRAE climate zone from a single year of ... | _climate_zone dry_bulb_temperature must have | a timestep of 1.'
if dbt.header.unit != 'C':
dbt = dbt.to_unit('C')
# compute the number of heating and cooling degree days
cooling_deg_days, heating_deg_days = 0, 0
for t in dbt.values:
cdd = (t - 10) / 24 if t > 10 else 0
cooling_deg_days += cdd
hdd = (18 - t) / 24... |
yahoo/Image-Builder | build.py | Python | apache-2.0 | 15,634 | 0.002111 | #!/usr/bin/python
# vi: ts=4 expandtab
#
# Copyright (C) 2012 Yahoo! Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/l... | fu | nctor = getattr(mod, 'modify')
# Give the modules a copy of the config
# and not the 'real' thing, so that
# they can't screw it up...
args = [real_name, root_dir, copy.deepcopy(config)]
functor(*args)
except:
print("Exception in module %r:... |
flaing/gemrb | gemrb/GUIScripts/GUIRECCommon.py | Python | gpl-2.0 | 19,924 | 0.044017 | # -*-python-*-
# GemRB - Infinity Engine Emulator
# Copyright (C) 2011 The GemRB Project
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) ... | :
GemRB.FillPlayerInfo (pc, Portrait.Name () + "M", Portrait.Name () + "S")
else:
GemRB.FillPlayerInfo (pc, Portrait.Name () + "L", Portrait.Name () + "S | ")
CloseSubCustomizeWindow ()
return
def PortraitLeftPress ():
global PortraitPictureButton
PortraitPictureButton.SetPicture (Portrait.Previous () + PortraitNameSuffix, "NOPORTLG")
def PortraitRightPress ():
global PortraitPictureButton
PortraitPictureButton.SetPicture (Portrait.Next () + PortraitNameSuffix, ... |
infobloxopen/infoblox-netmri | infoblox_netmri/api/broker/v3_8_0/discovery_setting_broker.py | Python | apache-2.0 | 69,668 | 0.002081 | from ..broker import Broker
class DiscoverySettingBroker(Broker):
controller = "discovery_settings"
def index(self, **kwargs):
"""Lists the available discovery settings. Any of the inputs listed may be be used to narrow the list; other inputs will be ignored. Of the various ways to query lists, using... | iscovery settings matching the input criteria. This met | hod provides a more flexible search interface than the index method, but searching using this method is more demanding on the system and will not perform to the same level as the index method. The input fields listed below will be used as in the index method, to filter the result, along with the optional query string a... |
janelia-ros/zaber_stage_ros | nodes/pose_and_debug_publisher.py | Python | bsd-3-clause | 1,472 | 0.01019 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import roslib; roslib.load_manifest('zaber_stage')
import rospy
import actionlib
from geometry_msgs.msg import Pose
from zaber_stage.msg import PoseAndDebugInfo
from zaber_stage.srv import GetPoseAndDebugInfo,GetPoseAndDebugInfoResponse
def pose_publisher():
rospy... | )
pub_pose_and_debug = rospy.Publisher('/zaber_stage_node/pose_and_debug_info',PoseAndDebugInfo,queue_size=10)
rospy.wait_for_service('/zaber_stage_node/get_pose_and_debug_info')
get_pose_and_debug_info = rospy.ServiceProxy('/zaber_stage_node/get_pose_and_debug_info',GetPoseAndDebugInfo,persistent=True)
... | e.pose_and_debug_info.zaber_response_error:
pub_pose.publish(response.pose_and_debug_info.pose)
pub_pose_and_debug.publish(response.pose_and_debug_info)
except rospy.ServiceException, e:
rospy.logwarn('zaber_stage pose_and_debug_publisher service call failed! %s'%e)
... |
cmand/scamper | sc_tracebox.py | Python | bsd-3-clause | 7,053 | 0.013895 | #!/usr/bin/env python
#
# Program: $Id: $
# Author: R | obert Beverly <rbeverly@nps.edu>
# Description: Experimental tracebox warts parser
import sys
import struct
import dpkt
from sc_warts import *
if dpkt.__version__ == '1.8':
print "Upgrade dpkt"
sys.exit(-1)
TRACEBOXTYPE = 0x0c
def dict_diff(a, b):
diff = dict()
for k in a:
if k in b:
if b[k] != a[... | Reader(WartsReader):
def __init__(self, wartsfile, verbose=False):
super(WartsTraceBoxReader, self).__init__(wartsfile, verbose)
def next(self):
while True:
obj = self.next_object()
if not obj:
return (False, False)
if (obj.typ == TRACEBOXTYPE):
return (obj.flags, obj.pkt... |
OkCupid/okws | test/regtest/cases/98.py | Python | gpl-2.0 | 542 | 0.027675 | test = "tes | t of the localtime() function"
import time
times = [ 0, 100000, int (time.time()) ] |
filedata = """
{$
for (i, %(times)s) {
locals { v : localtime(i) }
print ("${v[0]} ${v[1]} ${v[2]} ${v[3]} ${v[4]} ");
}
$}
""" % { "times" : times }
# in publand, localtime(0) should give the time now
times[0] = int (time.time())
outcome_v = []
for i in times:
lt = time.localtime (i)
o... |
TobiHartmann/hotspot | benchmarks/run_tests.py | Python | gpl-2.0 | 18,824 | 0.020399 | import os
import shlex
import datetime
import time
import shutil
from subprocess import Popen, PIPE
home = "/home/tobias/"
vm_config = " -XX:+PrintCodeCache "
# Benchmark configurations
dacapo_names = ("avrora", "batik", "fop", "h2", "jython", "luindex", "lusearch" ,"pmd", "sunflow", "tomcat", "tradebeans", "xalan")
... | .scimark.sparse startup.serial startup.sunflow startup.xml.transform startup.xml.validation compress crypto.aes crypto.rsa crypto.signverify mpegaudio scimark.fft.large scimark.lu.large | scimark.sor.large scimark.sparse.large scimark.fft.small scimark.lu.small scimark.sor.small scimark.sparse.small scimark.monte_carlo serial sunflow xml.validation"
cmd_specjbb2005 = "-cp './jbb.jar:./check.jar' spec.jbb.JBBmain -propfile SPECjbb.props"
cmd_specjbb2013 = "-jar " + home + "/programs/SPECjbb2013/specjbb2... |
MediaMath/Diamond | src/collectors/diskspace/diskspace.py | Python | mit | 9,080 | 0 | # coding=utf-8
"""
Uses /proc/mounts and os.statvfs() to get disk space usage
#### Dependencies
* /proc/mounts
#### Examples
# no exclude filters at all
exclude_filters =,
# exclude everything that begins /boot or /mnt
exclude_filters = ^/boot, ^/mnt
# exclude everything that includes the le... | space metrics collection",
})
return config_help
def get_def | ault_config(self):
"""
Returns the default collector settings
"""
config = super(DiskSpaceCollector, self).get_default_config()
config.update({
# Enabled by default
'enabled': 'True',
'path': 'diskspace',
# filesystems to examine
... |
vrk-kpa/api-catalog | ckanext/ckanext-apicatalog_ui/ckanext/apicatalog_ui/admindashboard.py | Python | mit | 15,229 | 0.00243 | from __future__ import absolute_import
import logging
import ckan.logic as logic
import ckan.model as model
import ckan.lib.dictization.model_dictize as model_dictize
import ckan.lib.dictization as dictization
from sqlalchemy import func, text, or_, and_
from datetime import datetime, timedelta
from .utils import packa... | try:
toolkit.check_access('admin_dashboard', context, {})
# Fetch invalid resources
invalid_resources = fetch_invalid_resources()
# Query package statistics
statistics = fetch_package_statistics()
# Find packageless organizations and produce a chan | gelog
(packageless_organizations, packageless_organizations_changelog) = \
fetch_packageless_organizations_and_changelog(context)
# Generate activity stream snippet
# FIXME: Disabled because fetch_recent_package_activity_list_html is not ported to CKAN 2.9
# package_activity... |
UManPychron/pychron | pychron/hardware/mdrive/__init__.py | Python | apache-2.0 | 1,003 | 0.000997 | # ===============================================================================
# Copyright 2016 Jake Ross
#
# Licensed under the Apache License, Versio | n 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
#... | DITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===============================================================================
# ============= enthought library imports =======================
# ============= stan... |
kergely/Character-creator-szerep | src/skills.py | Python | mit | 4,916 | 0.000407 | import dices
class skill(object):
"""
Contains a skill.
calling is done by skill(bases,value,known=True)
bases::string : attributes it depends on. (either ABCx2 or ABC+XYZ format)
value: value of the skill. If left empty, standard is calculated.
study(learned) --> learned is added to the valu... | W"),
"Sing": skill("CHA+POW", encaffect=False),
"Stealth": skill("DEX+INT"),
"Swim": skill("STR+CON"),
"Unarmed": skill("STR+DEX"),
"Willpower": skill("POWx2"),
}
# standard is used to store the standard skills used in the Mythras franchise
professionallist = {
"Acrobatics": skill("STR+ DEX"),... | skill("INT+CHA"),
"Craft": skill("DEX+INT"),
"Culture": skill("INTx2", encaffect=False),
"Devotion": skill("POW+CHA"),
"Disguise": skill("INT+CHA"),
"Engineering": skill("INTx2"),
"Exhort": skill("INT+CHA"),
"Folk Magic": skill("POW +CHA"),
"Gambling": skill("INT+POW"),
"Healing": s... |
dcloud/django-postgres-copy | setup.py | Python | mit | 1,511 | 0.001324 | from setuptools import setup
from distutils.core import Command
class TestCommand(Command):
user_options = []
def initialize_options(self | ):
pass
def finalize_options(self):
pass
def run(self):
import django
from django.core.management import call_command
from django.conf import settings
settings.configure(
DATABASES={
'default': {
'NAME': 'test',
... | 'sqlite': {
'NAME': 'sqlite',
'ENGINE': 'django.db.backends.sqlite3'
}
},
INSTALLED_APPS=("tests",),
)
django.setup()
call_command('test', 'tests.tests')
setup(
name='django-postgres-copy',
version='... |
acuriel/lsmdico | lsmdico/urls.py | Python | gpl-3.0 | 1,142 | 0.001751 | """lsmdico URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... | URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, | url
from . import views
#from django.contrib import admin
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name="index"),
url(r'^login/$', views.LoginView.as_view(), name="login"),
url(r'^logout/$', views.logout_view, name="logout"),
url(r'^manage/$', views.ManageView.as_view(), name="manage"),
... |
RedHatQE/cfme_tests | cfme/tests/services/test_pxe_service_catalogs.py | Python | gpl-2.0 | 6,083 | 0.002466 | # -*- coding: utf-8 -*-
import fauxfactory
import pytest
from widgetastic.utils import partial_match
from cfme import test_requirements
from cfme.infrastructure.provider import InfraProvider
from cfme.infrastructure.provider.rhevm import RHEVMProvider
from cfme.infrastructure.pxe import get_pxe_server_from_config
from... | pe="function")
def catalog_item(appliance, provider, dialog, catalog, provisioning,
setup_pxe_servers_vm_prov):
# generate_tests makes sure these have values
pxe_t | emplate, host, datastore, pxe_server, pxe_image, pxe_kickstart, pxe_root_password,\
pxe_image_type, pxe_vlan = map(
provisioning.get, (
'pxe_template', 'host', 'datastore', 'pxe_server', 'pxe_image', 'pxe_kickstart',
'pxe_root_password', 'pxe_image_type', 'vlan'
... |
goujonpa/jeankevin | views/settingsView.py | Python | mit | 7,278 | 0.000962 | #!/usr/local/bin/python
# -*-coding:Utf-8 -*
import os
import math
def GA_settings():
"""Provides the view for the user setting of the GA experiments and returns the settings set"""
options = {}
os.system("clear")
print('===== OPTIONS =====\n')
preset = int(raw_input(
"PRESET\n"
... | iterations"] = int(1000)
options["stopFitness"] = float(0.95)
options["base"] = int(10)
options['verbose'] = False
options['selectionMode'] = int(1)
options['mutationMode'] = '2LRNS'
options['recombinationMode'] = 'weighted'
options['sigmaBoost'] = True
elif ... | "] = int(x)
options['stopFitness'] = float(raw_input('\nStop Fitness:\n'))
print("\nGENERATIONS")
options["base"] = int(raw_input(
'n setting:\n'
'lambda (number of child from the father) = 8 * n\n'
'mu (number of best child selected to make new father) = l... |
rwoodley/SphericalPhotoBrowser | server/server.py | Python | apache-2.0 | 578 | 0.00173 | from flask import Flask, Response, make_response
from video_stream_handler import stream_handler
import log | ging
i | mport cv2
# see line 398 of connectionpool.py:
logging.basicConfig(level=logging.DEBUG)
thetav = None
app = Flask(__name__, static_url_path='/public', static_folder='../')
@app.route('/video_feed')
def video_feed():
cap = cv2.VideoCapture(0)
# cap.set(3, 3840)
# cap.set(4, 1920)
return Response(st... |
adkerr/tempest | tempest/api/compute/v3/servers/test_servers_negative.py | Python | apache-2.0 | 17,583 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apach... | IPv4 = '1.1.1.1.1.1'
self.assertRaises(exceptions.BadRequest,
self.create_test_server, accessIPv4=IPv4)
@attr(type=['negative', 'gate'])
def test_invalid_ip_v6_address(self):
# An access IPv6 address must match a valid address pattern
IPv6 = 'notvalid'
... | est_resize_nonexistent_server(self):
nonexistent_server = str(uuid.uuid4())
self.assertRaises(exceptions.NotFound,
self.client.resize,
nonexistent_server, self.flavor_ref)
@attr(type=['negative', 'gate'])
def test_resize_server_with_non_existe... |
dsp2003/e17p | src/e17p/remember11/ff/compression.py | Python | gpl-2.0 | 4,355 | 0.022273 | #!/usr/bin/env python3
#Copyright 2010 Sebastian Hagen
# This file is part of E17p.
#
# E17p is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any la... | len(data_in)
len_o = (len_i*9+7)//8 + 4
|
data_out = bytearray(len_o)
data_out[:4] = struct.pack('<L', len_i)
o = 4
i = 0
while(i < len_i):
data_out[o] = 0xff
data_out[o+1:o+9] = data_in[i:i+8]
i += 8
o += 9
if (len(data_out) != len_o):
raise ValueError('Compr... |
evanbrumley/django-report-tools | docs/source/charts/bar_chart_example.py | Python | bsd-2-clause | 900 | 0.002222 | class MyReport(Report):
renderer = GoogleChartsRenderer
bar_chart = charts.BarC | hart(title="Pony Populations", width="500")
multiseries_ba | r_chart = charts.BarChart(title="Pony Populations by Country", width="500")
def get_data_for_bar_chart(self):
data = ChartData()
data.add_column("Pony Type")
data.add_column("Population")
data.add_row(["Blue", 20])
data.add_row(["Pink", 20])
data.add_row(["Magical"... |
tkzeng/molecular-design-toolkit | moldesign/utils/callsigs.py | Python | apache-2.0 | 8,969 | 0.00301 | # Copyright 2016 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | ():
if name not in allexcept:
newparams.append(param)
else:
newparams = sig.parameters.values()
if inject_kwargs:
for name, default in inject_kwargs.iteritems():
newp = funcsigs.Parameter(name, funcsigs.Parameter.POSITIONAL_OR_K... |
newparams.append(newp)
newparams.sort(key=lambda param: param._kind)
sig = sig.replace(parameters=newparams)
else:
wraps = if_not_none(wraps, True)
# Get the docstring arguments
if update_docstring_args:
original_docs = GoogleDocArgumentInjector(original_f... |
alexdzul/friends | friends/apps/phonebook/admin.py | Python | mit | 299 | 0 | from django.contrib import admin
from friends.apps.phonebook.models import Contact
@admin.register(Contact)
class ContactAdmin(admin.ModelAdm | in):
list_display = ('id', 'first_name', 'last_name', 'phone_number')
list_filter = ('last_name', )
search_fields = ['fir | st_name', 'last_name']
|
oblique-labs/pyVM | rpython/rtyper/test/test_llann.py | Python | mit | 15,371 | 0.002797 | import py
from rpython.annotator import model as annmodel
from rpython.rtyper.llannotation import SomePtr, lltype_to_annotation
from rpython.conftest import option
from rpython.rtyper.annlowlevel import (annotate_lowlevel_helper,
MixLevelHelperAnnotator, PseudoHighLevelCallable, llhelper,
cast_instance_to_base... | y1 = ll_get(b, 1)
#
a2 = makelen4(A)
a2[0] = 2.0
return ll_get(a2, 1)
s = self.annotate(llf, [])
a = self.a
assert s == annmodel.SomeFloat()
seen = {}
def q(v):
s = a.binding(v)
if | s.is_constant():
return s.const
else:
return s.ll_ptrtype
vTs = []
for call in annotated_calls(a):
if derived(call, "ll_") or derived(call, "makelen4"):
func, T = [q(x) for x in call.args[0:2]]
if (func, T) in se... |
mjordan/linetweetbot | line_tweetbot.py | Python | unlicense | 3,096 | 0.003553 | #!/usr/bin/env python
from twitter import *
"""
Config variables
"""
# Set up authentication for this Twitter app.
oa_access_token = 'samplee320asuyiuwepjdiwu2'
oa_access_token_secret = 'samplemnbxcpw8383'
consumer_key = 'samplepekdncisyqgeq8d44d'
consumer_secret = 'sampleooojwydcw53ip'
# We read and write to the s... | et_chunks(line):
"""
Breaks lines up into chunks of a maximum of 140 characters long.
| However, we need to subtract the length of tweet_separator so we
can include it in tweets that contain partial sentences.
"""
chunk_length = 140 - len(tweet_separator)
line_length = len(line)
# If the line fits in one tweet, return it here.
if line_length < 140:
return [line]
# I... |
lino-framework/book | lino_book/projects/lets2/__init__.py | Python | bsd-2-clause | 86 | 0 | """This is the **second** appl | ication us | ed as example in
:doc:`/dev/lets/index`.
"""
|
f-prettyland/angr | angr/simos/windows.py | Python | bsd-2-clause | 20,273 | 0.00291 |
import os
import logging
import claripy
from ..errors import (
AngrSimOSError,
TracerEnvironmentError,
SimSegfaultException,
SimUnsupportedError,
SimZeroDivisionException,
)
from .. import sim_options as o
from ..tablespecs import StringTableSpec
from ..procedures import SIM_LIBRARIES as L
from .... |
LDR_addr = fun_stuff_addr + 0x2000
state.mem[TIB_addr + 0].dword = -1 # Initial SEH frame
state.mem[TIB_addr + 4].dword = state.regs.sp # stack base (high addr)
state.mem[TIB_addr + 8].dword = state.regs.sp - 0x100000 # stack limit (low addr)
state.mem[TI... | ].dword = 0xbad76ead # thread id
if self.project.loader.tls_object is not None:
state.mem[TIB_addr + 0x2c].dword = self.project.loader.tls_object.user_thread_pointer # tls array pointer
state.mem[TIB_addr + 0x30].dword = PEB_addr # PEB addr, of course
state.regs.f... |
onefinestay/sphinx-nameko-theme | docs/source/conf.py | Python | mit | 2,061 | 0 | # -*- coding: utf-8 -*-
"""Sphinx Readable Theme documentation build configuration file.
This file is execfile()d with the current directory set to its containing dir.
"""
import os
import sys
import pkg_resources
# Adding this directory to the sys path, to build autodoc of example module.
sys.path.insert(0, os.pa... | on ----------------------------------------------------
# Defining Sphinx extension modules.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode',
'sphinx.ext.intersphinx']
autodoc_default_flags = ['members', 'show-inher | itance']
autodoc_member_order = 'bysource'
# Don't display module names before objects titles, it's more readable.
add_module_names = False
intersphinx_mapping = {
'python': ('http://docs.python.org/2.7', None),
}
# The suffix of source filenames.
source_suffix = '.rst'
# The master toctree document.
master_doc... |
redbo/swift | swift/common/constraints.py | Python | apache-2.0 | 15,176 | 0.000066 | # Copyright (c) 2010-2012 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | request=req, content_type='text/plain')
bad_key = not check_utf8(key)
bad_value = value and not check_utf8(value)
if target_type in ('account', 'container') and (bad_key or bad_value):
return HTTPBadRequest(body='Metadata must be valid UTF-8',
... | uest=req, content_type='text/plain')
meta_count += 1
meta_size += len(key) + len(value)
if len(key) > MAX_META_NAME_LENGTH:
return HTTPBadRequest(
body='Metadata name too long: %s%s' % (prefix, key),
request=req, content_type='text/plain')
if l... |
exelearning/iteexe | exe/webui/templatemanagerpage.py | Python | gpl-2.0 | 11,217 | 0.002942 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# ===========================================================================
# eXeLearning
# Copyright 2017, CeDeC
#
# 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 Softwar... | ssionClients
from exe.webui.renderable import RenderableResource
from exe import | globals as G
from exe.engine.package import Package
from exe.export.pages import forbiddenPageNames
log = logging.getLogger(__name__)
class ImportTemplateError(Exception):
pass
class ImportTemplateExistsError(ImportTemplateError):
def __init__(self, local_template, absolute_template_dir, messa... |
Elico-Corp/openerp-7.0 | wms/wizard/stock_to_date.py | Python | agpl-3.0 | 11,857 | 0.004218 | # -*- coding: utf-8 -*-
# © 2011 SYLEAM Info Services (http://www.Syleam.fr)
# © 2011 Sebastien LANGE (sebastien.lange@syleam.fr)
# © 2014 Elico Corp (https://www.elico-corp.com)
# Licence AGPL-3.0 or later(http://www.gnu.org/licenses/agpl.html)
from openerp.osv import osv
from openerp.osv import fields
from openerp.... | Y r.date::date, product_id, warehouse_id
) subquery
ORDER BY date_move ASC
""",
(
tuple_warehouse_ids,
wizard.product_id.id,
tuple_wareho | use_ids,
tuple_warehouse_ids,
wizard.date_from,
wizard.date_to,
tuple_warehouse_ids,
wizard.product_id.id,
tuple_warehouse_ids,
tuple_warehouse_ids,
wizard.date... |
ZeitOnline/zeit.website | src/zeit/website/preview.py | Python | bsd-3-clause | 377 | 0 | import grokcore.component as grok
import zeit.cms.browser.preview
import zeit.website.interfaces
@grok.adapter(zeit.website.interfaces.IWebsiteContent, basestring)
@grok.implementer(zeit.cms.browser.interfaces.IPreviewURL)
def preview_u | rl(content, preview_type):
return zeit.cms.browser.preview.prefixed_url(
'website-%s-prefix' % preview_type, content.uniqu | eId)
|
hasadna/OpenCommunity | src/users/tests/invitation_test.py | Python | bsd-3-clause | 4,187 | 0.003583 | from django.core import mail
from django.test import TestCase
from users.default_roles import DefaultGroups
from users.models import Invitation, Membership, OCUser
from communities.tests.common import create_sample_community
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as ... | created_by=self.chairmen[0],
email="sample@email.com")
self.login_chairmen()
response = self.post_invite()
self.assertEqual(response.status_code, 400)
self.assertEqual(_("This user is already invited to this community."), respon... | "sample user", password="password")
Membership.objects.create(user=u, community=self.community, default_group_name=DefaultGroups.MEMBER)
self.login_chairmen()
response = self.post_invite()
self.assertEqual(response.status_code, 400)
self.assertEqual(_("This user alrea... |
CWSL/access-cm-tools | operations/compress_nc.py | Python | apache-2.0 | 1,765 | 0.002266 | #!/usr/bin/env python
from __future__ import print_function
import argparse
import sys
import os
import multiprocessing as mp
import subprocess as sp
import tempfile
import shlex
import shutil
"""
Compress all netcdf files under a directories.
compress_nc.py ~/exps/access/cm_1440x1080-1/archive/ ./'
This will recu... |
for file in files:
| if file.endswith(".nc"):
full_path = os.path.join(os.path.abspath(root), file)
if not os.path.islink(full_path):
netcdf_files.append(full_path)
return netcdf_files
def main():
parser = argparse.ArgumentParser()
parser.add_argument("dirs", narg... |
wjo1212/aliyun-log-python-sdk | tests/es_migration/test_mapping_index_converter.py | Python | mit | 3,908 | 0.000512 | #!/usr/bin/env python
# encoding: utf-8
# Copyright (C) Alibaba Cloud Computing
# All rights reserved.
import unittest
from aliyun.log.es_migration.mapping_index_converter import \
MappingIndexConverter
class TestMappingIndexConverter(unittest.TestCase):
def test_to_index_config(self):
mapping = ... | erter.to_index_config(mapping)
line_config = index_config.line_config
self.assertEqual(MappingIndexConverter.DEFAULT_TOKEN_LIST, line_config.token_list) |
self.assertTrue(line_config.chn)
def test_to_index_config_with_none(self):
index_config = MappingIndexConverter.to_index_config(None)
self.assertEqual(None, index_config)
if __name__ == '__main__':
unittest.main()
|
honur/django-tenant-schemas | tenant_schemas/tests/models.py | Python | mit | 354 | 0 | from django.db import models
from tenant_schemas.models import TenantMixin
# as Te | nantMixin is an abstract model, it needs to be created
class Tenant(TenantMixin):
pass
class Meta:
app_label = 'tenant_schemas'
class NonAutoSyncTenant(TenantMixin):
auto_create_schema = False
class | Meta:
app_label = 'tenant_schemas'
|
scipy/scipy-svn | scipy/sparse/csgraph.py | Python | bsd-3-clause | 2,341 | 0.000854 | """Compressed Sparse graph algorithms"""
__docformat__ = "restructuredtext en"
__all__ = ['cs_graph_components']
import numpy as np
from sparsetools import cs_graph_components as _cs_graph_components
from csr import csr_matrix
from base import isspmatrix
_msg0 = 'x must be a symmetric square matrix!'
_msg1 = _msg... | Parameters
-----------
x: nda | rray-like, 2 dimensions, or sparse matrix
The adjacency matrix of the graph. Only the upper triangular part
is used.
Returns
--------
n_comp: int
The number of connected components.
label: ndarray (ints, 1 dimension):
The label array of each connected component (-2 is us... |
cournape/responses | setup.py | Python | apache-2.0 | 1,534 | 0 | #!/usr/bin/env python
"""
responses
=========
A utility library for mocking out the `requests` Python library.
:copyright: (c) 2013 Dropbox, Inc.
"""
from setuptools import setup
from setuptools.command.test import test as TestCommand
import sys
setup_requires = []
if 'test' in sys.argv:
setup_requires.append(... | .finalize_options(self)
self.test_args = ['test_responses.py']
self.test_suite = True
def run_tests(self):
# import here, cause outside the eggs aren't loaded
import pytest
errno = pytest.main(self.test_args)
sys.exit(errno | )
setup(
name='responses',
version='0.2.2',
author='David Cramer',
description=(
'A utility library for mocking out the `requests` Python library.'
),
long_description=open('README.rst').read(),
py_modules=['responses'],
zip_safe=False,
install_requires=install_requires,
... |
interlegis/sapl | sapl/base/models.py | Python | gpl-3.0 | 12,876 | 0.000234 | from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.db.models.deletion import CASCADE
from django.db.models.signals import post_migrate
from django.db.utils import DEFAULT_DB_ALIAS
from django.utils.translat... | 'Perguntar se é pra gerar protocolo ao incorporar')),
('N', _('Nunca Protocolar ao incorporar uma proposição')),
)
documentos_administrativos = models.CharField(
max_length=1,
verbose_name=_('Visibilidade dos Documentos Administrativos'),
choices=TIPO_DOCUMENTO_ADMINISTRATIV | O, default='O')
estatisticas_acesso_normas = models.CharField(
max_length=1,
verbose_name=_('Estatísticas de acesso a normas'),
choices=RELATORIO_ATOS_ACESSADOS, default='N')
sequencia_numeracao_proposicao = models.CharField(
max_length=1,
verbose_name=_('Sequência de n... |
nithincvpoyyil/nithincvpoyyil.github.io | test.py | Python | mit | 1,191 | 0.036104 | def goodSegement1(badList,l,r):
sortedBadList = sorted(badList)
current =sortedBadList[0]
maxVal = 0
for i in range(len(sortedBadList)):
current = sortedBadList[i]
maxIndex = i+1
# first value
if i == 0 and l<=current<=r:
val = current - l
prev... | s,e)",current,next)
print("maxVal:",maxVal-1)
pass
goodSegement1([2,5,8,10,3],1,12)
goodS | egement1([37,7,22,15,49,60],3,48)
|
c3nav/c3nav | src/c3nav/editor/api.py | Python | apache-2.0 | 29,810 | 0.003187 | from functools import wraps
from itertools import chain
from django.db.models import Prefetch, Q
from django.urls import Resolver404, resolve
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _
from rest_framework.authentication import SessionAuthentication
from ... | changeset.wrap_model('Building')
Door = request.changeset.wrap_model('Door')
LocationGroup = request.changeset.wrap_model('LocationGroup')
WifiMeasurement = request.changeset.wrap_model('WifiMeasurement')
level = request.GET.get('level')
space = request.GET.get('space')
... | nly level or space can be specified.')
level = get_object_or_404(Level.objects.filter(Level.q_for_request(request)), pk=level)
edit_utils = LevelChildEditUtils(level, request)
if not edit_utils.can_access_child_base_mapdata:
raise PermissionDenied
level... |
beni55/bookmarkdown | setup.py | Python | mit | 1,280 | 0.004688 | """blatter"""
setup_info = dict(
name="bookmarkdown",
description="Write books in Markdown.",
version="0.0.1",
author='Steve Losh',
author_email='steve@stevelosh.com',
license='MIT License',
url='http://bitbucket.org/sjl/bookmarkdown/',
packages=['bookmarkdown'],
scripts = ['book... | fiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
| 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Internet :: WWW/HTTP :: Site Management',
'Topic :: Software Development :: Pre-processors',
'Topic :: Text Processing :: Markup :: HTML',
'Topic :: Utilities',
]
)
try:
from setuptools import setup
... |
GeoODK/onadata | onadata/libs/utils/timing.py | Python | bsd-2-clause | 1,938 | 0 | import time
import datetime
from itertools import chain
from django.utils import timezone
from onadata.apps.logger.models.attachment import Attachment
from onadata.apps.main.models.meta_data import MetaData
from django.contrib.auth.models import User
def print_time(func):
"""
@print_time
Put this decorat... | def wrapped_func(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
seconds = end - start
print "SECONDS:", seconds, func.__name__, kwargs
return result
return wrapped_func
def get_header_date_format(date_modified):
format = ... | return get_header_date_format(timezone.now())
if isinstance(_object, Attachment):
_object = _object.instance
elif isinstance(_object, MetaData):
_object = _object.xform
elif isinstance(_object, User):
_object = _object.profile
_date = _object.date_modified
return get_h... |
jmcnamara/XlsxWriter | xlsxwriter/test/comparison/test_chart_points05.py | Python | bsd-2-clause | 1,577 | 0 | ###############################################################################
#
# Tests for XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompar... | self.set_filename('chart_p | oints05.xlsx')
def test_create_file(self):
"""Test the creation of an XlsxWriter file with point formatting."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({'type': 'line'})
chart.axis_ids = [45471616, 46804992]
... |
mrjoes/flask-admin | examples/file/app.py | Python | bsd-3-clause | 774 | 0 | import os
import os.path as op
from flask import Flask
fr | om flask.ext import admin
from flask.ext.admin.contrib import fileadmin
# Create flask app
app = Flask(__name__, template_folder='templates', static_folder='files')
# Create dummy secrey key so we can use flash
app.config['SECRET_KEY'] = '12345 | 6790'
# Flask views
@app.route('/')
def index():
return '<a href="/admin/">Click me to get to Admin!</a>'
if __name__ == '__main__':
# Create directory
path = op.join(op.dirname(__file__), 'files')
try:
os.mkdir(path)
except OSError:
pass
# Create admin interface
admin =... |
uclouvain/OSIS-Louvain | ddd/logic/learning_unit/tests/use_case/write/test_update_class_service.py | Python | agpl-3.0 | 8,871 | 0.003269 | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... | er=None,
volume_second_quadrimester=annual_volume - 1,
)
with self.assertRaises(MultipleBusinessExceptions | ) as class_exceptions:
update_effective_class(cmd, self.learning_unit_repository, self.effective_class_repository)
self.assertIsInstance(
class_exceptions.exception.exceptions.pop(),
AnnualVolumeInvalidException
)
def test_should_ignore_volumes_consistency_when_n... |
django-rea/nrp | django_rea/api/apps.py | Python | agpl-3.0 | 120 | 0 | from django.apps | import AppConfig
class ApiAppConfig(AppConfig):
| name = 'django_rea.api'
verbose_name = 'Api'
|
timmahrt/praatIO | praatio/klattgrid.py | Python | mit | 8,030 | 0.000249 | """
Functions for reading/writing/manipulating klattgrid files
A klattgrid can be used for speech synthesis/resynthesis.
For more information on the praat klattgrid:
http://www.fon.hum.uva.nl/praat/manual/KlattGrid.html
There are three kinds of data types in a klattgrid:
null tiers (contain no data points -- seem to ... | on exit after resynthesis with a klattgrid
utils.runPraatScript(praatEXE, scriptFN, [wavFN, klattFN, outputWavFN, method])
def _openNormalKlattgrid(data: str) -> Klattgrid:
kg = Klattgrid()
# Toss header
data = data.split("\n\n", 1)[1]
# Not sure if this is needed
startI = data.index("point... | = data.index("\n", startI)
# Find sections
sectionIndexList = _findIndicies(data, "<exists>")
sectionIndexList.append(-1)
for i in range(len(sectionIndexList) - 1):
dataTuple = _getSectionHeader(data, sectionIndexList, i)
name, minT, maxT, sectionData, sectionTuple = dataTuple
... |
mojones/Axelrod | axelrod/eigen.py | Python | mit | 2,189 | 0.00137 | """
Compute the principal eigenvector of a matrix using power iteration.
See also numpy.linalg.eig which calculates all the eigenvalues and
eigenvectors.
"""
import numpy
def normalise(nvec):
"""Normalises the given numpy array."""
return nvec / numpy.sqrt(numpy.dot(nvec, nvec))
def squared_error(vector_1,... | on(mat, initial):
"""
Generator o | f successive approximations.
Params
------
mat: numpy.matrix
The matrix to use for multiplication iteration
initial: numpy.array, None
The initial state. Will be set to numpy.array([1, 1, ...]) if None
Yields
------
Successive powers (mat ^ k) * initial
"""
vec = i... |
wolverineav/networking-bigswitch | networking_bigswitch/plugins/bigswitch/db/migration/alembic_migrations/versions/kilo_add_base_bsn_plugin.py | Python | apache-2.0 | 5,765 | 0 | # Copyright 2011 OpenStack Foundation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless req... | mn('dst_ip', sa.String(16), nullable=False),
sa.Column('expected_result',
Enum("reached destination", "dropped by route",
"dropped by policy", "dropped due to private segment",
"packet in", "forwarded", "dropped", "multipl | e sources",
"unsupported", "invalid input", name="expected_result"),
nullable=False),
sa.Column('test_time', TIMESTAMP(timezone=True), nullable=True),
sa.Column('test_result', Enum("pass", "fail", "pending"),
nullable=False, default="pending"),
... |
quasiyoke/telegram-bot-server | telegram_bot_server/server.py | Python | lgpl-3.0 | 6,225 | 0.002249 | # telegram-bot-server
# Copyright (C) 2017 quasiyoke
#
# You should have received a copy of the GNU Lesser General Public License v3
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import asyncio
import logging
import traceback
from .error import BotError
from .middleware import AuthMiddleware,... | if updates_future is not None:
updates_future.set_result(updates)
def _setup_routes(self):
self._app.router.add_route('*', f'/bot{TOKEN_PATTERN}/deleteWebhook', self._handle_delete_webhook)
self._app.router.add_route('*', f'/bot{TOKEN_PATTERN}/getUpdates', self._handle_get_u... | _PATTERN}/sendMessage', self._handle_send_message)
self._app.router.add_route('*', f'/bot{TOKEN_PATTERN}/setWebhook', self._handle_set_webhook)
def run(self):
web.run_app(
self._app,
host='0.0.0.0',
port=self._configuration.port,
)
|
tonygalmiche/is_plastigray | wizard/assistent_report.py | Python | mit | 2,803 | 0.014695 | # -*- coding: utf-8 -*-
from openerp import models,fields,api
import datetime
import time
class assistent_report1(models.TransientModel):
_name = "assistent.report1"
def date_debut_mois():
now = datetime.date.today() # Date du jour
date_debut_mois = datetime.da... | rt_data.site)+ '&date_jour=' + str(report_data.date_jour)+ '&date_mois=' + str(report_data.date_mois)+'&detail='+str(report_data.detail)+'&employee='+str(report_data.employee.id)+'&interimaire='+str(report_data.interimaire)+'&saut_page='+str(report_data.saut_page)+ '&date_debut=' + str(report_data.date_debut)+ '&date_f... | t_data.date_fin)
return {
'name' : 'Go to website',
'res_model': 'ir.actions.act_url',
'type' : 'ir.actions.act_url',
'target' : 'current',
'url' : url
}
|
duedil-ltd/pyfilesystem | fs/tests/__init__.py | Python | bsd-3-clause | 46,382 | 0.000539 | #!/usr/bin/env python
"""
fs.tests: testcases for the fs module
"""
from __future__ import with_statement
# Send any output from the logging module to stdout, so it will
# be captured by nose and reported appropriately
import sys
import logging
logging.basicConfig(level=logging.ERROR, stream=sys.stdout)
from ... | rtTrue(self.fs.isdir("dir1"))
self.assertTrue(self.fs.exists("dir1"))
self.assertTrue(self.fs.exists("a.txt"))
self.fs.remove("a.tx | t")
self.assertFalse(self.fs.exists("a.txt"))
def test_listdir(self):
def check_unicode(items):
for item in items:
self.assertTrue(isinstance(item, unicode))
self.fs.setcontents(u"a", b(''))
self.fs.setcontents("b", b(''))
self.fs.setcontents("foo... |
krassowski/Anki-Night-Mode | night_mode/__init__.py | Python | gpl-3.0 | 577 | 0.006932 | from aqt import mw
from anki.hoo | ks import addHook
#addons should selectively load before or after a delay of 666
NM_RESERVED_DELAY = 666
night_mode = None
def delayedLoader():
"""
Delays loading of NM to avoid addon conflicts.
"""
global night_mode
from .night_mode import NightMode
night_mode = NightMode()
night_mo... | if not night_mode:
mw.progress.timer(
NM_RESERVED_DELAY, delayedLoader, False
)
else:
night_mode.load()
addHook('profileLoaded', onProfileLoaded)
|
log2timeline/dfwinreg | run_tests.py | Python | apache-2.0 | 1,027 | 0.009737 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Script to run the tests."""
from __future__ import print_function
import sys
import unittest
# Change PYTHONPATH to include dependencies.
sys.path.insert(0, '.')
import utils.dependencies # pylint: disable=wrong-import-position
if __name__ == '__main__':
print('... | st-file')
dependency_helper = utils.dependencies.DependencyHelper()
if not dependency_helper.CheckTestDependencies():
sys.exit(1)
test_suite = unittest.TestLoader().discover('tests', pattern='*.py')
tes | t_results = unittest.TextTestRunner(verbosity=2).run(test_suite)
if not test_results.wasSuccessful():
sys.exit(1)
|
Yelp/docker-custodian | tests/docker_autostop_test.py | Python | apache-2.0 | 2,726 | 0 | try:
from unittest import mock
except ImportError:
import mock
from docker_custodian.docker_autostop import (
build_container_matcher,
get_opts,
has_been_running_since,
main,
stop_container,
stop_containers,
)
def test_stop_containers(mock_client, container, now):
matcher = mock.M... | ith(id)
def test_build_container_matcher():
prefixes = ['one_', 'two_']
matcher = build_container_matcher(prefixes)
as | sert matcher('one_container')
assert matcher('two_container')
assert not matcher('three_container')
assert not matcher('one')
def test_has_been_running_since_true(container, later_time):
assert has_been_running_since(container, later_time)
def test_has_been_running_since_false(container, earlier_tim... |
tobiashochguertel/postman-proxy_server.py | twisted-proxy.py | Python | apache-2.0 | 2,098 | 0.004766 | #!/usr/bin/python
from twisted.internet import reactor
from twisted.web import http
from twisted.web.proxy import Proxy, ProxyRequest, ProxyClientFactory, ProxyClient
from PIL import ImageFile
from PIL.ImageFile import Par | ser
from StringIO import StringIO
class InterceptingProxyClient(ProxyClient):
def __init__(self, *args, **kwargs):
ProxyClient.__init__(self, *args, **kwargs)
self.image_parser = None
def handleHeader(self, key, value):
if key == "Content-Type" and value in ["image/jpeg", | "image/gif", "image/png"]:
self.image_parser = Parser()
if key == "Content-Length" and self.image_parser:
pass
else:
ProxyClient.handleHeader(self, key, value)
def handleEndHeaders(self):
if self.image_parser:
pass #Need to calculate and send ... |
google-research/runtime-error-prediction | core/models/ipagnn.py | Python | apache-2.0 | 6,218 | 0.004986 | """IPA-GNN models."""
from typing import Any
from flax import linen as nn
import jax
import jax.numpy as jnp
from core.data import error_kinds
from core.modules.ipagnn import compressive_ipagnn
from core.modules.ipagnn import encoder
from core.modules.ipagnn import ipagnn
from core.modules.ipagnn import logit_math
f... | num_embeddings=vocab_size,
feature | s=config.hidden_size,
)
self.docstring_encoder = encoder.TransformerEncoder(
config=self.docstring_transformer_config)
if config.use_compressive_ipagnn:
self.ipagnn = compressive_ipagnn.SkipIPAGNN(
config=config,
info=self.info,
max_steps=max_steps,
)... |
hyesun03/k-board | kboard/board/models.py | Python | mit | 3,211 | 0.000626 | from django.core.urlresolvers import reverse
from django.db import models
from django.db.models import Q
from core.models import TimeStampedModel
from accounts.models import Account
class Board(models.Model):
def __str__(self):
return 'Board Name: ' + self.name
def get_absolute_url(self):
re... | tQuerySet(models.QuerySet):
| def search(self, search_flag, query):
if search_flag == 'TITLE':
return self.filter(title__contains=query)
elif search_flag == 'CONTENT':
return self.filter(content__contains=query)
elif search_flag == 'BOTH':
return self.filter(Q(title__contains=query) | Q(... |
qedsoftware/commcare-hq | corehq/ex-submodules/casexml/apps/phone/const.py | Python | bsd-3-clause | 738 | 0 | # how long a cached payload sits around for (in seconds).
INITIAL_SYNC_CACHE_TIMEOUT = 60 * 60 # 1 hour
# the threshold for setting a cached payload on initial sync (in | seconds).
# restores that take less than this time will not be cached to allow
# for rapid iteration on fixtures/cases/etc.
INITIAL_SYNC_CACHE_THRESHOLD = 60 # 1 minute
# if a sync is happening asynchronously, we wait for this long for a result to
# initially be returned, otherwise we return a 202
INITIAL_ASYNC_TIMEO... | der parameter. Ask the phone to retry in this many seconds
# to see if the task is done.
ASYNC_RETRY_AFTER = 30
ASYNC_RESTORE_CACHE_KEY_PREFIX = "async-restore-task"
RESTORE_CACHE_KEY_PREFIX = "ota-restore"
|
quequino/Revolution | plugin.program.vpnicity/yt.py | Python | gpl-2.0 | 16,924 | 0.012527 |
#
# Copyright (C) 2013 Sean Poyser
#
#
# This code is a derivative of the YouTube plugin for XBMC
# released under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 3
# Copyright (C) 2010-2012 Tobias Ussing And Henrik Mosgaard Jensen
#
# This Program is free soft... | hlsvp"):
video[u"hlsvp"] = flashvars[u"hlsvp"]
for url_desc in flashvars[u"url_encoded_fmt_stream_map"].split(u","):
url_desc_map = cgi.parse_qs(url_desc)
if not (url_desc_map.has_key(u"url") or url_desc_map.has_key(u"stream")):
| continue
key = int(url_desc_map[u"itag"][0])
url = u""
if url_desc_map.has_key(u"url"):
url = urllib.unquote(url_desc_map[u"url"][0])
elif url_desc_map.has_key(u"conn") and url_desc_map.has_key(u"stream"):
url = urllib.unquote(url_desc_map[u"conn"][0])
... |
ejherran/acaest | Grafos/general/Edge.py | Python | gpl-3.0 | 250 | 0.02 | class Edge():
def __init__(self):
self.origin = None
self.goal = None
self.value = None
| self.isDouble = Fals | e
self.pX = [] # To Draw
self.pY = []
|
mtmail/Nominatim | test/python/mock_legacy_word_table.py | Python | gpl-2.0 | 3,310 | 0.003625 | """
Legacy word table for testing with functions to prefil and test contents
of the table.
"""
class MockLegacyWordTable:
""" A word table for testing using legacy word table structure.
"""
def __init__(self, conn):
self.conn = conn
with conn.cursor() as cur:
cur.execute("""CREA... | operator TEXT)""")
conn.commit()
def add_special(self, word_token, word, cls, typ, oper):
with self.conn.cursor() as cur:
cur.execute("""INSERT INTO word (wor | d_token, word, class, type, operator)
VALUES (%s, %s, %s, %s, %s)
""", (word_token, word, cls, typ, oper))
self.conn.commit()
def add_country(self, country_code, word_token):
with self.conn.cursor() as cur:
cur.execute("INSERT INTO ... |
ProfessorX/Config | .PyCharm30/system/python_stubs/-1247972723/gtk/gdk/WindowType.py | Python | gpl-2.0 | 832 | 0.007212 | # encoding: utf-8
# module gtk.gdk
# from /usr/lib/python2.7/dist-packages/gtk-2.0/gtk/_gtk.so
# by generator 1.135
# no doc
# imports
from exceptions import Warning
import gio as __gio
import gobj | ect as __gobject
import gobject._gobject as __gobject__gobject
import pango as __pango
import pangocairo as __pangocairo
class WindowType(__gobject.GEnum):
# no doc
def __init__(self, * | args, **kwargs): # real signature unknown
pass
__weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""list of weak references to the object (if defined)"""
__dict__ = None # (!) real value is ''
__enum_values__ = {
0: 0,
1: 1,
... |
OpenEntityMap/oem-client-anidb | examples/anidb_incremental_local_server.py | Python | bsd-3-clause | 2,697 | 0.001112 | from argparse import ArgumentParser
from flask import Flask, abort, send_from_directory
import json
import logging
import os
app = Flask(__name__)
log = logging.getLogger(__name__)
packages = {}
@app.route('/<package>/<version>/<database>/<collection>/index.<extension>')
def serve_index(package, version, database, c... | path = os.path.join(packages[package][version], database, collection) |
# Ensure index exists
filename = 'index.%s' % extension
if not os.path.exists(os.path.join(path, filename)):
abort(404)
# Serve file
mimetype = None
if extension.endswith('json'):
mimetype = 'application/json'
return send_from_directory(path, filename, mimetype=mimetype... |
xhava/hippyvm | hippy/objects/closureobject.py | Python | mit | 2,726 | 0.001834 | from hippy.objects.instanceobject import W_InstanceObject
from hippy.klass import W_InvokeCall, def_class
from hippy.builtin import wrap_method, ThisUnwrapper
from hippy.function import Function
class W_CallClosure(W_InvokeCall):
def __init__(self, klass, call_func, w_obj, closure):
W_InvokeCall.__init__(s... | Object), 'args_w | '],
name='Closure::__invoke')
def closure_invoke(interp, this, args_w):
return this._func.call_args(interp, args_w)
k_Closure = def_class('Closure', [closure_invoke])
def new_closure(space, func, w_this, static=False):
w_res = W_ClosureObject(func, k_Closure,
k_Closure... |
hzeller/rpi-rgb-led-matrix | bindings/python/samples/rotating-block-generator.py | Python | gpl-2.0 | 2,383 | 0.001259 | #!/usr/bin/env python
from samplebase import SampleBase
import math
def scale_col(val, lo, hi):
if val < lo:
return 0
if val > hi:
| return 255
return 255 * (val - lo) / (hi - lo)
def rotate(x, y, sin, cos):
return x * cos - y * sin, x * sin + y * cos
class RotatingBlockGenerator(SampleBase):
def __init__(self, *args, **kwargs):
super(RotatingBlockGenerator, self).__init__(*args, **kwargs)
def run(self):
... | .matrix.height / 2
rotate_square = min(self.matrix.width, self.matrix.height) * 1.41
min_rotate = cent_x - rotate_square / 2
max_rotate = cent_x + rotate_square / 2
display_square = min(self.matrix.width, self.matrix.height) * 0.7
min_display = cent_x - display_square / 2
... |
AndroidOpenSourceXperia/android_scripts | devhost.py | Python | gpl-2.0 | 15,780 | 0.002155 | #!/usr/bin/env python2
# dev-host-cl Copyright (c) 2013 by GermainZ <germanosz@gmail.om>
# Requirements: python2
# python2-requests
#
# Dev-Host API documentation
# http://d-h.st/api
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Li... | -delete" command
parser_delf = subparsers.add_parser("file-delete",
parents=[parser_c, parser_u],
help="Delete file")
# Create the parser for the "file-move" command
parser_mvf = subparsers.add_parser("file-move",
... | lp=("Use if you want to change the folder."
" Specify folder_id or 0 for root directory"))
# Create the parser for the "get-folder-info" command
parser_getfo = subparsers.add_parser("folder-get-info",
parents=[parser_fo, parser_u],
... |
DVS-P2P/bubblestorm | testbed/src/testbed/models/HostInteraction.py | Python | gpl-3.0 | 2,749 | 0.04438 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import datetime
import logging
from ..base import Utils
from ..base.Constants import *
from .Base import *
log = logging.getLogger(__name__)
class CopyDataWrapper(DB_Obj):
'''
file/folder wrapper
'''
def checkLocalFileAccess(self):
for path in glob.glob(self.pa... |
for key in self.FIELDS:
self.setDB(key, valuesDict[key])
self.identName = 'ExperimentData "{0}"'.format(self.getDB('path'))
self.checkTarget()
self.checkLocalFileAccess()
class NodeData(CopyDataWrapper):
'''
a node data file/folder, i.e. protoype_config_files, keyValueTestFile, ...
'''
FIELDS = [... | valuesDict):
for key in self.FIELDS:
self.setDB(key, valuesDict[key])
self.identName = 'NodeData "{0}"'.format(self.getDB('path'))
self.checkTarget()
self.checkLocalFileAccess()
def isNodegroupData(self):
return True
def matchNodeGroup(self, nodeGroup):
return (self.getDB('node_group') == None o... |
otsaloma/nfoview | nfoview/errors.py | Python | gpl-3.0 | 1,118 | 0 | # -*- coding: utf-8 -*-
# Copyright (C) 2008 Osmo Salomaa
#
# 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 pr... | tionError` can be used to provide essential checks | of boolean
values instead of optional debug checks.
"""
pass
|
patrick-kidger/equinox | equinox/nn/composed.py | Python | apache-2.0 | 3,841 | 0.002083 | import typing
from typing import Any, Callable, List, Optional, Sequence
import jax
import jax.nn as jnn
import jax.random as jrandom
from ..custom_types import Array
from ..module import Module, static_field
from .linear import Linear
def _identity(x):
return x
if getattr(typing, "GENERATING_DOCUMENTATION", ... | isation. (Keyword only argument.)
"""
super().__init__(**kwargs)
keys = jrandom.split(key, depth + 1)
layers = []
if depth == 0:
layers.append(Linear(in_size, out_size, key=keys[0]))
else:
layers.append(Linear(in_size, width_size, key=keys[0]))
... | for i in range(depth - 1):
layers.append(Linear(width_size, width_size, key=keys[i + 1]))
layers.append(Linear(width_size, out_size, key=keys[-1]))
self.layers = layers
self.in_size = in_size
self.out_size = out_size
self.width_size = width_size
... |
Micronaet/micronaet-bom | csv_setup_inventory_delta/delta.py | Python | agpl-3.0 | 7,673 | 0.007429 | # -*- coding: utf-8 -*-
###############################################################################
#
# 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 a... | rp.tools.float_utils import float_round as round
from openerp.tools import (DEFAULT_SERVER_DATE_FORMAT,
DEFAULT_SERVER_DATETIME_FORMAT,
DATETIME_FORMATS_MAP,
float_compare)
_logger = logging.getLogger(__name__)
class ClassNameCamelCase(orm.Model):
""" Model name: C | lassNameCamelCase
"""
_inherit = 'product.product.import.inventory'
filename = '/home/administrator/photo/xls/inventory' # TODO parametrize
def action_correct_delta_from_csv(self, cr, uid, ids, context=None):
''' Generate report status for delta inventory
Read files for ge... |
anthonylife/TaobaoCompetition2014 | src/mbtalmf/train.py | Python | gpl-2.0 | 3,123 | 0.008966 | #!/usr/bin/env python
#encoding=utf8
#Copyright [2014] [Wei Zhang]
#Licensed under the Apache License, Version 2.0 (the "License");
#y | ou 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, sof | tware
#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.
###################################################################
# D... |
coati-00/nepi | nepi/activities/urls.py | Python | gpl-2.0 | 1,778 | 0 | from django.conf.urls import url, patterns
'''Want to switch to class based views but not sure how'''
from nepi.activities.views import (UpdateConversationView,
| DeleteConversationView,
ScenarioListView,
| ScenarioDetailView,
ScenarioDeleteView,
CreateConverstionView,
SaveResponse,
LastResponse,
CreateCalendar,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.