repo_name
stringlengths
5
104
path
stringlengths
4
248
content
stringlengths
102
99.9k
alxgu/ansible
lib/ansible/modules/cloud/amazon/kinesis_stream.py
#!/usr/bin/python # Copyright: Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], ...
tsheasha/fullerite
src/diamond/collectors/mongodb/test/testmongodb.py
#!/usr/bin/python # coding=utf-8 ################################################################################ from test import CollectorTestCase from test import get_collector_config from test import unittest from test import run_only from mock import MagicMock from mock import patch from mock import call from di...
ChopChopKodi/pelisalacarta
python/main-classic/lib/atom/service.py
#!/usr/bin/python # # Copyright (C) 2006, 2007, 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
HopeFOAM/HopeFOAM
ThirdParty-0.1/ParaView-5.0.1/VTK/Examples/ImageProcessing/Python/ImageInteractor.py
#!/usr/bin/env python # This example shows how to use the InteractorStyleImage and add your # own event handling. The InteractorStyleImage is a special # interactor designed to be used with vtkImageActor in a rendering # window context. It forces the camera to stay perpendicular to the # x-y plane. import vtk from v...
yland/coala
tests/coalaDbusTest.py
import unittest from unittest.case import SkipTest try: from coalib import coala_dbus from gi.repository import GLib except ImportError: raise SkipTest("python-gi or python-dbus not installed") class GlibMainLoopTest: @staticmethod def run(): raise AssertionError class coalaDbusTest(un...
jennifer0703/robotframework-selenium2library
src/Selenium2Library/keywords/_selectelement.py
from selenium.webdriver.support.ui import Select from keywordgroup import KeywordGroup class _SelectElementKeywords(KeywordGroup): # Public def get_list_items(self, locator): """Returns the values in the select list identified by `locator`. Select list keywords work on both lists and combo b...
andreaso/ansible
lib/ansible/playbook/playbook_include.py
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # 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) an...
MicroTrustRepos/microkernel
src/l4/pkg/python/contrib/Doc/includes/email-unpack.py
#!/usr/bin/env python """Unpack a MIME message into a directory of files.""" import os import sys import email import errno import mimetypes from optparse import OptionParser def main(): parser = OptionParser(usage="""\ Unpack a MIME message into a directory of files. Usage: %prog [options] msgfile """) p...
aronparsons/spacewalk
client/rhel/rhnlib/test/10-tempfile.py
#!/usr/bin/python # # Test for tempfile creation # Use lsof to see how many open files we have # import sys import os import glob sys.path.append('..') from rhn.SmartIO import _tempfile def t(): f = _tempfile() for i in range(1024): f.write(("%s" % (i % 10)) * 1023 + "\n") f.seek(0, 2) assert...
vikasraunak/mptcp-1
src/config-store/bindings/modulegen__gcc_LP64.py
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers import pybindgen.settings import warnings class ErrorHandler(pybindgen.settings.ErrorHandler): def handle_error(self, wrapper, exception, traceback_): warnings.warn("exception %r in wrapper %s" % (exception, wrapper)) ...
bjolivot/ansible
lib/ansible/modules/notification/grove.py
#!/usr/bin/python # -*- coding: utf-8 -*- # # 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. ...
indictranstech/erpnext
erpnext/assets/doctype/asset_movement/asset_movement.py
# -*- coding: utf-8 -*- # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.model.document import Document class AssetMovement(Document): def validate(self): sel...
runarberg/servo
tests/wpt/run.py
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import argparse import multiprocessing import os import sys here = os.path.split(__file__)[0] servo_root = os.path.absp...
morrisonwudi/zipline
zipline/version.py
# # Copyright 2012 Quantopian, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr...
scripnichenko/nova
nova/objects/quotas.py
# Copyright 2013 Rackspace Hosting. # # 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...
ChinaQuants/bokeh
examples/plotting/server/scatter_selection.py
# The plot server must be running # Go to http://localhost:5006/bokeh to view this plot import numpy as np from bokeh.plotting import figure, show, output_server, vplot from bokeh.models import BoxSelectTool N = 100 x = np.linspace(0, 4*np.pi, N) y = np.sin(x) output_server("scatter_selection") TOOLS = "pan,wheel...
ckuethe/gnuradio
gr-analog/python/analog/qa_pll_carriertracking.py
#!/usr/bin/env python # # Copyright 2004,2007,2010-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at ...
garyjyao1/ansible
lib/ansible/modules/extras/cloud/lxc/lxc_container.py
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2014, Kevin Carter <kevin.carter@rackspace.com> # # 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...
openhatch/oh-mainline
vendor/packages/django-tastypie/tastypie/utils/validate_jsonp.py
# -*- coding: utf-8 -*- # Placed into the Public Domain by tav <tav@espians.com> # Modified for Python 3 compatibility. """Validate Javascript Identifiers for use as JSON-P callback parameters.""" from __future__ import unicode_literals import re from unicodedata import category from django.utils import six # ----...
webmedic/booker
src/gdata/apps/groups/service.py
#!/usr/bin/python # # Copyright (C) 2008 Google, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
leighpauls/k2cro4
third_party/python_26/Lib/distutils/tests/test_dist.py
# -*- coding: latin-1 -*- """Tests for distutils.dist.""" import distutils.cmd import distutils.dist import os import StringIO import sys import unittest import warnings from test.test_support import TESTFN class test_dist(distutils.cmd.Command): """Sample distutils extension command.""" user_options = [ ...
teeple/pns_server
work/install/Python-2.7.4/Lib/test/test_htmlparser.py
"""Tests for HTMLParser.py.""" import HTMLParser import pprint import unittest from test import test_support class EventCollector(HTMLParser.HTMLParser): def __init__(self): self.events = [] self.append = self.events.append HTMLParser.HTMLParser.__init__(self) def get_events(self): ...
smmribeiro/intellij-community
python/helpers/py3only/docutils/languages/ja.py
# -*- coding: utf-8 -*- # $Id: ja.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Hisashi Morita <hisashim@kt.rim.or.jp> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Tw...
GbalsaC/bitnamiP
venv/lib/python2.7/site-packages/pytz/__init__.py
''' datetime.tzinfo timezone definitions generated from the Olson timezone database: ftp://elsie.nci.nih.gov/pub/tz*.tar.gz See the datetime section of the Python Library Reference for information on how to use these modules. ''' # The Olson database is updated several times a year. OLSON_VERSION = '2015b' VERSI...
Microvellum/Fluid-Designer
win64-vc/2.78/python/lib/site-packages/numpy/core/_internal.py
""" A place for code to be called from core C-code. Some things are more easily handled Python. """ from __future__ import division, absolute_import, print_function import re import sys import warnings from numpy.compat import asbytes, bytes if (sys.byteorder == 'little'): _nbo = asbytes('<') else: _nbo = ...
ffissore/badger
yun/root/oauth2client/keyring_storage.py
# Copyright 2014 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
912/M-new
virtualenvironment/experimental/lib/python2.7/site-packages/django/conf/locale/vi/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # from __future__ import unicode_literals # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = r'\N\gà\y d \t\há\n\g n \nă\m Y' T...
samueldotj/TeeRISC-Simulator
src/arch/x86/isa/insts/system/invlpg.py
# Copyright (c) 2007-2008 The Hewlett-Packard Development Company # All rights reserved. # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to intellectual property relating # to a hardware imp...
shravya-ks/ECN-ns3
src/mesh/doc/source/conf.py
# -*- coding: utf-8 -*- # # ns-3 documentation build configuration file, created by # sphinx-quickstart on Tue Dec 14 09:00:39 2010. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All co...
fluxw42/youtube-dl
youtube_dl/extractor/unistra.py
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import qualities class UnistraIE(InfoExtractor): _VALID_URL = r'https?://utv\.unistra\.fr/(?:index|video)\.php\?id_video\=(?P<id>\d+)' _TESTS = [ { 'url': 'http://utv.unistra.fr/video.php?id...
gitaarik/django
tests/postgres_tests/test_functions.py
from datetime import datetime from time import sleep from django.contrib.postgres.functions import TransactionNow from . import PostgreSQLTestCase from .models import NowTestModel class TestTransactionNow(PostgreSQLTestCase): def test_transaction_now(self): """ The test case puts everything und...
unnikrishnankgs/va
venv/lib/python3.5/site-packages/tensorflow/contrib/tensor_forest/hybrid/python/models/stochastic_soft_decisions_to_data_then_nn.py
# 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...
Teamxrtc/webrtc-streaming-node
third_party/webrtc/src/chromium/src/third_party/jstemplate/compile.py
#!/usr/bin/env python # Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Combines the javascript files needed by jstemplate into a single file.""" import httplib import urllib def main(): srcs = [...
djedproject/djed.form
tests/test_timezone.py
import pytz from datetime import datetime from djed.testing import BaseTestCase class TestTimezoneField(BaseTestCase): _includes = ('djed.form',) def test_timezone_schema_to_form(self): from djed.form import null, TimezoneField typ = TimezoneField('test') self.assertTrue(typ.to_for...
Khroki/MCEdit-Unified
panels/control.py
from __future__ import unicode_literals from config import config import release import platform from albow import AttrRef, Row, Column from albow.resource import get_font from albow.controls import Label from albow.extended_widgets import HotkeyColumn from pygame import key from glbackground import Panel arch = pla...
ninjin/eepura
src/lib/ann.py
#!/usr/bin/env python ''' Parsing and handling BioNLP ST annotation files. Note: This is a very naive and rudimentary parser that only works well for this project, nothing fancy Author: Pontus Stenetorp <pontus stenetorp se> Version: 2012-03-07 ''' from common import Textbound, Event, Modifier ### Co...
victor-gil-sepulveda/PhD-ANMPythonHelpers
calculate_PCA_from_coordinates.py
''' Created on 22/05/2015 @author: user ''' from optparse import OptionParser import numpy from convert_geo_pca_to_nmd import load_sequences from pyRMSD.RMSDCalculator import RMSDCalculator from pca.emPCA import empca from anmichelpers.writers.pronmd import ProdyNMDWriter def get_seq_positions_with_known_residues(seq...
stryder199/RyarkAssignments
Assignment2/ttt/think_c/control_flow/three_x.py
question_type = 'input_output' source_language = 'C' parameter_list = [ ['$x','int'], ['$o0','string'],['$o1','string'],['$o2','string'], ['$o3','string'],['$o4','string'], ['$o5','string'],['$o6','string'],['$o7','string'], ['$o8','string'],['$o9','string'], ] tuple_list = [ ['three_x_forward_', [1,None,N...
yoshiori/sentry-notify-github-issues
setup.py
#!/usr/bin/env python from setuptools import setup, find_packages tests_require = [ 'nose', ] install_requires = [ 'sentry>=5.0.0', ] setup( name='sentry-notify-github-issues', version='1.0.0', author='Yoshiori Shoji', author_email='yoshiori@gmail.com', url='http://github.com/yoshiori/sen...
PrefPy/opra
compsocsite/polls/migrations/0107_auto_20180105_1858.py
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-01-05 23:58 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('polls', '0106_question_yesno2_enabled'), ] operations = [ migrations.AddField...
tomhettinger/simplestone
gameboard/Card.py
class Card(object): def __init__(self, contents=None): self.contents = contents self.hand = None if contents is not None: self.name = contents.name def can_play(self): side = self.hand.board.playerTurn availMana = self.hand.board.manaCurrent[side] co...
linan-zhou/leetcode_solutions
Array_Nesting.py
class Solution(object): def arrayNesting(self, nums): """ :type nums: List[int] :rtype: int """ dict = {} ans = 0 for i in nums: if i in dict: continue label = nums.index(i) dict[label] = 1 x = i ...
jaydeep17/crypto
src/caesarCipher.py
from operator import itemgetter def encrypt(text, key): txt = list(text) for i in range(len(txt)): txt[i] = chr(ord(txt[i]) + key) return ''.join(txt) def decrypt(cipherText, key): txt = list(cipherText) for i in range(len(txt)): txt[i] = chr(ord(txt[i]) - key) return ''.join...
charles-cooper/raiden
raiden/tests/integration/test_blockchainservice.py
# -*- coding: utf-8 -*- from __future__ import division import os import pytest from ethereum import _solidity from ethereum._solidity import compile_file from ethereum.utils import denoms from pyethapp.rpc_client import JSONRPCClient from pyethapp.jsonrpc import default_gasprice from raiden.network.rpc.client impor...
Azure/azure-sdk-for-python
sdk/logic/azure-mgmt-logic/azure/mgmt/logic/aio/operations/_integration_service_environment_managed_apis_operations.py
# 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 may ...
mabotech/mabo.io
py/vision/test1/imagescale-q-m.py
# -*- coding: utf-8 -*- #!/usr/bin/env python3 # Copyright © 2012-13 Qtrac Ltd. All rights reserved. # This program or module 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,...
jmoiron/daneel
daneel/plugins/summarize.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Summarize plugin. Listens for URLs and prints a summary.""" from daneel.plugins import weblib import logging logger = logging.getLogger(__name__) def summarize(context): msg = context.msg # skip command-ish things if msg.startswith("."): return ...
kailashbuki/predator
installed/preprocessor/apps/sanitizer/sanitizer.py
#!/usr/bin/env python # # Copyright (C) 2011 by kailash.buki@gmail.com # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use,...
theonion/django-bulbs
bulbs/ads/templatetags/ads.py
import json from django.template import Library, Context from django.template.loader import get_template register = Library() @register.simple_tag(takes_context=True) def ads_targeting(context): return get_template( "ads/ads-targeting.html" ).render( Context({ "targeting": conte...
badmofo/bmf-python
bmf/validate.py
#!/usr/bin/python # -*- coding: utf-8 -*- import re import datetime from decimal import Decimal from numbers import Number, Integral from .util import AttrDict DEFAULT_NOT_SPECIFIED = '849fd780-ff1e-11e1-9055-442a60fb615e' class ValidationError(Exception): def __init__(self, message, parameter=None): "...
Nodoka/Bioquality
graphing/bar_stacked_fojhori.py
#!/usr/bin/env python # a stacked bar plot with errorbars import numpy as np import matplotlib.pyplot as plt # extract columns of each dataset star_category = np.genfromtxt('../data/HoriFOJ_stardata.csv',delimiter=',',dtype=None,skip_header=1,usecols=0) taxa_no = np.genfromtxt('../data/HoriFOJ_stardata.csv',delimiter=...
njvack/masterfile
tests/validators/test_index_column.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the masterfile package: https://github.com/uwmadison-chm/masterfile # Copyright (c) 2020 Board of Regents of the University of Wisconsin System # Written by Nate Vack <njvack@wisc.edu> at the Center for Healthy Minds # at the University of Wisconsin-Madison. # Re...
anthill-services/anthill-common
anthill/common/sign.py
import abc from cryptography.hazmat.backends.openssl.backend import backend from cryptography.hazmat.primitives import serialization TOKEN_SIGNATURE_RSA = 'RS256' TOKEN_SIGNATURE_HMAC = 'HS256' class AccessTokenSignature(object, metaclass=abc.ABCMeta): def __init__(self): pass @abc.abstractmethod...
moodpulse/l2
refprocessor/processor.py
from typing import Tuple, Union, List from appconf.manager import SettingManager from refprocessor.age_parser import AgeRight from refprocessor.common import ValueRange, RANGE_IN from refprocessor.result_parser import ResultRight class RefProcessor: def __init__(self, ref: dict, age: List[int]): actual_k...
CelebornMcGinnis/Dungeons-and-Monsters
CharacterClasses.py
#This will be for creating new characters #imports import os.path class NewCharacter(object): def __init__( self, c_p, s_p, e_p, g_p, p_p,\ paralyzation_poison_death_magic,\ rod_staff_wand,\ petrification_polymorph,\ breath_weapon, spell,\ ...
Pancho/failiac
external/encoders.py
import json import decimal import datetime from django.utils.timezone import is_aware from bson import objectid class VersatileJSONEncoder(json.JSONEncoder): """ JSONEncoder subclass that knows how to encode date/time, ObjectID and decimal types. """ def default(self, obj): # See "Date Time String Format" in ...
vmware/nsxramlclient
tests/config.py
# coding=utf-8 # # Copyright © 2015 VMware, Inc. All Rights Reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated # documentation files (the "Software"), to deal in the Software without restriction, including without limitation # the rights to use, co...
fishilico/shared
windows/database_libraries/version_info.py
#!/usr/bin/env python3 # -*- coding:UTF-8 -*- # Copyright (c) 2020 Nicolas Iooss # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights...
philburr/pyecoplug
pyecoplug/plug.py
import socket import struct, time import pprint from threading import Thread, Event import random class EcoPlug(object): CONNECTION_TIMEOUT = 60 def __init__(self, data): self.plug_data = data # Name set for outlet in phone app self.name = data[3].decode('utf-8') # 'Manufacture...
moritzschaefer/the-search-engine
test/test_page_ranker.py
import os import tsg.indexer.page_rank as page_rank RAW_TEST_DIRECTORY = os.path.dirname(__file__) + "/files/pagerank/" files = [RAW_TEST_DIRECTORY + "author_a_A:Almaaf_Bader_Ali.html", RAW_TEST_DIRECTORY + "journal_ijea_ijea5.html", RAW_TEST_DIRECTORY + "conference_aaip_aaip2009.html"] def test_par...
avalentino/slim
slim/models.py
# -*- coding: utf-8 -*- """Models for the SLiM Flask application.""" from __future__ import absolute_import import datetime from flask_sqlalchemy import SQLAlchemy from flask_security import UserMixin, RoleMixin db = SQLAlchemy() # Security roles_users = db.Table( 'roles_users', db.Column('user_id', db....
lmazuel/azure-sdk-for-python
azure-mgmt-compute/azure/mgmt/compute/v2016_03_30/models/virtual_machine_scale_set_network_configuration.py
# 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 ...
alanlhutchison/empirical-JTK_CYCLE-with-asymmetry
previous_files/make_permutations/make_permutations_off_file.py
#!/usr/bin/env python """ This script makes N permutations based on the header of the sample file fed in to it. Author: Alan L. Hutchison, alanlhutchison@uchicago.edu, Aaron Dinner Group, University of Chicago """ import numpy as np import math import sys import random def main(): # header is of length 24 with per...
OneMoreGres/ScreenTranslator
share/updates/tessdata.py
import sys import os import subprocess import re def parse_language_names(): root = os.path.abspath(os.path.basename(__file__) + '/../../..') lines = [] with open(root + '/src/languagecodes.cpp', 'r') as f: lines = f.readlines() result = {} for line in lines: all = re.findall(r'"(....
shenfei/oj_codes
leetcode/python/n652_Find_Duplicate_Subtrees.py
from collections import defaultdict class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def serialize(root): if root is None: return '#' q = [root] i, j = 0, 0 while i <= j: node = q[i] i += 1 if nod...
PableraShow/Learn-to-program-with-Python-guide
01 - Expressions, variables and assignments/variables-names.py
# Variables - placeholders for important values # Names # Valid variable names consist of letters, numbers, and # underscores (_) and start with a letter or underscore # Valid num = 2 my_name = 3 it9 = 9 it_10 = 10 __do__this = 12 # Invalid - uncomment to see errors #9ish = 9.001 #so-cute = 32 ...
daviddiazvico/keras
examples/reuters_mlp.py
'''Train and evaluate a simple MLP on the Reuters newswire topic classification task. GPU run command: THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 python examples/reuters_mlp.py CPU run command: python examples/reuters_mlp.py ''' from __future__ import print_function import numpy as np np.random.seed(...
mihaimaruseac/blog-demos
reservoir_sampling/test/test.py
import operator import timeit d1={1: 1, 2: 2, 3: 8, 4: 3, 5: 6, 6: 9, 7: 17, 8: 4, 9: 20, 10: 7, 11: 15, 12: 10, 13: 10, 14: 18, 15: 18, 16: 5, 17: 13, 18: 21, 19: 21, 20: 8, 21: 8, 22: 16, 23: 16, 24: 11, 25: 24, 26: 11, 27: 112, 28: 19, 29: 19, 30: 19, 3077: 36, 32: 6, 33: 27, 34: 14, 35: 14, 36: 22, ...
CospanDesign/nysa-verilog
verilog/wishbone/host_interface/generic/pf_hi_tester/cocotb/dut_driver.py
#PUT LICENCE HERE! """ pf_hi_tester Driver """ import sys import os import time from array import array as Array sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir)) from nysa.host.driver import driver #Sub Module ID #Use 'nysa devices' to get a list of different availab...
khshim/lemontree
lemontree/utils/type_utils.py
""" This code includes useful functions for base types(list, tuple, dict). Most ideas came from google and stackoverflow. """ import numpy as np from collections import OrderedDict def uint_to_float(data): """ This function returns data in uint8 type to float32 type. """ return np.asarray(data, dtype...
custode/reviewboard
reviewboard/webapi/tests/mimetypes.py
from __future__ import unicode_literals def _build_mimetype(resource_name, fmt='json'): return 'application/vnd.reviewboard.org.%s+%s' % (resource_name, fmt) api_token_list_mimetype = _build_mimetype('api-tokens') api_token_item_mimetype = _build_mimetype('api-token') archived_item_mimetype = _build_mimetype(...
lowks/shared
test_s/fast/fn.py
import pytest import s def test_logic_immutalizes(): @s.fn.logic def fn(x): x[1] = 2 with pytest.raises(ValueError): fn({}) def test_stack(): start = s.fn._stack() @s.fn.logic def fn1(): assert s.fn._stack() == ('logic:{}:fn1'.format(__name__),) return fn2() ...
ianpreston/randomcouragewolf
webapp.py
from flask import Flask, render_template, g import BeautifulSoup import re import urllib2 import random import memcache app = Flask(__name__) @app.before_request def before_request(): g.memcache_client = memcache.Client(["127.0.0.1:11211"]) @app.route('/') def index(): # Pick a random page number from quick...
letuananh/omwtk
omwtk/prejp.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Japanese text preprocessor Latest version can be found at https://github.com/letuananh/omwtk Usage: ./prejp.py References: Python documentation: https://docs.python.org/ argparse module: https://docs.python.org/3/howto/argparse.html ...
KayaBaber/Computational-Physics
Assignment_2_nbody_simulator/Pre-GitHub-Versions/phys440_ps2_euler_real_datar.py
import math import numpy as np import matplotlib.pyplot as plt from datetime import datetime startTime = datetime.now() def angular_momentum(posArray, velArray, massArray): '''calculates the total angular momentum for a system of objects ''' numObjects=len(massArray) numDimensions=len(posArray[0]) ...
whateverpal/coinmetrics-tools
coincrawler/storage/__init__.py
class IStorage(object): def getBlockStorageAccess(self, currency): return None def getPriceStorageAccess(self, currency): return None class IBlockStorageAccess(object): def getBlockHeight(self): return 0 def storeBlock(self, block): return def getBlocksRange(self, offset, count): return [] def g...
s6530085/FundSpider
index/outputer.py
# -*- coding: utf-8 -*- __author__ = 'study_sun' import sys from spider_base.convenient import * reload(sys) sys.setdefaultencoding('utf-8') import pandas as pd from pylab import * mpl.rcParams['font.sans-serif'] = ['SimHei'] #指定默认字体 mpl.rcParams['axes.unicode_minus'] = False #解决保存图像是负号'-'显示为方块的问题 from termcolor impor...
codedsk/hubcheck
hubcheck/pageobjects/widgets/members_profile_password.py
from hubcheck.pageobjects.basepageelement import Text from hubcheck.pageobjects.widgets.members_profile_element import MembersProfileElement class MembersProfilePassword(MembersProfileElement): def __init__(self, owner, locatordict={}): super(MembersProfilePassword,self).__init__(owner,locatordict) ...
weehyong/k8scntkSamples
cifar-10/TrainResNet_CIFAR10.py
# Copyright (c) Microsoft. All rights reserved. # Licensed under the MIT license. See LICENSE.md file in the project root # for full license information. # ============================================================================== from __future__ import print_function import os import argparse import numpy as np...
spacelis/tcrawl
tcrawl/writer.py
#!python # -*- coding: utf-8 -*- """File: writer.py Description: This module contains a set of classes for writing to file system History: 0.1.0 The first version. """ __version__ = '0.1.0' __author__ = 'SpaceLis' import threading, re, os, gzip, json _MULTISLASH = re.compile(r'/+') def new_fil...
assamite/TwatBot
tweets/interjections.py
''' .. py:module:: interjections :platform: Unix Generate common English interjections for given stimulation. The available interjections have been created mostly according to this `site <http://www.vidarholen.net/contents/interjections/>`_. Intended usage follows roughly this scheme:: >>>import gensi...
historical-ctf/historical-ctf.github.io
static/scripts/task1/util.py
import math def serialize(s): """Serialize a string `s` into a number for RSA encryption.""" ctr = 0 i = len(s) for c in s: i = i - 1 ctr = ctr + (ord(c) * (256 ** i)) return ctr def deserialize(n): """Deserialize a number `n` that has been RSA decrypted into a string.""" ...
squadran2003/PYTHON-DIRECTORY-WATCHER
test.py
import unittest import directories class directoryTest(unittest.TestCase): def test_add_directories(self): result = " \n Directory added" self.assertNotEqual(directories.add_directories("/home/andy/Desktop/PYTHON-DIRECTORY-WATCHER/include","/home/andy/Desktop/PYTHON-DIRECTORY-WATCHER/test.bat",2),result) sel...
sampathweb/game-server
ws-chat.py
""" This is a simple example of WebSocket + Tornado + Redis Pub/Sub usage. Do not forget to replace YOURSERVER by the correct value. Keep in mind that you need the *very latest* version of your web browser. You also need to add Jacob Kristhammar's websocket implementation to Tornado: Grab it here: http://gist.githu...
BroganD1993/MoodleFUSE
tests/filesystem_tests.py
#!/usr/bin/env python # encoding: utf-8 from tests import MoodleFuseAppTestCase from tests.data.settings import DOWNLOADS import os class FilesystemTestCase(MoodleFuseAppTestCase): def cache_created_test(self): self.assertTrue(os.path.exists(DOWNLOADS)) def mount_created_test(self): self.a...
yueranyuan/vector_edu
learntools/emotiv/tests/test_emotiv_base.py
from itertools import izip import random import numpy as np from learntools.libs.common_test_utils import use_logger_in_test from learntools.data import cv_split from learntools.emotiv import BaseEmotiv, prepare_data from learntools.emotiv.tests.emotiv_simple import SimpleEmotiv from learntools.data import Dataset im...
kuroneko0214/ingress_capture_log
ingrex/xmlReader.py
from xml.etree import ElementTree as ET class xmlReader(object): def __init__(self): self.tree = ET.parse('./ingrex_lib/data.xml') def getdbinfo(self): dbinfo = {} dbinfoE = self.tree.findall('./database/') for i in dbinfoE: dbinfo[i.tag] = i.text return db...
echomobi/echo-sense
actions/adminActions.py
import django_version import logging from google.appengine.ext import webapp, db from models import * from constants import * import json import services import authorized import outbox import handlers class Install(handlers.BaseRequestHandler): '''Initialize / Install Echo Sense with first account / user P...
pymir3/pymir3
mir3/modules/tool/mergecsv2weka.py
import argparse import csv import mir3.data.feature_matrix as feature_matrix import mir3.module class MergeCSV2Weka(mir3.module.Module): def get_help(self): return """Merge feature matrix and CSV file with labels for using within Weka""" def build_arguments(self, parser): ...
ncos/hometasks
CMSC733/amitrokh_hw0/Part1/code/pin_it.py
#!/usr/bin/python import cv2 import numpy as np from optparse import OptionParser from os.path import isfile, join import sys, os, math # Color print class bcolors: HEADER = '\033[95m' PLAIN = '\033[37m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC ...
rolandgeider/OpenSlides
tests/unit/config/test_api.py
from unittest import TestCase from unittest.mock import patch from openslides.core.config import ConfigVariable, config from openslides.core.exceptions import ConfigNotFound class TestConfigVariable(TestCase): @patch('openslides.core.config.config', {'test_variable': None}) def test_default_value_in_data(sel...
dajobe/SoCo
soco/core.py
# -*- coding: utf-8 -*- # pylint: disable=fixme, protected-access """The core module contains the SoCo class that implements the main entry to the SoCo functionality """ from __future__ import absolute_import, unicode_literals import datetime import logging import re import socket from functools import wraps from xml...
tpbarron/rlflow
rlflow/core/rl_utils.py
import numpy as np import tensorflow as tf import scipy.signal # # Reward manipulation # def discount_rewards(x, gamma=0.9): """ Take 1D float array of rewards and compute the sum of discounted rewards at each timestep """ return scipy.signal.lfilter([1], [1, -gamma], x[::-1], axis=0)[::-1] def ...
lepus-ctf/lepus-api
src/lepus/serializers.py
# encoding=utf-8 from django.contrib.auth import authenticate from django.conf import settings from datetime import datetime from lepus import models from rest_framework import serializers, status, exceptions, fields class ValidationErrorDetail(object): def __init__(self, error="", message=""): self.er...
mozillazg/chendian-plus
chendian/book/migrations/0006_book_cover.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('book', '0005_auto_20150428_2125'), ] operations = [ migrations.AddField( model_name='book', name='co...
lechimp-p/streamr
tests/unit/test_io.py
# Copyright (C) 2015 Richard Klees <richard.klees@rwth-aachen.de> import pytest from streamr.io import read_file, to_json from streamr.base import from_list, to_list from test_core import _TestPipe import os import json class TestReadFile(_TestPipe): @pytest.fixture def pipe(self): return read_file ...
tomplus/wordbook
wordbook/dictbase.py
import asyncio import re import enum import logging from wordbook.exceptions import DictError, DictConnectionError, InvalidDatabase, InvalidStrategy class ResponseCodes(enum.IntEnum): DATABASES_PRESENT = 110 STRATEGIES_AVAILABLE = 111 DATABASE_INFORMATION = 112 HELP_TEXT = 113 SERVER_INFORMATION...
facebookresearch/ParlAI
parlai/zoo/dodecadialogue/build.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Pretrained models from The Dialogue Dodecathlon. The dodecadialogue_v2.tgz file is always downloaded, and contains 1...
Nachtfeuer/concept-py
concept/math/factorization.py
""" Factorization functions. .. module:: functions :platform: Unix, Windows :synopis: math factorization functions. .. moduleauthor:: Thomas Lehmann <thomas.lehmann.private@googlemail.com> ======= License ======= Copyright (c) 2015 Thomas Lehmann Permission is hereby granted, free of charg...
The-Fonz/adventure-track
backend/telegrambot/db.py
import asyncio import datetime from os import environ import asyncpg from sqlalchemy import MetaData, Table, Column, Integer, DateTime, create_engine from ..utils import record_to_dict, getLogger logger = getLogger('telegrambot.db') metadata = MetaData() # Only used for table creation, no ORM message = Table('user...