repo_name stringlengths 5 104 | path stringlengths 4 248 | content stringlengths 102 99.9k |
|---|---|---|
atruberg/django-custom | tests/admin_inlines/admin.py | from __future__ import absolute_import
from django.contrib import admin
from django import forms
from .models import *
site = admin.AdminSite(name="admin")
class BookInline(admin.TabularInline):
model = Author.books.through
class NonAutoPKBookTabularInline(admin.TabularInline):
model = NonAutoPKBook
cl... |
technologiescollege/Blockly-rduino-communication | scripts_XP/Tools/Scripts/reindent.py | #! /usr/bin/env python3
# Released to the public domain, by Tim Peters, 03 October 2000.
"""reindent [-d][-r][-v] [ path ... ]
-d (--dryrun) Dry run. Analyze, but don't make any changes to, files.
-r (--recurse) Recurse. Search for all .py files in subdirectories too.
-n (--nobackup) No backup. Does not make ... |
halexan/Headquarters | src/headquarters/packet/slow.py | # Copyright (C) 2013 Nippon Telegraph and Telephone Corporation.
#
# 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 appli... |
Teamxrtc/webrtc-streaming-node | third_party/webrtc/src/chromium/src/third_party/mojo/src/mojo/public/tools/bindings/pylib/mojom_tests/generate/generator_unittest.py | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import imp
import os.path
import sys
import unittest
def _GetDirAbove(dirname):
"""Returns the directory "above" this file containing |dirname| (which mus... |
phil235/-tg-station | tools/linux_build.py | #!/usr/bin/env python
import subprocess
import os
import sys
import argparse
import time
from subprocess import PIPE, STDOUT
null = open("/dev/null", "wb")
def wait(p):
rc = p.wait()
if rc != 0:
p = play("sound/misc/compiler-failure.ogg")
p.wait()
assert p.returncode == 0
sys.... |
mjtamlyn/django | tests/utils_tests/test_safestring.py | from django.template import Context, Template
from django.test import SimpleTestCase
from django.utils import html, text
from django.utils.functional import lazy, lazystr
from django.utils.safestring import SafeData, mark_safe
class customescape(str):
def __html__(self):
# implement specific and obviously... |
yosshy/nova | nova/db/sqlalchemy/migrate_repo/versions/272_add_keypair_type.py | # Copyright (c) 2015 Cloudbase Solutions SRL
# 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
#
# Unles... |
GrandmasterK/XScheduler | venv/lib/python2.7/site-packages/googleapiclient/schema.py | # Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
Bryan792/dotfiles | vim/vim.symlink/eclim/autoload/eclim/python/rope/refactor/wildcards.py | from rope.base import ast, evaluate, builtins, pyobjects
from rope.refactor import patchedast, occurrences
class Wildcard(object):
def get_name(self):
"""Return the name of this wildcard"""
def matches(self, suspect, arg):
"""Return `True` if `suspect` matches this wildcard"""
class Suspec... |
austinharris/gem5-riscv | src/arch/x86/isa/insts/simd64/integer/shift/right_arithmetic_shift.py | # Copyright (c) 2007 The Hewlett-Packard Development Company
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implemen... |
LumPenPacK/NetworkExtractionFromImages | win_build/nefi2_win_amd64_msvc_2015/site-packages/networkx/algorithms/tests/test_smetric.py |
from nose.tools import assert_equal,raises
import networkx as nx
def test_smetric():
g = nx.Graph()
g.add_edge(1,2)
g.add_edge(2,3)
g.add_edge(2,4)
g.add_edge(1,4)
sm = nx.s_metric(g,normalized=False)
assert_equal(sm, 19.0)
# smNorm = nx.s_metric(g,normalized=True)
# assert_equal(sm... |
cselis86/edx-platform | common/lib/xmodule/xmodule/annotatable_module.py | import logging
from lxml import etree
from pkg_resources import resource_string
from xmodule.x_module import XModule
from xmodule.raw_module import RawDescriptor
from xblock.fields import Scope, String
import textwrap
log = logging.getLogger(__name__)
# Make '_' a no-op so we can scrape strings
_ = lambda text: tex... |
cortext/crawtextV2 | ~/venvs/crawler/lib/python2.7/site-packages/yaml/error.py |
__all__ = ['Mark', 'YAMLError', 'MarkedYAMLError']
class Mark(object):
def __init__(self, name, index, line, column, buffer, pointer):
self.name = name
self.index = index
self.line = line
self.column = column
self.buffer = buffer
self.pointer = pointer
def get... |
diogocs1/comps | web/openerp/report/render/rml2txt/utils.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the... |
ahmadiga/min_edx | common/djangoapps/student/migrations/0018_auto.py | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding index on 'CourseEnrollment', fields ['created']
db.create_index('student_courseenrollment', ['creat... |
huran2014/huran.github.io | wot_gateway/usr/lib/python2.7/sndhdr.py | """Routines to help recognizing sound files.
Function whathdr() recognizes various types of sound file headers.
It understands almost all headers that SOX can decode.
The return tuple contains the following items, in this order:
- file type (as SOX understands it)
- sampling rate (0 if unknown or hard to decode)
- nu... |
Bluehorn/requests | requests/models.py | # -*- coding: utf-8 -*-
"""
requests.models
~~~~~~~~~~~~~~~
This module contains the primary objects that power Requests.
"""
import os
import socket
from datetime import datetime
from io import BytesIO
from .hooks import dispatch_hook, HOOKS
from .structures import CaseInsensitiveDict
from .status_codes import cod... |
asermax/django-mercadopago | django_mercadopago/migrations/0005_auto_20151009_1836.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mp', '0004_preference_owner'),
]
operations = [
migrations.AlterField(
model_name='notification',
na... |
ashbc/tgrsite | newsletters/urls.py | from django.urls import path
from . import views
app_name = "newsletters"
urlpatterns = [
path('', views.Index.as_view(template_name='newsletters/index.html'), name='newsletters_index'),
path('create/', views.Create.as_view(template_name='newsletters/create.html'), name='newsletters_create'),
path('<int:... |
HeartUnchange/aiospider | examples/ex2.py | #!/usr/bin/python3
#-*- coding:utf-8 -*-
#import os
#os.environ['PYTHONASYNCIODEBUG'] = '1'
'''
This example will show you how to add targets while crawling.
'''
from aiospider import Spider
from urllib.parse import urljoin
from pyquery import PyQuery
import os
from os.path import splitext, basename, exists, isdir, j... |
AbhishekGahlot/cda | checkdomain.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import sys
import urllib2
from tabulate import tabulate
def _check_domain(urls=['google.com']):
data = []
for url in urls:
try:
content = json.loads( urllib2.urlopen('https://domainr.com/api/json/info?&q='+url).read() )
data.append( [conten... |
abanaiyan/sniper | output/relan/4-cores/parsec-streamcluster-test-nuca-cache-1000-3-local/power.py | power = {'Core': [{'Area': 52.369399999999999,
'Execution Unit/Area': 8.2042000000000002,
'Execution Unit/Complex ALUs/Area': 0.23543500000000001,
'Execution Unit/Complex ALUs/Gate Leakage': 0.0132646,
'Execution Unit/Complex ALUs/Peak Dynamic': 0.00031174799999999998,
... |
mattvonrocketstein/smash | smashlib/ipy3x/nbconvert/exporters/tests/test_exporter.py | """
Module with tests for exporter.py
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#---... |
LINKIWI/linkr | test/backend/test_api/test_auth.py | import linkr # flake8: noqa: F401
import mock
import util.response
from test.backend.factory import UserFactory
from test.backend.test_case import LinkrTestCase
from uri.auth import AuthCheckURI, AuthLoginURI, AuthLogoutURI
class TestAuth(LinkrTestCase):
_multiprocess_can_split_ = True
def test_api_auth_c... |
subhankarb/dpr-api | app/auth/authorization.py | # -*- coding: utf-8 -*-
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
from app.package.models import Package
from app.profile.models import User, Publisher, PublisherUser, UserRoleEnum
roles_action_mappings = {
... |
rlabbe/filterpy | filterpy/common/discretization.py | # -*- coding: utf-8 -*-
"""Copyright 2015 Roger R Labbe Jr.
FilterPy library.
http://github.com/rlabbe/filterpy
Documentation at:
https://filterpy.readthedocs.org
Supporting book at:
https://github.com/rlabbe/Kalman-and-Bayesian-Filters-in-Python
This is licensed under an MIT license. See the readme.MD file
for mor... |
fsxfreak/club-suite | clubsuite/suite/migrations/0035_auto_20170306_0219.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-06 02:19
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('suite', '0034_merge_20170305_0108'),
]
operations = [
migrations.AlterModel... |
marcelomiky/PythonCodes | Coursera/CICCP1/conta_primos.py | def n_primos(n):
def éPrimo(k):
divisores = 0
for i in range(1,k):
if k % i == 0:
divisores += 1
if divisores >= 2:
return False
else:
return True
conta_primos = 0
for i in range(2, n+1):
if éPrimo(i) == True:
... |
guaka/lowlink | lowlink.py | #!/usr/bin/env python
"""
lowlink.py
Recursively creates lower case symlinks to filenames with uppercase letters.
(c) 2013 Kasper Souren
See LICENSE
"""
import os
def lowlink(path = '.'):
cwd = os.getcwd() # os.walk can't handle path changes very well
for root, dirs, files in os.walk(path):
... |
drptbl/instarecon | src/ip.py | #!/usr/bin/env python
import itertools
import sys
import time
import ipaddress as ipa # https://docs.python.org/3/library/ipaddress.html
import lookup
class IP(object):
"""
IP and information specific to it. Hosts contain multiple IPs,
as a domain can resolve to multiple IPs.
Keyword arguments:
... |
majikpig/ubtech | tara.py | #the following lines will allow you to use buttons and leds
import btnlib as btn
import ledlib as led
import time
#the led.startup() function cycles through the leds
led.startup()
time.sleep(1)
print("All on and off")
#to turn on all leds, use the led.turn_on_all(2) function:
led.turn_on_all()
time.slee... |
albert12132/templar | tests/markdown_test/list_test.py | from tests.markdown_test.test_utils import MarkdownTest
class ListTest(MarkdownTest):
def testBasic(self):
text = """
* item 1
* item 2
* item 3
"""
expect = """
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
... |
jddixon/xlattice_py | src/xlattice/overlay.py | # xlattice_py/xlattice/overlay.py
"""
A Overlay is characterized by an address space, a transport protocol,
and possibly a set of rules for navigating the address space using
the protocol.
A Overlay may either be system-supported, like TCP/IP will
normally be, or it may explicitly depend upon an underlying
Overlay, i... |
mazulo/tango_with_django_project | rango/migrations/0004_category_slug.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('rango', '0003_auto_20150408_1924'),
]
operations = [
migrations.AddField(
model_name='category',
nam... |
venetay/Photo-Competition | mpc/urls.py | from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from mpc import views
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^$', views.index, name='index... |
TachibanaYuji/surflag | app/server/surflag/point/migrations/0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-11-25 15:37
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Point'... |
mcmontero/tinyAPI | base/data_store/ConnectionManager.py | # ----- Info ------------------------------------------------------------------
__author__ = 'Michael Montero <mcmontero@gmail.com>'
# ----- Imports ---------------------------------------------------------------
from tinyAPI.base.config import ConfigManager
from tinyAPI.base.data_store.MySQL import MySQL
from tinyA... |
joowani/dtags | dtags/commands/untag.py | import sys
from pathlib import Path
from typing import List, Optional, Set, Tuple
from dtags import style
from dtags.commons import (
dtags_command,
get_argparser,
normalize_dirs,
normalize_tags,
prompt_user,
)
from dtags.files import load_config_file, save_config_file
USAGE = "untag [-y] [DIR ...... |
Maplecroft/Magellan | tests/dep_utils_PyPIHelper_tests.py | """
Test suite for the Magellan dep_utils module.
Tests are for PyPIHelper class
"""
from magellan.deps_utils import PyPIHelper
import unittest
# from mock import MagicMock, mock_open, patch
class TestPackageClass(unittest.TestCase):
"""Base class for testing boilerplate."""
pass
class TestAcquireJSONInf... |
brianjpetersen/bocce | bocce/cookies.py | # standard libraries
import os
import collections.abc
import collections
#import http.cookies
# third party libraries
pass
# first party libraries
pass
__where__ = os.path.dirname(os.path.abspath(__file__))
class RequestCookies(collections.abc.Mapping):
def __init__(self, **cookies):
self._cookies ... |
wearespindle/subscriptionform | users/migrations/0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-12-20 15:02
from __future__ import unicode_literals
import django.contrib.auth.models
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', ... |
dnxbjyj/python-basic | gui/wxpython/wxPython-demo-4.0.1/demo/agw/GradientButton.py | #!/usr/bin/env python
import wx
import os
import sys
try:
dirName = os.path.dirname(os.path.abspath(__file__))
except:
dirName = os.path.dirname(os.path.abspath(sys.argv[0]))
sys.path.append(os.path.split(dirName)[0])
try:
from agw import gradientbutton as GB
bitmapDir = "bitmaps/"
except ImportErr... |
facelessuser/backrefs | tests/test_quickcheck.py | """Test `Quick Check`."""
import unittest
from backrefs import uniprops
import re
class TestNFCQuickCheck(unittest.TestCase):
"""Test `NFC Quick Check` access."""
def test_table_integrity(self):
"""Test that there is parity between Unicode and ASCII tables."""
re_key = re.compile(r'^\^?[a-z0... |
mhotwagner/backstage | facade/models.py | from django.db import models
from ckeditor.fields import RichTextField
from solo.models import SingletonModel
from phonenumber_field import modelfields as phonenumber_models
from foti.models import Foto
from opere.models import Opera
from scritti.models import Scritto
class Profile(SingletonModel):
name = mod... |
vivaxy/algorithms | python/problems/shortest_completing_word.py | """
https://leetcode.com/problems/shortest-completing-word/
https://leetcode.com/submissions/detail/132960422/
"""
import sys
class Solution:
def shortestCompletingWord(self, licensePlate, words):
"""
:type licensePlate: str
:type words: List[str]
:rtype: str
"""
c... |
pragmaticbadger/django-notification | notification/engine.py |
import sys
import time
import logging
import traceback
try:
import cPickle as pickle
except ImportError:
import pickle
from django.conf import settings
from django.core.mail import mail_admins
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from lockfile import FileL... |
aisayko/django-xe-currencies | example/xetest/xetest/settings.py | # Django settings for xetest 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', 'sqlite3' or 'oracle'.
'NAME': 'xetest.... |
zhenghuihu/django-skeleton | config/settings/prd.py | '''
production setting
'''
# include all base settings
from .base import * # pylint: disable=W0401,W0614
# include credentials (not included in repo)
from . import credentials as crd # pylint: disable=W0401,W0611
# disable debugging
DEBUG = False
# ========================
# SECRET_KEY
# https://d... |
cirruscluster/cirruscluster | cirruscluster/ext/ansible/inventory/__init__.py | # (c) 2012, 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) any lat... |
pycket/pycket | pycket/test/conftest.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# conftest - configuring pytest, especially funcargs
#
import pycket.config # to configure early
import random
import pytest
from rpython.rlib.objectmodel import specialize, we_are_translated
def replace(func):
@specialize.call_location()
def replacement(*args)... |
percyfal/snakemakelib-core | snakemakelib/graphics/mgeom.py | '''
Author: Per Unneberg
Created: Tue Dec 1 08:59:21 2015
NOTE: the functions in this module allow for plotting of multiple
columns of a data frame. If ggplot conventions are to be followed, the
data frame should first be stacked. I keep these here for now as I'm
uncertain what is the best way forward.
'''
from bo... |
Hashish420/SCRYPTCOIN | contrib/spendfrom/spendfrom.py | #!/usr/bin/env python
#
# Use the raw transactions API to spend bitcoins received on particular addresses,
# and send any change back to that same address.
#
# Example usage:
# spendfrom.py # Lists available funds
# spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00
#
# Assumes it will talk to a bitcoind or Bit... |
jrg365/gpytorch | test/utils/test_linear_cg.py | #!/usr/bin/env python3
import os
import random
import unittest
import torch
from gpytorch.utils.linear_cg import linear_cg
class TestLinearCG(unittest.TestCase):
def setUp(self):
if os.getenv("UNLOCK_SEED") is None or os.getenv("UNLOCK_SEED").lower() == "false":
self.rng_state = torch.get_r... |
StoicLoofah/foodmarks | foodmarks/fm/views.py | import datetime
import json
import math
import operator
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from django.db.models import Q, Count
from django.http import HttpResponse, HttpResponseServerError
from d... |
Azure/azure-sdk-for-python | sdk/agrifood/azure-agrifood-farming/samples/sample_hello_world.py | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
"""
FILE: sample_hello_world.py
DESCRIPTION:
This sample demonstrates the most basic operation that can be
performed - creation of a Farmer. Use this to understand how to
create the client object, how to authenticate it, and make s... |
algorhythms/LeetCode | 964 Least Operators to Express Number.py | #!/usr/bin/python3
"""
Given a single positive integer x, we will write an expression of the form
x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc. is either
addition, subtraction, multiplication, or division (+, -, *, or /). For
example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of ... |
lilsweetcaligula/Online-Judges | hackerrank/algorithms/implementation/easy/chocolate_feast/py/solution.py | #!/bin/python3
import sys
def solution(n, c, m):
cnt = n // c
if m > 0:
w = cnt
while w >= m:
x = w // m
w = w - m * x + x
cnt += x
return cnt
t = int(input())
for a0 in range(t):
n, c, m = map(int, input().split(' '))
cnt = so... |
Timidger/Wikia | wikia/tests/search_test.py | # -*- coding: utf-8 -*-
import unittest
from collections import defaultdict
from wikia import wikia
from request_mock_data import mock_data
# mock out _wiki_request
class _wiki_request(object):
calls = defaultdict(int)
@classmethod
def __call__(cls, params):
cls.calls[params.__str__()] += 1
return m... |
Infatum/neural-networks | src/test_cases.py | import numpy as np
import feed_forward_neural_network as DNN
# todo: this -> Add autodoc
def gradient_cheking(y, theta, forward_prop, back_prop, epsilon=1e-7):
"""
:param y:
:param theta:
:param forward_prop:
:param back_prop:
:param epsilon:
:return:
"""
J_plus, J_minus = forward_... |
ricorx7/donkey | donkeycar/parts/sensors/lidar.py | """
Lidar
"""
import time
import numpy as np
class RPLidar():
def __init__(self, port='/dev/ttyUSB0'):
from rplidar import RPLidar
self.port = port
self.frame = np.zeros(shape=365)
self.lidar = RPLidar(self.port)
self.lidar.clear_input()
time.sleep(1... |
sdukhovni/clyde-go | purge.py | #!/usr/bin/env python3
#
# Purges a message from Clyde's memory; the full text of the message
# should be provided on stdin followed by EOF.
import json
import sys
prefix_len = 2
words = sys.stdin.read().split()
with open("chain.json") as f:
chain = json.load(f)
ngram = [""]*(prefix_len-1) + ["START"]
for wor... |
mikelum/pyspeckit | pyspeckit/cubes/cubes.py | """
~~~~~~~~
cubes.py
~~~~~~~~
From `agpy <http://code.google.com/p/agpy/source/browse/trunk/agpy/cubes.py>`_,
contains functions to perform various transformations on data cubes and their
headers.
"""
from __future__ import print_function
from astropy.extern.six.moves import xrange
from numpy import sqrt,repeat,ind... |
imk1/IMKTFBindingCode | makeClustergram.py | import sys
import argparse
import pylab
import numpy as np
import matplotlib.pyplot as plt
from heatmapcluster import heatmapcluster
def parseArgument():
# Parse the input
parser=argparse.ArgumentParser(description=\
"Make a clustergram of a matrix")
parser.add_argument("--matFileName", required=True,\
help='... |
xtream1101/slackbot-task-queue | example/commands.py | import re # noqa
import logging
import argparse
from slackbot_queue import slack_controller, queue
# import commands here
from example import Example
from example2 import Example2
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = loggin... |
tridesclous/tridesclous | tridesclous/online/onlinewaveformhistviewer.py | import numpy as np
import matplotlib.cm
import matplotlib.colors
from ..gui import QT
import pyqtgraph as pg
from pyqtgraph.util.mutex import Mutex
import pyacq
from pyacq import WidgetNode,ThreadPollInput, StreamConverter, InputStream
#~ _dtype_spike = [('index', 'int64'), ('label', 'int64'), ('jitter', 'float64'... |
aasiutin/electrum | gui/qt/history_list.py | #!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2015 Thomas Voegtlin
#
# 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... |
aurule/npc | npc/formatters/sectioners.py | """
Module for generating section headings
"""
import tempfile
from pathlib import Path
from mako.template import Template
from npc import util
def get_sectioner(key, heading_level, prefs):
"""
Helper to get the right built-in sectioner object
Creates a new sectioner object based on `key`. The special k... |
chipx86/reviewboard | reviewboard/reviews/features.py | """Feature definitions for reviews."""
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from djblets.features import Feature, FeatureLevel
class ClassBasedActionsFeature(Feature):
"""A feature for class-based actions.
With this enabled, extensions may use the ... |
FarhadurFahim/ims | ims_app/migrations/0014_auto_20170416_0425.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-04-15 22:25
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ims_app', '0013_stocks'),
]
operations = [
migrations.RemoveField(
... |
jkonecki/autorest | ClientRuntimes/Python/msrestazure/msrestazure/version.py | # --------------------------------------------------------------------------
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the ""Software""),... |
bjweiner/ARTN | gui/flask_rts2/flask_rts2/__init__.py | from __future__ import print_function
from flask import Flask, send_file
from flask import render_template
from flask_basicauth import BasicAuth
import requests
import json
import glob
import os
import sys
#from rts2 import rtsapi
app = Flask(__name__)
app.config.from_object(__name__)
CONFIG_PATH = "/home/rts2obs/.mt... |
udger/udger-python | udger/tests/runperftest.py | import time
from udger import Udger
"""
Running in both Python 2 and Python 3 like this:
$ PYTHONPATH=../.. python2 runperftest.py
$ PYTHONPATH=../.. python3 runperftest.py
"""
udger = Udger('')
uas = [line.rstrip('\n') for line in open('ua.txt')]
start_time = time.time()
step_time = start_time
for i in range(1... |
SunDwarf/curious | curious/ipc/__init__.py | # This file is part of curious.
#
# curious is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# curious is distributed in the ho... |
Tagtoo/cookie_atm | gce_operation.py | #!/usr/bin/env python
## Google APIs
# apiclient
from apiclient.discovery import build
# Oauth2
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import run
# Python Built-in Libraries
import httplib2
import trackback
__author__ = "Colin Su <littl... |
behrtam/xpython | exercises/flatten-array/flatten_array_test.py | import unittest
from flatten_array import flatten
# Tests adapted from `problem-specifications//canonical-data.json` @ v1.2.0
class FlattenArrayTest(unittest.TestCase):
def test_no_nesting(self):
inputs = [0, 1, 2]
expected = [0, 1, 2]
self.assertEqual(flatten(inputs), expected)
def... |
jpellikk/ebnlib | test/ftests/cases/test_02.py | from ftest import TestCase
from ftest import TestProcess
import signal
class TestCaseImpl(TestCase):
def __init__(self):
TestCase.__init__(self, "test_02")
self.server1 = None
self.server2 = None
self.client1 = None
def ramp_up(self):
# Create server and client proces... |
clementm916/CP2 | app/serializers.py | from flask_restful import fields
item_serializer = {
'id': fields.Integer,
'name': fields.String,
'description': fields.String,
'date_created': fields.DateTime,
'date_modified': fields.DateTime,
'done': fields.Boolean
}
bucketlist_serializer = {
'id': fields.Integer,
'name': fields.... |
gnarula/eden_deployment | controllers/msg.py | # -*- coding: utf-8 -*-
"""
Messaging Module - Controllers
"""
module = request.controller
resourcename = request.function
if not settings.has_module(module):
raise HTTP(404, body="Module disabled: %s" % module)
# -----------------------------------------------------------------------------
def index():
... |
qijiepan/djwebapp | djblog/blog/views.py | from django.shortcuts import render
# Create your views here.
# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from blog.models import Post
def index(request):
posts = Post.objects.all()
return render_to_response("blog... |
bundgus/python-playground | matplotlib-playground/examples/pylab_examples/image_nonuniform.py | '''
This illustrates the NonUniformImage class, which still needs
an axes method interface; either a separate interface, or a
generalization of imshow.
'''
from matplotlib.pyplot import figure, show
import numpy as np
from matplotlib.image import NonUniformImage
from matplotlib import cm
interp = 'nearest'
x = np.li... |
Lowingbn/iccpy | simulations/aquarius.py | import iccpy.gadget
import matplotlib.pyplot as pl
import numpy as np
import iccpy.utils
sim_label = { 'aqa' : 'A', 'aqb' : 'B', 'aqc':'C', 'aqd':'D', 'aqe':'E' }
last_snapnum = { 'aqa2' : 1023, 'aqa3' : 511, 'aqa4' : 1023, 'aqb2' : 127, 'aqc2' : 127, 'aqd2' : 127, 'aqe2' : 127 }
r_200 = { 'aqa1' : 245.67, 'aqa2' : 2... |
eespaillat/RoommateManagerApp | roommatemanager/api/migrations/0003_item_item_finished.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-04-12 00:22
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0002_auto_20160411_2108'),
]
operations = [
migrations.AddField(
... |
zer0yu/ZEROScan | plugins/CVE-2018-7600.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from thirdparty import requests
from bs4 import BeautifulSoup
import random
import string
import sys
import base64
import urllib
def expInfo():
expInfo={}
expInfo["appName"] = "Drupal"
expInfo["appVersion"] = "Drupal < 7.58"
expInfo["author"] = "Z3r0yu"
... |
m4droid/TransantiagoScanner | fabfile.py | from datetime import datetime
from fabric.api import env
from fabric.colors import yellow
from fabric.context_managers import cd, shell_env
from fabric.operations import run
from fabric.contrib.files import exists
GIT_REPO = {
'url': 'https://github.com/m4droid/TransantiagoScanner.git',
'name': 'Transantiago... |
justinmeister/The-Stolen-Crown-RPG | data/components/textbox.py | __author__ = 'justinarmstrong'
import copy
import pygame as pg
from .. import setup, observer, tools
from .. import constants as c
class NextArrow(pg.sprite.Sprite):
"""Flashing arrow indicating more dialogue"""
def __init__(self):
super(NextArrow, self).__init__()
self.image = setup.GFX['fanc... |
zlsun/ProjectEuler | 062.py | #-*- encoding: utf-8 -*-
"""
Cubic permutations
The cube, 41063625 (345^3), can be permuted to produce two other cubes: 56623104 (384^3) and 66430125 (405^3). In fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube.
Find the smallest cube for which exactly five per... |
likedots/ldterra | terra_server/views/views.py | import os
from flask import send_from_directory, render_template, request
__author__ = 'cvl'
from terra_server import app
@app.route('/')
def index():
return render_template("index.html")
def get_abs_path():
abs_path = os.path.dirname(os.path.abspath(__file__))
current_folder = '/' + os.path.basename(ab... |
wq/offline-website-logger | setup.py | import subprocess
from setuptools import setup, find_packages
LONG_DESCRIPTION = """
Django REST app to help track page/screen views (and other events) in
offline-capable websites/web-apps/hybrid apps.
"""
def parse_markdown_readme():
"""
Convert README.md to RST via pandoc, and load into memory
(fallbac... |
marktsuchida/NDMake | ndmake/mux.py | from ndmake import debug
from ndmake import dispatch
dprint = debug.dprint_factory(__name__)
@dispatch.tasklet
def multiplex(trigger_chan, notification_request_chan):
# Blocks until a message is received on trigger_chan. Once received, sends
# the message to all channels that have been received on
# notif... |
blairg23/TweetyPy | Tweety.py | # coding: utf-8
import oauth2
import urlparse
import webbrowser
import json
import requests
import os
from requests_oauthlib import OAuth1
class Tweety():
def __init__(self, url='https://api.twitter.com/1.1/', consumer_key=None, consumer_secret=None, key=None, secret=None, debug=False):
self._consumer_key = consum... |
dsanders11/django-migrate-project | tests/test_migrateproject.py | from __future__ import unicode_literals
from copy import copy
import os
import shutil
import sys
import tempfile
from django.apps import apps
from django.conf import settings
from django.core.management import call_command
from django.core.management.base import CommandError
from django.db import connections, DEFAUL... |
Kashomon/pyrite | pyrite/data_structures/properties.py | # Copyright (c) 2011 by Joshua Hoak, Alissa Pajer
# Licensed under the MIT License
# Authors: Josh Hoak (jrhoak@gmail.com)
import date_prop
import tags_prop
import title_prop
class PropertiesParser(object):
def __init__(self, parse_type, options):
self.options = options
self.parsers = {
"title" :... |
xmedius/sendsecure-filepoller | sendsecurefilepoller/servicehelpers.py | import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import logging
from utils import create_rotating_log, get_config, process_jobs_in_folder
class XMSSServiceRunner (win32serviceutil.ServiceFramework):
_svc_name_ = "sendsecurefilepoller"
_svc_display_name_ = "SendS... |
TaDaa/.vim | dependencies/windows/ycm/ycm/python/ycm/completers/completer_utils.py | #!/usr/bin/env python
#
# Copyright (C) 2013 Strahinja Val Markovic <val@markovic.io>
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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 ... |
InseeFr/Pogues-Back-Office | docker/eXist-seed/app/connector.py | import requests
from requests.auth import HTTPBasicAuth
import sys
import os
from string import rfind
import base64
class XdbException(Exception):
'''Exist db connector exception'''
class Connector:
def __init__(self, url, user, password):
self.url = url
self.auth = HTTPBasicAuth(user, passwo... |
acutesoftware/virtual-AI-simulator | tests/test_environments_worlds.py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# test_environments_worlds.py
import os
import sys
import unittest
root_folder = os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + os.sep + ".." )
pth = root_folder + os.sep + 'vais'
sys.path.append(pth)
import worlds
import world_generator
class TestToolboxCl... |
Rikanishu/static-bundle | static_bundle/utils.py | # encoding: utf-8
import os
import shutil
import codecs
def prepare_path(path):
"""
Path join helper method
Join paths if list passed
:type path: str|unicode|list
:rtype: str|unicode
"""
if type(path) == list:
return os.path.join(*path)
return path
def read_from_file(file_p... |
tuomassalo/puheenvuorot | puhsite/taysistunto/feeds/SpeakerFeed.py | # -*- coding: utf-8 -*-
from django.contrib.syndication.views import Feed
from taysistunto.models import Speaker
from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.template import loader, Context
class SpeakerFeed(Feed):
link = "/puhujat/"
def title(self, obj):
... |
wasit7/cs426 | lectures/week07_bokeh/bokeh_scatter02.py | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 22 11:17:44 2015
@author: Wasit
"""
import time
import numpy as np
from six.moves import zip
from bokeh.plotting import *
def transition(sx,sy,vx,vy,m):
dt=1
G=0.1
epsilon=1e0
# http://http.developer.nvidia.com/GPUGems3/gpugems3_ch31.html
for i... |
ua-snap/downscale | snap_scripts/downscaling_L48/downscale_cmip5_L48.py | # downscale the prepped cmip5 data used in running the TEM model (IEM)
# author: Michael Lindgren
if __name__ == '__main__':
import glob, os, rasterio, itertools
from functools import partial
import downscale
from downscale import preprocess
import numpy as np
import argparse
# # parse the commandline argument... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.