code stringlengths 2 1.05M | repo_name stringlengths 5 104 | path stringlengths 4 251 | language stringclasses 1
value | license stringclasses 15
values | size int32 2 1.05M |
|---|---|---|---|---|---|
import json
class AbstractionUtility(object):
@staticmethod
def read_json(json_file):
# read json data
with open(json_file, 'r') as f:
data = json.load(f)
# change json key string to int
converted_data = {}
for key, value in data.iteritems():
co... | studiawan/pygraphc | pygraphc/abstraction/AbstractionUtility.py | Python | mit | 2,712 |
#!/usr/bin/env python
import sys, re, subprocess
def usage():
print '''\
Usage: %s <program name> <test file>
''' % sys.argv[0]
def escape(s, code):
return '\033[%sm%s\033[0m' % (code, s)
def red(s):
return escape(s, 91)
def green(s):
return escape(s, 92)
def main():
try:
prog_name, fi... | bdusell/romaji-cpp | test/run_test.py | Python | mit | 1,881 |
studentencijfers = [
[95, 92, 86],
[66, 75, 54],
[89, 72, 100],
[34, 0, 0]
];
"""
Calculate the average in a two dimentional list
@param {List(List(Int))} studenten - Two dimentional list of Ints
@return {list(Float)} One dimentional list of the average of the input
"""
def gemiddelde_per_student(stud... | AtlasDev/TICT-V1PROG-15 | les-5/practice/5_6.py | Python | mit | 863 |
import json
_log = []
enabled = False
def start_logging():
global _log
global enabled
_log = []
enabled = True
def stop_logging():
global enabled
enabled = False
def get_log():
return json.dumps(_log, indent=2)
def add_to_log(obj):
if enabled:
_log.append(obj)
def log... | ypersyntelykos/GitSavvy | common/util/debug.py | Python | mit | 893 |
from flex.datastructures import (
ValidationDict,
)
from flex.constants import (
OBJECT,
)
from flex.validation.common import (
generate_object_validator,
)
from .operation import (
operation_validator,
)
from .parameters import (
parameters_validator,
)
path_item_schema = {
'type': OBJECT,
}
... | pipermerriam/flex | flex/loading/schema/paths/path_item/__init__.py | Python | mit | 1,084 |
from unittest import mock
from model_mommy import mommy
from django.conf import settings
from django.core.management import call_command
from django.test import TestCase
from django.utils import timezone
from meupet.models import Pet, PetStatus
class RequestActionTest(TestCase):
@staticmethod
def test_requ... | dirtycoder/pets | pets/meupet/tests/test_command_requestaction.py | Python | mit | 797 |
# 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... | vmware/nsxramlclient | tests/clusterprep.py | Python | mit | 2,874 |
pps = """bdwdjjo avricm cjbmj ran lmfsom ivsof
mxonybc fndyzzi gmdp gdfyoi inrvhr kpuueel wdpga vkq
bneh ylltsc vhryov lsd hmruxy ebnh pdln vdprrky
fumay zbccai qymavw zwoove hqpd rcxyvy
bcuo khhkkro mpt dxrebym qwum zqp lhmbma esmr qiyomu
qjs giedut mzsubkn rcbugk voxk yrlp rqxfvz kspz vxg zskp
srceh xdwao reshc shecr... | justanotherdot/advent-linguist | 2017/aoc_04.py | Python | mit | 23,369 |
#--coding:utf-8--
#InfoExtractor.py
import json
from __tmpl__ import cfgFile
from __tmpl__ import Extractor
class Extract(object):
"""Multiprocessing safe"""
def __init__(self):
"""
Load cfg File
Use ReExtractor
Initialize it
"""
cfg = cfgFile.cfgFileIn()
... | nday-dev/Spider-Framework | src/InfoExtractor.py | Python | mit | 709 |
""" simpleimap.py, originally from http://p.linode.com/2693 on 2009/07/22
Copyright (c) 2009 Timothy J Fontaine <tjfontaine@gmail.com>
Copyright (c) 2009 Ryan S. Tucker <rtucker@gmail.com>
"""
import email
import imaplib
import logging
import platform
import re
import time
class __simplebase:
""" __simple base
... | rtucker/imap2maildir | simpleimap.py | Python | mit | 17,416 |
import _plotly_utils.basevalidators
class BordercolorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self,
plotly_name="bordercolor",
parent_name="layout.xaxis.rangeselector",
**kwargs
):
super(BordercolorValidator, self).__init__(
plot... | plotly/plotly.py | packages/python/plotly/plotly/validators/layout/xaxis/rangeselector/_bordercolor.py | Python | mit | 464 |
import pytest
from src.Numbers.credit_card_validator import CardValidator, CardError
class TestCreditCard:
def test_valiator_success(self):
card = CardValidator(4556821195558787)
assert card.__str__() == "************8787"
assert card.__repr__() == "<Credit Card: ************8787>"
d... | roghu/py3_projects | tests/Numbers/test_credit_card_validator.py | Python | mit | 1,051 |
from Markets import Poloniex
from Markets import YoBit
p = Poloniex.Poloniex(None, None)
y = YoBit.Yobit(None, None)
#pPairs = [i for i in p.getTickers().keys()]
#yPairs = [i for i in y.getTickers().keys()]
#pPairs.sort()
#yPairs.sort()
yBook = y.returnOrderBook('dash_btc')
pBook = p.returnOrderBook('BTC_DASH')
yB... | lorganthesorn/CryptoArb | Analysis/calculator.py | Python | mit | 603 |
# Author: Abhishek Divekar, Jan 2016. Licence: Creative Commons.
import os
import sqlite3
import datetime
def get_conn(db_file_name):
#makes a new file if it does not exist
BASE_DIR = os.path.dirname(os.path.abspath(__file__)) #gets direcotry path in which file is stored.
db_path = os.path.join(BASE_DI... | ARDivekar/SearchDistribute | other/Legacy/sqliteDefaults.py | Python | mit | 9,396 |
from django.shortcuts import render
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse_lazy
from .models import Rental
class BookRentView(CreateView):
model = Rental
fields = ['who', 'what']
success_url = '/' | raf-programmer/django-biblioteka | rental/views.py | Python | mit | 290 |
import hmac
import config
from jinja2 import Environment, FileSystemLoader
jinja2_env = Environment(loader=FileSystemLoader(
config.TEMPLATE_DIRS), autoescape=True)
class BaseHandler(object):
def __init__(self):
self.request = None
self.response = None
def make_secure_value(self, value):... | xstrengthofonex/code-live-tutorials | python_web_development/database/handlers/base_handler.py | Python | mit | 1,866 |
from django.core.exceptions import ObjectDoesNotExist
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from ui.models import Location
from pysnmp.entity.rfc3413.oneliner import cmdgen
class Command(BaseCommand):
help = '''Capture network status of all the hosts ... | gwu-libraries/loggins | loggins/ui/management/commands/map_network_hosts.py | Python | mit | 2,508 |
# -*- encoding:utf-8 -*-
from __future__ import unicode_literals
MESSAGES = {
"%d min remaining to read": "zostáva %d minút na čítanie",
"Also available in:": "Tiež dostupné v:",
"Archive": "Archív",
"Categories": "Kategórie",
"Comments": "Komentáre",
"LANGUAGE": "Slovenčina",
"Languages:":... | immanetize/nikola | nikola/data/themes/base/messages/messages_sk.py | Python | mit | 1,431 |
"""Plugin loading and management logic and classes."""
import logging
import sys
import entrypoints
from flake8 import exceptions
from flake8 import utils
if sys.version_info >= (3, 3):
import collections.abc as collections_abc
else:
import collections as collections_abc
LOG = logging.getLogger(__name__)
_... | lmregus/Portfolio | python/design_patterns/env/lib/python3.7/site-packages/flake8/plugins/manager.py | Python | mit | 17,752 |
import logging
import mapnik
import xml.etree.ElementTree as ET
import os
import subprocess
import tempfile
# Set up logging
logging.basicConfig(format="%(asctime)s|%(levelname)s|%(message)s", level=logging.INFO)
# Parameters
shpPath = "C:/Projects/BirthsAndPregnanciesMapping/data/2014-04-24/Zanzibar/Zanzibar.shp"
ep... | hishivshah/WorldPop | code/create_zanzibar_boundary_map.py | Python | mit | 1,981 |
# __author__ = 'Exter'
from functools import wraps
import time
def timed(f):
@wraps(f)
def wrapper(*args, **kwds):
current_milli_time = lambda: int(round(time.time() * 1000))
start = current_milli_time()
result = f(*args, **kwds)
elapsed = current_milli_time() - start
print "%s took %d ms to ... | exter/pycover | tools/timed_wrapper.py | Python | mit | 386 |
"""Suite Standard Suite: Common terms for most applications
Level 1, version 1
Generated from /Applications/Internet Explorer.app
AETE/AEUT resource version 1/0, language 0, script 0
"""
import aetools
import MacOS
_code = '****'
class Standard_Suite_Events:
_argmap_get = {
'as' : 'rtyp',
}
de... | MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-2.3/Lib/plat-mac/lib-scriptpackages/Explorer/Standard_Suite.py | Python | mit | 1,705 |
# -*- coding: utf-8 -*-
from ...core.tags.registry import register
from .forms import LikeForm
@register.inclusion_tag('spirit/comment/like/_form.html')
def render_like_form(comment, like, next=None):
form = LikeForm()
return {'form': form, 'comment_id': comment.pk, 'like': like, 'next': next}
| nitely/Spirit | spirit/comment/like/tags.py | Python | mit | 306 |
from __future__ import print_function, division
from argparse import Namespace
from random import randint
import myhdl
from myhdl import instance, delay, StopSimulation
from rhea import Clock, Reset, Global
from rhea.system import Wishbone
from rhea.cores.sdram import SDRAMInterface
from rhea.cores.sdram import sd... | cfelton/rhea | test/test_cores/test_sdram/test_sdram.py | Python | mit | 3,406 |
# -*- coding: utf-8 -*-
from flask import request, url_for
from sqlalchemy import desc
from werkzeug.contrib.atom import AtomFeed
from . import blueprint
from .utils import requested_blog_user, make_external
from app.models import Post
@blueprint.route("/recent.atom")
def rss_feed(user_slug):
blog_user = reques... | Depado/MarkDownBlog | app/modules/blog/rss.py | Python | mit | 1,049 |
# -*- coding: iso-8859-15 -*-
import datetime
import selenium_settings
from base_test import SeleniumBaseTest
class SignupTest(SeleniumBaseTest):
PASSWORD = 's3l3n1uM'
PASSWORD2 = 'sel3n1uM2'
PASSWORD3 = 'sel3n1uM3'
def setUp(self):
super(SignupTest, self).setUp()
self.admin_login()... | jessamynsmith/eggtimer-server | selenium/test_signup.py | Python | mit | 6,622 |
#!/usr/bin/python
# (C) 2015-2106 - Muthiah Annamalai
# parse data files for Tamil proper nouns
from __future__ import print_function
import codecs
import json
import pprint
import re
import sys
import tamil
class WordList:
# data structure for a WordList containing only one category
def __init__(self, cat)... | Ezhil-Language-Foundation/open-tamil | solthiruthi/data_parser.py | Python | mit | 3,224 |
#!/usr/bin/env python
# -*- coding: windows-1251 -*-
# Copyright (C) 2005 Roman V. Kiseliov
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must reta... | deonwu/Goku | scripts/GokuCtrl/ipa4django/views/pyExcelerator/BIFFRecords.py | Python | mit | 88,384 |
import statistics
from typing import TextIO, Tuple, Dict
from aoc2019.intcode import Computer, read_program
def render_screen(computer: Computer, screen: Dict[Tuple[int, int], int]):
while computer.output:
x = computer.output.popleft()
y = computer.output.popleft()
val = computer.output.p... | bertptrs/adventofcode | 2019/aoc2019/day13.py | Python | mit | 1,338 |
import atexit
connection = None
connection_function = None
reconnect_function = None
hooks = None
def set_connection_function(_connection_function):
global connection
global connection_function
connection_function = _connection_function
connection = connection_function()
def disconnect():
globa... | Dark-Bob/mro | mro/connection.py | Python | mit | 910 |
# import re
# COMMENT_PATERN = re.compile("([^\\\\])%.*($)", flags=re.MULTILINE)
# REDACT = "%"
# COMMENT_REPLACE = "\\1{}\\2".format(REDACT)
# def strip_comments(document_contents):
# return COMMENT_PATERN.sub(COMMENT_REPLACE, document_contents)
import strip_comments
def strip_latex_comments(document_contents):
... | nschank/latexml | stringutil.py | Python | mit | 2,656 |
"""
This is an example showing how to use the mgd2d solver.
A 4th order accurate solution is obtained with the 5pt stencil,
by using deferred correction.
"""
import numpy as np
import time
from mgd2d import FMG,V_cycle
#analytical solution
def Uann(x,y,n):
return np.sin(2*n*np.pi*x)*np.sin(2*n*np.pi*y)
#RHS corres... | AbhilashReddyM/GeometricMultigrid | example_FMG_defcor.py | Python | mit | 3,299 |
from collections import Counter, defaultdict
import math
import pprint
import functools
# Advanced material here, feel free to ignore memoize if you like.
# Long story short, it remembers the inputs and outputs to functions,
# and if the same input is seen multiple times, then rather than
# running the function multi... | npoznans/python_etl | bayes_evening_workshop/Naive_Bayes_Evening_Workshop/classifiers.py | Python | mit | 6,290 |
class Solution:
def pushDominoesSim(self, dominoes: str) -> str:
prev, curr, N = None, ["."] + list(dominoes) + ["."], len(dominoes)
while prev != curr:
prev = curr[:]
i = 1
while i <= N:
if curr[i] == "." and prev[i - 1] == "R" and prev[i + 1] != ... | l33tdaima/l33tdaima | p838m/push_dominoes.py | Python | mit | 1,778 |
# -*- codeing: utf-8 -*-
def bubble_sort(to_sort):
index = 0
while index < len(to_sort):
offset = index
while offset > 0 and to_sort[offset - 1] > to_sort[offset]:
temp = to_sort[offset]
to_sort[offset] = to_sort[offset - 1]
to_sort[offset - 1] = temp
... | Alex-Diez/python-tdd-katas | old-katas/sort-kata/day-1.py | Python | mit | 2,549 |
from django import forms
from django.conf import settings
from django.contrib import admin
from storybase.admin import StorybaseModelAdmin, StorybaseStackedInline
from storybase_help.models import HelpTranslation, Help
class HelpTranslationAdminForm(forms.ModelForm):
class Meta:
model = HelpTranslation
... | denverfoundation/storybase | apps/storybase_help/admin.py | Python | mit | 1,189 |
from __future__ import unicode_literals
import logging
import six
from rbtools.api.errors import APIError
from rbtools.clients.errors import MergeError, PushError
from rbtools.commands import Command, CommandError, Option, RB_MAIN
from rbtools.utils.commands import (build_rbtools_cmd_argv,
... | reviewboard/rbtools | rbtools/commands/land.py | Python | mit | 16,983 |
from django.core.management.base import BaseCommand
from django.conf import settings
from angular_scaffold.management.commands.helpers._generate_limiter import generate_limiter
class Command(BaseCommand):
help = 'Adds the rootScope Rate limiter for your services'
def handle(self, *args, **options):
... | mc706/django-angular-scaffold | angular_scaffold/management/commands/createlimiter.py | Python | mit | 520 |
"""Cloud browser package."""
from __future__ import with_statement
import os
from sys import version_info
from setuptools import find_packages, setup
from cloud_browser import __version__
###############################################################################
# Environment and Packages.
####################... | ryan-roemer/django-cloud-browser | setup.py | Python | mit | 2,485 |
import numpy as np
import pandas as pd
from utils.constants import *
from utils.strings import *
class Processor:
'''Preprocessor for Bitcoin prices dataset as obtained by following the procedure
described in https://github.com/philipperemy/deep-learning-bitcoin'''
def __init__(self, config, logger):
... | samre12/deep-trading-agent | code/process/processor.py | Python | mit | 3,261 |
from kodrive import syncthing_factory as factory
client = factory.get_handler()
| Jvlythical/KoDrive | tests/mock/cli.py | Python | mit | 81 |
from flask_user import DBAdapter
class DataStoreAdapter(DBAdapter):
""" An Wrapper to be use by Flask User to interact with
the database in this case, the DataStore """
def __init__(self, db, objMOdel):
super().__init__(db, objMOdel)
def get_object(self, ObjectClass, pk):
""" Ret... | oldani/nanodegree-blog | app/models/datastore_adapter.py | Python | mit | 2,094 |
import gitlab
from .. import mock, wrapped_config_get
gitlab.Gitlab("") # instantiation necessary to discover gitlab ProjectManager
class _GitlabProject:
def __init__(self, status):
self.commits = {"my_ref": self._Commit(status)}
self.tags = self._Tags()
self.releases = self._Releases()... | relekang/python-semantic-release | tests/mocks/mock_gitlab.py | Python | mit | 4,092 |
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
from typing import TYPE_CHECKING
import msal
from .._internal import AadClient, AsyncContextManager
from .._internal.get_token_mixin import GetTokenMixin
from ..._cred... | Azure/azure-sdk-for-python | sdk/identity/azure-identity/azure/identity/aio/_credentials/certificate.py | Python | mit | 3,645 |
#Created on 14 Aug 2014
#@author: neil.butcher
from PySide2 import QtCore, QtWidgets
from pyqt_units.CurrentUnitSetter import setter
class UnitDisplay(QtWidgets.QWidget):
def __init__(self, parent, measurement=None, measurementLabel='normal'):
QtWidgets.QWidget.__init__(self, parent)
self.layo... | ergoregion/pyqt-units | pyqt_units/MeasurementWidgets.py | Python | mit | 6,390 |
import asyncio
import datetime
import unicodedata
import xml.etree.ElementTree as et
import discord
from bs4 import BeautifulSoup
from discord.ext import tasks
from discord_slash import cog_ext
from discord_slash.model import SlashCommandOptionType
from discord_slash.utils.manage_components import (create_actionrow,
... | Maselkov/GW2Bot | guildwars2/notifiers.py | Python | mit | 37,063 |
import os
import sys
from setuptools import setup
# Utility function to read the README file.
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
# The argparse module was introduced in python 2.7 or python 3.2
REQUIRES = ["argparse"] if sys.version[:3] in ('2.6', '3.0', '3.1') els... | musically-ut/seqfile | setup.py | Python | mit | 1,646 |
#!/usr/bin/env python
""" Package install script. """
import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
f = open(os.path.join(os.path.dirname(__file__), "README.rst"))
readme = f.read()
f.close()
setup(
name="pdfjinja",
version="1.1.0",
author="Ram... | rammie/pdfjinja | setup.py | Python | mit | 799 |
# -*- coding: utf-8 -*-
"""Flask app initialization."""
import os.path
from flask import Flask
from flask.ext.mako import MakoTemplates
app = Flask(__name__) # pylint: disable-msg=C0103
mako = MakoTemplates(app) # pylint: disable-msg=C0103
| stxnext-kindergarten/presence-analyzer-kgrela | src/presence_analyzer/main.py | Python | mit | 244 |
# 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 ... | Azure/azure-sdk-for-python | sdk/cognitiveservices/azure-cognitiveservices-search-customsearch/azure/cognitiveservices/search/customsearch/models/_models_py3.py | Python | mit | 29,187 |
########################################
# Automatically generated, do not edit.
########################################
from pyvisdk.thirdparty import Enum
VirtualMachineFlagInfoMonitorType = Enum(
'debug',
'release',
'stats',
)
| xuru/pyvisdk | pyvisdk/enums/virtual_machine_flag_info_monitor_type.py | Python | mit | 248 |
import os
from setuptools import setup
from tornadose import __version__
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="tornadose",
version=__version__,
author="Michael V. DePalatis",
author_email="mike@depalatis.net",
description="Tornado-se... | mivade/tornadose | setup.py | Python | mit | 988 |
from data_vault import VaultEnvironment
class KeeperApiHelper:
_expected_commands = []
_vault_env = VaultEnvironment()
@staticmethod
def communicate_expect(actions):
# type: (list) -> None
KeeperApiHelper._expected_commands.clear()
KeeperApiHelper._expected_commands.extend(act... | Keeper-Security/Commander | unit-tests/helper.py | Python | mit | 1,017 |
# Read from an MQTT queue and write events to Influxdb
import argparse
import asyncio
import time
import sys
from collections import namedtuple
from thingflow.base import Scheduler, SensorEvent
from thingflow.adapters.mqtt import MQTTReader
import thingflow.filters.select # adds select() method
import thingflow.filte... | jfischer/micropython-iot-hackathon | example_code/server_mqtt_to_influx.py | Python | mit | 2,908 |
""" UnitTests for the SimpleHTTPServer
"""
import mock
import unittest
class TestHTTPServerHandler(unittest.TestCase):
"""
"""
def setUp(self):
self.handler = mock.Mock()
def test_do_GET(self):
pass
def test_do_POST(self):
pass
def tearDown(self):
self.handler()
... | martynbristow/gabbi-examples | test_server.py | Python | mit | 367 |
# -*- coding: utf-8 -*-
"""
Written by Daniel M. Aukes.
Email: danaukes<at>seas.harvard.edu.
Please see LICENSE.txt for full license.
"""
from . import constraints
from . import classtools
from . import design
from . import popupcad_file
from . import genericlaminate
from . import genericshapebase
from . import generi... | Skylion007/popupcad | popupcad/filetypes/__init__.py | Python | mit | 701 |
import time as real_time
import unittest
import jwt as jwt_lib
from mock import patch
from twilio.jwt import Jwt, JwtDecodeError
class DummyJwt(Jwt):
"""Jwt implementation that allows setting arbitrary payload and headers for testing."""
ALGORITHM = 'HS256'
def __init__(self, secret_key, issuer, subje... | twilio/twilio-python | tests/unit/jwt/test_jwt.py | Python | mit | 9,331 |
#
# ti-sac.py is a Titanium plug-in for Sublime Text 3
#
# developed by Steve Rogers, SpiralArm Consulting Ltd (www.spiralarm.uk)
# @sarmcon
#
#
import sublime, sublime_plugin, os
import Titanium.lib.tiutils as Ti
# This will create a new Alloy Widget
class sacAlloyWidgetCommand(sublime_plugin.WindowCommand):
def ... | magnatronus/titanium-sac | titanium-sac.py | Python | mit | 4,652 |
import os
import stat
import sys
import attr
import pytest
from _pytest import pathlib
from _pytest.pathlib import Path
def test_tmpdir_fixture(testdir):
p = testdir.copy_example("tmpdir/tmpdir_fixture.py")
results = testdir.runpytest(p)
results.stdout.fnmatch_lines(["*1 passed*"])
@attr.s
class FakeC... | tomviner/pytest | testing/test_tmpdir.py | Python | mit | 12,284 |
# -*- coding: utf-8 -*-
"""
Class stores integer values for various types of moves in algebraic notation.
Copyright © 2016 Aubhro Sengupta. All rights reserved.
"""
MOVEMENT = 0
CAPTURE = 1
KING_SIDE_CASTLE = 2
QUEEN_SIDE_CASTLE = 3
EN_PASSANT = 4
PROMOTE = 5
CAPTURE_AND_PROMOTE = 6
NOT_IMPLEMENTED = 7
LONG... | LordDarkula/chess_py | chess_py/core/algebraic/notation_const.py | Python | mit | 330 |
from .endpoint import Endpoint
from .exceptions import MissingRequiredFieldError
from .fileuploads_endpoint import Fileuploads
from .. import RequestFactory, DatasourceItem, PaginationItem, ConnectionItem
import os
import logging
import copy
import cgi
from contextlib import closing
# The maximum size of a file that c... | Talvalin/server-client-python | tableauserverclient/server/endpoint/datasources_endpoint.py | Python | mit | 6,780 |
def test(options, buildout):
from subprocess import Popen, PIPE
import os
import sys
python = options['python']
if not os.path.exists(python):
raise IOError("There is no file at %s" % python)
if sys.platform == 'darwin':
output = Popen([python, "-c", "import platform; print (pla... | upiq/plonebuild | python/src/test-python.py | Python | mit | 873 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0006_only_one_slug_for_group'),
]
operations = [
migrations.AddField(
model_name='entry',
na... | Velmont/tabulagratulatoria | tg/core/migrations/0007_add_pay_address_fields.py | Python | mit | 1,148 |
#!/usr/bin/python
"""This script run the pathologic """
try:
import copy, optparse, sys, re, csv, traceback
from os import path, _exit, rename
import logging.handlers
from glob import glob
import multiprocessing
from libs.python_modules.utils.errorcodes import *
from libs.python_modules.utils.sy... | kishori82/MetaPathways_Python.3.0 | libs/python_scripts/MetaPathways_rpkm.py | Python | mit | 16,444 |
# coding: utf-8
from __future__ import unicode_literals
"""
This module provides classes to perform fitting of molecule with arbitrary
atom orders.
This module is supposed to perform exact comparisons without the atom order
correspondence prerequisite, while molecule_structure_comparator is supposed
to do rough compa... | rousseab/pymatgen | pymatgen/analysis/molecule_matcher.py | Python | mit | 24,855 |
import numpy as np
import pandas as pd
from lexos.models.rolling_window_model import RollingWindowsModel, \
RWATestOptions
from lexos.receivers.rolling_window_receiver import RWAFrontEndOptions, \
WindowUnitType, RWATokenType, RWARatioTokenOptions, RWAWindowOptions, \
RWAAverageTokenOptions, RWAPlotOptions
... | WheatonCS/Lexos | test/unit_test/test_rolling_windows_model.py | Python | mit | 12,643 |
# -*- coding: utf-8 -*-
# Mersenne Twister implementation
from _random import Random
import six
class MT19937(object):
def __init__(self, seed):
mt = [0] * 624
mt[0] = p = seed & 0xffffffff
for mti in six.moves.range(1, 624):
mt[mti] = p = (1812433253 * (p ^ (p >> 30)) + mti) ... | Kronuz/Xapiand | contrib/python/cuuid/mertwis.py | Python | mit | 495 |
import _plotly_utils.basevalidators
class ColorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(self, plotly_name="color", parent_name="contour.line", **kwargs):
super(ColorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... | plotly/plotly.py | packages/python/plotly/plotly/validators/contour/line/_color.py | Python | mit | 405 |
#!usr/bin/python
import wiki
from wiki import pagegen, timedate
import re, time, sys
wiki.setUser('Legobot III')
#get the list of protection templates...
fulllist = []
gen = pagegen.category(wiki.Page('Category:Protection templates'))
for page in gen:
if page.isTemplate():
name = page.titlewonamespace()
fulllist.a... | legoktm/pythonwikibot | scripts/protfix.py | Python | mit | 3,387 |
import traceback
from datetime import datetime
import os
from tempfile import gettempdir
import subprocess
from dateutil import tz
from mongoalchemy.session import Session
from pymongo import MongoClient
class MigrationBase(object):
def __init__(self, name, db_name):
self.name = name
self.db_name... | jf-parent/webbase | {{cookiecutter.project_name}}/server/model/migrationbase.py | Python | mit | 4,218 |
# 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 ... | Azure/azure-sdk-for-python | sdk/appplatform/azure-mgmt-appplatform/azure/mgmt/appplatform/v2022_01_01_preview/operations/_certificates_operations.py | Python | mit | 25,002 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-03-31 09:59
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('snippets', '0003_auto_20160331_0952'),
]
operations = [
migrations.AlterFiel... | vitorfs/cmdbox | cmdbox/snippets/migrations/0004_auto_20160331_0959.py | Python | mit | 592 |
""" Parser for the negative goals.
Allows to parse sets of the form, e.g., {i-j-k : i!=j & j!=k & i!=k} U
{i,j : i<3 & j<=3}, meaning that i should not know whether j knows the secret
of k, for i, j, k distinct, and that i should not know the secret of j for
either i = 1, 2 and j = 1, 2, 3.
Also allows instantiated neg... | FaustineMaffre/GossipProblem-PDDL-generator | neggoalsparser/parser.py | Python | mit | 3,303 |
'''
- login and get token
- process 2FA if 2FA is setup for this account
- Validates password for changing password using forgot password
'''
import requests
import json
get_token_url = "https://api.canopy.cloud:443/api/v1/sessions/"
validate_otp_url = "https://api.canopy.cloud:443/api/v1/sessions/otp/validate.json... | Mesitis/community | sample-code/Python/20 Users/validate_token.py | Python | mit | 2,764 |
# coding: utf-8
# In[2]:
import time
from bs4 import BeautifulSoup
import sys, io
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.proxy import *
# @author Ranjeet Singh <ranjeetsingh867@gmail.com>
# Modify it according to your requirements
no_of... | ranjeet867/google-play-crawler | crawl_play_store.py | Python | mit | 3,421 |
import numpy as np
import plotly.graph_objs as go
def p2c(r, theta, phi):
"""Convert polar unit vector to cartesians"""
return [r * np.sin(theta) * np.cos(phi),
r * np.sin(theta) * np.sin(phi),
r * np.cos(theta)]
# return [-r * np.cos(theta),
# r * np.sin(theta) * np.sin(... | cydcowley/Imperial-Visualizations | visuals_EM/Waves and Dielectrics/plotly_arrows.py | Python | mit | 2,137 |
"""A configuration management class built on top of etcd
See: http://python-etcd.readthedocs.org/
It provides a read-only access and just exposes a nested dict
"""
import functools
import time
import etcd3
from conman.conman_base import ConManBase
def thrice(delay=0.5):
"""This decorator tries failed operation... | the-gigi/conman | conman/conman_etcd.py | Python | mit | 3,240 |
"""Compute the sound field generated by a sound source.
The Green's function describes the spatial sound propagation over time.
.. include:: math-definitions.rst
"""
from __future__ import division
import numpy as np
from .. import util
from .. import defs
def point(xs, signal, observation_time, grid, c=None):
... | chris-hld/sfs-python | sfs/time/source.py | Python | mit | 3,359 |
#!/usr/bin/python
# Afficher les dix nombres suivants la valeur N donnée en paramètre
def show_num(a):
for i in range(10):
print(a, end='')
a += 1
print('Donne moi une valeur : ', end='')
a = int(input())
show_num(a)
| sumaxime/LIFAP1 | TD/TD3/Code/Python/3.py | Python | mit | 243 |
"""
WSGI config for <%= slug %> 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_... | vadimadr/generator-djdj | generators/app/templates/django_project_template/wsgi.py | Python | mit | 428 |
#!/usr/bin/env python3.5
'''
openlut: A package for managing and applying 1D and 3D LUTs.
Color Management: openlut deals with the raw RGB values, does its work, then puts out images with correct raw RGB values - a no-op.
Dependencies:
-numpy: Like, everything.
-wand: Saving/loading images.
-PyOpenGL - For image ... | so-rose/openlut | main.py | Python | mit | 1,931 |
"""
[2017-07-17] Challenge #324 [Easy] "manual" square root procedure (intermediate)
https://www.reddit.com/r/dailyprogrammer/comments/6nstip/20170717_challenge_324_easy_manual_square_root/
Write a program that outputs the highest number that is lower or equal than the square root of the given number, with
the given ... | DayGitH/Python-Challenges | DailyProgrammer/DP20170717A.py | Python | mit | 795 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from config.template_middleware import TemplateResponse
from gaebusiness.business import CommandExecutionException
from tekton import router
from gaecookie.decorator import no_csrf
from badge_app import badge_facade
from routes import badg... | raphaelrpl/portal | backend/appengine/routes/badges/new.py | Python | mit | 940 |
#!/usr/bin/env python3
#******************************************************************************
# (C) 2019, Stefan Korner, Austria *
# *
# The Space Python Library is free software; you can redi... | Stefan-Korner/SpacePyLibrary | Tutorial/Example_7.py | Python | mit | 2,134 |
from mongoengine import ValidationError
from tornkts.base.server_response import ServerError
class ValidateMixin(object):
def validate_model(self, prefix=None):
if prefix is not None:
prefix += '.'
else:
prefix = ''
try:
self.validate()
except V... | ktsstudio/tornkts | tornkts/mixins/validate_mixin.py | Python | mit | 578 |
"""
Upload a file to a server (or other filesystem)
Usage:
python upload.py FILENAME <FS URL>
example:
python upload.py foo.txt ftp://example.org/uploads/
"""
import os
import sys
from fs import open_fs
_, file_path, fs_url = sys.argv
filename = os.path.basename(file_path)
with open_fs(fs_url) as fs:
... | PyFilesystem/pyfilesystem2 | examples/upload.py | Python | mit | 523 |
#!/usr/bin/python
import Adafruit_DHT
sensor = Adafruit_DHT.DHT11
pin = 4
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
if humidity is not None and temperature is not None:
print 'Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity)
else:
print 'Failed to get reading. Try again!'
| valeriodelsarto/valecasa_bot | hum_temp_sensor.py | Python | mit | 317 |
"""views for the :mod:`apps.grid` app"""
from django.conf import settings
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.models import User
from django.core.cache import cache
from django.core.urlresolvers import reverse
from django.db.models import Count
from... | cartwheelweb/packaginator | apps/grid/views.py | Python | mit | 12,655 |
import datetime
import time
import base64
from pyope.ope import OPE, ValueRange
from Crypto.Cipher import AES
from Crypto import Random
from es import Elasticsearch
KEY = b'key goes here!!!' # 16 bytes
INDEX_NAME = "test-index"
class AESCipher:
BLOCK_SIZE = 16
def pad(self, s):
return s + (self.BL... | ilvar/pysearchable | pysearchable/generic.py | Python | mit | 3,543 |
import sys
import c2p
import traceback
from antlr4 import * # type: ignore
from antlr4.error.ErrorListener import ErrorListener # type: ignore
from c2p.grammar.antlr.SmallCLexer import SmallCLexer
from c2p.grammar.antlr.SmallCParser import SmallCParser
from c2p.grammar.ast.visitor import ASTVisitor
from c2p.grammar.as... | Sibert-Aerts/c2p | src/main.py | Python | mit | 2,477 |
# -*- coding: utf-8 -*-
from __future__ import division
from __future__ import unicode_literals
from collections import namedtuple
import json
import logging
import time
from collections import namedtuple
from slackclient import SlackClient
class SlackBot(object):
def __init__(self, settingsFilePath='settings.j... | mightypenguin/qotd | slackbot.py | Python | mit | 4,015 |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "google_maps_urlerator.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| thedanotto/google-maps-urlerator | manage.py | Python | mit | 264 |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'templates/$', views.templates, name='templates'),
]
| wispwisp/supportNotebook | responseTemplates/urls.py | Python | mit | 184 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2017-01-03 10:30
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0026_auto_20161215_2204'),
]
operations = [
migrations.AddField(
... | bomjacob/htxaarhuslan | main/migrations/0027_auto_20170103_1130.py | Python | mit | 977 |
import os
import argparse
import tensorflow as tf
import numpy as np
import sys
sys.path.append('../')
from reader import flickr8k_raw_data
def make_example(image_feature, caption_feature, id):
# The object we return
ex = tf.train.SequenceExample()
# A non-sequential feature of our example
sequence_le... | chintak/image-captioning | scripts/tfrecord_writer.py | Python | mit | 5,331 |
"""
The MIT License (MIT)
Copyright (c) [2015-2018] [Andrew Annex]
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, copy, modif... | drbitboy/SpiceyPy | spiceypy/__init__.py | Python | mit | 1,313 |
# coding: utf-8
"""
Salt Edge Account Information API
API Reference for services # noqa: E501
OpenAPI spec version: 5.0.0
Contact: support@saltedge.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import swagger_cl... | ltowarek/budget-supervisor | third_party/saltedge/test/test_rates_response.py | Python | mit | 900 |
""" Write the pseudocode and code for a function that reverses the words in a sentence. Input: "This is awesome" Output: "awesome is This". Give the Big O notation. """
def reverse(sentence):
""" split original sentence into a list, then append elements of the old list to the new list starting from last to first.... | megasan/210-CT | coursework 6.py | Python | mit | 903 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-19 18:40
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('mqtt_logger', '0002_mqttsubscription_active'),
]
operations = [
migrations.AlterMod... | ast0815/mqtt-hub | mqtt_logger/migrations/0003_auto_20161119_1840.py | Python | mit | 664 |
import os
import sympy
from example_helper import save_example_fit
from scipy_data_fitting import Data, Model, Fit
#
# Example of a fit to a sine wave with error bars.
#
name = 'wave'
# Load data from a csv file.
data = Data(name)
data.path = os.path.join('examples','data', 'wave.csv')
data.genfromtxt_args['skip_he... | razor-x/scipy-data_fitting | examples/wave.py | Python | mit | 1,252 |