repo_name
stringlengths
5
104
path
stringlengths
4
248
content
stringlengths
102
99.9k
kaffeel/oppia
integrations_dev/openedx_xblock/xblock-oppia/oppia/oppia.py
# coding: utf-8 # # Copyright 2015 The Oppia 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 requi...
anryko/ansible
lib/ansible/playbook/__init__.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...
Architektor/PySnip
venv/lib/python2.7/site-packages/Cython/Plex/Scanners.py
#======================================================================= # # Python Lexical Analyser # # # Scanning an input stream # #======================================================================= from __future__ import absolute_import import cython cython.declare(BOL=object, EOL=object, EOF=object, NO...
yahman72/robotframework
utest/utils/test_timestampcache.py
import time import unittest from robot.utils.asserts import assert_equals from robot.utils.robottime import TimestampCache class FakeTimestampCache(TimestampCache): def __init__(self, epoch): TimestampCache.__init__(self) self.epoch = epoch + self.timezone_correction() def _get_epoch(self):...
nicememory/pie
pyglet/contrib/currently-broken/scene2d/tests/scene2d/RECT_FLAT_DEBUG.py
#!/usr/bin/env python '''Testing rect map debug rendering. You should see a checkered square grid. Press escape or close the window to finish the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest from render_base import RenderBase import scene2d from scene2d.debug import gen_rect_ma...
shekkbuilder/pyNES
pynes/c6502.py
# -*- coding: utf-8 -*- address_mode_def = {} address_mode_def['S_IMPLIED'] = dict(size=1, short='sngl') address_mode_def['S_IMMEDIATE'] = dict(size=2, short='imm') address_mode_def['S_IMMEDIATE_WITH_MODIFIER'] = dict(size=2, short='imm') address_mode_def['S_ACCUMULATOR'] = dict(size=1, short='acc') address_mode_def['...
odubno/microblog
venv/lib/python2.7/site-packages/migrate/versioning/util/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """.. currentmodule:: migrate.versioning.util""" import warnings import logging from decorator import decorator from pkg_resources import EntryPoint import six from sqlalchemy import create_engine from sqlalchemy.engine import Engine from sqlalchemy.pool import StaticPool...
vileopratama/vitech
src/addons/purchase/partner.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from openerp import api, fields, models class res_partner(models.Model): _name = 'res.partner' _inherit = 'res.partner' @api.multi def _purchase_invoice_count(self): PurchaseOrder = self.env['pu...
thaim/ansible
lib/ansible/modules/network/fortimanager/fmgr_ha.py
#!/usr/bin/python # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distribut...
garyjyao1/ansible
lib/ansible/modules/core/cloud/amazon/s3.py
#!/usr/bin/python # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed...
jmesteve/saas3
openerp/addons/mail/wizard/invite.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2012-Today OpenERP SA (<http://www.openerp.com>) # # This program is free software: you can redistribute it and/or modify # it under the terms o...
sdoran35/hate-to-hugs
venv/lib/python3.6/site-packages/jinja2/__init__.py
# -*- coding: utf-8 -*- """ jinja2 ~~~~~~ Jinja2 is a template engine written in pure Python. It provides a Django inspired non-XML syntax but supports inline expressions and an optional sandboxed environment. Nutshell -------- Here a small example of a Jinja2 template:: {% ...
jmesteve/saas3
openerp/addons/board/controllers.py
# -*- coding: utf-8 -*- from xml.etree import ElementTree from openerp.addons.web.controllers.main import load_actions_from_ir_values from openerp.addons.web.http import Controller, route, request class Board(Controller): @route('/board/add_to_dashboard', type='json', auth='user') def add_to_dashboard(self, m...
rooshilp/CMPUT410Lab6
virt_env/virt1/lib/python2.7/site-packages/django/conf/global_settings.py
# Default Django settings. Override these with settings in the module # pointed-to by the DJANGO_SETTINGS_MODULE environment variable. # This is defined here as a do-nothing function because we can't import # django.utils.translation -- that module depends on the settings. gettext_noop = lambda s: s #################...
ChinaMassClouds/copenstack-server
openstack/src/nova-2014.2/nova/openstack/common/report/views/text/header.py
# Copyright 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
beni55/edx-platform
lms/djangoapps/notifier_api/serializers.py
from django.contrib.auth.models import User from django.http import Http404 from rest_framework import serializers from openedx.core.djangoapps.course_groups.cohorts import is_course_cohorted from notification_prefs import NOTIFICATION_PREF_KEY from lang_pref import LANGUAGE_KEY class NotifierUserSerializer(serializ...
Teamxrtc/webrtc-streaming-node
third_party/webrtc/src/chromium/src/third_party/cython/src/Cython/Compiler/Scanning.py
# cython: infer_types=True, language_level=3, py2_import=True # # Cython Scanner # import os import platform import cython cython.declare(EncodedString=object, any_string_prefix=unicode, IDENT=unicode, print_function=object) from Cython import Utils from Cython.Plex.Scanners import Scanner from Cyth...
Russell-IO/ansible
lib/ansible/module_utils/facts/system/service_mgr.py
# Collect facts related to system service manager and init. # # 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) a...
wxgeo/geophar
wxgeometrie/sympy/polys/domains/pythonintegerring.py
"""Implementaton of :class:`PythonIntegerRing` class. """ from __future__ import print_function, division from sympy.polys.domains.integerring import IntegerRing from sympy.polys.domains.groundtypes import ( PythonInteger, SymPyInteger, python_sqrt, python_factorial, python_gcdex, python_gcd, python_lcm, ) f...
ahmadiga/min_edx
common/lib/xmodule/xmodule/library_tools.py
""" XBlock runtime services for LibraryContentModule """ from django.core.exceptions import PermissionDenied from opaque_keys.edx.locator import LibraryLocator, LibraryUsageLocator from search.search_engine_base import SearchEngine from xmodule.library_content_module import ANY_CAPA_TYPE_VALUE from xmodule.modulestore ...
JBonsink/GSOC-2013
tools/ns-allinone-3.14.1/ns-3.14.1/src/visualizer/visualizer/hud.py
import goocanvas import core import math import pango import gtk class Axes(object): def __init__(self, viz): self.viz = viz self.color = 0x8080C0FF self.hlines = goocanvas.Path(parent=viz.canvas.get_root_item(), stroke_color_rgba=self.color) self.hlines.lower(None) self.vl...
duckinator/boreutils
test/test_tty.py
""" Tests for `tty`. https://pubs.opengroup.org/onlinepubs/9699919799/utilities/tty.html """ # from helpers import check, check_version, run from helpers import check_version, run def test_version(): """Check that we're using Boreutil's implementation.""" assert check_version("tty") def test_missing_args(...
looooo/pivy
scons/scons.py
#! /usr/bin/env python # # SCons - a Software Constructor # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 The SCons Foundation # # 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 ...
brownhead/email-client
eclient/source.py
class Source: def __init__(self): self.config = None def set_config(self, config): """config should be some dict""" self.config = config def sync(self): """returns list of DSFSDF, is a coroutine""" pass import feedparser, pprint, asyncio, aiohttp class FeedSource(Source): @asyncio.coroutine def sync(s...
bearstech/modoboa
modoboa/admin/tests/test_password_schemes.py
from __future__ import unicode_literals from django.core.urlresolvers import reverse from modoboa.core.models import User from modoboa.lib.tests import ModoTestCase from .. import factories class PasswordSchemesTestCase(ModoTestCase): @classmethod def setUpTestData(cls): """Create test data.""" ...
alexis-jacq/signals
tools/R_DQL.py
from Tkinter import * import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torch.autograd as autograd from torch.autograd import Variable master = Tk() goal = 0 var_goal = StringVar() GAMMA = 0.9 last_state = Variable(torch.Tensor([0,0])).unsqueeze...
Dagur/sarpur-xbmc
plugin.video.sarpur/util/player.py
#!/usr/bin/env python # encoding: UTF-8 import xbmcgui import xbmcplugin import sarpur def play(url, name, live=False): """ Play audio or video on a given url" :param url: Full url of the video :param name: Stream name """ item = xbmcgui.ListItem(name, path=url) if live: item.se...
Julian/Great
great/models/music.py
from sqlalchemy import ( Boolean, Column, Date, Enum, ForeignKey, Integer, Table, Unicode, sql, ) from great.models.core import METADATA, table from great.models._guid import GUID def music_table(*args, **kwargs): args += ( Column("mbid", GUID, nullable=True, unique=True), Column("spotify_uri...
mtdx/ml-algorithms
svm/kernels.py
# import numpy as np from numpy import linalg import cvxopt import cvxopt.solvers def linear_kernel(x1, x2): return np.dot(x1, x2) def polynomial_kernel(x, y, p=3): return (1 + np.dot(x, y)) ** p def gaussian_kernel(x, y, sigma=5.0): return np.exp(-linalg.norm(x - y) ** 2 / (2 * (sigma ** 2))) class...
yono/tiarra_dbi_log_importer
tiarra_dbi_log_importer.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime import os import re import sys from lib.model import nick, channel, log def import_file(filename, parent): _nick = {} infile = open(filename).read().splitlines() date = os.path.basename(filename).replace('.txt', '') re_sentence = re.comp...
au9ustine/org.au9ustine.puzzles.pythonchallenge
pc/level_08.py
import unittest import urllib2 import requests import logging import re import urllib import os import os.path import bz2 # Default is warning, it's to suppress requests INFO log logging.basicConfig(format='%(message)s') def solution(): un = 'BZh91AY&SYA\xaf\x82\r\x00\x00\x01\x01\x80\x02\xc0\x02\x00 \x00!\x9ah3M...
bblais/Classy
classy/ssdf/setup.py
# -*- coding: utf-8 -*- # Copyright (c) 2011, Almar Klein description = 'Simple Structured Data Format.' long_description = """ Simple Structured Data Format ----------------------------- Ssdf is a simple format for stroring structured data. It supports seven data types, two of which are container elements: ...
MICC/MICC
micc/pgraph.py
import multiprocessing as mp from graph import shift from time import sleep def count(adj_node, adj_list): return adj_list.count(adj_node) def loop_dfs( current_node, start_node, graph, current_path, nodes_to_faces): if len(current_path) >= 3: path_head_3 = current_path[-3:] previous_three...
jmhal/elastichpc
base/platform/malleable/__init__.py
import CCAPython.gov.cca import logging import time import collections # Configure Logging logger = logging.getLogger('root') def mape_k_loop(platform_component, reconfiguration_port): """ This is the method for the process running the monitoring loop. """ # Extract Contract Information if platform_co...
xurxodiz/iria
iria/modules/dice/dice.py
import logging from telegram import ParseMode from telegram.ext import CommandHandler from . import rollem commands = ["roll"] logger = logging.getLogger(__package__) def register(dp): dp.add_handler(CommandHandler(commands, roll)) logger.info(f"Registered for commands {commands}") def roll(update, conte...
RoseLeBlood/pyMD
pyMD-Server.py
#! /usr/bin/python # -*- coding: utf-8 -*- # PythenMusicDeamon (pyMD) Server # # $Id: $ # # Copyright (c) 2017 Anna-Sophia Schroeck <annasophia.schroeck at outlook.de> # Permission is granted to anyone to use this software for any purpose, # including commercial applications, and to alter it and redistribute it # fr...
crs4/clay
tests/test_mqtt.py
# -*- coding: utf-8 -*- # # Copyright (c) 2012-2015, CRS4 # # 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...
USTB-LETTers/judger
utils.py
# -*- coding: utf-8 -*- import os import uuid import signal import docker import tarfile import checksumdir from contextlib import contextmanager from logzero import logger from config import DEFAULT_LIMITS, CPU_TO_REAL_TIME_FACTOR, DEFAULT_GENERATE_FILE_SIZE, TEMP_DIR, WORKING_DIR from exceptions import CrazyBoxErr...
Vladkryvoruchko/PSPNet-Keras-tensorflow
utils/preprocessing.py
import os import random import numpy as np from scipy.misc import imresize, imread from scipy.ndimage import zoom from collections import defaultdict DATA_MEAN = np.array([[[123.68, 116.779, 103.939]]]) def preprocess_img(img, input_shape): img = imresize(img, input_shape) img = img - DATA_MEAN img = img[...
emencia/porticus
porticus/templatetags/porticus_tags.py
# -*- coding: utf-8 -*- """ Common templates tags for porticus """ from six import string_types from django.conf import settings from django import template from django.utils.safestring import mark_safe from django.shortcuts import get_object_or_404 from porticus.models import Gallery, Album register = template.Libr...
JB26/Bibthek
lib/auth.py
"""Authentication process""" import cherrypy import lib.db_users as db_users def check_auth(required=True, user_role=None): """Check authentication""" if required: user = db_users.user_by_session(cherrypy.session.id) if user == None: cherrypy.lib.sessions.expire() raise ...
rabitt/motif
motif/utils.py
# -*- coding: utf-8 -*- """ Utility methods for motif """ import csv from mir_eval import melody import numpy as np import os def validate_contours(index, times, freqs, salience): '''Check that contour input is well formed. Parameters ---------- index : np.array Array of contour numbers t...
DavidLP/hass_scripts
setup.py
#!/usr/bin/env python # This setup relies on setuptools since distutils is insufficient and # badly hacked code from setuptools import setup, find_packages version = '0.0.1' author = 'David-Leon Pohl' author_email = 'david-leon.pohl@rub.de' with open('requirements.txt') as f: required = f.read().splitlines() set...
BenjaminEHowe/library-api
setup.py
#!/usr/bin/env python3 from setuptools import find_packages,setup VERSION = '0.1.0.dev1' install_requires = [ 'beautifulsoup4>=4.4.1', 'requests>=2.4.3', ] setup( name="Library API", version=VERSION, description="Privides access to various libraries (book borrowing places, not code libraries).", ...
sebasvega95/feature-matching
tests/surf_test.py
import cv2 import numpy as np HESSIAN_THRESHOLD = 400 FLANN_INDEX_KDTREE = 0 def test_surfmatch(ref_img, query_img, num_kp=None, min_match=10): ''' Tests the SURF matcher by finding an homography and counting the percentage of inliers in said homography. Parameters ---------- ref_img: ndarra...
sameenjalal/mavenize-beta
mavenize/lib/db/DownloadAuthors.py
from movie.models import Movie import urllib as urllib import urllib2,json import os,glob from django.template import defaultfilters import unicodedata author_list = [] BASE='http://api.rottentomatoes.com/api/public/v1.0/' KEY='mz7z7f9zm79tc3hcaw3xb85w' movieURL=BASE+'movies.json' def main(): print('starting.')...
mitschabaude/nanopores
nanopores/tools/solvermethods.py
from dolfin import has_lu_solver_method lusolver = "superlu_dist" if has_lu_solver_method("superlu_dist") else "default" direct = dict( reuse = False, iterative = False, lusolver = lusolver, ) direct_reuse = dict( reuse = True, iterative = False, lusolver = lusolver, luparams = dict( ...
vickenty/ookoobah
ookoobah/menu_mode.py
from __future__ import division import sys import os import pyglet from pyglet.gl import * from pyglet.window import key import mode import gui class MenuMode(mode.Mode): name = "menu_mode" def connect(self, controller): super(MenuMode, self).connect(controller) self.init_opengl() self...
placeB/translation-service
server/interactions/handlers/ios.py
# -*- coding: utf-8 -*- # # Created on 2/7/16 by maersu from core.utils import IOS from django.utils.encoding import smart_str from interactions.handlers.base import BaseWriter import re from translations.models import TranslatedItem IOS_KEY_VALUE = re.compile(r'"(?P<key>.*?)"\s*?=\s*?"(?P<value>.*?)";', re.MULTILINE...
jmhal/elastichpc
beta/trials/static/Computation.py
import logging import os import time import subprocess def number_of_nodes(): _file = open(os.environ['HOME'] + "/machinefile", "r") n = len ([ l for l in _file.readlines() if l.strip(' \n') != '' ]) _file.close() return n return def log(msg): logging.debug("COMPUTATION: " + msg) return def co...
adsabs/biblib-service
biblib/tests/unit_tests/test_manage.py
""" Tests the methods within the flask-script file manage.py """ import os import unittest import testing.postgresql from biblib.app import create_app from biblib.manage import CreateDatabase, DestroyDatabase, DeleteStaleUsers from biblib.models import Base, User, Library, Permissions from sqlalchemy import create_eng...
aspidites/beets
beets/autotag/match.py
# This file is part of beets. # Copyright 2011, Adrian Sampson. # # 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, ...
DougFirErickson/arcplus
ArcToolbox/Scripts/sdeconn.py
""" Name: sdeconn.py Description: Utility functions for sde connections Author: blord-castillo (http://gis.stackexchange.com/users/3386/blord-castillo) Do on the fly connections in python using Sql Server direct connect only. Eliminates the problem of database connection files being inconsistent from machi...
ronekko/chainer
chainer/links/loss/black_out.py
import numpy from chainer.backends import cuda from chainer.functions.loss import black_out from chainer import link from chainer.utils import walker_alias from chainer import variable class BlackOut(link.Link): """BlackOut loss layer. .. seealso:: :func:`~chainer.functions.black_out` for more detail. ...
leejz/misc-scripts
add_annotations_to_fasta.py
#!/usr/bin/env python """ -------------------------------------------------------------------------------- Created: Jackson Lee 1/28/14 This script reads in a fasta file and a tab delimited text file of annotations and replaces the header line with matched annotations Input fasta file format: any fasta file I...
warnes/irrigatorpro
irrigator_pro/farms/migrations/0002_auto_20150513_0054.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import farms.models class Migration(migrations.Migration): dependencies = [ ('farms', '0001_initial'), ] operations = [ migrations.AlterField( model_name='cropseason', ...
MatrixCrawler/ansible-lint
lib/ansiblelint/rules/LineTooLongRule.py
# Copyright (c) 2016, Will Thames and contributors # Copyright (c) 2018, Ansible Project from ansiblelint import AnsibleLintRule class LineTooLongRule(AnsibleLintRule): id = '204' shortdesc = 'Lines should be no longer than 120 chars' description = ( 'Long lines make code harder to read and ' ...
bvujicic/yml-to-env
tests/test_config.py
import os import pytest import yaml from yml_config import Config @pytest.fixture() def data(): return { 'bool': False, 'number': 1, 'string': 'test_string', 'sequence': ['item1', 'item2', 'item3'], 'mapping': { 'key1': 'value1', 'key2': { ...
jamesgk/feaTools
Lib/feaTools/parser.py
import re class FeaToolsParserSyntaxError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) # used for removing all comments commentRE = re.compile("#.*") # used for finding all strings stringRE = re.compile( "\"" # " "([^...
dfm/ketu
ketu/one_d_search.py
# -*- coding: utf-8 -*- from __future__ import division, print_function, unicode_literals __all__ = ["OneDSearch"] import os import h5py import numpy as np from .pipeline import Pipeline from ._compute import compute_hypotheses class OneDSearch(Pipeline): cache_ext = ".h5" query_parameters = dict( ...
gwu-libraries/social-feed-manager
sfm/ui/views.py
import os from django.conf import settings from django.contrib import auth from django.contrib.auth.decorators import login_required, user_passes_test from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.core.urlresolvers import reverse from django.db import connection from django.http ...
levilucio/SyVOLT
UMLRT2Kiltera_MM/Properties/Multiplicity/Himesis/HNew1orMoreNamePart2_CompleteLHS.py
from core.himesis import Himesis, HimesisPreConditionPatternLHS import cPickle as pickle from uuid import UUID class HNew1orMoreNamePart2_CompleteLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HNew1orMoreNamePart2_CompleteLHS. ...
arpho/mmasgis5
mmasgis/DataSource.py
from PyQt4 import QtCore,QtGui import re # Initialize Qt resources from file resources.py from sessionClasses import * class DataSource(): """ gestisce le operazioni di lettura e scrittura sui settings di Qt per la gestione degli utenti """ def __init__(self,company,application): """ @param string: name-space...
skoczen/polytester
polytester/parsers/nose.py
import re from .default import DefaultParser class NoseParser(DefaultParser): name = "nose" def command_matches(self, command): return "nosetests" in command or "-m nose" in command def num_passed(self, result): return self.num_total(result) - self.num_failed(result) def num_total(...
pocin/kbc-mailchimp-writer
tests/test_utils.py
""" Test utility functions """ from unittest.mock import Mock import csv import json import requests import pytest from mailchimp3 import MailChimp from mcwriter.utils import (serialize_dotted_path_dict, serialize_lists_input, serialize_members_input, ...
khalibartan/pgmpy
pgmpy/factors/base.py
from abc import abstractmethod from pgmpy.extern.six.moves import reduce class BaseFactor(object): """ Base class for Factors. Any Factor implementation should inherit this class. """ def __init__(self, *args, **kwargs): pass @abstractmethod def is_valid_cpd(self): pass def...
somilasthana/esearch
ESDatabaseMetaStore.py
import sys import PConstant class DummySchema(object): def __init__(self): self.request_body = {} def schema(): return self.request_body class TrialSchema(object): def __init__(self): self.request_body = { "settings": { "analysis": { ...
kidscancode/gamedev
tutorials/shmup/shmup-3.py
# KidsCanCode - Game Development with Pygame video series # Shmup game - part 3 # Video link: https://www.youtube.com/watch?v=33g62PpFwsE # Collisions and bullets import pygame import random WIDTH = 480 HEIGHT = 600 FPS = 60 # define colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, ...
accepton/accepton-python
accepton/response.py
class Response(dict): def __init__(self, *args, **kwargs): super(Response, self).__init__(*args, **kwargs) for (key, value) in self.items(): self[key] = self.convert_value(value) def __getattr__(self, name): return self.__getitem__(name) def __getitem__(self, item): ...
AisakaTiger/Learn-Python-The-Hard-Way
ex16.py
from sys import argv script, filename = argv print "We're going to erase %r." % filename print "If you dont want that, hit CTRL-C(^C)." print "If you do want that, hit RETURN." raw_input("?") print"Opening the file..." target = open(filename,'w') print "Truncating the file. Goodbye!" target.truncate() print "Now ...
langdev/log.langdev.org
logviewer/app.py
import os import io import re import time import json import random import datetime import itertools import functools import sqlite3 import sphinxapi from contextlib import closing import flask from flask import (Flask, request, redirect, session, url_for, render_template, current_app, jsonify) fro...
cloudconsole/cloudconsole
setup.py
"""A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject """ # Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding # from codecs import open from os import path here = path.abs...
SkillSmart/ConferenceManagementSystem
SessionManagement/models.py
import requests from django.conf import settings from django.db import models from django.urls import reverse_lazy from UserManagement.models import Attendent, ExpertProfile, Team # Import for Google Maps Plugin from django_google_maps import fields as map_fields from django.utils.text import slugify from datetime imp...
fujimotos/Eubin
test/test_pop3.py
import unittest import tempfile import shutil import os from tempfile import TemporaryDirectory from threading import Thread from eubin import pop3 from mockserver import POP3Server class TestStatelog(unittest.TestCase): def setUp(self): self.tmpdir = TemporaryDirectory() self.logpath = os.path.joi...
mozillazg/django-simple-projects
projects/custom-context-processors/mysite/settings.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Django settings for mysite project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', ...
alaudet/hcsr04sensor
recipes/metric_depth.py
from hcsr04sensor import sensor # Created by Al Audet # MIT License def main(): """Calculate the depth of a liquid in centimeters using a HCSR04 sensor and a Raspberry Pi""" trig_pin = 17 echo_pin = 27 # Default values # unit = 'metric' # temperature = 20 hole_depth = 80 # cent...
kankiri/pabiana
demos/smarthome/smarthome/__init__.py
from pabiana import Area, repo from pabiana.utils import multiple from . import utils area = Area(repo['area-name'], repo['interfaces']) premise = utils.setup config = { 'clock-name': 'clock', 'clock-slots': multiple(1, 6), 'context-values': { 'temperature': 18, 'window-open': False } } @area.register def i...
RihanWu/vocabtool
dict/base_class.py
# -*- coding: utf-8 -*- """This module contains base class for dictionary entry""" class Entry(): """Store info of a word that is one part of speech. Store pronounciation,sound, part of speech, word explanation and example sentences about one word or expression. """ def __init__(self): ...
jacobdein/nacoustik
nacoustik/wave.py
""" Wave class Jacob Dein 2016 nacoustik Author: Jacob Dein License: MIT """ from sys import stderr from os import path from sox import file_info import numpy as np from scipy.io import wavfile class Wave: """Create wave object""" def __init__(self, wave): """ Parameters ---------- wave: file path...
rheineke/log_merge
main.py
"""Read any number of files and write a single merged and ordered file""" import time import fastparquet import numpy as np import pandas as pd def generate_input_files(input_filenames, n, max_interval=0): for i_fn in input_filenames: df = _input_data_frame(n, max_interval=...
fp12/yahtr
tests/tests_utils.py
import unittest from yahtr.utils.attr import get_from_dict, copy_from_instance from yahtr.utils.color import Color class Dummy: pass class TestAttr(unittest.TestCase): def setUp(self): self.dummy = Dummy() self.args = ['p1', 'p2', 'p3'] self.d = {'p1': 'p1', 'p2': None, 'p4': {}} ...
Tim-Erwin/marshmallow-jsonapi
marshmallow_jsonapi/exceptions.py
# -*- coding: utf-8 -*- """Exception classes.""" class JSONAPIError(Exception): """Base class for all exceptions in this package.""" pass class IncorrectTypeError(JSONAPIError, ValueError): """Raised when client provides an invalid `type` in a request.""" pointer = '/data/type' default_message = '...
JanMalte/secondhandshop_server
src/volunteers/templatetags/volunteer.py
""" Second-Hand-Shop Project @author: Malte Gerth @copyright: Copyright (C) 2015 Malte Gerth @license: MIT @maintainer: Malte Gerth @email: mail@malte-gerth.de """ from django import template from events.models import get_active_event __author__ = "Malte Gerth <mail@malte-gerth.de>" __copyright__ = "Co...
mindeng/crypto-utils
padding-oracle-attack/poa_test.py
#! /usr/bin/env python from hashlib import md5 from Crypto.Cipher import AES from Crypto import Random import struct class PaddingError(Exception): pass def derive_key_and_iv(password, salt, key_length, iv_length): d = d_i = '' while len(d) < key_length + iv_length: d_i = md5(d_i + password + sal...
iandennismiller/mdx_journal
mdx_journal/__init__.py
import re from markdown.preprocessors import Preprocessor from markdown import Extension __version__ = "0.1.1" class JournalPreprocessor(Preprocessor): pattern_time = re.compile(r'^(\d{4})$') pattern_date = re.compile(r'^(\d{4}-\d{2}-\d{2})$') def run(self, lines): return [self._t1(self._t2(line...
nschloe/quadpy
src/quadpy/s2/_stroud.py
import numpy as np import sympy from ..helpers import book, untangle, z from ._albrecht import albrecht_4 as stroud_s2_9_1 from ._albrecht import albrecht_5 as stroud_s2_11_2 from ._albrecht import albrecht_6 as stroud_s2_13_2 from ._albrecht import albrecht_7 as stroud_s2_15_2 from ._albrecht import albrecht_8 as str...
guilhermebr/python-docx
tests/oxml/parts/test_document.py
# encoding: utf-8 """ Test suite for the docx.oxml.parts module. """ from __future__ import absolute_import, print_function, unicode_literals import pytest from .unitdata.document import a_body from ..unitdata.section import a_type from ..unitdata.text import a_p, a_pPr, a_sectPr class DescribeCT_Body(object): ...
GeorgeGkas/Data_Structures_and_Algorithms_in_Python
Chapter2/R-2/4.py
class Flower: """A flower.""" def __init__(self, name, petals, price): """Create a new flower instance. name the name of the flower (e.g. 'Spanish Oyster') petals the number of petals exists (e.g. 50) price price of each flower (measured in euros) """ self...
Kulbear/deep-learning-nano-foundation
lectures/backpropagation.py
import numpy as np def sigmoid(x): """Calculate sigmoid""" return 1 / (1 + np.exp(-x)) x = np.array([0.5, 0.1, -0.2]) target = 0.6 learning_rate = 0.5 weights_input_hidden = np.array([[0.5, -0.6], [0.1, -0.2], [0.1, 0.7]]) weights_hidden_ou...
carlosperate/LightUpPi-Alarm
LightUpHardware/unicornhatmock.py
# -*- coding: utf-8 -*- # # Mock module for the Unicorn Hat package # # Copyright (c) 2015 carlosperate http://carlosperate.github.io # # Licensed under The MIT License (MIT), a copy can be found in the LICENSE file # # This is a simple mock module that will print to screen the unicorn hat package # calls. It is used t...
staab/maria-code
knitter/main.py
import sys import os if len(sys.argv) < 2: print "Please include a template to knit." sys.exit(1) if sys.argv[1] == 'list': print "Available templates:\n" print "\n".join(os.listdir('./templates')) sys.exit(0) try: with open("./templates/%s" % sys.argv[1], 'r') as f: template = f.read...
JiangKlijna/leetcode-learning
py/263 Ugly Number/UglyNumber.py
# Write a program to check whether a given number is an ugly number. # Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. # For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. # Note that 1 is typically treated as an ugly number. class Solution(object): ...
joke2k/faker
faker/providers/job/ja_JP/__init__.py
from .. import Provider as BaseProvider class Provider(BaseProvider): """ source: https://ja.wikipedia.org/wiki/%E8%81%B7%E6%A5%AD%E4%B8%80%E8%A6%A7 """ jobs = [ "アイドル", "アーティスト", "アートディレクター", "アナウンサー", "アニメーター", "医師", "イラストレーター", "医療事務員...
davidxmoody/kata
project-euler/completed/first-attempt/euler4.py
x, y = 999, 999 pals = [] def is_palindrome(num): strnum = str(num) for i in range(len(strnum)/2): if strnum[i]!=strnum[-1-i]: return False return True while x>0: while y>0: if is_palindrome(x*y): pals.append(x*y) y -= 1 x -= 1 y = 999 print 'palindrome is:', max(pals)
rzzzwilson/morse_trainer
test.py
""" CLI program to continually send a morse string. Usage: test [-h] [-s c,w] <string> where -h means print this help and stop -s c,w means set char and word speeds and <string> is the morse string to repeatedly send The morse sound is created in a separate thread. """ import sys import os import...
tanium/pytan
EXAMPLES/PYTAN_API/ask_manual_question_sensor_with_filter_and_3_options.py
#!/usr/bin/env python """ Ask a manual question using human strings by referencing the name of a single sensor. Also supply a sensor filter that limits the column data that is shown to values that contain Windows (which is short hand for regex match against .*Windows.*). Also supply filter options that re-fetches any...
slippers/blogging_security
main/blogging/__init__.py
from main import app, db from main.security import security, user_datastore from flask.ext.blogging import SQLAStorage, BloggingEngine # configure the bloggin storeage for the blog.db # using multiple database bound to sqlalchemy storage = SQLAStorage(db=db, bind="blog") # create all the tables db.create_all() # sta...
Guest007/vgid
apps/living/views.py
# -*- coding: utf-8 -*- from django.shortcuts import render from django.views.generic import View, ListView, DetailView from .models import Living, LivingType from endless_pagination.views import AjaxListView class LivingList(AjaxListView): model = Living # queryset = Living.objects.filter(is_publish=True)#.o...
outrofelipe/Python-para-zumbis
lista-3b/03_primo.py
''' Lista 3b - Exercício 3 Verifique se um inteiro positivo n é primo. Felipe Nogueira de Souza Twitter: @_outrofelipe ''' n = int(input('Informe um número inteiro positivo: ')) i = 2 primo = True while i <= n - 1: if n % i == 0: primo = False break i += 1 if primo: print('O número %d é p...
myusuf3/racks
setup.py
from racks import __version__ import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup dependencies = ['docopt', 'termcolor'] def publish(): os.system("python setup.py sdist upload") if sys.argv[-1] == "publish": publish() sys.exit() setup( ...