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 |
|---|---|---|---|---|---|---|---|---|
happz/ducky | ducky/asm/lexer.py | Python | mit | 2,836 | 0.012694 | import ply.lex
#
# Lexer setup
#
instructions = (
'NOP', 'INT', 'IPI', 'RETINT', 'CALL', 'RET', 'CLI', 'STI', 'HLT', 'RST', 'IDLE',
'PUSH', 'POP', 'INC', 'DEC', 'ADD', 'SUB', 'CMP', 'J', 'AND', 'OR', 'XOR', 'NOT',
'SHL', 'SHR', 'SHRS', 'LW', 'LS', 'LB', 'LI', 'LIU', 'LA', 'STW', 'STS', 'STB',
'MOV', 'SWP', 'MU... | t.lexpos)
raise AssemblyIllegalCharError(c = t.value[0], location = loc, line = t.lexer.parser.lineno_to_line(t.lineno))
class AssemblyLexer(object):
def __init__(self):
self._lexer = ply.lex.lex()
def token(self, *args, **kwa | rgs):
return self._lexer.token(*args, **kwargs)
def input(self, *args, **kwargs):
return self._lexer.input(*args, **kwargs)
|
blackspiraldev/jira-python | jira/packages/requests_oauth/__init__.py | Python | bsd-2-clause | 235 | 0 | # requests-oauth 0.4.0
# Hacked to | support RSA-SHA1 encryption for Atlassian OAuth.
# Original author: Miguel Araujo
# Forked from https://github.com/maraujop/requests_oauth
# Original license: 3-clause BSD
from hook impo | rt OAuthHook
|
firebitsbr/pwn_plug_sources | src/wifizoo/wifiglobals.py | Python | gpl-3.0 | 8,025 | 0.04486 | # WifiZoo
# complains to Hernan Ochoa (hernan@gmail.com)
import curses.ascii
from scapy import *
import datetime
import WifiZooEntities
import os
class WifiGlobals:
def __init__(self):
self.APdict = {}
self.AccessPointsList = []
self.ProbeRequestsListBySSID = []
self.ProbeRequestsListBySRC = []
self._hasPr... | replace('-',':').lower()
if vendormac == myMAC:
return vendorname
return 'Unknown'
def addCookie(self, aCookie):
self._CookiesList.append(aCookie)
return
def getCookiesList(self):
return self._Cook | iesList
def setCookie(self, aCookie):
self._Cookie = aCookie
def getCookie(self):
return self._Cookie
def setHasPrismHeaders(self, aBoolean):
self._hasPrismHeaders = aBoolean
def hasPrismHeaders(self):
return self._hasPrismHeaders
def getClients(self):
return self.APdict
def logDir(self):
if not ... |
deerwalk/voltdb | tests/scripts/valleak.py | Python | agpl-3.0 | 3,161 | 0.003796 | #!/usr/bin/env python
# This file is part of VoltDB.
# Copyright (C) 2008-2017 VoltDB Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitati... | )
valgrind_error = valgrind_error_file.read()
valgrind_error_file.close()
valgrind_output.close()
# Find the last summary | block in the valgrind report
# This ignores forks
summary_start = valgrind_error.rindex("== ERROR SUMMARY:")
summary = valgrind_error[summary_start:]
append_valgrind = False
if error == 0:
assert "== ERROR SUMMARY: 0 errors" in summary
# Check for memory leaks
if "== def... |
liorvh/CuckooSploit | lib/cuckoo/core/scheduler.py | Python | gpl-3.0 | 21,948 | 0.000456 | # Copyright (C) 2010-2015 Cuckoo Foundation.
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
import os
import time
import shutil
import logging
import Queue
from threading import Thread, Lock
from lib.cuckoo.common.config import Config
from li... | s, R | unReporting
from lib.cuckoo.core.resultserver import ResultServer
log = logging.getLogger(__name__)
machinery = None
machine_lock = Lock()
latest_symlink_lock = Lock()
active_analysis_count = 0
class CuckooDeadMachine(Exception):
"""Exception thrown when a machine turns dead.
When this exception has been ... |
EdDev/vdsm | tests/osinfo_test.py | Python | gpl-2.0 | 1,439 | 0 | #
# Copyright 2016 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in th... | dsmTestCase
from testlib import permutations, expandPermutations
from vdsm import osinfo
@expandPermutations
class TestOsinfo(VdsmTestCase):
@permutations([
[b'', ''],
[b'\n', ''],
[b'a', 'a'],
[b'a\n', 'a'],
[b'a\nb', 'a']
])
def test_kernel_args(self, test_input... | s(f.name),
expected_result)
|
USGSDenverPychron/pychron | pychron/envisage/tasks/actions.py | Python | apache-2.0 | 14,692 | 0.000204 | # ===============================================================================
# Copyright 2013 Jake Ross
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses... | )
def perform(self, event):
pass
# from pychron.envisage.user_login import get_user
#
# base_id, cuser = self._get_current_user(event)
# user = get_user(current=cuser)
# if user:
# # from pychron.paths import paths
# # set login file
#... | self, event):
pass
# from pychron.envisage.user_login import get_src_dest_user
#
# base_id, cuser = self._get_current_user(event)
# src_name, dest_names = get_src_dest_user(cuser)
#
# if src_name:
#
# for di in dest_names:
# des... |
cemsbr/expyrimenter | tests/test_executor.py | Python | gpl-3.0 | 4,989 | 0.0002 | import unittest
from mock import Mock, patch
from expyrimenter import Executor
from expyrimenter.runnable import Runnable
from subprocess import CalledProcessError
from concurrent.futures import ThreadPoolExecutor
import re
class TestExecutor(unittest.TestCase):
output = 'TestExecutor output'
outputs = ['Tes... | esults)
def test_against_runnable_memory_leak(self):
executor = Executor()
| with patch.object(Runnable, 'run'):
executor.run(Runnable())
executor.wait()
self.assertEqual(0, len(executor._future_runnables))
def test_against_function_memory_leak(self):
executor = Executor()
executor.run_function(background_function)
executor.wait()
... |
wooey/Wooey | wooey/tasks.py | Python | bsd-3-clause | 10,721 | 0.002332 | from __future__ import absolute_import
import os
import subprocess
import sys
import tarfile
import tempfile
import traceback
import zipfile
from threading import Thread
import six
from django.utils.text import get_valid_filename
from django.core.files import File
from django.conf import settings
from celery import T... |
:param script_version: :py:class:`~wooey.models.core.ScriptVersion`
:return: boolean
Returns true if a new version was downloaded.
"""
script_path = script_version.script_path
local_storage = utils.get_storage(local=True)
script_exists = local_storage.exists(script_path.name)
| if not script_exists:
local_storage.save(script_path.name, script_path.file)
return True
else:
# If script exists, make sure the version is valid, otherwise fetch a new one
script_contents = local_storage.open(script_path.name).read()
script_checksum = utils.get_checksum(bu... |
segasai/astrolibpy | my_utils/from_hex.py | Python | gpl-3.0 | 1,118 | 0.027728 | # Copyright (C) 2009-2010 Sergey Koposov
# This file is part of astrolibpy
#
# astrolibpy 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 Found | ation, either version 3 of the License, or
# (at your option) any later version.
#
# astrolibpy 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 f... | rg/licenses/>.
import numpy, re
def from_hex(arr, delim=':'):
r=re.compile('\s*(\-?)(.+)%s(.+)%s(.+)'%(delim,delim))
ret=[]
for a in arr:
m = r.search(a)
sign = m.group(1)=='-'
if sign:
sign=-1
else:
sign=1
i1 = int(m.group(2))
i2 = int(m.group(3))
i3 = float(m.group(4))
val = sign*(int(i1)+... |
perkinslr/pypyjs | tools/rematcher.py | Python | mit | 4,972 | 0.000402 |
import os
import sys
from time import time as clock
from rpython.rlib import jit
from rpython.rlib import rrandom
from rpython.jit.codewriter.policy import JitPolicy
# The regex is built up from a combination individual Regex objects.
# Each is responsiblef for implementing a specific operator.
class Regex(object... | ft, right, empty):
Regex.__init__(self, empty)
self.left = left
self.right = right
def reset(self):
self.left.reset()
self.right.reset()
Regex.reset(self)
class Alternative(Binary):
def __init__(self, left, right):
empty = left.empty | right.empty
... | arked_left | marked_right
class Repetition(Regex):
_immutable_fields_ = ["re"]
def __init__(self, re):
Regex.__init__(self, 1)
self.re = re
def _shift(self, c, mark):
return self.re.shift(c, mark | self.marked)
def reset(self):
self.re.reset()
Regex.reset(se... |
tecknicaltom/xhtml2pdf | xhtml2pdf/util.py | Python | apache-2.0 | 27,717 | 0.003355 | # -*- coding: utf-8 -*-
from reportlab.lib.colors import Color, CMYKColor, getAllNamedColors, toColor, \
HexColor
from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT, TA_JUSTIFY
from reportlab.lib.units import inch, cm
import base64
import httplib
import logging
import mimetypes
import os.path
import re
im... | # e.g., value = "<css function: rgb(153, 51, 153)>", go figure:
r, g, b = [int(x) for x in rgb_re.search(value).groups()]
value = "#%02x%02x%02x" % (r, g, b)
else:
# Shrug
pass
return toColor(value, default) # Calling the reportlab function
def getBorderStyl | e(value, default=None):
# log.debug(value)
if value and (str(value).lower() not in ("none", "hidden")):
return value
return default
mm = cm / 10.0
dpi96 = (1.0 / 96.0 * inch)
_absoluteSizeTable = {
"1": 50.0 / 100.0,
"xx-small": 50.0 / 100.0,
"x-small": 50.0 / 100.0,
"2": 75.0 / 10... |
iw3hxn/LibrERP | l10n_it_sale/models/inherit_sale_order.py | Python | agpl-3.0 | 2,854 | 0.002803 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2010-2012 Associazione OpenERP Italia
# (<http://www.openerp-italia.org>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero ... | ####################################################
from openerp.osv import orm, fields
class sale_order(orm.Model):
_inherit = "sale.order"
_columns = {
'cig': fields.char('CIG', size=15, help="Codice identificativo di gara"),
' | cup': fields.char('CUP', size=15, help="Codice unico di Progetto")
}
#-----------------------------------------------------------------------------
# EVITARE LA COPIA DI 'NUMERO cig/cup'
#-----------------------------------------------------------------------------
def copy(self, cr, uid, id, d... |
sandeepdsouza93/TensorFlow-15712 | tensorflow/python/client/timeline_test.py | Python | apache-2.0 | 7,065 | 0.00368 | # Copyright 2016 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... | tadata.HasField('step_stats'))
step_stats = run_metadata.step_stats
devices = [d.device for d in step_stats.dev_stats]
self.assertTrue('/job:localhost/replica:0/task:0/cpu:0' in devices)
tl = timeline.Timeline(step_stats)
ctf = tl.generate_chrome_trace_format()
self._validateTrace(ctf)
tl = ... | w=False)
self._validateTrace(ctf)
tl = timeline.Timeline(step_stats)
ctf = tl.generate_chrome_trace_format(show_memory=False)
self._validateTrace(ctf)
tl = timeline.Timeline(step_stats)
ctf = tl.generate_chrome_trace_format(show_memory=False,
show_datafl... |
idning/redis-rdb-tools | tests/parser_tests.py | Python | mit | 14,949 | 0.009967 | import unittest
import os
import math
from rdbtools import RdbCallback, RdbParser
class RedisParserTestCase(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_empty_rdb(self):
r = load_rdb('empty_database.rdb')
self.assert_('start_rdb' in r... | iry[0]['expires_ms_precision']
self.assertEquals(expiry.year, 2022)
self.assertEquals(expiry.month, 12)
self.assertEquals(expiry.day, 25)
self.assertEquals(expiry.hour, 10)
self.assertEquals(expiry.minute, 11)
self.assertEquals(expiry.second, 12)
self.assertEquals... | 125], "Positive 8 bit integer")
self.assertEquals(r.databases[0][0xABAB], "Positive 16 bit integer")
self.assertEquals(r.databases[0][0x0AEDD325], "Positive 32 bit integer")
def test_negative_integer_keys(self):
r = load_rdb('integer_keys.rdb')
self.assertEquals(r.databases[... |
HPC-buildtest/buildtest-framework | docs/scripting_examples/ex1.py | Python | mit | 300 | 0.003333 | import os
from buildtest.defaults import BUILDTEST_ROOT
from buildtest.menu.build import discover_buildspecs
included_bp, excluded_bp = discover_buildspecs(
buildspec=[os.path.join(BUILDTEST_ROOT, "tu | torials")]
)
print(f"discovered_buildspec: {included_bp} excluded bui | ldspec: {excluded_bp}")
|
fs714/drcontroller | drcontroller/db/init_db.py | Python | apache-2.0 | 38 | 0 | from | db_Dao import init_db
init_db()
| |
dNG-git/pas_upnp | src/dNG/data/upnp/services/abstract_service.py | Python | gpl-2.0 | 20,705 | 0.008211 | # -*- coding: utf-8 -*-
"""
direct PAS
Python Application Services
----------------------------------------------------------------------------
(C) direct Netware Group - All rights reserved
https://www.direct-netware.de/redirect?pas;upnp
The following license agreement remains valid unless any additions or
changes a... | rvice implementation for server services.
:author: direct Netware Group et al.
:copyright: direct Netware Group - All rights reserved
:package: pas
:subpackage: upnp
:since: v0.2.00
:license: https://www.direct-netware.de/redirect?licenses;gpl
GNU General Public License 2
"""
def ... | structor __init__(AbstractService)
:since: v0.2.00
"""
Service.__init__(self)
ClientSettingsMixin.__init__(self)
self.configid = None
"""
UPnP configId value
"""
self.host_service = False
"""
UPnP service is managed by host
"""
self.type... |
markbrough/iati-country-tester | segment_ro.py | Python | mit | 3,383 | 0.005912 | #!/usr/bin/env python
# Takes apart large IATI XML files and outputs one file per reporting org.
# Copyright 2013 Mark Brough.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License v3.0 as
# published by the Free Software Foundation, e... | encoding="UTF-8")
metadata.writerow({
'org':org,
'orgname':data['orgname'],
'orgtype':data['orgtype'],
'filename':prefix+"-"+org | +'.xml',
'package_name': prefix+"-"+org,
'package_title': data['title']})
print "Finished writing data, find the files in", output_directory
metadata_file.close()
if __name__ == '__main__':
arguments = sys.argv
arguments.pop(0)
prefix = arguments[0]
arguments.po... |
sharmaking/CoIntegrationAnalysis | windowController.py | Python | mit | 579 | 0.03255 | #!/usr/bin/p | ython
# -*- coding: utf-8 -*-
#windowController.py
from PyQt4 import QtGui
import sys, multiprocessing
import mainWindow, windowListerner
class QWindowsController(multiprocessing.Process):
def __init__(self, messageBox):
super(QWindowsController, self).__init__()
self.messageBox = messageBox
def run(self):
ap... | self.messageBox)
wListerner.start()
#显示主窗口
QMain.show()
sys.exit(app.exec_())
|
alexmojaki/birdseye | birdseye/__main__.py | Python | mit | 72 | 0 | from birdseye.server | import main
if __name__ | == '__main__':
main()
|
mattvonrocketstein/smash | smashlib/ipy3x/html/services/kernelspecs/tests/test_kernelspecs_api.py | Python | mit | 4,428 | 0.001355 | # coding: utf-8
"""Test the kernel specs webservice API."""
import errno
import io
import json
import os
import shutil
pjoin = os.path.join
import requests
from IPython.kernel.kernelspec import NATIVE_KERNEL_NAME
from IPython.html.utils import url_path_join
from IPython.html.tests.launchnotebook import NotebookTest... | url_path_join('kernelspecs', name, path))
class APITest(NotebookTestBase):
"""Test the kernelspec web service API"""
def setUp(self):
ipydir = self.ipython_dir.name
sample_kernel_dir = pjoin(ipydir, 'kernels', 'sample')
try:
os.makedirs(sample_kernel_dir)
except O... | .json'), 'w') as f:
json.dump(sample_kernel_json, f)
with io.open(pjoin(sample_kernel_dir, 'resource.txt'), 'w',
encoding='utf-8') as f:
f.write(some_resource)
self.ks_api = KernelSpecAPI(self.base_url())
def test_list_kernelspecs_bad(self):
""... |
FedoraScientific/salome-paravis | test/VisuPrs/StreamLines/F7.py | Python | lgpl-2.1 | 1,521 | 0.001972 | # Co | pyright (C) 2010-2014 CEA/DEN, EDF R&D
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is d... | See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# See http://www.salome-platform.org/ or ... |
Drowrin/Weeabot | cogs/anilist.py | Python | mit | 4,392 | 0.003189 | from datetime import datetime, timedelta
import dateutil.parser
import discord
from discord.ext import commands
import utils
def not_season_or_year(ctx):
now = datetime.now()
return AniList.seasons[now.month // 3] not in ctx.message.content or str(now.year) not in ctx.message.content
class AniList(utils.Se... | parse(anime["start_date"])
days[d.weekday()].append(anime)
anilist_url = f'http://anilist.co/browse/anime?sort=start_date-desc&year={year}&season={season}'
| e: discord.Embed = discord.Embed(
title=f"{season.title()} {year} Anime",
url=anilist_url,
color=self.season_colors[season]
)
for day, shows in enumerate(days):
shows = sorted(shows, key=lambda a: a['start_date_fuzzy'])
value = [
... |
tschijnmo/drudge | drudge/_tceparser.py | Python | mit | 5,439 | 0 | """
Tensor Contraction Engine output parser.
This module provides parsers of the output of the Tensor Contraction Engine of
So Hirata into Tensor objects in drudge.
"""
import collections
import itertools
import re
from sympy import nsimplify, sympify, Symbol
from drudge import Term
#
# The driver function
# --... | parsed from the term specification
part of the TCE line. This function will use the factors string in the
square bracket to turn it into a list of terms for the final value of the
line.
"""
# The regular expression for a factor.
factor_regex = r'\s*'.join([
r'(?P<sign>[+-])',
r... | *'
mismatch_regex = r'.'
regex = '(?P<factor>{})|(?P<mismatch>{})'.format(
factor_regex, mismatch_regex
)
# Iterate over the factors.
terms = []
for match_res in re.finditer(regex, factors_str):
# Test if the result matches a factor.
if match_res.group('factor') is None... |
prplfoundation/prpl-hypervisor | bin/board-control.py | Python | isc | 1,093 | 0.013724 | import serial
from time import sleep
import base64
import sys
def readSerial():
while True:
response = ser.readline();
return response
# main
ser = serial.Serial(port='/dev/ttyACM0', baudrate=115200, timeout=3)
ser.isOpen()
# Wait UART Listener VM to be done.
while(1):
message = readSerial()
i... | if 'keyCode' in message:
hex_keyCode = message[9:-1]
break
print "KeyCode: ", hex_keyCode
binary_keyCode = base64.b16decode(hex_keyCode.upper())
while(1):
print "ARM Commands: "
print "1 - Start"
print "2 - Stop"
c = '0'
| while c!='1' and c!='2':
c = raw_input('Input:')
print 'Sending the arm command...'
for i in range(0, len(binary_keyCode)):
ser.write(binary_keyCode[i])
ser.flush()
ser.write(c.encode())
ser.write('\n'.encode())
ser.flush()
print 'Board response: %s' % readSeri... |
hehongliang/tensorflow | tensorflow/contrib/cluster_resolver/python/training/slurm_cluster_resolver.py | Python | apache-2.0 | 8,923 | 0.003474 | # 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 applicable ... | aults to True.
rpc_layer: (Optional) The protocol TensorFlow uses to communicate between
nodes. Defaults to 'grpc'.
Returns:
A ClusterResolver object which can be used with distributed TensorFlow.
Raises:
RuntimeE | rror: If requested more GPUs per node then available or requested
more tasks then assigned tasks.
"""
# check if launched by mpirun
if 'OMPI_COMM_WORLD_RANK' in os.environ:
self._rank = int(os.environ['OMPI_COMM_WORLD_RANK'])
num_tasks = int(os.environ['OMPI_COMM_WORLD_SIZE'])
else:
... |
kickstandproject/wildcard | wildcard/dashboards/admin/info/tables.py | Python | apache-2.0 | 2,073 | 0 | # -*- coding: utf-8 -*-
# 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, softw... | ()
# if not configured in this region, neither option makes sense
if service.host:
return options[0] if not service.disabled else options[1]
return None
class ServicesTable(tables.DataTable):
id = tables.Column('id', verbose_name=_('Id'), hidden=True)
name = tables.Column("name", verbose_n... | bose_name=_('Host'))
enabled = tables.Column(get_enabled,
verbose_name=_('Enabled'),
status=True)
class Meta:
name = "services"
verbose_name = _("Services")
table_actions = (ServiceFilterAction,)
multi_select = False
... |
pbabik/OGCServer | conf/fcgi_app.py | Python | bsd-3-clause | 198 | 0.010101 | from ogcserv | er.cgiserver import Handler
from jon import fcgi
class OGCSe | rverHandler(Handler):
configpath = '/path/to/ogcserver.conf'
fcgi.Server({fcgi.FCGI_RESPONDER: OGCServerHandler}).run()
|
diblaze/TDP002 | 2.3/testdemo/test/demo_test.py | Python | mit | 614 | 0.006515 | #!/usr/bin/env python
"""
Test module for demo.py.
Runs various tests on the demo module. Simply run this module to test
the demo.py module.
"""
import test
import demo
def test_echo():
print("In echo test")
echo = demo.echo("hej")
test.assert_equal("hej", echo)
test.assert_not_equal(None, echo)
de... | ests():
test.run_tests([test_echo,
test_add])
if __name__ == "__main__":
run_module_tests()
| |
ThomasA/pywt | pywt/tests/test_functions.py | Python | mit | 1,468 | 0 | #!/usr/bin/env python
from __future__ import division, print_function, absolute_import
from numpy.testing import (run_module_suite, assert_almost_equal,
assert_allclose)
import pywt
def test_centrfreq():
# db1 is Haar function, frequency=1
w = pywt.Wavelet('db1')
expected = 1
... | ion=12)
assert_almost_equal(result, expected, decimal=3)
# db2, frequency=2/3
w = pywt.Wavelet('db2')
expected = 2/3.
result = pywt.centfrq(w, precision=12)
assert_almost_equal(result, expected)
def test_scal2frq_scale():
scale = 2
delta = 1
w = pywt.Wavelet('db1')
expected = 1... | cted, decimal=3)
def test_scal2frq_delta():
scale = 1
delta = 2
w = pywt.Wavelet('db1')
expected = 1. / delta
result = pywt.scal2frq(w, scale, delta, precision=12)
assert_almost_equal(result, expected, decimal=3)
def test_intwave_orthogonal():
w = pywt.Wavelet('db1')
int_psi, x = pyw... |
kennethreitz-archive/mead | mead/core/tools/date_time.py | Python | isc | 3,456 | 0.000289 | # Part of Mead. See LICENSE file for full copyright and licensing details.
import datetime, re
def datetime_convert(time):
"""
Convert time to YYYYY-MM-DD HH:MM:SS
"""
_time = str(time)
retime = re.compile(r'\W+')
_list = retime.split(_time)
if len(_list) >= 6:
year = int(_list[... | time = datetime_convert(time)
if retard:
_time = str(retard)
| retime = re.compile(r'\W+')
_list = retime.split(_time)
hour = int(_list[0]) * 3600
minute = int(_list[1]) * 60
time2 = hour + minute
new_time = time - datetime.timedelta(0, time2)
else:
new_time = time
return new_time.time()
def format_date(date, format=Non... |
0xPhoeniX/MazeWalker | MazeTracer/PyScripts/post_regopenkeyexa.py | Python | lgpl-3.0 | 1,056 | 0.001894 | import ctypes
import json
def post_analyzer(HKEY_hKey,
LPCTSTR_lpSubKey,
DWORD_ulOptions,
REGSAM_samDesired,
PHKEY_phkResult,
**kwargs):
lpSubKey = ctypes.c_char_p.from_address(LPCTSTR_lpSubKey)
hKey = ctypes.c_void_p.fro... | ata'] = 'HKCR'
elif hKey.value == 0x80000001:
result['data'] = 'HKCU'
elif hKey.value == 0x80000002:
result['data'] = 'HKLM'
elif hKey.value == 0x80000003:
result['data'] = 'HKU'
elif hKey.value == 0x80000005:
result['data'] = 'HKCC'
... | es.append(result)
return json.dumps(res)
|
detiber/lib_openshift | lib_openshift/models/v1_cluster_role_list.py | Python | apache-2.0 | 6,290 | 0.001272 | # coding: utf-8
"""
OpenAPI spec version:
Generated by: https://github.com/swagger-api/swagger-codegen.git
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
... | :type: str
"""
self._kind = kind
@property
def api_version(self):
"""
Gets the api_version of this V1 | ClusterRoleList.
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#resources
:return: The ap... |
ViMiao/PythonLearning | ProgrammingPython/C01/dump_db_classes.py | Python | gpl-3.0 | 177 | 0.00565 | import shelve |
db = shelve.open('class-shelve')
for key in db:
print(key, '=>\n)', db[key].name, db[key].pay)
bob = db['bob']
print(bob.lastNa | me())
print(db['tom'].lastName) |
ekarulf/pymp | setup.py | Python | mit | 461 | 0.043384 | fro | m setuptools import setup, find_packages
setup(
name = "pymp",
version = "0.1",
url = 'http://www.fort-awesome.net/wiki/pymp',
license = 'MIT',
description = "A very specific case when Python's multiprocessing library doesn't work",
author = 'Erik Karulf',
# Below this line is tasty Kool-Ai... | '],
) |
metamarcdw/PyBitmessage-I2P | src/i2p/test/test_socket.py | Python | mit | 12,449 | 0.019038 |
# --------------------------------------------------------
# test_socket.py: Unit tests for socket, select.
# --------------------------------------------------------
# Make sure we can import i2p
import sys; sys.path += ['../../']
import traceback, time, thread, threading, random, copy
from i2p import socket, selec... | y:
multithread_wait_time = 500.0
may_need_increase = False
kwargs = {'in_depth': 0, 'out_depth': 0}
if raw:
C = socket.socket('Carola', socket.SOCK_RAW, **kwargs)
D = socket.socket('Davey', socket.SOCK_RAW, **kwargs)
else:
C = socket.socket('Carol', socket.SOCK_DGRAM, **kwargs)
| D = socket.socket('Dave', socket.SOCK_DGRAM, **kwargs)
global C_recv, D_recv, C_got, D_got, __lock
C_recv = [] # Packets C *should* receive
D_recv = [] # Packets D *should* receive
C_got = [] # Packets C actually got
D_got = [] # Packets D actually got
... |
AutorestCI/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_11_01/operations/usages_operations.py | Python | mit | 4,282 | 0.002102 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | version. Constant value: "2017-11-01".
"""
models = models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize | = deserializer
self.api_version = "2017-11-01"
self.config = config
def list(
self, location, custom_headers=None, raw=False, **operation_config):
"""List network usages for a subscription.
:param location: The location where resource usage is queried.
:type lo... |
I-sektionen/i-portalen | wsgi/iportalen_django/articles/migrations/0013_auto_20151021_0155.py | Python | mit | 598 | 0.00335 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('articles', '0012_article_organisations'),
]
operations = [
migrations.AlterField(
| model_name='article',
name='organisations',
field=models.ManyToManyField(default=None, help_text='Organisation/organisationer som artikeln hör till',
blank=True, to='organisations.Organisat | ion', verbose_name='organisationer'),
),
]
|
fmichea/lpbm | lpbm/exceptions.py | Python | bsd-3-clause | 2,013 | 0.000497 | # lpbm/exceptions.py - All the errors that can be raised in the program.
# Author: Franck Michea < franck.michea@gmail.com >
# License: New BSD License (See LICENSE)
class GeneralOptionError(Exception):
def __init__(self, name):
self.name = name
def __str__(self):
msg = 'Could not find or cal... | def __init__(self, id, name):
self.id, self.name = id, name
def __str__(self):
return 'There is no {} with this id ({}).'.format(self.name, self.id)
# Field Errors
class FieldReadOnlyError(Exception):
def __str__(self):
return 'Cannot assign read-only value.'
class FieldRequir... | str__(self):
msgs = [
'ConfigOptionField.__init__ takes one or two arguments.',
'See documentation for more details.',
]
return ' '.join(msgs)
# Model Errors
class AttributeNotAFieldError(Exception):
def __init__(self, attr_name):
self.attr_name = attr_nam... |
dialounke/pylayers | pylayers/antprop/diff.py | Python | mit | 13,499 | 0.029632 | """
.. currentmodule:: pylayers.antprop.diff
.. autosummary::
:members:
"""
from __future__ import print_function
import doctest
import os
import glob
import numpy as np
import scipy.special as sps
import matplotlib.pyplot as plt
import pdb
def diff(fGHz,phi0,phi,si,sd,N,mat0,matN,beta=np.pi/2):
""" Luebbers... | I[c2]
thn[c2] = BN[c2]*np.pi-PHI0[c2]
er0 = np.real(mat0['epr'])
err0 = np.imag(mat0['epr'])
ur0 = np.real(mat0['mur'])
urr0 = np.imag(mat0['mur'])
sigma0 = mat0['sigma']
deltah0 = mat0['roughness']
| erN = np.real(matN['epr'])
errN = np.imag(matN['epr'])
urN = np.real(mat0['mur'])
urrN = np.imag(mat0['mur'])
sigmaN = matN['sigma']
deltahN = matN['roughness']
Rsofto,Rhardo = R(tho,k,er0,err0,sigma0,ur0,urr0,deltah0)
Rsoftn,Rhardn = R(thn,k,erN,errN,sigmaN,urN,urrN,deltahN)
#-------... |
jtoppins/beaker | Server/bkr/server/alembic/versions/2e171e6198e6_add_data_migration_table.py | Python | gpl-2.0 | 863 | 0.005794 | # This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
"""Add data_migration table
Revision ID: 2e171e6198e6
Revises: 15d3fad... | port Column, Integer, Unicode, DateTime
def upgrade():
op.create_table('data_m | igration',
Column('id', Integer, primary_key=True),
Column('name', Unicode(255), nullable=False, unique=True),
Column('finish_time', DateTime),
mysql_engine='InnoDB')
def downgrade():
op.drop_table('data_migration')
|
nestauk/inet | inet/sources/companies_house.py | Python | mit | 1,473 | 0 | # -*- coding: utf-8 -*-
import logging
import chwrapper
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
class CompaniesHouseClient():
def __init__(self):
self._ch = chwrapper.Search()
def get_company_data(self, k, v):
"""Search companies house for the data"""
... | ompany number."""
try:
company_number = v.get('company_data')[0].get('company_number')
except IndexError as e:
logger.warn("No Company data found.", e) |
return []
if not company_number:
logger.warn("No postal code found for {}".format(k))
return []
r = self._ch.officers(company_number)
items = r.json()['items']
data = []
for item in items:
data.append(item)
return data
... |
kburts/django-playlist | django_playlist/songs/urls.py | Python | mit | 465 | 0.021505 | from django.conf.urls import patterns, url
f | rom .views import PlaylistList, PlaylistDetail, SongList, SongUpdate
urlpatterns = patterns('songs.views',
url(r'^playlists$', PlaylistList.as_view(), name='playlists_list'),
url(r'^playlists/(?P<playlist_pk>[0-9]+)/$', PlaylistDetail.as_view(),
name="playlist_detail"),
url(r'^songs$', SongList.as_view(), name='... | /(?P<song_pk>[0-9]+)/$', SongUpdate.as_view(),
name='songs_update'),
) |
robmcmullen/peppy | peppy/i18n/ar.py | Python | gpl-2.0 | 2,474 | 0.017785 | # -*- coding: utf-8 -*-
#This is generated code - do not edit
encoding = 'utf-8'
dict = {
'&About...': '&\xd8\xb9\xd9\x86...',
'&Delete Window': '&\xd8\xa7\xd8\xad\xd8\xb0\xd9\x81 \xd8\xa7\xd9\x84\xd9\x86\xd8\xa7\xd9\x81\xd8\xb0\xd8\xa9',
'&Describe Action': '&\xd8\xa3\xd9\x88\xd8\xb5\xd9\x81 \xd8\xa7\xd9\x84\xd8\xb9\x... | \xd8\xb6\xd9\x8a\xd9\x84\xd8\xa7\xd8\xaa...',
'&Revert': '&\xd8\xa5\xd8\xb3\xd8\xaa\xd8\xb1\xd8\xac\xd8\xb9',
'&Save...': '&\xd8\xad\xd9\x81\xd8\xb8...',
'&Show Toolbars': '&\xd | 8\xb9\xd8\xb1\xd8\xb6 \xd8\xb4\xd8\xb1\xd9\x8a\xd8\xb7 \xd8\xa7\xd9\x84\xd8\xa3\xd8\xaf\xd9\x88\xd8\xa7\xd8\xa9',
'&Word Count': '&\xd8\xb9\xd8\xaf \xd8\xa7\xd9\x84\xd9\x83\xd9\x84\xd9\x85\xd8\xa7\xd8\xaa',
'About this program': '\xd8\xad\xd9\x88\xd9\x92\xd9\x84 \xd9\x87\xd8\xb0\xd8\xa7 \xd8\xa7\xd9\x84\xd8\xa8\xd8\xb1... |
GiulioRossetti/ndlib | ndlib/models/compartments/NodeNumericalAttribute.py | Python | bsd-2-clause | 2,351 | 0.005104 | from ndlib.models.compartments.Compartment import Compartiment
import networkx as nx
import numpy as np
import operator
__author__ = 'Giulio Rossetti'
__license__ = "BSD-2-Clause"
__email__ = "giulio.rossetti@gmail.com"
class NodeNumericalAttribute(Compartiment):
def __init__(self, attribute, value=None, op=Non... | s__, self).__init__(kwargs)
self.__available_operators = {"==": operator.__eq__, "<": operator.__lt__,
">": operator.__gt__, "<=": operator.__le__,
| ">=": operator.__ge__, "!=": operator.__ne__,
"IN": (operator.__ge__, operator.__le__)}
self.attribute = attribute
self.attribute_range = value
self.probability = probability
self.operator = op
if self.attribute_range i... |
UltimateNate/TURPG | PyAnimationEngine.py | Python | gpl-3.0 | 2,064 | 0.009205 | # PyAnimation - Animation, in a terminal.
# Copyright (C) 2015 Nathaniel Olsen
#
# 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 ... | have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import time
import os
EngineVersion = "0.3-indev"
def clear():
os.system('clear')
# The Legacy wait for legacy or outdated programs.
def legacywait():
time.sleep( | 0.4)
def legacywait2():
time.sleep(0.2)
def legacywait3():
time.sleep(0.1)
# The new wait.
def waitpoint1():
time.sleep(0.1)
def waitpoint2():
time.sleep(0.2)
def waitpoint3():
time.sleep(0.3)
def waitpoint4():
time.sleep(0.4)
def waitpoint5():
time.sleep(0.5)
def waitpo... |
ArtezGDA/text-IO | Martijn/format.py | Python | mit | 170 | 0.058824 |
import my_data_file
d = my_data_file.my_data
print "Hello my name i | s %s and i am %d years of age and my coolnes is %d " % (d [ 'naam' ], d [ 'age' ], d ['cool | heid']) |
twm/yarrharr | yarrharr/application.py | Python | gpl-3.0 | 20,459 | 0.000978 | # Copyright © 2013, 2015, 2016, 2017, 2018, 2020, 2022 Tom Most <twm@freecog.net>
#
# 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 lat... | gh the message is
# generated by the browser and might indicate a script injection.
# See <https://github.com/cmcaine/tridactyl/issues/109> and
# <https://bugzilla.mozilla.org/show_bug.cgi?id=1267027>.
return b""
self._log.debug(
"Content Security Poli... | userAgent=", ".join(request.requestHeaders.getRawHeaders("User-Agent", [])),
report=report,
)
return b"" # Browser ignores the response.
class FallbackResource(Resource):
"""
Resource which falls back to an alternative resource tree if it doesn't
have a matching child r... |
MindPass/Code | Interface_graphique/PyQt/application/classeGestion.py | Python | gpl-3.0 | 24,892 | 0.028687 | import sqlite3
import sys
"""<Mindpass is a intelligent password manager written in Python3
that checks your mailbox for logins and passwords that you do not remember.>
Copyright (C) <2016> <Cantaluppi Thibaut, Garchery Martial, Domain Alexandre, Boulmane Yassine>
This program is free software: you can r... | pdate(requete, (nouveau_mdp , self.position +1))
print("Mdp changée en"+ nouveau_mdp)
for k in range(len(self.objet.pwds)):
if(self.objet.pwds[k].nom == nouveau_mdp):
liste_label_name =[]
for eleme | nt in self.objet.pwds[k].labels:
liste_label_name.append(element.text())
if(nouveau_mdp not in liste_label_name):
self.objet.pwds[k].label(self.site_web.text())
break
# On met à jour le groupBox de l'ancienn mdp
for k in range(len(self.objet.pwds)):
if(self.objet.pwds[k].nom == ancien_mdp):
... |
hubo1016/vlcp | vlcp/protocol/openflow/defs/openflow13.py | Python | apache-2.0 | 130,995 | 0.031612 | '''
/* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
* Junior University
* Copyright (c) 2011, 2012 Open Networking Foundation
*
* We are making the OpenFlow specification and associated documentation
* (Software) available for public use and benefit with the expectation
* that others will use, modify... | 29, #/* Controller/switch message */
)
ofp_type_reply_set = set([OFPT_ECHO_REPLY, OFPT_FEATURES_REPLY, OFPT_GET_CONFIG_REPLY, OFPT_MULTIPART_REPLY, OFPT_BARRIER_REPLY, OFPT_QUEUE_GET_CONFIG_REPLY, OFPT_ROLE_REPLY, OFPT_GET_ASYNC_REPLY])
ofp_type_asyncmessage_set = set([OFPT_PACKET_IN, OFPT_FLOW_R... | OFP13_VERSION
ofp_msg = nstruct(name = 'ofp_msg',
base = common.ofp_msg_mutable,
criteria = lambda x: x.header.version == OFP_VERSION,
init = packvalue(OFP_VERSION, 'header', 'version'),
classifyby = (OFP_VERSION,),
... |
TomAugspurger/pandas | pandas/tests/base/test_conversion.py | Python | bsd-3-clause | 14,519 | 0.000551 | import numpy as np
import pytest
from pandas.core.dtypes.common import is_datetime64_dtype, is_timedelta64_dtype
from pandas.core.dtypes.dtypes import DatetimeTZDtype
import pandas as pd
from pandas import CategoricalIndex, Series, Timedelta, Timestamp
import pandas._testing as tm
from pandas.core.arrays import (
... |
(np.array([0, 1], dtype=np.int64), np.ndarray, "int64"),
(np.array(["a", "b"]), np.ndarray, "object"),
(pd.Categorical(["a", "b"]), pd.Categorical, "category"),
| (
pd.DatetimeIndex(["2017", "2018"], tz="US/Central"),
DatetimeArray,
"datetime64[ns, US/Central]",
),
(
pd.PeriodIndex([2018, 2019], freq="A"),
PeriodArray,
pd.core.dtypes.dtypes.PeriodDtype("A-DEC"),
),
(pd.Interva... |
Onager/plaso | tests/cli/helpers/storage_file.py | Python | apache-2.0 | 1,615 | 0.004334 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the storage file CLI arguments helper."""
import argparse
import unittest
from plaso.cli import tools
from plaso.cli.helpers i | mport stor | age_file
from plaso.lib import errors
from tests.cli import test_lib as cli_test_lib
class StorageFileArgumentsHelperTest(cli_test_lib.CLIToolTestCase):
"""Tests for the storage file CLI arguments helper."""
# pylint: disable=no-member,protected-access
_EXPECTED_OUTPUT = """\
usage: cli_helper.py [STORAGE_FI... |
raphaeldore/analyzr | analyzr/utils/file.py | Python | mit | 2,428 | 0.002471 | import errno
import os
import sys
from contextlib import contextmanager
@contextmanager
def open_with_error(filename: str, mode: str = "r", encoding: str = "utf-8"):
try:
f = open(filename, mode=mode, encoding=encoding)
except IOError as err:
yield None, err
else:
try:
... | = os.path.splitext(base_filename)
min_nbr, max_nbr = 1, 2
while os.path.isfile(
os.path.join(folder, pattern.format(filename=filename, nb=str(max_nbr), ext=file_extension)) | ):
min_nbr = max_nbr
max_nbr *= 2
while max_nbr != min_nbr + 1:
pivot = int((max_nbr + min_nbr) / 2)
if os.path.isfile(
os.path.join(folder, pattern.format(filename=filename, nb=str(pivot), ext=file_extension))):
min_nbr = pivot
else:
... |
mothyjohn/VELA-CLARA-Controllers | General/enums/bin/Release/test.py | Python | gpl-3.0 | 307 | 0.022801 | import sys,os
import numpy as np
#os.envir | on["EPICS_CA_AUTO_ADDR_LIST"] = "NO"
#os.environ["EPICS_CA_ADDR_LIST"] = "192.168.82.10"
| #os.environ["EPICS_CA_MAX_ARRAY_BYTES"] = "10000000000"
import velaINJMagnetControl as VIMC
a = VIMC.velaINJMagnetController(True,False)
print( np.array(a.getQuadNames()))
|
franek/weboob | modules/youtube/test.py | Python | agpl-3.0 | 1,394 | 0.002152 | # -*- coding: utf-8 -*-
# Copyright(C) 2010-2011 Romain Bignon
#
# This file is part of weboob.
#
# weboob 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... | OUT 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 GNU Affero General Public License
# along with weboo | b. If not, see <http://www.gnu.org/licenses/>.
from weboob.tools.test import BackendTest
from weboob.capabilities.video import BaseVideo
class YoutubeTest(BackendTest):
BACKEND = 'youtube'
def test_search(self):
l = list(self.backend.search_videos('lol'))
self.assertTrue(len(l) > 0)
... |
1upon0/rfid-auth-system | GUI/printer/Pillow-2.7.0/Tests/test_lib_pack.py | Python | apache-2.0 | 5,896 | 0 | from helper import unittest, PillowTestCase, py3
from PIL import Image
class TestLibPack(PillowTestCase):
def pack(self):
pass # not yet
def test_pack(self):
def pack(mode, rawmode):
if len(mode) == 1:
im = Image.new(mode, (1, 1), 1)
else:
... | GB;16", 2), (8, 64, 0))
self.assertEqual(unpack("RGB", "BGR;16", 2), (0, 64, 8))
self.assertEqual(unpack("RGB", "RGB;4B", 2), (17, 0, 34))
self.assertEqual(unpack("RGB", "RGBX", 4), (1, 2, 3))
self.assertEqual(unpack("RGB", "BGRX", 4), (3, 2, 1))
self.assertEqual(unpack("RGB", "... | assertEqual(unpack("RGBA", "RGBA", 4), (1, 2, 3, 4))
self.assertEqual(unpack("RGBA", "BGRA", 4), (3, 2, 1, 4))
self.assertEqual(unpack("RGBA", "ARGB", 4), (2, 3, 4, 1))
self.assertEqual(unpack("RGBA", "ABGR", 4), (4, 3, 2, 1))
self.assertEqual(unpack("RGBA", "RGBA;15", 2), (8, 131, 0, 0)... |
brownian/frescobaldi | frescobaldi_app/lydocument.py | Python | gpl-2.0 | 8,870 | 0.000676 | # This file is part of the Frescobaldi project, http://www.frescobaldi.org/
#
# Copyright (c) 2013 - 2014 by Wilbert Berendsen
#
# 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
... | r(index)
@property
def document(self):
"""Return the QTextDocument we were instantiated with."""
retu | rn self._d
@property
def filename(self):
"""Return the document's local filename, if any."""
return self.document.url().toLocalFile()
def plaintext(self):
"""The document contents as a plain text string."""
return self._d.toPlainText()
def setplaintext(self, text):
... |
yangdw/PyRepo | src/annotation/haven/haven/autoreload.py | Python | mit | 5,900 | 0.002712 | # Autoreloading launcher.
# Borrowed from Peter Hunt and the CherryPy project (http://www.cherrypy.org).
# Some taken from Ian Bicking's Paste (http://pythonpaste.org/).
#
# Portions copyright (c) 2004, CherryPy Team (team@cherrypy.org)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with ... | n
# and/or other materials provided with the distribution.
# * Neither the name of the CherryPy Team nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT... | IMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE G... |
kidmose/python-course | mandelbrot/tests/__init__.py | Python | mit | 674 | 0.004451 | """
Test suite for module.
Holds constants and methods shared among multiple tests.
See submodules for individual tests.
"""
import os
import shutil
PARAM_LIST = {
| 'pre_min': 100,
'pre_max': 101,
'Pre': 10,
'pim_min': -101,
'pim_max': -100,
'Pim': 14,
'T': 16,
'I': 20,
}
OUTPUT_DIR = "test-output"
def purge_output_dir(p | ath=OUTPUT_DIR):
delete_output_dir(path=path)
if os.path.exists(path):
raise Exception("Failed to removed test output folder")
os.makedirs(path)
def delete_output_dir(path=OUTPUT_DIR):
if os.path.isfile(path):
os.remove(path)
if os.path.isdir(path):
shutil.rmtree(path)
|
toddsifleet/equals | equals/constraints/containing.py | Python | mit | 440 | 0 | from .base import Base
cl | ass Containing(Base):
_description = 'containing: {}'
def _check(self, value):
# This will check list like objects
for v in self.args:
if v not in value:
return False
# This will check dictionary like objects
for k, v in self.kwargs.items():
... | return True
|
defance/edx-platform | common/djangoapps/enrollment/management/tests/test_enroll_user_in_course.py | Python | agpl-3.0 | 2,563 | 0.00039 | """ Test the change_enrollment command line script."""
import ddt
import unittest
from uuid import uuid4
from django.conf import settings
from django.core.management import call_command
from django.core.management.base import CommandError
from enrollment.api import get_enrollment
from student.tests.factories import ... | n_course | ',
*command_args
)
# Second run does not impact the first run (i.e., the
# user is still enrolled, no exception was raised, etc)
user_enroll = get_enrollment(self.username, self.course_id)
self.assertTrue(user_enroll['is_active'])
@ddt.data(['--email', '... |
oinopion/pipeye | pipeye/urls.py | Python | bsd-2-clause | 820 | 0.004878 | from django.conf.urls import patterns, include, url
| from django.core.urlresolvers import reverse_lazy
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'pipeye.views.home', name='home'),
url(r'^watches/', include('pipeye.watches.urls')),
url(r'^packages/', include('pipeye.packages.urls')),
url(r'^accounts/', in... | backend>\w+)/$',
'social_auth.views.complete', name='login_complete'),
url(r'^logout/$', 'django.contrib.auth.views.logout',
{'next_page': reverse_lazy('home')}, name='logout'),
# admin
url(r'^admin/', include(admin.site.urls)),
)
|
siliconchris1973/fairytale | RASPI-stuff/python-codeline/fairytale/main.py | Python | apache-2.0 | 3,954 | 0.006576 | #!/usr/bin/env python3
# encoding: utf-8
"""
main.py
The entry point for the book reader application.
"""
__version_info__ = (0, 0, 1)
__version__ = '.'.join(map(str, __version_info__))
__author__ = "c.guenther@mac.com"
import time
import sqlite3
import pdb
import signal
import sys, os
import rfid
import config
i... | is is where we look for new RFID cards on the RFID reader. If one is
| present and different from the book that's currently playing, in which case:
1. Stop playback of the current book if one is playing
2. Start playing
"""
while True:
if self.player.is_playing():
self.on_playing()
elif self.player.finished... |
Newterm/florence | editor/toolkit.py | Python | gpl-2.0 | 16,795 | 0.050491 | #!/usr/bin/python
import cairo
import gtk
import copy
def abs(x):
if x < 0:
return -x
else:
return x
class object:
def __init__(self, name, x, y, w, h):
self.name = name
self.x = x
self.y = y
self.w = w
self.h = h
# huddung vector
self.dx = 0
self.dy = 0
# 0 = normal ; 1 = active ; 2 = select... | ctx.rectangle(self.x+self.w-10, self.y, 10, 10)
crctx.fill()
crctx.rectangle(self.x, self.y+self.h-10, 10, 10)
crctx.fill()
crctx.rectangle(self.x+self.w-10, self.y+self.h-10, 10, 10)
crctx.fill()
#edge anchors
crctx.rectangle(self.x, self.y+(self.h/2)-5, 10, 10)
crctx.fill()
crctx.rectangle(... | f.w/2)-5, self.y, 10, 10)
crctx.fill()
crctx.rectangle(self.x+(self.w/2)-5, self.y+self.h-10, 10, 10)
crctx.fill()
else:
crctx.set_source_rgba(0, 0, 0, 1)
crctx.rectangle(self.x, self.y, self.w, self.h)
crctx.stroke()
xbearing, ybearing, width, height, xadvance, yadvance = crctx.text_extents ( sel... |
rhdedgar/openshift-tools | openshift_tools/monitoring/ocutil.py | Python | apache-2.0 | 4,378 | 0.001827 | #!/usr/bin/env python
# vim: expandtab:tabstop=4:shiftwidth=4
"""
Interface to OpenShift oc command
"""
#
# Copyright 2015 Red Hat Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License ... | in(random.choice(string.ascii_uppercase + string.digits) fo | r _ in range(7))
)
shutil.copy(self.config_file, file_name)
atexit.register(cleanup_file, file_name)
self.config_file = file_name
def _run_cmd(self, cmd, base_cmd='oc', ):
""" Actually execute the command """
cmd = " ".join([base_cmd, '--config', self.config_file, '... |
woodymit/millstone | genome_designer/pipeline/variant_calling/freebayes.py | Python | mit | 10,343 | 0.002127 | """Wrapper for running Freebayes.
"""
import collections
import errno
import fileinput
import glob
import tempfile
import os
import shutil
import subprocess
import vcf
from celery import task
from django.conf import settings
from main.models import Dataset
from main.model_utils import get_dataset_with_type
from pipe... | tal_obs = float(sum(sample['AO']) + sample['RO'])
if total_obs > 0:
af = sum([float(ao) / total_obs for ao in sample['AO']])
# if a single alternate allele:
else:
total_obs = float(sample['AO'] + sample... | af = float(sample['AO']) / total_obs
except:
af = 0.0
# new namedtuple with the additional format field
CallData = collections.namedtuple(
'CallData',
sample.data._fields+('AF',))
... |
nyarasha/firemix | plugins/radial_wipe.py | Python | gpl-3.0 | 1,645 | 0.001824 | # This file is part of Firemix.
#
# Copyright 2013-2016 Jonathan Evans <jon@craftyjon.com>
#
# Firemix 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.
#
# Firemix 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.
#
# Yo... | h
from lib.transition import Transition
from lib.buffer_utils import BufferUtils
class RadialWipe(Transition):
"""
Implements a radial wipe (Iris) transition
"""
def __init__(self, app):
Transition.__init__(self, app)
def __str__(self):
return "Radial Wipe"
def reset(self):... |
kuenishi/vHut | src/admin_server/vhut/agent/vhut/vhutac.py | Python | gpl-2.0 | 12,562 | 0.006064 | # -*- coding: utf-8 -*-
'''
Copyright 2011 NTT Software Corporation.
All Rights Reserved.
@author NTT Software Corporation.
@version 1.0.0
$Date: 2010-08-31 09:54:14 +0900 (火, 31 8 2010) $
$Revision: 435 $
$Author: NTT Software Corporation. $
'''
import os
import sys
from optparse import OptionParser
f... | ('--mac', action='store', type='string', dest='mac', help="instance's MAC address")
psr.add_option('--publicip', action='store', type='string', des | t='publicip', help='public IP address binding by NAT')
psr.add_option('--privateip', action='store', type='string', dest='privateip', help='private IP address binding by NAT')
psr.add_option('--bridge', action='store', type='string', dest='bridge', help='instance bridge prefix name')
psr.add_option('--fi... |
pburdet/hyperspy | hyperspy/_signals/eels.py | Python | gpl-3.0 | 48,505 | 0.000309 | # -*- coding: utf-8 -*-
# Copyright 2007-2011 The HyperSpy developers
#
# This file is part of HyperSpy.
#
# HyperSpy 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... | shift is not computed
and set to nan.
Returns
-------
zlpc : Signal subclass
The estimated position of the maximum of the ZLP peak.
Notes
-----
This function only works when the zero-loss peak is the most
intense feature in the spectrum.... | ively use `estimate_shift1D`.
See Also
--------
estimate_shift1D, align_zero_loss_peak
"""
self._check_signal_dimension_equals_one()
self._check_navigation_mask(mask)
zlpc = self.valuemax(-1)
if self.axes_manager.navigation_dimension == 1:
zl... |
nadrees/PyRosalind | Python Village/INI4.py | Python | unlicense | 243 | 0.004115 | __author__ = 'Nathen'
# | get min and max bounds
| a, b = map(lambda i: int(i), input('Nums: ').split(' '))
# create generator of all odd nums
nums = [x for x in range(a, b + 1) if x % 2 == 1]
# sum nums
ans = sum(nums)
# print answer
print(ans) |
rohanraja/cgt_distributed | examples/char.py | Python | mit | 12,474 | 0.010742 | """
A nearly direct translation of Andrej's code
https://github.com/karpathy/char-rnn
"""
from __future__ import division
import cgt
from cgt import nn, utils, profiler
import numpy as np, numpy.random as nr
import os.path as osp
import argparse
from time import time
from StringIO import StringIO
from param_collection... | grad=np.zeros_like(theta)+1e-6, scratch=np.empty_like(theta),
step_size=step_size, decay_rate=decay_rate, count=0)
class Loader(object):
def __init__(self, data_dir, size_batch, n_unroll, split_fractions):
input_file = osp.join(data_dir,"input.txt")
preproc_file = osp.join(data_dir, "p... | npz")
run_preproc = not osp.exists(preproc_file) or osp.getmtime(input_file) > osp.getmtime(preproc_file)
if run_preproc:
text_to_tensor(input_file, preproc_file)
data_file = np.load(preproc_file)
self.char2ind = {char:ind for (ind,char) in enumerate(data_file["chars"])}
... |
nnic/home-assistant | homeassistant/components/verisure.py | Python | mit | 5,074 | 0 | """
components.verisure
~~~~~~~~~~~~~~~~~~~
Provides support for verisure components.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/verisure/
"""
import logging
import time
from datetime import timedelta
from homeassistant import bootstrap
from homeas... | True
SHOW_SMARTPLUGS = True
SHOW_LOCKS = True
SHOW_MOUSEDETECTION = True
CODE_DIGITS = 4
# if wrong password was given don't try again
WRONG_PASSWORD_GIVEN = False
MIN_TIME_BETWEEN_REQUESTS = timedelta(seconds=1)
| def setup(hass, config):
""" Setup the Verisure component. """
if not validate_config(config,
{DOMAIN: [CONF_USERNAME, CONF_PASSWORD]},
_LOGGER):
return False
from verisure import MyPages, LoginError, Error
global SHOW_THERMOMETERS, SHOW_H... |
zhkzyth/a-super-fast-crawler | crawler.py | Python | mit | 9,133 | 0.00478 | #!/usr/bin/env python
# encoding: utf-8
"""
crawler.py
~~~~~~~~~~~~~
主要模块,爬虫的具体实现。
"""
import re
import time
import logging
import threading
import traceback
from hashlib import md5
from bs4 import BeautifulSoup
from datetime import datetime
from collections import deque
from locale import getdefaultlocale
from urlpar... | :1.只获取http或https网页;2.保证每个链接只访问一次
url, pageSource = webPage.getDatas()
hrefs = self._getAllHrefsFromPage(url, pageSource)
for href in hrefs:
if self._isHttpOrHttpsProtocol(href):
if not self._isHrefRepeated(href):
self.unvisitedHrefs.append(href)
... | mPage(self, url, pageSource):
'''解析html源码,获取页面所有链接。返回链接列表'''
hrefs = []
soup = BeautifulSoup(pageSource)
results = soup.find_all('a',href=True)
for a in results:
#必须将链接encode为utf8, 因为中文文件链接如 http://aa.com/文件.pdf
#在bs4中不会被自动url编码,从而导致encodeException
... |
kamyu104/GoogleCodeJam-2014 | Round 1B/the-repeater.py | Python | mit | 2,367 | 0.00169 | # Copyright (c) 2016 kamyu. All rights reserved.
#
# Google Code Jam 2014 Round 1B - Problem A. The Repeater
# https://code.google.com/codejam/contest/2994486/dashboard#s=p0
#
# Time: O(X * N), N is the number | of strings,
# X is the number of characters in the frequency string.
# Space: O(X * N)
#
from random import randint
def find_kth_largest(nums, k):
def partition_around_pivot(left, right, pivot_idx, nums):
pivot_value = nums[pivot_idx]
new_pivot_idx = left
nums[pivot_idx], ... | t):
if nums[i] > pivot_value:
nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i]
new_pivot_idx += 1
nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right]
return new_pivot_idx
left, right = 0, len(nums) - 1
while lef... |
ketancmaheshwari/hello-goog | src/python/collectionsexample.py | Python | apache-2.0 | 718 | 0.001393 | #!/bin/env python
import itertools
import collections
def read_table(filename):
with open(filename) as fp:
| header = next(fp).split()
rows = [line.split()[1:] for line in fp if line.strip()]
columns = zip(*rows)
data = dict(zip(header, columns))
return data
table = read_table("../../data/colldata.txt")
pots = sorted(table)
alphabet = "+-?"
for num in range(2, len(table) + 1):
for group in... | |
fxia22/ASM_xf | PythonD/site_python/Numeric/MA/__init__.py | Python | gpl-2.0 | 119 | 0 | f | rom MA_version import version as __version__
from MA_version import version_info as __version_info__
from MA impo | rt *
|
BdEINSALyon/resa | permissions/views.py | Python | gpl-3.0 | 589 | 0.005093 | import requests
from django.shortcuts import render
# Create your views here.
from django.template.response import Templ | ateResponse
from account.models import OAuthToken
def list_azure_groups(request):
token = OAuthToken.objects.filter(user=request.user, service__name='microsoft').last()
if token is None:
return ''
r = requests.get('https://graph.microsoft.com/v1.0/groups',
headers={'Auth | orization': 'Bearer {}'.format(token.auth_token)})
return TemplateResponse(request, 'permissions/azure.html', context={'groups': r.json()['value']})
|
OWASP/django-DefectDojo | dojo/admin.py | Python | bsd-3-clause | 103 | 0 | from auditlog.models import LogEntry
from django.contrib import admin
admin.site.unregister(Log | Entry) | |
wkentaro/fcn | fcn/external/fcn.berkeleyvision.org/nyud-fcn32s-hha/solve.py | Python | mit | 616 | 0.001623 | import caffe
import surgery, score
import numpy as np
import os
import setproctitle
setproctitle.setproctitle(os.path.basename(os.getcwd()))
weights = '../ilsvrc-nets/vgg16-fcn.caffemodel'
# init
caffe.set_device(int(sys.argv[1]))
caffe.set_mode_gpu()
solver = caffe.SGDSolver('solver.prototxt')
solver.net.copy_fro... | np.loadtxt('../data/nyud/test.txt', dtype=st | r)
for _ in range(50):
solver.step(2000)
score.seg_tests(solver, False, val, layer='score')
|
kubeflow/pipelines | backend/api/python_http_client/test/test_api_run_storage_state.py | Python | apache-2.0 | 1,436 | 0.003482 | # coding: utf-8
"""
Kubeflow Pipelines API
This file contains REST API specification for Kubeflow Pipelines. The file is autogenerated from the swagger definition.
Contact: kubeflow-pipelines@google.com
Generated by: https://openapi-generator.tech
"""
from __future__ import ab | solute_import
import unittest
import datetime
import kfp_server_api
from kfp_server_api.models.api_run_storage_state import ApiRunStorageState # noqa: E501
from kfp_server_api.rest import ApiException
class TestApiRunStorageState(unittest.TestCase):
"""ApiRunStorageState unit test stubs"""
def setUp(self):... | self):
pass
def make_instance(self, include_optional):
"""Test ApiRunStorageState
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included """
# model = kfp_server_api.models.api_r... |
bitmazk/django-unshorten | unshorten/tests/rate_limit_tests.py | Python | mit | 1,841 | 0 | """Tests for the simple rate limiting classes of the ``unshorten`` app."""
from mock import Mock
from django.conf import settings
from django.test import TestCase
from mixer.backend.django import mixer
from ..backend im | port RateLimit
from ..models import APICallDayHistory
class SimpleRateLimitTestCase(TestCase):
"""Tests for the ``SimpleRateLimit`` class."""
| longMessage = True
def setUp(self):
self.history = mixer.blend('unshorten.APICallDayHistory',
amount_api_calls=2500)
self.request = Mock(user=self.history.user)
def test_is_rate_limit_exceeded(self):
"""Test for the ``is_rate_limit_exceeded`` meth... |
radumas/qgis2web | leafletScriptStrings.py | Python | gpl-2.0 | 20,814 | 0.002114 | from utils import scaleToZoom
def jsonScript(layer):
json = """
<script src="data/json_{layer}.js\"></script>""".format(layer=layer)
return json
def scaleDependentLayerScript(layer, layerName):
min = layer.minimumScale()
max = layer.maximumScale()
scaleDependentLayer = """
if (map.ge... | ToLayer}
}}
}});
| layerOrder[layerOrder.length] = json_{safeLayerName}JSON;""".format(safeLayerName=safeLayerName, pointToLayer=pointToLayer)
return jsonPoint
def clusterScript(safeLayerName):
cluster = """
var cluster_group{safeLayerName}JSON = new L.MarkerClusterGroup({{showCoverageOnHover: false}});
cluster_... |
xueyaodeai/DjangoWebsite | superlists/wsgi.py | Python | mit | 398 | 0 | """
WSGI c | onfig for superlists project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MO... | _wsgi_application()
|
jnewland/home-assistant | homeassistant/components/gearbest/__init__.py | Python | apache-2.0 | 30 | 0 | """The gearbest com | ponent." | ""
|
voutilad/courtlistener | cl/search/migrations/0033_auto_20160819_1214.py | Python | agpl-3.0 | 473 | 0.002114 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('search', '0032 | _auto_20160819_1209'),
]
operations = [
migrations.AlterField(
model_na | me='docket',
name='nature_of_suit',
field=models.CharField(help_text=b'The nature of suit code from PACER.', max_length=1000, blank=True),
),
]
|
intel/ipmctl | BaseTools/Source/Python/Ecc/Database.py | Python | bsd-3-clause | 14,225 | 0.005413 | ## @file
# This file is used to create a database used by ECC tool
#
# Copyright (c) 2007 - 2014, Intel Corporation. All rights reserved.<BR>
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. Th... | self.TblFdf.Create() |
#
# Init each table's ID
#
self.TblDataModel.InitID()
self.TblFile.InitID()
self.TblFunction.InitID()
self.TblPcd.InitID()
self.TblReport.InitID()
self.TblInf.InitID()
self.TblDec.InitID()
self.TblDsc.InitID()
... |
guilhermerc/fournir-au-public | tools/fann_input_norm.py | Python | gpl-3.0 | 2,101 | 0.005236 | #! /usr/bin/env python3
import sys
import csv
import menu_map
import datetime
db_input = sys.argv[1]
def normalize_elem(min_, max_, value):
'''DESCUBRA'''
return (value - min_)/(max_ - min_) - 0.5
def normalize(array, min_, max_):
'''DESCUBRA'''
for i in range(0, len(array)):
array[i] = norm... | []
target = []
traindb = csv.reader(db_in, delimiter='\t', quotechar='"')
for row in traindb:
date = row[0].split('-')
date_info = datetime.date(int(date[0]), int(date[1]), int(date[2])).timetuple()
day_of_the_week.append(float(date_info.tm_wday))
month.append(float(date_info... | nd(float(row[4]))
rain_acc.append(float(row[5]))
nutri_week.append(float(row[6]))
vacation.append(float(row[7]))
strike.append(float(row[8]))
total_enrolled.append(float(row[9]))
target.append(float(row[3]))
# normalizing values into -0.5 - 0.5 range
day_of_the_we... |
sagnik17/Movie-Recommendation-System | mrs/recsys/cf.py | Python | gpl-3.0 | 387 | 0.005168 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# create a class for correlation matrix and other class to find out simi | lar users who have rated a particular movie w.r.t. a particular user based on correlation
import numpy as np
import pandas as pd
class Correlation:
| """
"""
def pearson(self, rating_matrix):
return pd.DataFrame(rating_matrix.T).corr().as_matrix()
|
vliangzy/sillypool | sillypool/spider/parser/xpath.py | Python | apache-2.0 | 2,885 | 0.000365 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2017 liangzy
#
# 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... | '天津', '广西', '内蒙', '西藏',
'新疆', '宁夏', '香港', '澳门']
for area in china_area:
if area in country:
return "中 | 国"
return country
|
Trust-Code/trust-addons | trust_sale/models/__init__.py | Python | agpl-3.0 | 1,413 | 0 | # -*- encoding: utf-8 -*-
###############################################################################
# #
# Copyright (C) 2015 Trustcode - www.trustcode.com.br #
# ... | #
# #
# 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. ... | #
# 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, see <http://www.gnu.org/licen... |
autosportlabs/RaceCapture_App | spacer.py | Python | gpl-3.0 | 1,123 | 0.005343 | #
# Race Capture App
#
# Copyright (C) 2014-2017 Autosport Labs
#
# This file is part of the Race Capture App
#
# This 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 ... | later version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See the GNU General Public License for | more details. You should
# have received a copy of the GNU General Public License along with
# this code. If not, see <http://www.gnu.org/licenses/>.
from kivy.uix.widget import Widget
class HorizontalSpacer(Widget):
def __init__(self, **kwargs):
super(HorizontalSpacer, self).__init__( **kwargs)
s... |
excelly/xpy-ml | omop/simu_flow.py | Python | apache-2.0 | 2,109 | 0.009483 | import sys
import os
import shutil as sh
import logging as log
import multiprocessing as mp
import ex.util as eu
from OMOP import OMOP
import base
eu.InitLog(log.INFO)
dat_dest="D:/Documents/DataSet/omop/simulation/"
# dat_dest="~/h/data/omop/simulation/"
def DoTask(configs):
modifier=configs[0]
folder= | base.Simulate(
modifier, validation=True, n_drug=10, n_cond=10, n_person=500,
cond_alt=configs[1], ob_alt=configs[2], drug_alt=configs[3],
dexposure_alt=configs[4],doutcome_alt=configs[5],ind_alt=configs[6],
no_simu=True)
ds=OMOP(modifier, f | older)
ds.CreateDB()
ds.OrderDB()
ds.IndexDB()
ds.JoinDrugCond(simu=True)
ds.ExpandCondOccur(simu=True)
ds.GenCountTable()
return(folder)
if __name__ == '__main__':
if len(sys.argv) > 1 and sys.argv[1].startswith('s'):
log.info('''OMOP Single threaded simulation.''')
p... |
nagaozen/my-os-customizations | home/nagaozen/.gnome2/gedit/plugins/better-defaults/__init__.py | Python | gpl-3.0 | 6,370 | 0.027002 | # -*- coding: utf-8 -*-
# Gedit Better Defaults plugin
# Copyright (C) 2017 Fabio Zendhi Nagao
#
# 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 o... | ue)
view.set_data("vscrolling_helper", (0.0, 0.0))
size_allocate_id = view.connect("size-allocate", self.on_size_allocate)
view.set_data("on_size_allocate_id", size_allocate_id)
va = view.get_vadjustment()
value_change_id = va.connect("value_changed", self.on_value_changed)
view.set_data("on_value_change... | ("on_value_changed_id") )
view.disconnect( view.get_data("on_size_allocate_id") )
view.set_smart_home_end(False)
def activate_doc(self, doc):
save_id = doc.connect("save", self.on_document_save)
doc.set_data("on_save_id", save_id)
def deactivate_doc(self, doc):
doc.disconnect( view.get_data("on_save_id"... |
TemosEngenharia/RPI-IO | RPi_IO/rpi_io.py | Python | agpl-3.0 | 6,968 | 0.004167 | # -*- coding: utf-8 -*-
import RPi.GPIO as GPIO
from models import session
from models import Device
from models import Module
from models import Event_Log
from time import sleep
from sys import stdout
# Modules pins and description
M1A = session.query(Module).filter(Module.name == 'M1A').first()
M1B = session.query(M... | le).filter(Module.name == 'M6C').first()
M7A = session.query(Module).filter(Module.name == 'M7A').first()
M7B = | session.query(Module).filter(Module.name == 'M7B').first()
M7C = session.query(Module).filter(Module.name == 'M7C').first()
# Statup inputs BCM pin
input_pins = [0, 1, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25]
# Statup outputs BCM pin
output_pins = [26, 27]
def main():
... |
python-xlib/python-xlib | examples/xfixes-selection-notify.py | Python | lgpl-2.1 | 2,764 | 0.002894 | #!/usr/bin/python3
#
# examples/xfixes-selection-notify.py -- demonstrate the XFIXES extension
# SelectionNotify event.
#
# Copyright (C) 2019
# Tony Crisci <tony@dubstepdish.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public Licen... | on 2/3 compatibility.
from __future__ import print_function
import sys
import os
import time
# Change path so we find Xlib
sys.path.append(os.path.join | (os.path.dirname(__file__), '..'))
from Xlib.display import Display
from Xlib.ext import xfixes
def main(argv):
if len(sys.argv) != 2:
sys.exit('usage: {0} SELECTION\n\n'
'SELECTION is typically PRIMARY, SECONDARY or CLIPBOARD.\n'
.format(sys.argv[0]))
display = Disp... |
qrkourier/ansible | lib/ansible/plugins/action/dellos6.py | Python | gpl-3.0 | 4,351 | 0.001379 | # 2016 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible is distrib... | . If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import sys
import copy
from ansible import constants as C
from ansible.plugins.action.normal import ActionM | odule as _ActionModule
from ansible.module_utils.six import iteritems
from ansible.module_utils.dellos6 import dellos6_argument_spec
from ansible.module_utils.basic import AnsibleFallbackNotFound
try:
from __main__ import display
except ImportError:
from ansible.utils.display import Display
display = Displ... |
melvinodsa/odsatransform | Code/Test_Reverse_Transform.py | Python | apache-2.0 | 2,316 | 0.007772 | ## @file Test_Reverse_Transform.py
#
# This script file has simple implementation the reverse odsa transform algorithm
## reverse_jumps function
#
# make reverse jumps to the elloborateed output
def reverse_jumps(letter, index, input_text):
output = input_text
for x in xrange(0, len(letter)):
output =... | in(output))
fo.close()
inSize += len(output)
outSize += len( | letter_map)+len(letter_transform)+len(index_map)+len(index_transform)
len_letter_map += len(letter_map)
print 'Input size =', inSize, ' bytes.'
print 'Output size =', outSize, ' bytes.'
print 'Actual file size =', ((outSize*2)+len_letter_map+4), ' bytes'
print 'Efficency =', (100 - (outSize)*100/inSize), '%'
pr... |
xolox/python-coloredlogs | coloredlogs/syslog.py | Python | mit | 11,849 | 0.001772 | # Easy to use system logging for Python's logging module.
#
# Author: Peter Odding <peter@peterodding.com>
# Last Change: December 10, 2020
# URL: https://coloredlogs.readthedocs.io
"""
Easy to use UNIX system logging for Python's :mod:`logging` module.
Admittedly system logging has little to do with colored terminal... | ~coloredlogs.level_to_number()`.
:returns: A :class:`~logging.handlers.SysLogHandler` object or :data:`None` (if the
system logging daemon is unavailable).
The process of connecting to the system logging daemon goes as follows:
- The following two socke | t types are tried (in decreasing preference):
1. :data:`~socket.SOCK_RAW` avoids truncation of log messages but may
not be supported.
2. :data:`~socket.SOCK_STREAM` (TCP) supports longer messages than the
default (which is UDP).
"""
if not address:
address = find_syslo... |
hying-caritas/ibsuite | ibpy/ibpy/image.py | Python | gpl-2.0 | 12,386 | 0.00549 | #
# Copyright 2008 Huang Ying <huang.ying.caritas@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
import... | for i in range(0, len(rows) - 2, 2):
inkh = rows[i+1] - rows[i]
ninkh = rows[i+3] - rows[i+2]
nimg.paste(img.crop((left, rows[i], right, rows[i+1])), (0, cy))
cy = cy + inkh
if inkh < minh_ink or ninkh < minh_ink:
eh = minh_empty
... | mg.paste(img.crop((left, rows[-2], right, rows[-1])), (0, cy))
return pimg_ref.derive(nimg)
class ColumnCondense(object):
def __init__(self, config):
object.__init__(self)
self.unpaper_keep_size = config.unpaper_keep_size
def convert(self, pimg_ref, out_file_name = None):
img = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.