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 |
|---|---|---|---|---|---|---|---|---|
glenjarvis/Lemonade | src/lemonade/models/chart_of_accounts.py | Python | bsd-3-clause | 3,271 | 0 | #!/usr/bin/env python
# pylint: disable=W0201
"""Chart of Accounts Module for the Lemonade accounting project"""
import csv
from collections import OrderedDict
from lemonade import helpers
class ChartOfAccountsFormatException(Exception):
"""Exception when parsing Chart of Accounts"""
pass
class MissingAc... | ow([account_number,
self._accounts[account_number]])
helpers.close_file_if_necessary(handler, do_i_close)
def from_csv(self, | input_file):
"""Read Chart of Accounts from file given in Excel dialect CSV"""
handler, do_i_close = helpers.check_or_open_file(input_file, 'r')
spreadsheet = csv.reader(handler, dialect="excel")
self.populate_accounts(spreadsheet)
helpers.close_file_if_necessary(handler, do_... |
prolifik/Furrycoin | contrib/seeds/makeseeds.py | Python | mit | 709 | 0.015515 | #!/usr/bin/env python
#
# Generate pnSeed[] from Pieter's DNS seeder
#
NSEEDS=600
import re
import sys
from subprocess import check_output
def main():
lines = sys.stdin.readlines()
ips = []
pattern = re.compile(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}):11000")
for line in lines:
m | = pattern.match(line)
if m is None:
continue
ip = 0
for i in range(0,4):
ip = ip + (int(m.group(i+1)) << (8*(i)))
if ip == 0:
continue
ips.append(ip)
for row in range(0, min(NSEEDS,len(ips)), 8):
print " " + ", ".join([ "0x%08x... | n__':
main()
|
south-coast-science/scs_core | tests/sys/timeout_test.py | Python | mit | 494 | 0 | #!/usr/bin/env python3
"""
Created on 17 Sep 2019
@author: Bruno Beloff ([email protected])
"""
import time
from scs_core.sys.time | out import Timeout
# --------------------------------------------------------------------------------------------------------------------
# run...
timeout = Timeout(5)
print(timeout)
print("-")
try:
with timeout:
time.sleep(10)
print("slept")
except TimeoutError:
print("TimeoutEr | ror")
finally:
print("done")
|
Southpaw-TACTIC/TACTIC | src/install/service/win32_service.py | Python | epl-1.0 | 2,526 | 0.015439 | ###########################################################
#
# Copyright (c) 2005, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced | , transmitted,
# or disclosed in any way without written permission.
#
#
#
# Repurposed from http://docs.cherrypy.org/cherrypy22-as-windows-service
'''
The most basic (working) CherryPy 2.2 Windows service possible.
Requires Mark Hammond's pywin32 package.
'''
__all__ = ['TacticService']
import os, sys
import wi... | def __init__(self):
self.monitor = TacticMonitor()
def init(self):
self.monitor.mode = "init"
self.monitor.execute()
def run(self):
self.monitor.mode = "monitor"
self.monitor.execute()
def write_stop_monitor():
'''write a stop.monitor file to notify Tacti... |
clemkoa/scikit-learn | sklearn/ensemble/forest.py | Python | bsd-3-clause | 78,779 | 0.000114 | """Forest of trees-based ensemble methods
Those methods include random forests and extremely randomized trees.
The module structure is the following:
- The ``BaseForest`` base class implements a common ``fit`` method for all
the estimators in the module. The ``fit`` method of the base ``Forest``
class calls the ... | verb | ose=0, class_weight=None):
"""Private function used to fit a single tree in parallel."""
if verbose > 1:
print("building tree %d of %d" % (tree_idx + 1, n_trees))
if forest.bootstrap:
n_samples = X.shape[0]
if sample_weight is None:
curr_sample_weight = np.ones((n_sample... |
3DGenomes/tadbit | _pytadbit/utils/three_dim_stats.py | Python | gpl-3.0 | 28,455 | 0.00376 | """
30 Oct 2013
"""
import sys
from warnings import catch_warnings, simplefilter
from itertools import combinations
from math import pi, sqrt, cos, sin, acos
from copy import deepcopy
import numpy as np
from numpy.random import shuffle as np_shuffle
from scipy.stats import skew, kurtosis, norm as sc_no... | st = sqrt(dst)
uxvywz = - u*x - v*y - w*z
one = (-u * (uxvywz))
two = (-v * (uxvywz))
tre = (-w * (uxvywz))
onep = sqrtdst * (- w*y + v*z)
twop = sqrtdst * (+ w*x - u*z)
trep = sqrtdst * (- v*x + u*y)
for k in range(int(n)):
ang = k * offset
cosang = cos(ang)
dco... | nang) / dst,
(two * (1 - cosang) + y * dcosang + twop * sinang) / dst,
(tre * (1 - cosang) + z * dcosang + trep * sinang) / dst]
)
return points
def square_distance(part1, part2):
"""
Calculates the square distance between two particles.
... |
donkirkby/live-py-plugin | setup.py | Python | mit | 1,514 | 0 | import setuptools
with open("space_tracer.md") as f:
long_description = f.read()
about = {}
with open("plugin/PySrc/space_tracer/about.py") as f:
exec(f.read(), about)
# noinspection PyUnresolvedReferences
setuptools.setup(
name=about['__title__'],
version=about['__version__'],
author=about['__aut... | "Intended Audience :: Developers",
"Topic :: Software Development :: Debuggers",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Py... | lopment Status :: 5 - Production/Stable",
"Environment :: Console"
],
project_urls={
'Bug Reports': 'https://github.com/donkirkby/live-py-plugin/issues',
'Source': 'https://github.com/donkirkby/live-py-plugin'}
)
|
schleichdi2/OpenNfr_E2_Gui-6.0 | lib/python/Components/SearchCovers.py | Python | gpl-2.0 | 32,601 | 0.033279 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from Plugins.Plugin import PluginDescriptor
from Components.ActionMap import *
from Components.Label import Label
from Components.Sources.StaticText import StaticText
from Components.MultiContent import MultiContentEntryText, MultiContentEntryPixmap, MultiContentE... | ssageBox
from Screens.VirtualKeyBoard import VirtualKeyBoard
from twisted.web.client import getPage
from twisted.web.client import downloadPage
from twisted.web import client, error as weberror
from twisted.internet import reactor
from twisted.internet import defer
from urllib import urlencode
import sys | , os, re, shutil, time
from threading import Thread
from os import listdir as os_listdir, path as os_path
from re import compile
import re
try:
from enigma import eMediaDatabase
isDreamOS = True
except:
try:
file = open("/proc/stb/info/model", "r")
dev = file.readline().strip()
file.close()
if... |
weilneb/twitter-utils | twutils/__init__.py | Python | mit | 48 | 0.020833 | #!/usr/bin/ | env python
from TweetGrabber imp | ort * |
cloudteampro/juma-editor | JumaEditor.app/Contents/Resources/juma_bin.py | Python | mit | 1,472 | 0.036005 | #!/usr/bin/env python
import os
import os.path
import platform
import sys
##----------------------------------------------------------------##
def isPythonFrozen():
return hasattr( sys, "frozen" )
def getMainModulePath():
if isPythonFrozen():
p = os.path.dirname(unicode(sys.executable, sys.getfilesystemencoding(... | th.dirname( mainfile )
else:
import __main__
if hasattr( __main__, "__gii_path__" ):
return __main__.__gii_path__
else:
mainfile = os.path.realpath( __main__.__file__ )
return os.path.dirname( mainfile )
##----------------------------------------------------------------##
jumapath = getMainModulePath(... | = getMainModulePath() + '/editor/lib/3rdparty'
thirdPartyPathCommon = thirdPartyPathBase + '/common'
if platform.system() == u'Darwin':
thirdPartyPathNative = thirdPartyPathBase + '/osx'
else:
thirdPartyPathNative = thirdPartyPathBase + '/windows'
sys.path.insert( 0, jumapath )
sys.path.insert( 2, thirdPartyPathNat... |
matt-graham/hmc | mici/autodiff.py | Python | mit | 2,376 | 0.000842 | """Automatic differentation fallback for constructing derivative functions."""
import mici.autograd_wrapper as autograd_wrapper
"""List of names of valid differential operators.
Any automatic differentiation framework wrapper module will need to provide
all of these operators as callables (with a single function as... | n if an alternative
implementation of the derivative function has not been provided.
Args:
diff_func (None or Callable): Either a callable implementing the
required derivative function or `None` if none was provided.
func (Callable): Function to differentiate.
diff_op_name (... | required derivative function.
name (str): Name of derivative function to use in error message.
Returns:
Callable: `diff_func` value if not `None` otherwise generated
derivative of `func` by applying named differential operator.
"""
if diff_func is not None:
return dif... |
stormsson/procedural_city_generation_wrapper | vendor/josauder/procedural_city_generation/roadmap/iteration.py | Python | mpl-2.0 | 1,126 | 0.009769 | # -*- coding: utf-8 -*-
from __future__ import division
fro | m procedural_city_generation.roadmap.getSuggestion import getSuggestion
from procedural_city_generation.roadmap.check import check
from procedural_city_generation.additional_stuff.Singleton import Singleton
singleton=Singleton("roadmap")
def iteration(front):
"""
Gets Called in the mainloop.
Manages the f... | for vertex in front:
for suggested_vertex in getSuggestion(vertex):
newfront=check(suggested_vertex, vertex, newfront)
#Increments index of each element in queue
singleton.global_lists.vertex_queue=[[x[0], x[1]+1] for x in singleton.global_lists.vertex_queue]
#Finds elements in queue... |
rgayon/plaso | tests/test_lib.py | Python | apache-2.0 | 6,202 | 0.004676 | # -*- coding: utf-8 -*-
"""Shared functions and classes for testing."""
from __future__ import unicode_literals
import io
import os
import shutil
import re
import tempfile
import unittest
from dfdatetime import time_elements
from dfvfs.lib import definitions as dfvfs_definitions
from dfvfs.path import factory as pat... | urns:
str: path of the test file.
"""
# Note that we need to pass the individual path segments to os.path.join
# and not a list.
return os.path.join(TEST_DATA_PATH, *path_segments)
def CopyTimestampFromSring(time_string):
"""Copies a date and time string to a Plas | o timestamp.
Args:
time_string (str): a date and time string formatted as:
"YYYY-MM-DD hh:mm:ss.######[+-]##:##", where # are numeric digits
ranging from 0 to 9 and the seconds fraction can be either 3 or 6
digits. The time of day, seconds fraction and timezone offset are
optional... |
HiSPARC/station-software | user/python/Lib/bsddb/test/test_replication.py | Python | gpl-3.0 | 21,476 | 0.01071 | """TestCases for distributed transactions.
"""
import os
import time
import unittest
from test_all import db, test_support, have_threads, verbose, \
get_new_environment_path, get_new_database_path
#----------------------------------------------------------------------
class DBReplication(unittest.TestCase)... | is necessary in BDB 4.5, since DB_EVENT_REP_STARTUPDONE
# is not generated if the master has no new transactions.
# This is solved in BDB 4.6 (#15542).
import time
timeout = time.time()+60
while (time.time()<timeout) and not (self.confirmed_master and self.client_startupdone) :
... | ut. On windows this may be a deep issue, on other
# platforms it is likely just a timing issue, especially on slow
# virthost buildbots (see issue 3892 for more). Even though
# the timeout triggers, the rest of this test method usually passes
# (but not all of it always, see below). S... |
Purg/SMQTK | python/smqtk/algorithms/__init__.py | Python | bsd-3-clause | 1,219 | 0.005742 | from smqtk.utils import SmqtkObject
from smqtk.utils import Configurable, plugin |
__all__ = [
'SmqtkAlgorithm',
'Classifier', 'SupervisedClassifier', 'get_classifier_impls',
'DescriptorGenerator', 'get_descriptor_generator_impls',
'NearestNeighborsIndex', 'g | et_nn_index_impls',
'HashIndex', 'get_hash_index_impls',
'LshFunctor', 'get_lsh_functor_impls',
'RelevancyIndex', 'get_relevancy_index_impls',
]
class SmqtkAlgorithm (SmqtkObject, Configurable, plugin.Pluggable):
"""
Parent class for all algorithm interfaces.
"""
@property
def name(se... |
juliotrigo/django-accounts | accounts/context_processors.py | Python | bsd-3-clause | 544 | 0 | # -*- coding: utf-8 -*-
"""accounts | context processors.
A set of request processors that return dictionaries to be merg | ed into a
template context. Each function takes the request object as its only parameter
and returns a dictionary to add to the context.
These are referenced from the setting TEMPLATE_CONTEXT_PROCESSORS and used by
RequestContext.
"""
from __future__ import unicode_literals
def url(request):
"""
Adds url-r... |
cuoretech/syncform | database_config.py | Python | gpl-3.0 | 2,408 | 0.033223 | #**************************************
# Current Database Info
#**************************************
# To Access...
# from database_config import db_config
# from py2neo import neo4j
# graph_db = neo4j.GraphDatabaseService(db_config['uri'])
db_config = {}
#db_config['address'] = "http://162.212.130.189"
... | eplaced by Label Constants at a later time)
IN | D_COMP = "Company"
IND_DEP = "Departments"
IND_TITLE = "Titles"
IND_USER = "Users"
IND_UNASSIGNED = "Unassigned"
IND_UNCONFIRMED = "Unconfirmed"
IND_CAL = "Calendars"
IND_EVENT = "Events"
IND_TASK = "Tasks"
IND_SUBTASK = "Subtasks"
IND_WORKSPACE = "Workspaces"
IN... |
alinko32a/pimouse_ros | scripts/buzzer3.py | Python | gpl-3.0 | 445 | 0.006742 | #!/usr/bin/env python
import rospy
from std_msgs.msg import UInt16
def write_freq(hz=0):
bfile = "/dev/rtbuzzer0"
try:
with open(bfile, "w") as f:
f.write | (str(hz) + "\n")
| except IOError:
rospy.logerr("can't write to " + bfile)
def recv_buzzer(data):
write_freq(data.data)
if __name__ == '__main__':
rospy.init_node('buzzer')
rospy.Subscriber("buzzer", UInt16, recv_buzzer)
rospy.spin()
|
rainest/dance-partner-matching | networkx/readwrite/tests/test_yaml.py | Python | bsd-2-clause | 1,300 | 0.024615 | """
Unit tests for yaml.
"""
import os,tempfile
from nose import SkipTest
from nose.tools import assert_true,assert_equal
import networkx as nx
class TestYaml(object):
@classmethod
def setupClass(cls):
global yaml
try:
import yaml
except I | mportError:
raise SkipTest('y | aml not available.')
def setUp(self):
self.build_graphs()
def build_graphs(self):
self.G = nx.Graph(name="test")
e = [('a','b'),('b','c'),('c','d'),('d','e'),('e','f'),('a','f')]
self.G.add_edges_from(e)
self.G.add_node('g')
self.DG = nx.DiGraph(self.G)
... |
mediatum/mediatum | core/test/test_legacy_update_create.py | Python | gpl-3.0 | 1,051 | 0.002854 | # -*- coding: utf-8 -*-
"""
:copyright: (c) 2016 by the mediaTUM authors
:license: GPL3, see COPYING for details
"""
from __future__ import absolute_import
from utils.date import parse_date
from core.test.factories import DocumentFactory
# adding more test functions may fail, see the comments for the following... | node = DocumentFactory()
session.add(node)
node["testattr"] = "new"
session.commit()
req.app_cache = {}
# well, guest users shouldn't update nodes, but it's ok for a test ;)
req.session["user_id"] = guest_user.id
node["test | attr"] = "changed"
session.commit()
assert node.creator == some_user.getName()
assert node.updateuser == guest_user.getName()
assert node.creationtime <= node.updatetime
assert parse_date(node.updatetime)
|
bgrig/Rice-Bioe-421-521-Final-Project | master.py | Python | gpl-2.0 | 7,297 | 0.009456 | #! /usr/bin/python
import serial
import os
import sys
import time
import re
import glob
#Output stdout to log file
#sys.stdout = open("log.txt", "a")
#Port Definitions
port = "/dev/ttyACM0"
baud = 115200
#counts
zCount = 0
#Regular Expression Compilation
xRE = re.compile(" X(-?[0-9]+[.]?[0-9]*)")
yRE = re.compile(... | r=rambo):
global zCount
print("waitOnMove Line: " + line.strip())
MoveCheck = isMove(lin | e)
if not MoveCheck:
print("Not a move")
return
print("Is a move")
if re.search("G28", line):
homeWait(ZHOME)
return
else:
#x_destination = xRE.search(line)
#y_destination = yRE.search(line)
z_search = zRE.search(line)
z_destination =... |
PabloCastellano/libreborme | borme/management/commands/importborme.py | Python | agpl-3.0 | 2,559 | 0 | from django.core.management.base import BaseCommand
from django.utils import timezone
import logging
import time
from borme.models import Config
from borme.parser.importer import import_borme_download
# from borme.parser.postgres import psql_update_documents
import borme.parser.importer
from libreborme.utils import ... | action='store_true',
default=False,
help='Do not download any file')
parser.add_argument(
'--no-missing',
action='store_true',
default=False,
help='Abort if local file is not found')
# json only,... | tions):
self.set_verbosity(int(options['verbosity']))
start_time = time.time()
import_borme_download(options['from'][0],
options['to'][0],
local_only=options['local_only'],
no_missing=options['no_missing']... |
STIXProject/python-stix | stix/version.py | Python | bsd-3-clause | 130 | 0 | # Copyright (c) 2017, The | MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
__version__ = "1.2. | 0.11"
|
pythonpopayan/bermoto | backend/simulation/app_clients.py | Python | mit | 394 | 0 | """
"""
import websocket
import json
from time import sleep
cla | ss app_client(object):
def __init__(self, url):
self.ws = websocket.create_connection(url)
def send(self, message):
self.ws.send(json.dumps(message))
sleep(0.5)
result = self.ws.recv()
print(result)
return json.loads(result)
def close(self):
self.ws. | close()
|
Trigition/MTG-DataScraper | mtg_dataminer/paths.py | Python | mit | 1,594 | 0.005646 | #!/usr/bin/env python
CARD_IMAGE_TOKEN_CLASS = 'card-small-icon'
CARD_TEXT_BOX_CLASS = 'card-text'
### PATHS
### If Gatherer changes how it stores card details, the paths
### can be edited here
# Path for card links on a search result page
CARD_LINKS = '//tr/td/div/span[@class="cardTitle"]/a'
# Path to the table wh... | ble[@clas | s="cardDetails"]'
# Describe where the card image and card details are located
CARD_IMAGE_CONTAINER = './/td[contains(@class,"leftCol")]'
CARD_DETAILS_CONTAINER = './/td[contains(@class,"rightCol")]'
### ---END PATHS--- ###
### CARD DETAIL PATHS
# Card details are in rows
ROW_PATH = './/div[contains(@class, "row")]... |
samuraisam/lexical_uuid | lexical_uuid/alchemy.py | Python | mit | 999 | 0.012012 | import lexical_uuid
from sqlalchemy.dialects.postgresql import BYTEA
from sqlalchemy.typ | es import TypeDecorator
class LexicalUUID(TypeDecorator):
impl = BYTEA
def __init__(self):
self.impl.length = 16
super(LexicalUUID, self).__init__(length=self.impl.length)
def process_bind_param(self, value, dialect=None):
if value and isinstance(value, lexical_uuid.LexicalUUID):
return valu... | f lexical_uuid.LexicalUUID).".format(value))
else:
return None
def process_result_value(self, value, dialect=None):
if value:
return lexical_uuid.LexicalUUID(value=value)
else:
return None
def is_mutable(self):
return False
__doc__ = """
Usage::
class Entity(db.Model):
id ... |
delvelabs/htcap | core/crawl/lib/shared.py | Python | gpl-2.0 | 778 | 0.005141 | # -*- coding: utf-8 -*-
"""
HTCAP - beta 1
Author: [email protected]
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any lat... | kies = []
allowed_domains = set()
excluded_urls = set()
probe_cm | d = []
options = {}
|
WaveBlocks/WaveBlocksND | WaveBlocksND/Interface/NormWavepacket.py | Python | bsd-3-clause | 4,912 | 0.001425 | """The WaveBlocks Project
Compute the norms of the homogeneous wavepackets as well as the sum of all norms.
@author: R. Bourquin
@copyright: Copyright (C) 2010, 2011, 2012, 2013, 2016 R. Bourquin
@license: Modified BSD License
"""
from WaveBlocksND import BlockFactory
from WaveBlocksND import BasisTransformationHAWP... | eate_basis_shape(descr)
KEY = ("q", "p", "Q", "P", "S", "adQ")
# Iterate over all timesteps
for i, step in enumerate(timesteps):
print(" Computing norms of timestep %d" % step)
# Retrieve simulation data
params = iom.load_inhomogwavepacket_parameters(timestep=step, blockid=blockid... | fs = iom.load_inhomogwavepacket_coefficients(timestep=step, get_hashes=True, blockid=blockid)
# Configure the wavepacket
HAWP.set_parameters(params, key=KEY)
HAWP.set_basis_shapes([BS[int(ha)] for ha in hashes])
HAWP.set_coefficients(coeffs)
# Transform to the eigenbasis.
... |
deepmind/deepmind-research | density_functional_approximation_dm21/density_functional_approximation_dm21/export_saved_model.py | Python | apache-2.0 | 2,047 | 0.002931 | #!/usr/bin/env python3
# Copyright 2021 DeepMind Technologies Limited.
#
# 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 b... | IONAL = flags.DEFINE_enum_class('functional',
neural_numint.Functional.DM21,
neural_numint.Functional,
'Functional to export.')
def export(
functional: neural_numint.Functional,
export_path: str,
... | to a single saved_model.
Args:
functional: functional to export.
export_path: path to saved the model to.
batch_dim: number of grid points to process in a single call.
"""
ni = neural_numint.NeuralNumInt(functional)
ni.export_functional_and_derivatives(
export_path=export_path, batch_dim=bat... |
jwodder/javaproperties | test/test_loads_xml.py | Python | mit | 4,001 | 0.0005 | from collections import OrderedDict
import pytest
from javaproperties import loads_xml
@pytest.mark.parametrize(
"s,d",
[
("<properties></properties>", {}),
(
'<properties><entry key="key">value</entry></properties>',
{"key": "value"},
),
(
'... |
' <entry key="key">value</entry>\n'
"</properties>\n",
{"key": "value"},
),
(
"<properties>\n"
' <entry key="key">value</entry>\n'
' <something | -else key="foo">bar</something-else>\n'
"</properties>\n",
{"key": "value"},
),
(
'<properties><entry key="goat">🐐</entry></properties>',
{"goat": "\U0001F410"},
),
],
)
def test_loads_xml(s, d):
assert loads_xml(s) == d
def test_... |
saelo/sekretaer | sekretaer/core.py | Python | mit | 5,590 | 0.003221 | #!/usr/bin/env python
#coding: UTF-8
#
# (c) 2014 Samuel Groß <[email protected]>
#
import os
import sys
import importlib
from time import sleep
try:
import concurrent.futures
except ImportError:
pass
#
# Functions
#
def warn(msg):
sys.stderr.write('WARNING: ' + msg + '\n')
def err(msg):
sys.stderr.... | me.startswith('_'):
modules.append(filename[:-3])
for module_name in modules:
try:
module = importlib.import_module('sekretaer.modules.' + module_name)
except Exception as e:
warn("[sekretaer] Failed to load module '{}': {}".format(module_... | artswith('_') and callable(getattr(module, a))]
for f in functions:
if hasattr(f, 'mod_type'):
if f.mod_type == 'source' and f.name in self.config['sources_enabled']:
self.sources.append(f)
elif f.mod_type == 'sink' and f.name i... |
m-kal/DirtyBoots | src/datamgr.py | Python | gpl-3.0 | 10,361 | 0.024901 | import uuid
import sqlite3
from datetime import date, timedelta
import logging
import dblog
class datamgr( object ):
"""
Handles database creation/setup, queries, and importation
"""
_dbConn = { }
_dbCurs = { }
_db = None
# default name/location of the merged history database
DEF_DB_L... | = db
def db(self):
return self._db
def closeConn( self ):
"""
Close the database connection
| """
self.curs( ).close( )
self.conn( ).close( )
def conn( self ):
return self._dbConn
def curs( self ):
return self._dbCurs
def log( self, msg, level = logging.INFO ):
"""
For consistent logging format within all handler functions
"""
dblog.... |
auag92/n2dm | Asap-3.8.4/OpenKIMexport/subprocess_py27.py | Python | mit | 1,883 | 0.001593 | # This file is part of the Python 2.7 module subprocess.py, included here
# for compatibility with Python 2.6.
#
# It is still under the original, very open PSF license, see the original
# copyright message included below.
#
# subprocess - Subprocesses with accessible I/O streams
#
# For more information about this mod... | import Popen, CalledProcessError, PIPE
def check_output(*popenargs, | **kwargs):
r"""Run command with arguments and return its output as a byte string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the returncode
attribute and output in the output attribute.
The arguments are the same as fo... |
Actifio/actifio-python-package | samples/mdl_analyser/app.py | Python | mit | 2,375 | 0.028211 | #!/usr/bin/env python3
from flask import Flask
from Actifio import Actifio
from chartjs import ChartJS, ChartDatalet, ChartDataset
#from mdl_analyser import MDL
import getpass
import base64
import os
import json
import argparse
from datetime import datetime
cli_args = argparse.ArgumentParser(description="CLI Argume... | lications ():
appnamelist = {}
for m in mdldata['result']:
if not m['appname'] in | appnamelist.keys():
appnamelist[m['appname']] = m['appid']
return json.dumps(appnamelist)
@mdl_analyser.route("/chartdata")
def gen_chart_for_all ():
chart = ChartJS("MDL Analyser", stacked=True)
chart.set_legend()
for m in mdldata['result']:
if not m['appid'] == '0':
stat_day = datetime... |
stackforge/monasca-notification | monasca_notification/retry_engine.py | Python | apache-2.0 | 3,769 | 0.001061 | # (C) Copyright 2015-2016 Hewlett Packard Enterprise Development LP
# Copyright 2017 Fujitsu LIMITED
#
# 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/LICE... | on_data['notification_timestamp'])
if wait_duration > 0:
time.sleep(wait_duration)
sent, failed = self._notifier.send([notificat | ion])
if sent:
self._producer.publish(CONF.kafka.notification_topic,
[notification.to_json()])
if failed:
notification.retry_count += 1
notification.notification_timestamp = time.time()
if no... |
kperun/nestml | PyNestML.py | Python | gpl-2.0 | 881 | 0 | #
# PyNestML.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST 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 lat... | # NEST is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with NES... | PyNestML.
"""
if __name__ == '__main__':
main(sys.argv[1:])
|
MrWhoami/WhoamiBangumi | Iqiyi.py | Python | mit | 1,032 | 0.001953 | # -*- coding:utf_8 -*-
import urllib2
from bs4 import BeautifulSoup
from Bangumi import Bangumi
class Iqiyi(Bangumi):
link = "http://www.iqiyi.com/dongman/bangum | i.html"
name = u"爱奇艺"
def getBangumi(self):
"""Youku processing function"""
# Get Iqiyi bangumi HTML
req = urllib2.Request(self.link)
res = urllib2.urlopen(req)
html = res.read()
# Give the HTML to BeautifulSoup
# TODO: Change the parser to lxml for bette... | ce
soup = BeautifulSoup(html, "html.parser")
bweek = soup.find(id='widget-qycpweekly')
# Get the list of the week
for child in bweek.children:
if child.name == None:
continue
wd = int(child['data-day']) + 1
binfos = child.find_all('h4')... |
plotly/plotly.py | packages/python/plotly/plotly/validators/histogram2d/_uid.py | Python | mit | 388 | 0 | import _plotly_utils.basevalidators
class UidValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(self, plotly_name="uid", parent_name="histogram2d", **kw | args):
super(UidValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
| edit_type=kwargs.pop("edit_type", "plot"),
**kwargs
)
|
Branlala/docker-sickbeardfr | sickbeard/lib/hachoir_parser/game/laf.py | Python | mit | 2,900 | 0.008966 | # -*- coding: utf-8 -*-
"""
LucasArts Font parser.
Author: Cyril Zorin
Creation date: 1 January 2007
"""
from lib.hachoir_parser import Parser
from | lib.hachoir_core.field import (FieldSet,
UInt8, UInt16, UInt32, Gen | ericVector)
from lib.hachoir_core.endian import LITTLE_ENDIAN
class CharData(FieldSet):
def __init__(self, chars, *args):
FieldSet.__init__(self, *args)
self.chars = chars
def createFields(self):
for char in self.chars:
yield CharBitmap(char, self, "char_bitmap[]")
class CharBitmap(FieldSet):
... |
chadmv/cmt | scripts/cmt/rig/spaceswitch.py | Python | mit | 4,654 | 0.003223 | """Space switching without constraints or extra DAG nodes.
Contains functions to create a space switching network as well as seamlessly switching
between spaces.
Example Usage
=============
::
import cmt.rig.spaceswitch as spaceswitch
# Create the space switch
spaceswitch.create_space_switch(
p... |
node, drivers, switch_attribute=None, use_translate=True, use_rotate=True
):
"""Creates a space switch network.
The network uses the offsetParentMatrix attribute and does not create any
constraints or new | dag nodes.
:param node: Transform to drive
:param drivers: List of tuples: [(driver1, "spaceName1"), (driver2, "spaceName2")]
:param switch_attribute: Name of the switch attribute to create on the target node.
"""
if switch_attribute is None:
switch_attribute = "space"
if cmds.objExis... |
marcusmoller/pyorpg-server | src/datahandler.py | Python | mit | 40,001 | 0.00335 | import random
from database import *
from packettypes import *
from gamelogic import *
from objects import *
from constants import *
from utils import *
import globalvars as g
#debug
import time
class DataHandler():
def handleData(self, index, data):
jsonData = decodeJSON(data)
packetType = jsonD... | has been created')
alertMsg(index, "Your account has been created!")
else:
g.serverLogger.info('Account name has already been taken!')
| alertMsg(index, "Sorry, that account name is already taken!")
''' Player login '''
def handleLogin(self, index, jsonData):
if not isPlaying(index):
if not isLoggedIn(index):
plrName = jsonData[0]["name"]
plrPassword = jsonData[0]["password"]
... |
WikipediaLibrary/TWLight | TWLight/users/oauth.py | Python | mit | 22,204 | 0.001711 | import logging
from mwoauth import ConsumerToken, Handshaker, AccessToken
from mwoauth.errors import OAuthException
import urllib.parse
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import login, authenticate
from django.contrib.auth.models import User
from django.core.e... | :
email = identity["email"]
except KeyError:
email = None
username = self._get_username(identity)
# Since we are not providing a password argument, this will call
# set_unusable_password, which is exactly what we want; users created
# via OAuth should on... | user = User.objects.create_user(username=username, email=email)
logger.info("User user successfully created.")
return user
def _create_editor(self, user, identity):
# ------------------------- Create the editor --------------------------
logger.info("Creating editor.")
... |
pythonprobr/notmagic | pt-br/baralho.py | Python | mit | 4,006 | 0.003744 | #!/usr/bin/env python3
"""
>>> baralho = Baralho()
>>> len(baralho)
52
>>> baralho[0]
Carta(valor='2', naipe='paus')
>>> baralho[-1]
Carta(valor='A', naipe='espadas')
>>> from random import choice
>>> choice(baralho) #doctest:+SKIP
Carta(valor='4', naipe='paus')
... | e Jacks in a baralho.
::
>>> [carta for carta in baralho i | f carta.valor=='J']
[Carta(valor='J', naipe='paus'), Carta(valor='J', naipe='ouros'), Carta(valor='J', naipe='copas'), Carta(valor='J', naipe='espadas')]
Ranking by alternate color naipes: ouros (lowest), followed by paus, copas, and espadas (highest).
>>> hand = [Carta(valor='2', naipe='ouros'), Carta(valor=... |
openprocurement/openprocurement.tender.belowthreshold | openprocurement/tender/belowthreshold/tests/chronograph.py | Python | apache-2.0 | 5,547 | 0.001803 | # -*- coding: utf-8 -*-
import unittest
from openprocurement.api.tests.base import snitch
from openprocurement.tender.belowthreshold.tests.base import (
TenderContentWebTest,
test_lots,
test_bids,
test_organization
)
from openprocurement.tender.belowthreshold.tests.chronograph_blanks import (
# Te... | switch_to_unsuccessful,
# TenderAucti | onPeriodResourceTest
set_auction_period,
reset_auction_period,
# TenderComplaintSwitchResourceTest
switch_to_ignored_on_complete,
switch_from_pending_to_ignored,
switch_from_pending,
switch_to_complaint,
# TenderAwardComplaintSwitchResourceTest
award_switch_to_ignored_on_complete,
... |
romejoe/ExampleCluster | Cluster.py | Python | gpl-2.0 | 1,560 | 0.042949 | from abc import ABCMeta, abstractmethod
class Cluster:
__metaclass__ = ABCMeta
@abstractmethod
def _getClusterInfo(cluster):
pass
def _getClusterDistance(clusterA, clusterAInfo, clusterB, clusterBInfo):
pass
def Cluster(clusters, verbose=False):
iterCount = 0
while( len(clusters) > 1):
if verbose... | tmp = (self._getClusterDistance(clusters[a], clusterInfo[a], clusters[b], clusterInfo[b]), a, b)
if MergeCandidate == None or MergeCandidate[0] > tmp[0]:
MergeCandidate = tmp
if verbose:
print MergeCandidate
a = MergeCandidate[1]
b = MergeCandidate[2]
if a > b:
tmp = a
a = b
... | mp
clusters[a] = clusters[a] + clusters[b]
del clusters[b]
if verbose:
print "clusters:"
for x in clusters:
print x
iterCount = iterCount + 1
if verbose:
print "===Iter Done==="
return clusters
def ClusterCSVFile(filepath, verbose=False):
points = []
with open(filepath, 'r') ... |
superdesk/superdesk-core | apps/common/components/base_component.py | Python | agpl-3.0 | 653 | 0 | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Cop | yright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefab | ric.org/superdesk/license
class BaseComponent:
"""This is a basic interface for defining components.
The only requirement is to implement the name method that
uniquely identifies a component. It should also define other
methods that implement the component functionality.
"""
@classmethod
... |
jackzhao-mj/ok-client | demo/sqlite/tests/q2.py | Python | apache-2.0 | 548 | 0 | test = {
'name': 'Question 2',
'points': 2,
'suites': [
{
'type': 'sqlite',
'setup': r"""
sqlite> .open hw1.db
""",
'cases': [
{
'code': r"""
sqlite> select * from colors;
red|primary
blue|pri | mary
green|secondary
yellow|primary
""",
},
{
'code': r"""
sqlite> select color from colors;
red
| blue
green
yellow
""",
},
],
}
]
}
|
VitalPet/addons-onestein | auth_oauth_disable_login_with_odoo/__manifest__.py | Python | agpl-3.0 | 394 | 0 | # -*- coding: utf-8 -*-
# Copyright 2016 Onestein (<http://www | .onestein.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': 'OAuth2 Disable Login with Odoo.com',
'version': '10.0.1.0.0',
'category': 'Tools',
'author': 'Onestein',
| 'license': 'AGPL-3',
'depends': ['auth_oauth'],
'data': [
'data/auth_oauth_data.xml',
],
}
|
scylladb/scylla-cluster-tests | sdcm/sct_events/prometheus.py | Python | agpl-3.0 | 1,895 | 0.003694 | # This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later v | ersion.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See LICENSE for more details.
#
# Copyright (c) 2020 | ScyllaDB
"""
This is an example of how we'll send info into Prometheus.
Currently it's not in use, since the data we want to show, doesn't fit Prometheus model,
we are using the GrafanaAnnotator
"""
import logging
import threading
from typing import Tuple, Any
from sdcm.prometheus import nemesis_metrics_obj
from s... |
uclouvain/osis_louvain | assessments/business/score_encoding_export.py | Python | agpl-3.0 | 7,914 | 0.00278 | ##############################################################################
#
# 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 ... | person.first_name,
person.email,
score,
str(justification),
end_date])
row_number += 1
__coloring_non_edita | ble(worksheet, row_number, score, exam_enroll.justification_final)
lst_exam_enrollments = list(exam_enrollments)
number_session = lst_exam_enrollments[0].session_exam.number_session
learn_unit_acronym = lst_exam_enrollments[0].session_exam.learning_unit_year.acronym
academic_year = lst_exam_enrollments... |
Sciprios/SatisfiabilitySimulator | PartyProblemSimulator/BooleanEquation/unit_tests/test_nde_And.py | Python | mit | 1,504 | 0.003324 | from unittest.mock import MagicMock, Mock
from unittest import TestCase
from PartyProblemSimulator.BooleanEquation.BooleanNode import BooleanNode
from PartyProblemSimulator.BooleanEquation.AndNode import AndNode
class aBooleanNode(BooleanNode): # pragma: no cover
""" This class is a boolean node. """
def say(... | fake_false_child = Mock() # A child to return false.
nde = AndNode(aBooleanNode(), aBooleanNode()) # Instantiate a node with replaceable children.
fake_true_child.evaluate = MagicMock(return_value=True)
fake_false_child.evaluate = MagicMock(return_value=False)
# 1 AND 1
... | d
nde._rhs_child = fake_false_child
self.assertFalse(nde.evaluate({}))
# 1 AND 0
nde._lhs_child = fake_true_child
nde._rhs_child = fake_false_child
self.assertFalse(nde.evaluate({}))
# 0 AND 1
nde._lhs_child = fake_false_child
nde._rhs_child = fa... |
maysara/pandora_image | pandora/document/managers.py | Python | gpl-3.0 | 3,174 | 0.002205 | # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
from django.db.models import Q, Manager
def parseCondition(condition, user):
'''
'''
k = condition.get('key', 'name')
k = {
'user': 'user__username',
}.get(k, k)
if not k:
k = 'name'
v = condition['value']
op = conditio... | ith',
'$': '__iendswith',
}.get(op, '__icontains'))
key = str(key)
if exclude:
q = ~Q(**{key: v})
else:
q = Q(**{key: v})
retu | rn q
def parseConditions(conditions, operator, user):
'''
conditions: [
{
value: "war"
}
{
key: "year",
value: "1970-1980,
operator: "!="
},
{
key: "country",
value: "f",
operator: "^"
... |
kklmn/xrt | examples/withShadow/04_06/04_dE_VCM_bending.py | Python | mit | 4,894 | 0.002452 | # -*- coding: utf-8 -*-
r"""
Bending of collimating mirror
-----------------------------
Uses :mod:`shadow` backend.
File: `\\examples\\withShadow\\03\\03_DCM_energy.py`
Influence onto energy resolution
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Pictures after monochromator,
:ref:`type 2 of global normalization<globalNorm>`. ... | ization<globalNorm>`
+----------+----------+----------+----------+
| |VCMRF1| | |VCMRF2| | |VCMRF3| | |
+----------+---------- | +----------+ |VCMRF4| |
| |VCMRF7| | |VCMRF6| | |VCMRF5| | |
+----------+----------+----------+----------+
.. |VCMRF1| image:: _images/04VCM_R0496453_norm1.*
:scale: 35 %
.. |VCMRF2| image:: _images/04VCM_R0568297_norm1.*
:scale: 35 %
.. |VCMRF3| image:: _images/04VCM_R0650537_norm1.*
:scale: 35 %
..... |
SuperTux/flexlay | flexlay/wip/sprite_stroke_drawer.py | Python | gpl-3.0 | 5,541 | 0.00397 | # Flexlay - A Generic 2D Game Editor
# Copyright (C) 2014 Ingo Ruhnke <[email protected]>
#
# 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)... | return
dabs = stroke.get_interpolated_dabs(DrawerProperties.current.get_spacing() *
DrawerProperties.current.get_size(),
DrawerProperties.current.get_spacing() *
Dr | awerProperties.current.get_size())
for i, dab in enumerate(self.dabs):
sprite = DrawerProperties.current.get_brush().get_sprite()
color = DrawerProperties.current.get_color()
sprite.set_color(color)
sprite.set_alpha((color.get_alpha() / 255.0) * dab.pressure)
... |
flavono123/LKFES | feature-evals/dio_aio/test.py | Python | gpl-3.0 | 3,826 | 0.006012 | #!/usr/bin/env python2
#-*-coding:utf-8-*-
import sys
import os
import subprocess
import numpy
import json
def exec_cmd(cmd):
return subprocess.Popen(cmd,
shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
... | t_iops(proc.stdout.read(), "randwrite")
tmp_buffer, tmp_cache = buf | fercache()
rand_write_buffer += tmp_buffer
rand_write_cache += tmp_cache
proc = fio("write")
write_iops += get_iops(proc.stdout.read(), "write")
tmp_buffer, tmp_cache = buffercache()
write_buffer += tmp_buffer
write_cache += tmp_cache
col_list = ["rand_read", "read", "rand_write", "write"]... |
espressif/esp-idf | tools/find_build_apps/__init__.py | Python | apache-2.0 | 493 | 0.002028 | from .cmake import BUILD_SYSTEM_CMAKE, CMakeB | uildSystem
from .common import (DEFAULT_TARGET, BuildError, BuildItem, BuildSystem, ConfigRule, config_rules_from_str,
setup_logging)
BUILD_SYSTEMS = {
BUILD_SYSTEM_CMAKE: CMakeBuildSystem,
}
__all__ = [
'BuildItem',
'BuildSystem',
'BuildError',
'ConfigRule',
'config_rules... | ,
]
|
skuda/client-python | kubernetes/client/models/v1_namespace_spec.py | Python | apache-2.0 | 3,316 | 0.001206 | # coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.6.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
... | elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.... | ))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
... |
Azure/azure-sdk-for-python | sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/operations/__init__.py | Python | mit | 640 | 0.004688 | # coding=utf-8
# ---------------------------- | ----------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for l | icense information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from ._management_group_diagnostic_settings_operations import ManagementGroupDi... |
tmgstevens/flume | flume-ng-doc/sphinx/conf.py | Python | apache-2.0 | 3,274 | 0.002749 | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | -%s The Apache Software Foundation' % date.today().year
keep_warnings = True
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
#version = ".".join(map(str, celery.VERS... | eference text.
add_function_parentheses = True
#intersphinx_mapping = {
# "http://docs.python.org/dev": None,
# "http://kombu.readthedocs.org/en/latest/": None,
# "http://django-celery.readthedocs.org/en/latest": None,
#}
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'trac'
highli... |
Sythelux/Picarto.bundle | Contents/Libraries/Shared/PicartoClientAPI/models/video_search_result.py | Python | bsd-3-clause | 3,920 | 0.001276 | # coding: utf-8
"""
Picarto.TV API Documentation
The Picarto.TV API documentation Note, for fixed access tokens, the header that needs to be sent is of the format: `Authorization: Bearer yourTokenHere` This can be generated at https://oauth.picarto.tv/ For chat API, see https://docs.picarto.tv/chat/chat.pr... | ))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
... | eq__(self, other):
"""
Returns true if both objects are equal
"""
if not isinstance(other, VideoSearchResult):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""... |
Compjeff/PokemonGo-Bot | pokemongo_bot/cell_workers/incubate_eggs.py | Python | mit | 8,649 | 0.002428 | from pokemongo_bot.human_behaviour import | sleep
from pokemongo_bot.base_task import BaseTask
class IncubateEggs(BaseTask):
SUPPORTED_TASK_API_VERSION = 1
last_km_walked = 0
def initialize(self):
self.ready_incubators = []
self.used_incubators = []
self.eggs = []
self.km_walked = 0
self.hatching_animation... | f.config.get("longer_eggs_first", True)
def work(self):
try:
self._check_inventory()
except:
return
if self.used_incubators and IncubateEggs.last_km_walked != self.km_walked:
self.used_incubators.sort(key=lambda x: x.get("km"))
km_left = self... |
jmontgom10/Mimir_pyPol | hackScript_setBadPixForPPOL.py | Python | mit | 905 | 0.001105 | # hack script to set the bad pixels to the | right value for PPOL
import os
import glob
import numpy as np
import astroimage as ai
ai.set_instrument('Mimir')
bkgFreeDir = 'C:\\Users\\Jordan\\FITS_data\\Mimir_data\\pyPol_Reduced\\201611\\bkgFreeHWPimages'
fileList = glob.glob(
os.path.join(bkgFreeDir, '*.fits')
)
for file1 in fileList:
print('processing... | Ns and bad values and set them to -1e6 so that PPOL will
# know what to do with those values.
tmpData = img.data
badPix = np.logical_not(np.isfinite(tmpData))
tmpData[np.where(badPix)] = -1e6
badPix = np.abs(tmpData) > 1e5
tmpData[np.where(badPix)] = -1e6
# Store the data in the image objec... |
lfrdm/medpy | bin/medpy_anisotropic_diffusion.py | Python | gpl-3.0 | 4,093 | 0.00733 | #!/usr/bin/python
"""
Executes gradient anisotropic diffusion filter over an image.
Copyright (C) 2013 Oskar Maier
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, o... | scription=__description__)
| parser.add_argument('input', help='Source volume.')
parser.add_argument('output', help='Target volume.')
parser.add_argument('-i', '--iterations', type=int, default=1, help='The number of smoothing iterations. Strong parameter.')
parser.add_argument('-k', '--kappa', type=int, default=50, help='The algorithm... |
linkedin/indextank-service | storefront/manage.py | Python | apache-2.0 | 776 | 0.002577 | #!/usr/bin/env python
from django.core.management import execute_manager
from os import environ
from sys import argv
environ['DJANGO_LOCAL'] = ''
if argv[1] == 'runserver':
environ['DJANGO_LOCAL'] = '1'
if argv[1].startswith('local'):
environ['DJANGO_LOCAL'] = '1'
argv[1] = argv[1][5:]
try:
import s... | 's causing an ImportError somehow.)\n" % __file__)
sys.ex | it(1)
if __name__ == "__main__":
execute_manager(settings)
|
EricMuller/mywebmarks-backend | requirements/twisted/Twisted-17.1.0/docs/core/benchmarks/linereceiver.py | Python | mit | 1,374 | 0.004367 | from __future__ import print_function
import math, time
from twisted.protocols import basic
| class CollectingLineReceiver(basic.LineReceiver):
def __init__(self):
self.lines = []
self.lineReceived = self.lines.append
def deliver(proto, chunks):
map(proto.dataReceived, chunks)
def benchmark(chunkSize, lineLength, numLines):
bytes = ('x' * lineLength + '\r\n') * numLines
chunkCo... | 1)*chunkSize])
assert ''.join(chunks) == bytes, (chunks, bytes)
p = CollectingLineReceiver()
before = time.clock()
deliver(p, chunks)
after = time.clock()
assert bytes.splitlines() == p.lines, (bytes.splitlines(), p.lines)
print('chunkSize:', chunkSize, end=' ')
print('lineLength:', l... |
gorpon/misc | python/euclid.py | Python | gpl-3.0 | 1,512 | 0.003307 | #!/usr/bin/env python3
def is_prime(a):
"""
stolen from stackoverflow
"""
return all(a % i for i in range(2, a))
def number_check(num):
"""
validate a number is whole and greater than zero
"""
if not isinstance(num, int):
print("num %s is not an integer" % str(num))
re... | mbers()
if num1 > num2:
return num1, num2
elif num2 > num1:
return num2, num1
else:
print("I didn't like your answers. try again.")
get_numbers()
def get_gcd(x, y):
"""
given larger and smaller number
:param x: the bi | gger of the two numbers
:param y: the lesser of the two numbers
:return gcd: the greated common denominator of the two numbers
"""
if x % y == 0:
return y
temp_x = x
while (temp_x - y) > 0:
temp_x -= y
return get_gcd(y, temp_x)
x, y = get_numbers()
print("the gcd... |
eunchong/build | third_party/twisted_10_2/twisted/names/common.py | Python | bsd-3-clause | 9,108 | 0.006478 | # -*- test-case-name: twisted.names.test -*-
# Copyright (c) 2001-2010 Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Base functionality useful to various parts of Twisted Names.
"""
import socket
from twisted.names import dns
from twisted.names.error import DNSFormatError, DNSServerError, DNSNameError
... | @see: twisted.names.cli | ent.lookupNameservers
"""
return self._lookup(name, dns.IN, dns.NS, timeout)
def lookupCanonicalName(self, name, timeout = None):
"""
@see: twisted.names.client.lookupCanonicalName
"""
return self._lookup(name, dns.IN, dns.CNAME, timeout)
def lookupMailBox(self,... |
rajalokan/keystone | keystone/conf/__init__.py | Python | apache-2.0 | 5,308 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | , 'keystone')
logging.captureWarnings(True)
def configure(conf=None):
if conf is None:
conf = CONF
conf.regist | er_cli_opt(
cfg.BoolOpt('standard-threads', default=False,
help='Do not monkey-patch threading system modules.'))
conf.register_cli_opt(
cfg.StrOpt('pydev-debug-host',
help='Host to connect to for remote debugger.'))
conf.register_cli_opt(
cfg.PortO... |
GALabs/StaticAid | static_aid/config.py | Python | mit | 3,707 | 0.004856 | from ConfigParser import ConfigParser, NoSectionError
from os.path import join, exists, realpath, curdir, dirname
from shutil import copyfile
### Application constants - these are not exposed to users via config files ###
# NOTE: Directories must match Gruntfile.js: jekyll > (serve|build) > options > (src|dest)
ROOT ... | d not exists(CONFIG_DEFAULTS_FILE_PATH):
print "Unable to find any config settings! Please create one of these two files:"
print "", CONFIG_FILE_PATH
print "", CONFIG_DEFAULTS_FILE_PATH
exit(1)
if not exists(CONFIG_FILE_PATH):
copyfile(CONFIG_DEFAULTS_FILE_PATH, CONFIG_FILE_PATH)
_config = ConfigPa... | er()
_config.read(CONFIG_FILE_PATH)
# Extract the config values - reference these in calling code
# NOTE: keys from config files are forced to lower-case when they are read by ConfigParser
# which extractor backend to use for loading data
dataExtractor = _configSection('DataExtractor')
# set DEFAULT value if necessa... |
tigerking/pyvision | src/pyvision/data/ml/mulSVM.py | Python | bsd-3-clause | 5,495 | 0.014741 | '''
Created on Jan 21, 2010
@author: nayeem
'''
import pyvision as pv
import numpy as np
import scipy as sp
from pyvision.vector.SVM import SVM
import csv
import os.path
import sys
sys.setrecursionlimit(1500)
class multiSVM:
'''
classdocs
'''
def __init__(self):
'''
Constructor
... | sum(mask)
print numThisClass
trThisClass = trainingdata[mask,:]
class_data.append(trThisClass)
centerThisClass = trThisClass.mean(axis=0)
print centerThisClass
means.append(centerThisClass)
print '*********************************************************************************... | *****************************************************************'
# print np.shape(covThisClass)
invCovMatThisClass = np.linalg.inv(covThisClass)
print np.shape(invCovMatThisClass)
# assert(0)
|
saltstack/salt | salt/modules/apf.py | Python | apache-2.0 | 3,165 | 0.00158 | """
Support for Advanced Policy Firewall (APF)
==========================================
:maintainer: Mostafa Hussein <[email protected]>
:maturity: new
:depends: python-iptables
:platform: Linux
"""
import salt.utils.path
from salt.exceptions import CommandExecutionError
try:
import iptc
IPTC_IMP... | salt '*' apf.disable
"""
if _status_apf():
return __apf_cmd("-f")
def enable():
"""
Load all firewall rules
CLI Example:
.. code-block:: bash
salt '*' apf.enable
"""
if not _status_apf():
return __apf_cmd("-s")
def reload():
"""
Stop (flush) ... | k:: bash
salt '*' apf.reload
"""
if not _status_apf():
return __apf_cmd("-r")
def refresh():
"""
Refresh & resolve dns names in trust rules
CLI Example:
.. code-block:: bash
salt '*' apf.refresh
"""
return __apf_cmd("-e")
def allow(ip, port=None):
"""
... |
magic0704/oslo.db | oslo_db/tests/utils.py | Python | apache-2.0 | 1,310 | 0 | # Copyright 2010-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 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 permiss... | t import moxstubout
import six
if six.PY3:
@contextlib.contextmanager
def nested(*contexts):
with contextlib.ExitStack() as stack:
yield [stack.enter_context(c) for c in contexts]
else:
nested = contextlib.nested
class BaseTestCase(test_base.BaseTestCase):
def setUp(self, conf=cf... |
wilderrodrigues/cloudstack_integration_tests | cit/integration/acs/tests/test_reset_vm_on_reboot.py | Python | apache-2.0 | 5,776 | 0.002251 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | ist response returns a valid list"
)
self.assertNotEqual(
list_vm_response,
None,
"Check virtual machine is listVirtualMachines"
)
vm_response = list_vm_response[0]
self.assertEqual(
vm_respo | nse.state,
'Running',
"Check the state of VM"
)
return
|
timkrentz/SunTracker | IMU/VTK-6.2.0/Web/Applications/Cone/server/vtk_web_cone.py | Python | mit | 3,893 | 0.002826 | r"""
This module is a VTK Web server application.
The following command line illustrate how to use it::
$ vtkpython .../vtk_web_cone.py
Any VTK Web executable script come with a set of standard arguments that
can be overriden if need be::
--host localhost
Interfac... | actor.SetMapper(mapper)
renderer.AddActor(actor)
renderer.ResetCamera()
renderWindow.Render()
# VTK Web application specific
_WebCone.view = renderWindow
self.Application.GetObjectIdMap().SetActiveObject("VIEW", renderWindow)
# ======... | ====
# Main: Parse args and start server
# =============================================================================
if __name__ == "__main__":
# Create argument parser
parser = argparse.ArgumentParser(description="VTK/Web Cone web-application")
# Add default arguments
server.add_argument... |
mulkieran/blk-DAG-tools | version.py | Python | gpl-2.0 | 1,244 | 0 | # -*- coding: utf-8 -*-
# Copyright (C) 2015 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in th... | be u | seful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# ... |
merlinthered/sublime-rainmeter | newskintools.py | Python | mit | 4,688 | 0.004693 | import os
import re
import time
import sublime
import sublime_plugin
import rainmeter
class RainmeterNewSkinFileCommand(sublime_plugin.WindowCommand):
"""Open a new view and insert a skin skeleton"""
def run(self):
view = self.window.new_file()
view.run_command(
"insert_snipp... | ame:",
"",
lambda name: self.create_skin(name),
| None,
None)
def create_skin(self, name):
skinspath = rainmeter.skins_path()
if not skinspath or not os.path.exists(skinspath):
sublime.error_message(
"Error while trying to create new skin: " +
"S... |
jmaher/treeherder | tests/webapp/api/test_performance_tags.py | Python | mpl-2.0 | 483 | 0.00207 | from django.urls import reverse
def test_perf_tags_get(authorized_sheriff_client, test_perf_tag, test_perf_tag_2):
resp = authorized_sheriff_client.get(reverse('performance-tags-list'))
assert res | p.status_code == 200
assert len(resp.json()) == 2
assert resp.json()[0]['id'] == test_perf_tag.i | d
assert resp.json()[0]['name'] == test_perf_tag.name
assert resp.json()[1]['id'] == test_perf_tag_2.id
assert resp.json()[1]['name'] == test_perf_tag_2.name
|
hftools/hftools | hftools/file_formats/hdf5/v_01.py | Python | bsd-3-clause | 4,699 | 0.003618 | # -*- coding: ISO-8859-1 -*-
#-----------------------------------------------------------------------------
# Copyright (c) 2014, HFTools Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#---------------------... | , **kw):
if isinstance(h5file, string_types):
fil = h5py.File(h5file, "r")
else:
fil = h5file
db = DataBlock()
grp = fil[name]
blockname = grp.attrs["Blockname"]
if blockname.lower() == "none":
| blockname = None
db.blockname = blockname
comments = grp["Comments"]
if "fullcomments" in comments and len(comments["fullcomments"]):
db.comments = Comments([cast_unicode(x).strip() for x in np.array(comments["fullcomments"])])
else:
db.comments = Comments()
ivardata = grp["... |
mengskysama/FoobarTTLyric | lrcserv.py | Python | gpl-3.0 | 8,866 | 0.010357 | # -*- coding: UTF-8 -*-
#auther mengskysama
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.httpclient
import lcs
from urllib import quote
from urllib import unquote
from tornado import gen
import ttlrcdump
listen_port = 38439
def ChooiseItem(xml, artist):
... |
finally:
request.finish()
elif (request.uri.f | ind('/?keyword=') != -1):
uri = request.uri.decode('gbk').replace('%20',' ')
if uri.find('&') != -1:
keyword = uri[10:uri.find('&')]
else:keyword = uri[10:]
#print repr(keyword)
keyword = keyword.encode('gbk')
#print repr(keyword)
keyword = keyword.de... |
miurahr/django-admin-tools | admin_tools/dashboard/dashboards.py | Python | mit | 10,473 | 0.000382 | """
Module where admin tools dashboard classes are defined.
"""
from django.template.defaultfilters import slugify
try:
from importlib import import_module
except ImportError:
# Django < 1.9 and Python < 2.7
from django.utils.importlib import import_module
from django.utils.translation import ugettext_lazy... | al
properties:
``title``
The dashboard title, by default, it is displayed above the dashboard
in a ``h2`` tag. Default v | alue: 'Dashboard'.
``template``
The template to use to render the dashboard.
Default value: 'admin_tools/dashboard/dashboard.html'
``columns``
An integer that represents the number of columns for the dashboard.
Default value: 2.
If you want to customize the look of your da... |
FescueFungiShare/hydroshare | hs_core/search_indexes.py | Python | bsd-3-clause | 13,185 | 0.000834 | from haystack import indexes
from hs_core.models import BaseResource
from django.db.models import Q
from datetime import datetime
class BaseResourceIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
short_id = indexes.CharField(model_attr='short_id')
... | ly ente | r one value "none"
if hasattr(obj, 'metadata'):
for creator in obj.metadata.creators.all():
if(creator.organization is not None):
organizations.append(creator.organization)
else:
if not none:
none = True
... |
drewcsillag/skunkweb | pylibs/skunkdoc/scanners/STMLScanner.py | Python | gpl-2.0 | 9,219 | 0.009762 | #
# Copyright (C) 2001 Andrew T. Csillag <[email protected]>
#
# You may distribute under the terms of either the GNU General
# Public License or the SkunkWeb License, as specified in the
# README file.
#
import globals
import os
from DT import DTTags, DTTagRegistry, DTLexer, DTParser, D... | lf.parsed = None
def _getDependsOnFull(self, tagname):
tags = _findTags(self.parsed, tagname)
if not tags:
return []
l = []
for tag in tags:
#print 'TAG=', tag.tagname
args = DTUtil.tagCall(tag, _depSpecs[tag.tagname], kwcol='kw')
l.ap | pend((tag.tagname, args['name'], args['kw']))
return l
def _getDependsOn(self, tagname):
return map(lambda x:x[1], self._getDependsOnFull(tagname))
def getDependancies(self):
self.dependancies = map(
lambda (tn,n,a):[tn, n, a.get('cache')],
self._getDependsO... |
Nebucatnetzer/tamagotchi | pygame/lib/python3.4/site-packages/faker/providers/phone_number/zh_CN/__init__.py | Python | gpl-2.0 | 589 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .. import Provider as PhoneNumberProvider
class Provider(PhoneNumberProvider):
phonenumbe | r_prefixes = [134, 135, 136, 137, 138, 139, 147, 150,
151, 152, 157, 158, 159, 182, 187, 188,
130, 131, | 132, 145, 155, 156, 185, 186,
145, 133, 153, 180, 181, 189]
formats = [str(i) + "########" for i in phonenumber_prefixes]
@classmethod
def phonenumber_prefix(cls):
return cls.random_element(cls.phonenumber_prefixes)
|
docker-solr/docker-solr | tools/serve_local.py | Python | apache-2.0 | 1,512 | 0.002646 | #!/usr/bin/env python3
#
# Script which serves local solr tgz files simulating an Apache mirror server
#
from http.server import BaseHTTPRequestHandler, HTTPServer
import os
import sys
PORT_NUMBER = 8083
#This class will handle any incoming request
class myHandler(BaseHTTPRequestHandler):
def do_GET(self):
... | NUMBER), myHandler)
print("Started local web server serving Solr artifacts on port %s" % P | ORT_NUMBER)
server.serve_forever()
except KeyboardInterrupt:
print("^C received, shutting down the web server")
server.socket.close() |
ValyrianTech/BitcoinSpellbook-v0.3 | trigger/recurringtrigger.py | Python | gpl-3.0 | 2,696 | 0.001855 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
from datetime import datetime
from helpers.loghelpers import LOG
from .trigger import Trigger
from .triggertype import TriggerType
from validators.validators import valid_amount, valid_timestamp
class RecurringTrigger(Trigger):
def __init__(self, trigger_... | elf.begin_time
LOG.info('Setting first activation of recurring trigger %s to %s' % (self.id, datetime.fromtimestamp(self.next_activation)))
self.multi = True
def json_encodable(self):
ret = super(RecurringTrigger, self).json_encodable()
ret.update({
'begin_time': s... | tion})
return ret
|
alexrudnick/terere | bibletools/unify_bibles.py | Python | gpl-3.0 | 1,141 | 0.003506 | #!/usr/bin/env python3
"""
Given two Bibles all in one file (with books and verses in any order), with one
verse per line, with lines like this:
BOOK_chapter_verse{TAB}Text of verse goes here...
... print out which verses are present in the first Bible but missing in the
second, and vice-versa.
"""
import sys
impo... | ed(list(left - right))
for verse in leftbutnotright:
print(verse)
print("[right but not left]")
rightbutno | tleft = sorted(list(right - left))
for verse in rightbutnotleft:
print(verse)
if __name__ == "__main__": main()
|
soul-F/forumdemo | article/views.py | Python | gpl-2.0 | 2,005 | 0.018734 | # coding: utf-8
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from django.shortcuts import render_to_response,redirect
from models import Article
from block.views import Demo
from django.contrib.auth.models import User
from django.template.context import RequestContext
f... | lock = Demo.objects.get(id=block_id)
articles = Article.objects.filter(block=block).order_by("-update_timestamp")
return render_to_response("article_list.html", {"articles":articles,"b":block},
context_instance=RequestContext(request))
@login_required
def create_article(reques... | if request.method == "GET":
return render_to_response("article_create.html",{"b":block},
context_instance=RequestContext(request))
else:
title = request.POST["title"].strip()
content = request.POST["content"].strip()
if not title or not content:
... |
bongo-project/bongo | src/libs/python/bongo/external/email/message.py | Python | gpl-2.0 | 32,690 | 0.001835 | # Copyright (C) 2001-2006 Python Software Foundation
# Author: Barry Warsaw
# Contact: [email protected]
"""Basic message object for the email package object model."""
__all__ = ['Message']
import re
from cStringIO import StringIO
# Intrapackage imports
import bongo.external.email.charset
from bongo.external.ema... | ist object, you modify the message's payload in place. Optional
i returns that index into the payload.
Optional decode is a flag indicating whether the payload should be
decoded or not, according to the Content-Transfer-Encoding header
(default is False).
When True and the mes... | , the payload will be
decoded if this header's value is `quoted-printable' or `base64'. If
some other encoding is used, or the header is missing, or if the
payload has bogus data (i.e. bogus base64 or uuencoded data), the
payload is returned as-is.
If the message is a multipart... |
zhangvs1988/zhangyl-Djangodemo | article/migrations/0007_auto_20160811_1915.py | Python | gpl-3.0 | 419 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-08-11 11:15
fr | om __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('article', '0006_article_owner'),
]
operations = [
migrations.RenameField(
model_name='article',
old_name='owner',
new_name... | |
aleksandarmilicevic/react | src/react/src/react/api/wrappers.py | Python | gpl-2.0 | 2,372 | 0.002108 | class Wrapper(object):
def __init__(self, target, robj=None, fname=None):
self._target = target
self._owner = robj
self._fname = fname
def unwrap(self):
return self._target
def append(self, *args, **kwargs):
return self._handle_mutation_call('append', *args, **kwa... | lf._target
else:
for x in self._target:
yield x
def __getattr__(self, name):
return getattr(self._target, name)
def __add__(sel | f, other):
if isinstance(other, Wrapper):
other = other.unwrap()
return Wrapper.wrap(self._target + other)
def __eq__(self, other): return self.__bop__("eq", other)
def __ne__(self, other): return self.__bop__("ne", other)
def __gt__(self, other): return self.__bop__("gt", other... |
google-research/google-research | kws_streaming/train/train_test.py | Python | apache-2.0 | 5,152 | 0.00427 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | _PrepareDummyDir(self, dir_name):
path = os.path.join(FLAGS.test_tmpdir, dir_name)
os.mkdir(path)
return path
def _GetDefaultFlags(self, split_data):
params = model_params.dnn_params()
params.data_dir = self._PrepareDummyTrainingData(
) if spl | it_data == 1 else self._PrepareDummyTrainingDataSplit()
params.wanted_words = 'a,b,c'
params.split_data = split_data
params.summaries_dir = self._PrepareDummyDir('summaries' + str(split_data))
params.train_dir = self._PrepareDummyDir('train' + str(split_data))
params.how_many_training_steps = '2'
... |
Psycojoker/dierentheater | scraper/management/commands/create_db_dumps.py | Python | agpl-3.0 | 932 | 0 | # lachambre.be to json sausage machine
# Copyright (C) 2011 Laurent Peuch <[email protected]>
#
# | This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, | or any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the... |
thomwiggers/onebot | onebot/plugins/execute.py | Python | bsd-3-clause | 1,513 | 0 | """
=====================================================
:mod:`onebot.plugins.execute` Run commands on connect
=====================================================
Run commands on connect
Config:
=======
.. code-block: ini
[bot]
includes=
onebot.plugins.execute
[onebot.plugins.execute]
comma... | bot.send(command)
@classmethod
def reload(cls, old): # pragma: no cover
return cls(old. | bot)
|
szhem/spark | python/pyspark/streaming/tests.py | Python | apache-2.0 | 62,306 | 0.001653 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | test_func(input, func, expected)
def test_filter(self):
"""Basic operation test for DStream.filter."""
input = [range(1, 5), range(5, 9), range(9, 13)]
def func(dstream):
return dstream.filter(lambda x: x % 2 == 0) |
expected = [[y for y in x if y % 2 == 0] for x in input]
self._test_func(input, func, expected)
def test_count(self):
"""Basic operation test for DStream.count."""
input = [range(5), range(10), range(20)]
def func(dstream):
return dstream.count()
expect... |
anaruse/chainer | tests/chainer_tests/functions_tests/connection_tests/test_bilinear.py | Python | mit | 6,944 | 0 | import unittest
import numpy
import chainer
from chainer.backends import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
def _uniform(*shape):
return numpy.random.uniform(-1, 1, shape).astype(numpy.float32)
@testing.parameteriz... | ch_size,) + self.in_shapes[0]
e2_shape = (self.batch_size,) + self.in_shapes[1]
e1_size = numpy.prod(self.in_shapes[0])
e2_size = numpy.prod(self.in_shapes[1])
self.e1 = _uniform | (*e1_shape)
self.e2 = _uniform(*e2_shape)
self.W = _uniform(e1_size, e2_size, self.out_size)
self.V1 = _uniform(e1_size, self.out_size)
self.V2 = _uniform(e2_size, self.out_size)
self.b = _uniform(self.out_size)
self.gy = _uniform(self.batch_size, self.out_size)
... |
mumuwoyou/vnpy-master | sonnet/python/modules/pondering_rnn.py | Python | mit | 7,717 | 0.00298 | # Copyright 2017 The Sonnet 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 applicable l... | r, halting_linear, x_ones):
"""The `body` of `tf.while_loop`."""
# Increase iteration count only for those elements that are still running.
all_ones = tf.constant(1, shape=(self._batch_size, 1), dtype=self._dtype)
is_iteration_over = tf.equal(cumul_halting, all_ones)
next_iteration = tf.where(is | _iteration_over, iteration, iteration + 1)
out, next_state = self._core(x, prev_state)
# Get part of state used to compute halting values.
halting_input = halting_linear(self._get_state_for_halting(next_state))
halting = tf.sigmoid(halting_input, name="halting")
next_cumul_halting_raw = cumul_haltin... |
tensorflow/tensorflow | tensorflow/python/distribute/one_device_strategy.py | Python | apache-2.0 | 18,606 | 0.004998 | # 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... | 0
for i in range(10):
result += strategy.run(step_fn, args=(i,))
print(result) # 90
```
"""
def __init__(self, device):
"""Creates a `OneDeviceStrategy`.
Args:
device: Device string identifier for the device on which the variables
should be placed. See class docs for more details ... | ))
distribute_lib.distribution_strategy_gauge.get_cell("V2").set(
"OneDeviceStrategy")
def experimental_distribute_dataset(self, dataset, options=None): # pylint: disable=useless-super-delegation
"""Distributes a tf.data.Dataset instance provided via dataset.
In this case, there is only one dev... |
danjac/ownblock | ownblock/ownblock/apps/storage/migrations/0004_auto_20140911_0341.py | Python | mit | 493 | 0.002028 | # | -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import ownblock.apps.storage.models
class Migration(migrations.Migration):
dependencies = [
('storage', '0003_item_photo'),
]
operations = [
migrations.AlterField(
model_n... | ),
),
]
|
laurentb/weboob | modules/caissedepargne/cenet/pages.py | Python | lgpl-3.0 | 14,121 | 0.002691 | # -*- coding: utf-8 -*-
# Copyright(C) 2012 Romain Bignon
#
# This file is part of a weboob module.
#
# This weboob module is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the Licens... | serUnavailable(self.d | oc['Erreur']['Titre'] or self.doc['Erreur']['Description'])
self.doc['DonneesSortie'] = json.loads(self.doc['DonneesSortie'])
class CenetAccountsPage(LoggedPage, CenetJsonPage):
ACCOUNT_TYPES = {'CCP': Account.TYPE_CHECKING}
@method
class get_accounts(DictElement):
item_xpath = "DonneesS... |
Cinntax/home-assistant | homeassistant/components/ebox/sensor.py | Python | apache-2.0 | 4,756 | 0.000631 | """
Support for EBox.
Get data from 'My Usage Page' page: https://client.ebox.ca/myusage
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.ebox/
"""
import logging
from datetime import timedelta
import voluptuous as vol
import homeassistant.helper... | _init__(self, username, password, httpsession):
"""Initialize the data object."""
from pyebox import EboxClient
self.client = EboxClient(username, password, REQUESTS_TIMEOUT, httpsession)
self.data = {}
@Throttle(MIN_TIME_BETWEEN_UPDATES)
async def async_update(self):
"... | self.client.fetch_data()
except PyEboxError as exp:
_LOGGER.error("Error on receive last EBox data: %s", exp)
return
# Update data
self.data = self.client.get_data()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.