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 |
|---|---|---|---|---|---|
# -*- coding: utf-8 -*-
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Time Series Analysis -- Generate statistical weigts from scatter
#
# Author: Jakob Rørsted Mosumgaard
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
##############################... | jakobmoss/tsa | utils/makeweights.py | Python | mit | 2,350 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('inbox', '0004_auto_20160410_2239'),
]
operations = [
migrations.AddField(
model_name='message',
name... | mas2tg/cs3240-f16-team07 | inbox/migrations/0005_message_blue.py | Python | mit | 430 |
#import list
import asyncio
import discord
from discord.ext import commands
import importlib.machinery
import datetime
import requests
import json
from bs4 import BeautifulSoup as BS
from requests import get as re_get
from random import *
from re import findall, match, search
TooBig = ["You know you make a cool bot an... | ImTheTom/discordBot | cogs/search.py | Python | mit | 12,276 |
import logging
import page_objects
def option_should_be_selected(text):
'''
Verifies specified dropdown option is selected.
Parameters
----------
text : str
Returns
-------
None
Raises
------
AssertionError
If the specified option is not selected.
'''
pag... | MooMan272/selenium_the_internet | verify/dropdown.py | Python | mit | 710 |
#!/usr/bin/python
import sys, os, subprocess, argparse, time
parser = argparse.ArgumentParser ()
parser.add_argument ( '-I', '--Interface', metavar='iface', dest='iface', action='store', help= argparse.SUPPRESS, required=True )
parser.add_argument ( '-M', '--MAC', metavar='MAC', dest='MAC', action='store', help=argpar... | Tylous/SniffAir | module/MAC_Changer.py | Python | mit | 710 |
#!/usr/bin/env python3
""" Sanzang Utils setup script for packaging and installation. """
from distutils.core import setup
with open('README.rst', 'r', encoding='utf-8') as fin:
LONG_DESCRIPTION = fin.read()
setup(
#
# Basic information
#
name='sanzang-utils',
version='1.3.3',
author='ya... | yaoguai/sanzang-utils | setup.py | Python | mit | 2,044 |
'''
Copyright 2013 Cosnita Radu Viorel
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, modify, merge, publish, distribute... | rcosnita/fantastico | fantastico/oauth2/models/tests/__init__.py | Python | mit | 1,175 |
#problem 4
import math
def isPalidrome(test):
return str(test) == str(test)[::-1] #op extended slicing feature
max = 0
for i in range(999,99,-1):
for j in range(999,99,-1):
prod = i*j
if isPalidrome(prod) and prod > max:
max = prod
print max | Lonkal/ProjectEuler | problem4.py | Python | mit | 255 |
#!/usr/bin/env python
"""symbal.py: Check for braces to be balanced"""
from stack import Stack
__author__ = 'Rohit Sinha'
def match_braces(opener, closer):
return "({[".index(opener) == ")}]".index(closer)
def brace_checker(brace_string):
stack = Stack()
isbal = True
index = 0
while index < l... | rohitsinha54/Learning-Python | algorithms/symbal.py | Python | mit | 889 |
# Create your views here.
from django.http import HttpResponse
from django.db.models import Sum
from confess.models import Post
from .middleware import retrieve_token
from .models import Like, MtmLike2Conf
from django.views.generic import TemplateView
import logging
from django.core import serializers
import json
logg... | amartinez1/nonymous | likes/views.py | Python | mit | 4,991 |
from tests.test_base import BaseTest, BaseTestLive
from mangopay.api import APIRequest as api
class RateLimit(BaseTest):
def test_rate_limits_update(self):
apis = api()
self.assertIsNone(apis.get_rate_limits())
BaseTestLive.get_ubo_declaration()
rate_limits = apis.get_rate_limits... | Mangopay/mangopay2-python-sdk | tests/test_rate_limit.py | Python | mit | 411 |
import scrapy
from locations.items import GeojsonPointItem
import itertools
def chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
def partition(l, n):
return list(chunks(l, n))
def process_hours(opening_hours):
ret_hours = []
for hours_str in opening_hours:
split_hours =... | iandees/all-the-places | locations/spiders/hm.py | Python | mit | 3,295 |
"""
Loads synthetic reaction datasets from USPTO.
This file contains loaders for synthetic reaction datasets from the US Patenent Office. http://nextmovesoftware.com/blog/2014/02/27/unleashing-over-a-million-reactions-into-the-wild/.
"""
from __future__ import division
from __future__ import unicode_literals
import ... | ktaneishi/deepchem | deepchem/molnet/load_function/uspto_datasets.py | Python | mit | 3,459 |
from src.graphDb import *
db = 'db/test.db'
def test_text_format():
assert text_format("asdkjhaeih") == "asdkjhaeih"
assert text_format("as&dkj>hae<ih") == "as&dkj>hae<ih"
assert text_format("") == ""
def test_creatingGroups():
conn = sqlite3.connect(db)
conn.execute("INSERT INTO TW... | planaspa/Data-Mining | tests/test_graphDb.py | Python | mit | 4,201 |
''' Module to store chemical elements related data.
'''
C12 = 1.99264648e-26 # mass of C12 (kg/atom)
amu = 1.66053904e-27 # atomic mass unit (kg)
chem_elements = {}
chem_elements['H'] = dict(index=1, mass=1.00794)
chem_elements['C'] = dict(index=6, mass=12.0107)
chem_elements['N'] = dict(index=7, mass=14.0067)
chem_... | PytLab/VASPy | vaspy/elements.py | Python | mit | 617 |
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, print_function, unicode_literals)
try:
import configparser
except ImportError:
from external.six.moves import configparser
import os
class Config(object):
def __init__(self, cli_args):
self.access_key_id = None
self.secret_ac... | jonhadfield/acli | lib/acli/config.py | Python | mit | 1,321 |
"""Benchmark runner.
Copyright 2013 by Rackspace Hosting, 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 a... | openilabs/falconlab | env/lib/python2.7/site-packages/falcon/cmd/bench.py | Python | mit | 944 |
#!/usr/bin/env python3
import sys
if len(sys.argv) != 2:
raise SystemExit('Incorrect usage. Use: ' + sys.argv[0] + ' <image.img>')
image_filename = sys.argv[1]
content = ''
with open(image_filename, 'rb') as f:
content = bytearray(f.read())
bytes_to_append = 512 - len(content) % 512
for i in range(b... | qwercik/brainfuckOS | utils/align-to-full-sector.py | Python | mit | 467 |
import time, sys, os, helper
from comodit_client.api import Client
from comodit_client.api.exceptions import PythonApiException
from comodit_client.rest.exceptions import ApiException
from combox.config import config
from helper import create_host, get_short_hostname, exec_cmd, exec_cmds, fork_cmd
def stop():
pr... | comodit/combox | combox/control.py | Python | mit | 569 |
# -*- coding: utf-8 -*-
"""This module contains custom roles to use in Sphinx.
"""
from docutils import nodes
def setup(app):
"""Install the extension.
Parameters:
app: Sphinx application context.
"""
app.add_role('arts', arts_docserver_role)
def arts_docserver_role(name, rawtext, text, li... | atmtools/typhon | typhon/utils/sphinxext.py | Python | mit | 1,221 |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def findBottomLeftValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
queue = [root... | ChuanleiGuo/AlgorithmsPlayground | LeetCodeSolutions/python/513_Find_Bottom_Left_Tree_Value.py | Python | mit | 432 |
from unittest import TestCase
from settings import settings
from office365.outlookservices.outlook_client import OutlookClient
from office365.runtime.auth.authentication_context import AuthenticationContext
class OutlookClientTestCase(TestCase):
"""SharePoint specific test case base class"""
@classmethod
... | vgrem/SharePointOnline-REST-Python-Client | tests/outlook_case.py | Python | mit | 1,082 |
"""
Django settings for tutorial project.
Generated by 'django-admin startproject' using Django 1.10.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
... | NewEvolution/django-rest | tutorial/settings.py | Python | mit | 3,277 |
# -*- coding: utf-8 -*-
"""
Let d(k) be the sum of all divisors of k.
We define the function S(N) = ∑1≤i≤N ∑1≤j≤N d(i·j).
For example, S(3) = d(1) + d(2) + d(3) + d(2) + d(4) + d(6) + d(3) + d(6) + d(9) = 59.
You are given that S(10^3) = 563576517282 and S(10^5) mod 10^9 = 215766508.
Find S(10^11) mod 10^9
"""
def ... | Ladeia/ProjectEuler | Problem439/Python/solution_1.py | Python | mit | 655 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from pycket import impersonators as imp
from pycket import values
from pycket import values_parameter, values_struct
from pycket.arity import Arity
from pycket.error import SchemeException
from pycket.prims.expose import... | pycket/pycket | pycket/prims/struct_structinfo.py | Python | mit | 11,050 |
# This file is part of Indico.
# Copyright (C) 2002 - 2022 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from datetime import time
from flask import request
from markupsafe import escape
from wtforms.fields imp... | indico/indico | indico/modules/events/surveys/forms.py | Python | mit | 7,812 |
#!/usr/bin/python
# System imports
# Panda Engine imports
from direct.showbase.DirectObject import DirectObject
from panda3d.core import *
from pandac.PandaModules import *
from panda3d.bullet import *
from direct.task.Task import Task
from direct.interval.IntervalGlobal import *
# Game imports
#-----... | grimfang/lext | core/level/builder.py | Python | mit | 26,314 |
n=1
i=1
while i<10:
print(n,"X 8 +",i,"=",n*8+i)
i=i+1
n=n*10+i
| alexandrebatista84/fundamentos-programacao | Aula Prática 2/Exercicio20.py | Python | mit | 84 |
import aiohttp_jinja2
import asyncio
import jinja2
from aiohttp import web
import settings
from auto.server.middlewares import middlewares
from auto.server.urls import url_patterns
loop = asyncio.get_event_loop()
app = web.Application(middlewares=middlewares)
aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoad... | beslave/auto-collector | auto/server/__init__.py | Python | mit | 678 |
"""
Created on 2013-1-19
@author: Administrator
"""
import doctest
def average(values):
"""Computes the arithmetic mean of a list of numbers.
>>> print(average([20, 30, 70]))
40.0
"""
return sum(values) / len(values)
doctest.testmod() # automatically validate the embedded tests
| quchunguang/test | testpy3/testdoctest.py | Python | mit | 305 |
from __future__ import print_function
import csv
import timeit
import datetime
import plugin_interface as plugintypes
class PluginCSVCollect(plugintypes.IPluginExtended):
def __init__(self, file_name="collect.csv", delim=",", verbose=False):
now = datetime.datetime.now()
self.time_stamp = '%d-%d-... | OpenBCI/OpenBCI_Python | openbci/plugins/csv_collect.py | Python | mit | 1,932 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
from .gcdt_logging import getLogger
from .utils import all_pages
from .kumo_core import stack_exists
log = getLogger(__name__)
def _stop_ec2_instances(awsclient, ec2_instances, wait=True):
"""Helper to stop ec2 instances.
By def... | glomex/gcdt | gcdt/kumo_start_stop.py | Python | mit | 17,372 |
# -*- coding: utf-8 -*-
"""The app module, containing the app factory function."""
from flask import Flask, render_template, Markup
from . import public, admin
from .extensions import *
from .config import Config
#extensions
def getPackage(num):
packages = {
"0": "No Package",
"1": "Basic Package"... | rileymjohnson/fbla | app/main.py | Python | mit | 3,324 |
from gisela.service import app
| toirl/gisela | gisela/__init__.py | Python | mit | 31 |
"""
Drawing plots
"""
import logging
from abc import ABCMeta, abstractmethod, abstractproperty
import matplotlib.pyplot as plt
import matplotlib.ticker as plticker
import numpy as np
from scipy.stats.mstats import gmean
from core import prepare
from core import styles
from config import Config
class FexPlot:
__... | tudinfse/fex | core/draw.py | Python | mit | 13,949 |
import time
import logging
import threading
import tempfile
import requests
import os
import nxm_api
MAX_BACKOFF_SECONDS = 120
DOWNLOAD_TIMEOUT = 5
MAX_ATTEMPTS = 20
DOWNLOAD_CHUNK_SIZE = 8192
class Download(object):
'''
Yay. This seems to do all the things
'''
def __init__(self, on_done_f, dl_id, de... | Yacoby/skyrim-package-manager | downloader.py | Python | mit | 7,201 |
import mock
import platform
import six
import unittest
from six import StringIO
from conans import tools
from conans.client.output import ConanOutput
from conans.client.tools.files import which
from conans.client.tools.oss import OSInfo
from conans.client.tools.system_pm import ChocolateyTool, SystemPackageTool,\
... | memsharded/conan | conans/test/unittests/client/tools/system_pm_test.py | Python | mit | 21,011 |
#!/usr/bin/env python
'''
catalog_harvesting/__init__.py
'''
import logging
import os
__version__ = '1.2.0'
LOGGER = None
def get_logger():
'''
Returns an initialized logger
'''
global LOGGER
if LOGGER is None:
LOGGER = logging.getLogger(__name__)
return LOGGER
def get_redis_con... | ioos/catalog-harvesting | catalog_harvesting/__init__.py | Python | mit | 762 |
#!/usr/bin/env python
from os.path import exists
from os import stat
from time import strftime, gmtime, time
from bottle import get, abort, response
from common import init
from wellpapp import RawWrapper, raw_exts
def fmttime(t):
return strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime(t))
def serve(fn, ext):
if not ... | drougge/wwwwellpapp | image.py | Python | mit | 1,071 |
"""Cover entities for the Overkiz (by Somfy) integration."""
| rohitranjan1991/home-assistant | homeassistant/components/overkiz/cover_entities/__init__.py | Python | mit | 61 |
import json
from django.core.exceptions import ValidationError
import app.productdb.models
def validate_json(value):
"""a simple JSON validator
:param value:
:return:
"""
try:
json.loads(value)
except:
raise ValidationError("Invalid format of JSON data string")
def validate_... | hoelsner/product-database | app/productdb/validators.py | Python | mit | 1,183 |
from flask import render_template
from website import app
@app.errorhandler(403)
def not_authorized(path):
return render_template('status/403.html'), 403
@app.errorhandler(404)
def page_not_found(path):
return render_template('status/404.html'), 404
@app.errorhandler(410)
def resource_gone(path):
retu... | fparma/events | website/errorhandler.py | Python | mit | 363 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'serika00'
import commands, socket, time, json, urllib2
#import sys
STATUS_PATH = "/fpm/status"
LISTEN_ADDR = "127.0.0.1:9000"
def go():
monit_keys = [
# 'pool
# 'start_time'
# 'process_manager'
# 'start_since'
('... | lilien1010/web_install | falcon-monit-scripts/phpfpm/phpfpm-monitor.py | Python | mit | 2,035 |
from enum import Enum
class Clothes(Enum):
Underwear = 1
Pants = 2
Shorts = 3
Socks = 4
Shoes = 5
Shirt = 6
Coat = 7
Hat = 8
Gloves = 9 | tomzx/decision-trees | clothes.py | Python | mit | 145 |
#!/usr/bin/env python
from __future__ import print_function
import os
import pickle
import platform
import random
import re
import string
import sys
from time import sleep
import traceback
import unittest
#from flaky import flaky
import py
import pytest
class FooTests(unittest.TestCase):
def test_foo_one(self)... | pycontribs/powertape | powertape/tests/tests.py | Python | mit | 527 |
"""All functions return a Component so you can easily pipe or compose them.
There are two types of functions:
- decorators: return the original component
- containers: return a new component
"""
from functools import lru_cache
import numpy as np
from omegaconf import OmegaConf
from pydantic import validate_argument... | gdsfactory/gdsfactory | gdsfactory/functions.py | Python | mit | 6,594 |
# -- PROGRAMMI 1. OSA - FUNKTSIOON TUTVUSTUS() --
# Defineerime funktsiooni, mis trükib ekraanile programmi tutvustuse ja sõnastikus olevate sõnade arvu
def tutvustus():
print("Inglise-eesti sõnastik (" + str(len(inglise_sõnad)) + " sõna)")
print("'v' - välju")
print("'a' - abi")
# -- PROGRAMMI 2. OS... | captainhungrykaboom/MTAT.TK.006 | 27. märts - 2. aprill ülesanded/sõanstik2.py | Python | mit | 2,725 |
'''
Appresponse module contains ApplicationResponse and FileDescriptor
classes which are used to parse response.
Usage:
>>> response = ApplicationResponse(xml_message)
>>> response.is_accepted() # Checks was the request accepted
'''
import os
import base64
import gzip
import logging
from lxml import etree
tr... | luojus/bankws | bankws/appresponse.py | Python | mit | 15,773 |
# The primary purpose of this module is to run data hashing and comparison functions
# It is also called during the intialization of modules to register their hashing and comparison functions.
# Try to leave all the boilerplate calls like DB access and JSON decoding in the main.py file
import hijackingprevention.sessi... | michardy/account-hijacking-prevention | hijackingprevention/api.py | Python | mit | 4,967 |
# 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/network/azure-mgmt-network/azure/mgmt/network/v2018_10_01/aio/operations/_network_interface_load_balancers_operations.py | Python | mit | 5,732 |
import socket
import random
import time
# A blocking server that simply sends hello to anyone who conncets to it
def blocking_server(bind='0.0.0.0', port=8080, queued_connections=5):
"""
This sets up a blocking socket. We will be listening for incomming
conncetions
"""
sock = socket.socket(socket... | mr-uuid/snippets | python/sockets/servers/blocking.py | Python | mit | 1,330 |
''''
This module is intended to contain the blueprints of the project
if you want more information about blueprints you can checkout this link:
http://flask.pocoo.org/docs/blueprints/
'''
| luanrafael/pygame-site | FlaskApp/src/views/__init__.py | Python | mit | 189 |
# with reference to: https://www.amazon.com/Make-Your-Own-Neural-Network-ebook/dp/B01EER4Z4G
import numpy as np
from numpy import random as rand
import scipy.special
from time import sleep
def main():
print('\nTesting 3 bit binary encoding classification')
# (out: [onehot], in: [binary])
binary_encodi... | deo1/deo1 | NaiveNet/NaiveNet.py | Python | mit | 5,324 |
#!/usr/bin/env python
'''
Naive parallel algorithm of prefix sum
http://people.cs.vt.edu/yongcao/teaching/cs5234/spring2013/slides/Lecture10.pdf
'''
import threading
# look maybe multiprocessing lib
import TestFunction
test_data = [2,6,2,3,5]
'''
Generic sum function
'''
def accumulate(in_list, amo... | dshpet/nure_TPDS | PrefixSum/PrefixSumParallelExtraNaive.py | Python | mit | 1,237 |
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
import hashlib
import secrets
import string
import tempfile
from datetime import timezone
from typing import Dict, Optional, List, Tuple, Union
from dateparser import parse
from urllib3 import disable_warnings
from math ... | VirusTotal/content | Packs/CortexXDR/Integrations/XDR_iocs/XDR_iocs.py | Python | mit | 17,908 |
#!/usr/bin/env python2
# Copyright (c) 2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import hashlib
import sys
import os
from random import SystemRandom
import base64
import hmac
if len(sys.a... | easycoin-core/Easycoin | share/rpcuser/rpcuser.py | Python | mit | 1,111 |
from scipy.io.wavfile import read
import matplotlib.pyplot as plt
from pylab import *
import PIL
from PIL import Image, ImageOps
import wave, struct, sys
import glob, os
for file in os.listdir("./"):
if file.endswith(".wav"):
print(file)
outputfile = file[:-4] + '.png'
input_data = read(fi... | sinneb/pyo-patcher | webroot/transformer.py | Python | mit | 791 |
from FileParsers.Parser import Parser
class CadenceSignOffSum(Parser):
def __init__(self, file):
super(CadenceSignOffSum, self).__init__(file)
@staticmethod
def match_line(regex1, line):
import re
line_variables = '.*(%s)[^\|]*\|[^\|]*\|[\s]*([\d.]*).*' % regex1
result = r... | tazmanrising/ppa | genCSV/FileParsers/Cadence/SignOffSum.py | Python | mit | 1,596 |
from numpy import matrix
# integer Size; integer nPQ, Matrix G; Matrix B; Array U
def JacMat(Size, nPQ, G, B, U):
# Method Of Every Entry Of Jacbean Matrix
f = U.real
e = U.imag
JacMat = zeros(Size, Size)
def Hij(B, G, e, f):
return -B*e+Gf
def Nij(B, G, e, f):
retur... | bitmingw/hexomega | assets/HOJacMat.py | Python | mit | 2,566 |
def vault(args):
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
if __name__ == "__main__":
vault(sys.argv)
| thatguystone/vault | vault/cmd.py | Python | mit | 136 |
"""
Django settings for proxyme project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
im... | alexsilva/proxyme | proxyme/settings.py | Python | mit | 2,487 |
if __name__ == '__main__':
n = int(input())
for i in range(n):
print(i**2)
| manishbisht/Competitive-Programming | Hackerrank/Practice/Python/1.introduction/05.Loops.py | Python | mit | 107 |
def int_list():
howmany = int(input("How many inputs? "))
nums = []
for i in range(howmany):
x = int(input("Input: "))
nums.append(x)
print(nums)
int_list()
| JSBCCA/pythoncode | early_projects/practice_loop.py | Python | mit | 191 |
"""coprop URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/dev/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-base... | Colorado-Realestate-Data/CO-Database | project/urls.py | Python | mit | 2,141 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-17 09:22
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [("impart", "0004_auto_20170117_0916")]
operations = [
mig... | jw/imagery | imagery/impart/migrations/0005_auto_20170117_0922.py | Python | mit | 621 |
#!/usr/bin/env python
import sys, os, logging, urllib, datetime
def fetchtemp():
cmd = '/opt/vc/bin/vcgencmd measure_temp'
line = os.popen(cmd).readline().strip()
output = line.split('=')[1].split("'")[0]#+' C'
return output
format = "%Y-%m-%d,%H:%M:%S"
today = datetime.datetime.today()
s = today.strftime(form... | mc3k/graph-stats | datagen.py | Python | mit | 433 |
# -*- coding: utf-8 -*-
from django.test import TestCase
from model_mommy import mommy
from core.models import Agenda, Deliberation
class CoreModelsTests(TestCase):
def test_agenda_create(self):
agenda = mommy.make(Agenda)
self.assertTrue(isinstance(agenda, Agenda))
self.assertEqual(age... | daneoshiga/agoracommuns | agoracommuns/agoracommuns/core/tests/test_models.py | Python | mit | 582 |
from django.shortcuts import render
from .models import Document, Corpus
from django.http import JsonResponse
from django.conf import settings
import json
import os
import re
import nltk
from nltk.corpus import *
from nltk.collocations import *
import string
import logging
logger = logging.getLogger('nltksite.nltkapp'... | wtamu-cisresearch/nltksite | nltkapp/views.py | Python | mit | 8,449 |
# -*- Mode: Python -*-
# Id: asyncore.py,v 2.51 2000/09/07 22:29:26 rushing Exp
# Author: Sam Rushing <rushing@nightmare.com>
# ======================================================================
# Copyright 1996 by Sam Rushing
#
# All Rights Reserved
#
# Permission to use, copy, modify,... | kenshinx/rps | script/proxycheck/asyncore.py | Python | mit | 20,290 |
'''
Created on Jun 29, 2016
This file shows an example of morphing to a pitch tier.
In f0_morph.py, the target pitch contour is extracted in the
script from another file. In this example, the pitch tier
could come from any source (hand sculpted or generated).
WARNING: If you attempt to morph to a pitch track that ha... | timmahrt/ProMo | examples/pitch_morph_to_pitch_contour.py | Python | mit | 2,635 |
# Copyright (c) 2018-2021, Neil Booth
#
# All rights reserved.
#
# This file is licensed under the Open BSV License version 3, see LICENCE for details.
'''Merkle trees, branches, proofs and roots.'''
from math import ceil, log
from aiorpcx import Event
from electrumx.lib.hash import double_sha256
class Merkle(obj... | kyuupichan/electrumx | electrumx/lib/merkle.py | Python | mit | 9,500 |
import argparse
import configparser
import sys
from io import StringIO
from pathlib import Path
from .mdgt import consolePrint, jsonPrint, listProvs
from .provider import Provider
from .webserve import serve as webserve
def setup_parser():
'''Initialize the argument parser.
Returns:
ArgumentParser in... | jjcamp/mdgt | mdgt/launcher.py | Python | mit | 3,287 |
# -*- coding: utf-8 -*-
# This example compares the available inverse Abel transform methods
# currently - direct, hansenlaw, and basex
# processing the O2- photoelectron velocity-map image
#
# Note it transforms only the Q0 (top-right) quadrant
# using the fundamental transform code
from __future__ import absolute_... | rth/PyAbel | examples/example_all_O2.py | Python | mit | 4,354 |
""" This aids with address validation by means of using REGEX
"""
import re
def validate_address(address):
"""
:param address:
:return: dictionary containing components of the address
that is with the keys: street_address, city, state, and zip
"""
regex = r'^([\d]+[\s[a-zA-Z/.\u00C0-\u... | dfehrenbach/Swen343_Human_Resources | hr/helpers/regex_helper.py | Python | mit | 1,258 |
from __future__ import absolute_import
import os
from celery import Celery
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ers_backend.settings')
from django.conf import settings
app = Celery('dataset_manager', backend="redis://localhost")
# Usin... | dumoulinj/ers | ers_backend/ers_backend/celery.py | Python | mit | 607 |
import wx
from testutil import main
def test_notaskbar():
f = lambda: wx.Frame(None, -1, style=wx.DEFAULT_FRAME_STYLE | wx.FRAME_NO_TASKBAR)
frames = [f() for x in xrange(10)]
for frame in frames:
frame.Destroy()
if __name__ == '__main__':
main(test_notaskbar) | ifwe/wxpy | src/tests/test_notaskbar.py | Python | mit | 289 |
from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from viewsets import PhotoListView, EditedPhotoListView, PhotoDetailView, \
EditedPhotoUpdateView
urlpatterns = [
url(r'^photos/$', PhotoListView.as_view()),
url(r'^photos/(?P<pk>[0-9]+)/$', PhotoDetailView.as_vi... | andela-jngatia/Picture-This | picturethis/imageeditor/urls.py | Python | mit | 561 |
import _plotly_utils.basevalidators
class LocationsValidator(_plotly_utils.basevalidators.DataArrayValidator):
def __init__(
self, plotly_name="locations", parent_name="isosurface.slices.z", **kwargs
):
super(LocationsValidator, self).__init__(
plotly_name=plotly_name,
... | plotly/python-api | packages/python/plotly/plotly/validators/isosurface/slices/z/_locations.py | Python | mit | 476 |
import numpy as np
import matplotlib.pyplot as plt
def bernstein(t, n, i):
cn = 1.0
ci = 1.0
cni = 1.0
for k in range(2, n, 1):
cn = cn * k
for k in range(1, i, 1):
if i == 1:
break
ci = ci * k
for k in range(1, n - i + 1, 1):
if n == i:
... | o-kei/design-computing-aij | ch5/curve.py | Python | mit | 983 |
import csv
import logging
log = logging.getLogger("safecity.locate.load_centerline")
from optparse import make_option
import os
from django.conf import settings
from django.contrib.gis.gdal import DataSource
from django.contrib.gis.gdal.error import OGRException
from django.contrib.gis.geos import fromstr, LineString,... | onyxfish/safecity | safecity/apps/locate/management/commands/load_centerline.py | Python | mit | 10,415 |
# coding: utf-8
"""`MemoryFS` opener definition.
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import typing
from .base import Opener
from .registry import registry
if typing.TYPE_CHECKING:
from typing import Text
from .parse import ... | PyFilesystem/pyfilesystem2 | fs/opener/memoryfs.py | Python | mit | 808 |
from CGATReport.Tracker import *
from IsoformReport import *
class imagesTracker(TrackerImages):
'''Convience Tracker for globbing images for gallery plot'''
def __init__(self, *args, **kwargs):
Tracker.__init__(self, *args, **kwargs)
if "glob" not in kwargs:
raise ValueError("T... | CGATOxford/CGATPipelines | CGATPipelines/pipeline_docs/pipeline_rnaseqdiffexpression/trackers/Isoform.py | Python | mit | 398 |
class Event:
MESSAGE = 'MESSAGE'
JOIN = 'JOIN'
LEAVE = 'LEAVE'
def __init__(self, _type, user, text):
self._type = _type
self.user = user
self.text = text
def __repr__(self):
return '[{}] {}: {}'.format(self._type, self.user, self.text)
def __str__(self):
return self.__repr__()
def message(user, te... | d3adc0d3/DeadBot | events.py | Python | mit | 509 |
"""
WSGI config for mums 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_SETTING... | scenting/mums | mums/wsgi.py | Python | mit | 386 |
import os
import sys
import unittest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from creditcard import formatter
class TestFormatter(unittest.TestCase):
def test_visa_number(self):
"""should identify a visa card numbers."""
visa_number = 4024007183310266
... | joshleeb/CreditCard | tests/formatter_spec.py | Python | mit | 3,269 |
'''Some helper functions for PyTorch, including:
- get_mean_and_std: calculate the mean and std value of dataset.
- msr_init: net parameter initialization.
- progress_bar: progress bar mimic xlua.progress.
'''
import os
import sys
import time
import math
import torch
_, term_width = os.popen('stty size', '... | roatienza/Deep-Learning-Experiments | versions/2020/transformer/code/ui.py | Python | mit | 3,932 |
# Problem 1
# Write a function called switch_ends() that takes a string
# and returns the string with the front and back letter switched
# Ex: switch_ends('part') -> 'tarp'
# switch_ends('abcdefg') -> 'gbcdefa'
# switch_ends('dog') -> 'god'
def switch_ends(string):
first = string[0]
last = string[-1]
... | Nethermaker/school-projects | intro/intro_challenge.py | Python | mit | 3,681 |
from django.db import models
from django.dispatch import receiver
from django.utils.encoding import python_2_unicode_compatible
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.core.validators import MaxValueValidator, MinValueValidator
from projects.models import Pro... | bilbeyt/ituro | ituro/results/models.py | Python | mit | 11,573 |
"""superharris URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Clas... | balbinot/superharris | superharris/urls.py | Python | mit | 828 |
from main.views import main
__all__ = ['main']
| sampathweb/cs109_twitterapp | app/blueprints/__init__.py | Python | mit | 48 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-18 23:22
from __future__ import unicode_literals
from django.db import migrations
import enumfields.fields
import wallet.enums
import enum
class TrxType(enum.Enum):
FINALIZED = 0
PENDING = 1
CANCELLATION = 2
class Migration(migrations.Migr... | uppsaladatavetare/foobar-api | src/wallet/migrations/0010_auto_20170218_2322.py | Python | mit | 640 |
# coding: utf8
"""
1. 每个文档自己训练一个Doc2Vec
2. 所有文档一起训练一个Doc2Vec
"""
import json
from gensim.models import Doc2Vec
from gensim.models.doc2vec import TaggedDocument
from stst.modules.features import Feature
from stst import utils
from stst import config
from stst.data import dict_utils
from stst.libs.kernel import vector_... | rgtjf/Semantic-Texual-Similarity-Toolkits | stst/features/features_nn.py | Python | mit | 4,605 |
from django.shortcuts import render
from django.http import HttpResponse
def home(request):
return render(request, 'home.html')
def contact(request):
return render(request, 'contact.html') | kaiocesar/simplemooc | simplemooc/core/views.py | Python | mit | 192 |
import pygame
pygame.init()
WIDTH=600
HEIGHT=480
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
while True:
events = pygame.event.get()
for event in events:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
print('this DOES work! :)')
| just-kir/just-kir.github.io | game_test.py | Python | mit | 295 |
'''
Created by auto_sdk on 2015.06.23
'''
from aliyun.api.base import RestApi
class Ecs20140526UnassociateEipAddressRequest(RestApi):
def __init__(self,domain='ecs.aliyuncs.com',port=80):
RestApi.__init__(self,domain, port)
self.AllocationId = None
self.InstanceId = None
def getapiname(self):
return 'ecs.ali... | francisar/rds_manager | aliyun/api/rest/Ecs20140526UnassociateEipAddressRequest.py | Python | mit | 364 |
# -*- coding:utf-8 -*-
import math
import web
import tx
def GetAdsPagination(assetid,page) :
html = ''
html = html + '<div name="pages" align="center">\n'
if assetid != None :
count = web.collection_ads.find({"asset":assetid}).count()
else :
count = web.collection_ads.find({"asset":{"$ne":"0"}}).count()
... | antchain/antchain.org | web/ads.py | Python | mit | 10,223 |
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.common.exceptions import NoSuchElementException
from webium import BasePage as WebiumBasePage, Find
class BasePage(WebiumBasePage):
url_path = None
a... | KorolevskyMax/TestFrameworkTemplate | pages/base_page.py | Python | mit | 1,954 |
# -*- encoding: utf-8 -*-
__author__ = 'kotaimen'
__date__ = '2/19/15'
class FormatError(Exception):
pass
class InvalidMapType(FormatError):
pass
class InvalidTileFormat(FormatError):
pass
class NoMatchingMapWriter(FormatError):
pass
| Kotaimen/stonemason | stonemason/formatbundle/exceptions.py | Python | mit | 259 |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Embeddable.src'
db.add_column(u'filer_embeddable_embeddab... | sthzg/djf-embeddable | filer_embeddable/migrations/0003_auto__add_field_embeddable_src__add_field_embeddable_width__add_field_.py | Python | mit | 8,845 |
class Entity(object):
RELEASE, RECORDING = range(0,2)
def __init__(self, *args, **kwargs):
pass
def json(self):
raise NotImplementedError
def parse_json(self, json):
raise NotImplementedError
| LordSputnik/python-mbio | mbio/entities/entity.py | Python | mit | 235 |