code stringlengths 6 947k | repo_name stringlengths 5 100 | path stringlengths 4 226 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k |
|---|---|---|---|---|---|
"""
An exception is what occurs when you have a run time error in your
program.
what you can do is "try" a statement wether it is invalid or not
if an error does occur withan that statement you can catch that error
in the except clause and print out a corresponding message
(or you can print out the error message).
... | ajn123/Python_Tutorial | Python Version 2/Advanced/exceptions.py | Python | mit | 1,154 |
'''
Created on 3 cze 2014
@author: Przemek
'''
from src.items.bytes import Bytes
from src.parser.measurable import Measurable
class StringIdItem(Measurable):
'''
classdocs
'''
def __init__(self, parent):
'''
Constructor
'''
Measurable.__init__(self, parent)
... | PrzemekBurczyk/dalvik-compiler | src/items/string_id_item.py | Python | mit | 347 |
"""
Based entirely on Django's setup.py
"""
from distutils.core import setup
from distutils.command.install import INSTALL_SCHEMES
import os
import sys
def fullsplit(path, result=None):
"""
Split a pathname into components (the opposite of os.path.join) in a
platform-neutral way.
"""
if result is ... | tjnapster555/django-edu | setup.py | Python | mit | 2,504 |
#!/usr/bin/python
#
# Temp Probe - CPU Status - JSON Output
#
# Jason A. Cox, @jasonacox
# https://github.com/jasonacox/SentryPI
import os
import glob
import time
import datetime
def cpu_temp():
result = 0
mypath = "/sys/class/thermal/thermal_zone0/temp"
with open(mypath, 'r') as mytmpfile:
f... | jasonacox/SentryPi | sentrypi-cpu.py | Python | mit | 941 |
import pytest
from eventum.lib.text import clean_markdown
@pytest.mark.parametrize(["markdown", "output"], [
('**Bold** text is unbolded.', 'Bold text is unbolded.'),
('So is *underlined* text.', 'So is underlined text.'),
('An [](http://empty-link).', 'An.'),
('A [test](https://adicu.com)', 'A test ... | danrschlosser/eventum | tests/test_text.py | Python | mit | 790 |
"""django_polls URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/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... | tms1337/polls-app | django_polls/urls.py | Python | mit | 820 |
from main import WeTransfer | creemerica/wetransfer-upload | wetransfer/__init__.py | Python | mit | 27 |
from model_3d import *
# ------------------------ Functions ------------------------------------------#
def test():
"""
A simple test routine to draw the quadcopter model
"""
# Creates a VPython Scene
scene = display(title='Quad_Test', x=0, y=0, width=800, height=600, center=(0,0,0),
... | guiccbr/autonomous-fuzzy-quadcopter | python/py_quad_control/models/py/test_3d.py | Python | mit | 1,343 |
import tensorflow as tf
from networks.network import Network
from fcn.config import cfg
zero_out_module = tf.load_op_library('lib/triplet_flow_loss/triplet_flow_loss.so')
class custom_network(Network):
def __init__(self):
self.inputs = cfg.INPUT
# self.input_format = input_format
self.num... | daweim0/Just-some-image-features | lib/networks/net_labeled_features_deeper.py | Python | mit | 16,354 |
from django.conf.urls import patterns
from django.conf.urls import url
from django.views.generic import TemplateView
from . import views
urlpatterns = patterns('',
url(
regex=r'^(?P<guide_version>\d+)/$',
view=views.EmailSignUpCreateView.as_view(),
name='email_signup'
),
url(
... | patrickbeeson/diy-trainer | diytrainer/guides/urls.py | Python | mit | 651 |
# -*- coding: utf-8 -*-
import memcache
# XXX where best to specify timeout? constructor or various methods?
class KestrelEnqueueException(Exception):
pass
class connection(object):
def __init__(self, servers, queue, reliable=True,
default_timeout=0, fanout_key=None):
if fanout_key... | maw/python-kestrel | kestrel.py | Python | mit | 2,224 |
"""
WSGI config for test_proj 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.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SET... | truetug/django-admin-helper | test_proj/test_proj/wsgi.py | Python | mit | 395 |
def clip_matrix(image_as_matrix, width, height, top, left, expand_by=0):
x1 = left
x2 = left + width
y1 = top
y2 = top + height
crop_img = image_as_matrix[y1-expand_by:y2+expand_by, x1-expand_by:x2+expand_by]
return crop_img
| aeivazi/classroom-tracking | src/face_clipper.py | Python | mit | 257 |
import re, os, datetime
from sopel import module
from sopel.config.types import StaticSection, ValidatedAttribute, FilenameAttribute
DEFAULT_CHANLOGS_DIR = os.getenv("HOME") + "/chanlogs"
DEFAULT_LINE_PATTERN = re.compile(r"^([^\s]*) <([^>]*)> (.*)$")
class GrepLogsSection(StaticSection):
dir = FilenameAttribu... | thegoonies/tools | sopel-modules/grep-logs.py | Python | mit | 2,449 |
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.views.... | Tusky/DjangoSample | blog/views.py | Python | mit | 2,273 |
def escapeChars(name):
'''Escape markdown characters to avoid usernames getting rendered weirdly in some cases.
The only known case is with underscores, and that is only in a special case, but we'll do a generalized fix here.
'''
return name.replace('_', '\\_')
| hswhite33/picturegame-bot | src/utils/MarkdownUtils.py | Python | mit | 279 |
class Actions:
@staticmethod
def Teleport(map, tileX, tileY):
def teleport(trigger, entity):
entity.TileX = tileX
entity.TileY = tileY
TeleportEntity(entity, map)
return teleport
| ericrrichards/rpgEngine | RpgEngine/RpgEngine/Scripts/Actions.py | Python | mit | 242 |
# -*- coding: utf-8 -*-
from datetime import datetime, timezone, timedelta
import pytest
class TestStr2Datetime(object):
@pytest.fixture
def target_func(self):
from poco.utils import str2datetime
return str2datetime
@pytest.mark.parametrize(
's,expected',
[
('... | kk6/poco | tests/test_utils.py | Python | mit | 1,427 |
"""LISY System 1/80 platform."""
| missionpinball/mpf | mpf/platforms/lisy/__init__.py | Python | mit | 33 |
# 435 - Non Overlapping Intervals (Medium)
# https://leetcode.com/problems/non-overlapping-intervals/
# How many intervals have to be erased from a list so that all
# remaining intervals are not overlapping?
class Solution(object):
def eraseOverlapIntervals(self, intervals):
"""
:type intervals: Li... | zubie7a/Algorithms | LeetCode/02_Medium/lc_435.py | Python | mit | 827 |
from django.db import models
from django_tabulate.base import tabulate_qs
class TabulateMixin(object):
def tabulate(self, **kwargs):
return tabulate_qs(self, **kwargs)
class TabulateQuerySet(TabulateMixin, models.QuerySet):
pass | todorvelichkov/django-tabulate | django_tabulate/mixins.py | Python | mit | 246 |
import json
import uuid
import unittest
from main import app
from app import redis
class FlaskTestCase(unittest.TestCase):
def setUp(self):
app.config['TESTING'] = True
self.app = app.test_client()
self.site_host = str(uuid.uuid4())
def tearDown(self):
pass # self.delete_site... | andychase/classwork | cs496/assignment_3/test.py | Python | mit | 2,361 |
from py2neo import neo4j
from nltk.corpus import wordnet as wn
from collections import defaultdict
import operator
#this routine will scan each word in the phrase, and if it has a hyphenation, attach that information in a node via the edge
#it will also attach both sides of the hypenation as new nodes
def analyze(gr... | codyhanson/puntective | part_of_speech.py | Python | mit | 1,081 |
#!/usr/bin/env python3
"""
A Module containing the classes which generate schema files from JSON.
"""
import json
def cmp_to_key(mycmp):
'Convert a cmp= function into a key= function'
class K:
def __init__(self, obj, *args):
self.obj = obj
def __lt__(self, other):
retu... | GluuFederation/community-edition-setup | schema/generator.py | Python | mit | 8,810 |
from sqlalchemy import *
from sqlalchemy.exceptions import OperationalError
from sqlalchemy.schema import DDL
import migrate.changeset
from migrate.changeset.exceptions import NotSupportedError
from migrate import *
metadata = MetaData(migrate_engine)
users_table = Table('users', metadata,
Column('id', Int... | JustinTulloss/harmonize.fm | masterapp/masterapp/model/manage/versions/22/22.py | Python | mit | 650 |
"""
Django settings for channel_worm project.
Generated by 'django-admin startproject' using Django 1.8.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build... | joebowen/ChannelWormDjango | ChannelWorm/channelworm/settings.py | Python | mit | 3,520 |
import _plotly_utils.basevalidators
class ShowticklabelsValidator(_plotly_utils.basevalidators.BooleanValidator):
def __init__(
self,
plotly_name="showticklabels",
parent_name="sunburst.marker.colorbar",
**kwargs
):
super(ShowticklabelsValidator, self).__init__(
... | plotly/python-api | packages/python/plotly/plotly/validators/sunburst/marker/colorbar/_showticklabels.py | Python | mit | 524 |
def format():
text = ""
stopword = ""
while True:
line = raw_input()
if line.strip() == stopword:
break
text += "%s\n" % line
text_arr = text.split('\n')
global arr
arr = [[] for _ in range(21)]
for i in range(21):
arr[i].append(text_arr[i])
... | KartikKannapur/Programming_Challenges | Project-Euler-Solutions/011.py | Python | mit | 1,639 |
from os import environ as env
import unittest
from .wpull import WpullArgs
from seesaw.item import Item
# taken form pipeline/pipeline.py
if 'WARC_MAX_SIZE' in env:
WARC_MAX_SIZE = env['WARC_MAX_SIZE']
else:
WARC_MAX_SIZE = '5368709120'
def joined(args):
return str.join(' ', args)
class TestWpullArgs(un... | Asparagirl/ArchiveBot | pipeline/archivebot/seesaw/wpullargs_test.py | Python | mit | 2,884 |
"""Support for mill wifi-enabled home heaters."""
import mill
import voluptuous as vol
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import (
CURRENT_HVAC_HEAT,
CURRENT_HVAC_IDLE,
FAN_ON,
HVAC_MODE_HEAT,
HVAC_MODE_OFF,
SUPPORT_FAN_MODE,
... | rohitranjan1991/home-assistant | homeassistant/components/mill/climate.py | Python | mit | 8,828 |
from typing import KeysView
from baby_steps import given, then, when
from district42 import optional, schema
def test_dict_empty_keys():
with given:
sch = schema.dict
with when:
res = sch.keys()
with then:
assert res == KeysView([])
def test_dict_keys():
with given:
... | nikitanovosibirsk/district42 | tests/dict/test_dict_keys.py | Python | mit | 572 |
#!usr/bin/env python
# -*- coding: utf-8! -*-
from collections import Counter, OrderedDict
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.cluster.hierarchy import ward, dendrogram
from sklearn.decomposition import PCA
from sklearn.metrics.pairwise import euclidean_distances
from s... | mikekestemont/beckett | code/analysis.py | Python | mit | 6,372 |
from __future__ import unicode_literals
import calendar
import datetime
from django.utils import http as http_utils
from daydreamer.tests.views.core import http
class TestCase(http.TestCase):
"""
Common utilities for testing HTTP view behaviors.
"""
# Utilities.
def format_etag(self, etag)... | skibblenybbles/django-daydreamer | daydreamer/tests/views/behaviors/http/base.py | Python | mit | 652 |
import _plotly_utils.basevalidators
class TypesrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self,
plotly_name="typesrc",
parent_name="scatterternary.marker.gradient",
**kwargs
):
super(TypesrcValidator, self).__init__(
plotly_name=pl... | plotly/plotly.py | packages/python/plotly/plotly/validators/scatterternary/marker/gradient/_typesrc.py | Python | mit | 454 |
# -*- coding: utf-8 -*-
#
# Bread documentation build configuration file, created by
# sphinx-quickstart on Wed Aug 7 20:51:04 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All c... | alexras/bread | docs/source/conf.py | Python | mit | 8,030 |
# -*- coding: utf-8 -*-
#
# -----------------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this softw... | Fendoe/open-hackathon-o | open-hackathon-client/src/client/__init__.py | Python | mit | 4,490 |
#!/usr/bin/env python
#encoding: utf-8
import numpy as np
from pylab import *
dt=0.01 # msec
tau=40.0 # msec
tmax=1000 # msec
V_spk=-20
V_thres=-50.0
V_reset=-70.0
E_leak=V_reset
R_m=10.0 # MΩ
tt=np.arange(0, tmax, dt) #0:dt:tmax
Nt=len(tt) #length(tt)
V=np.zeros((Nt,))
V2=np.zeros((Nt,))
S=np.zeros((Nt,))
S2=np.zero... | jdmonaco/vmo-feedback-model | src/spike_reset.py | Python | mit | 3,535 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# Core of the application, implement a part of the RFC 1459: Internet Relay Chat ProtocolA (Client side).
from Message import Message
from Action import Action
import socket
import string
import re
import time
#ssl support
from ssl import SSLSocket
##
# Core of the appl... | twpDone/SimpleAsIRC | Core.py | Python | mit | 5,635 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
__all__ = [
'__version_info__',
'__version__',
'__author__',
'__author_email__',
]
__version_info__ = (0, 4, 3)
__version__ = '.'.join([unicode(i) for i in __version_info__])
__author__ = 'David Vuong'
__author_email__ = 'david@imageinte... | ImageIntelligence/mimiron | mimiron/__init__.py | Python | mit | 334 |
import pandas as pd
import Indicators as indicators
import DataProvider as data
import datetime
def test_mstar():
start_date = datetime.datetime(2017, 12, 1)
end_date = datetime.datetime(2018, 1, 1)
df = data.read_morningstar('SPY', start_date, end_date, clean=True)
print df
def test_vortex... | gietal/Stocker | stocker3/Indicators_test.py | Python | mit | 618 |
"""
@name: PyHouse/src/Modules/Drivers/_test/test_Null.py
@author: D. Brian Kimmel
@contact: D.BrianKimmel@gmail.com
@copyright: (c) 2015-2018 by D. Brian Kimmel
@license: MIT License
@note: Created on Jul 30, 2015
@Summary:
"""
__updated__ = '2018-02-12'
# Import system type stuff
from twisted.tria... | DBrianKimmel/PyHouse | Project/src/Modules/Core/Drivers/_test/test_Null.py | Python | mit | 813 |
from infrastructure.routers import Router
from . import views
r = Router()
r.register('users', views.UsersViewSet) \
.register('groups', views.GroupsViewSet,
base_name='user-groups',
parents_query_lookups=['user'])
r.register('groups', views.GroupsViewSet) \
.register('permission... | lucasdavid/drf-base | src/authority/urls.py | Python | mit | 518 |
import os
from scytale import create_app
from scytale.ciphers import MixedAlphabet, Playfair, Fleissner, Trifid, Myszkowski
from scytale.models import db, Group, Message
from scytale.forms import MessageForm
def create_group(name):
print("Creating admin group ({})".format(name))
group = Group()
group.nam... | WilliamMayor/scytale.xyz | scripts/seed/seeder.py | Python | mit | 13,201 |
import re
import tempfile
from pathlib import Path
from unittest.mock import Mock, patch
import pytest
from _pytest.monkeypatch import MonkeyPatch
from backend.common import storage
from backend.common.storage.clients.gcloud_client import GCloudStorageClient
from backend.common.storage.clients.in_memory_client import... | the-blue-alliance/the-blue-alliance | src/backend/common/storage/tests/storage_test.py | Python | mit | 3,964 |
from djmoney.money import Money
from rest_framework import permissions, viewsets
from .models import Record
from .serializers import RecordSerializer
class RecordViewSet(viewsets.ModelViewSet):
serializer_class = RecordSerializer
permission_classes = (permissions.IsAuthenticated,)
queryset = Record.objec... | saks/hb | records/views.py | Python | mit | 1,196 |
import random
import numpy as np
from tpg.learner import Learner
from tpg.action_object import ActionObject
from tpg.program import Program
from tpg.team import Team
dummy_init_params = {
'generation': 0,
'actionCodes':[
0,1,2,3,4,5,6,7,8,9,10,11
]
}
dummy_mutate_params = {
'pProgMut': 0.5,... | Ryan-Amaral/PyTPG | tpg_tests/test_utils.py | Python | mit | 2,999 |
# coding: utf-8
from tests.util import build_grab
from tests.util import BaseGrabTestCase
class GrabXMLProcessingTestCase(BaseGrabTestCase):
def setUp(self):
self.server.reset()
def test_xml_with_declaration(self):
self.server.response['get.data'] =\
b'<?xml version="1.0" encoding... | istinspring/grab | tests/grab_xml_processing.py | Python | mit | 1,247 |
from django.contrib import admin
from moneymaker.models import Product
from moneymaker.models import Income
from moneymaker.models import Expense
from moneymaker.models import ExpenseCategory
from moneymaker.models import IncomeCategory
class ExpenseAdmin(admin.ModelAdmin):
list_display = ('date', '__unicode__')... | marthall/accounting | moneymaker/admin.py | Python | mit | 496 |
#!/usr/bin/env python
#
# __COPYRIGHT__
#
# 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,
... | timj/scons | test/Variables/ListVariable.py | Python | mit | 5,013 |
# -*- coding: utf-8 -*-
# -- cmd -- pip install PyUserInput
import time
import win32gui
import win32con
import PIL.ImageGrab
from pymouse import PyMouse
PIECE_X = 44
PIECE_Y = 40
NUM_X = 14
NUM_Y = 10
def getOrigin():
cwllk = '宠物连连看'.decode('utf8')
hwnd = win32gui.FindWindow("#32770", cwllk)
print hwnd
... | TarnumG95/PictureMatchCheater | merge/UI.py | Python | mit | 1,196 |
"""Module level configuration.
Fuel allows module-wide configuration values to be set using a YAML_
configuration file and `environment variables`_. Environment variables
override the configuration file which in its turn overrides the defaults.
The configuration is read from ``~/.fuelrc`` if it exists. A custom
confi... | mila-udem/fuel | fuel/config_parser.py | Python | mit | 7,045 |
from django.test import TestCase
from django.contrib.auth.models import User
from django.http import HttpRequest
from .factories import UserReferrerFactory, UserFactory, CampaignFactory
from referral_module import constants
from referral_module import models
def make_cookie_file(user_referrer):
cookie_file = '{... | moneypark/whydjango | referral_module/tests/test_user_registered.py | Python | mit | 3,083 |
"""
TestCommon.py: a testing framework for commands and scripts
with commonly useful error handling
The TestCommon module provides a simple, high-level interface for writing
tests of executable commands and scripts, especially commands and scripts
that interact with the file system. All methods throw... | EmanueleCannizzaro/scons | QMTest/TestCommon.py | Python | mit | 27,739 |
#!/usr/bin/python
import os
import sys
import subprocess
import optparse
import time
import platform
SCRIPT_NAME = "LGR_fluxes.R"
platform = platform.system() != "Windows"
def run(foldername, start, end, graph, t, large):
""" Execute SCRIPT_NAME with time series parameters.
Arguments:
filename -- the name of the... | wdonahoe/fluxes | LGR_fluxes.py | Python | mit | 2,057 |
import zeeguu_core
from zeeguu_core.model import Article, Language, LocalizedTopic
session = zeeguu_core.db.session
counter = 0
languages = Language.available_languages()
languages = [Language.find('da')]
for language in languages:
articles = Article.query.filter(Article.language == language).order_by(Article.i... | mircealungu/Zeeguu-Core | tools/tag_topics_in_danish.py | Python | mit | 1,205 |
from polyglot.nodeserver_api import SimpleNodeServer, PolyglotConnector
from polykevo_types import KevoDiscovery, KevoLock
VERSION = "0.2.0"
class KevoNodeServer(SimpleNodeServer):
controller = []
locks = []
def setup(self):
super(KevoNodeServer, self).setup()
self.poly.logger.info('Con... | cswelin/kevo-polyglot | polykevo.py | Python | mit | 1,943 |
import unittest
from leafpy import Leaf
from leafpy.auth import login
import vcr
USERNAME = 'dummyuser'
PASSWORD = 'dummypass'
class LoginTests(unittest.TestCase):
@vcr.use_cassette('tests/unit/cassettes/test_login.yaml',
filter_post_data_parameters=['UserId','Password'])
def test_login(self):
... | nricklin/leafpy | tests/unit/test_login.py | Python | mit | 2,246 |
#!/usr/bin/python
# -*- coding: gbk -*-
#coding=gbk
import pkgutil
import urlparse
import json
import logging
import urllib2
from argparse import ArgumentParser
import os
__all__ = ['main']
gfwlist_url = 'https://autoproxy-gfwlist.googlecode.com/svn/trunk/gfwlist.txt'
gfwlist_url = 'https://raw.githubusercontent.co... | 51itclub/51itclub.github.io | ChnRoutesPlus/gfwlist2pacplus/main.py | Python | mit | 5,601 |
import re
import romkan
entries = set()
for i, entry in enumerate(open("edict2", encoding="euc-jp")):
if i == 0:
continue
m = re.search("^[^/]*\\[([ぁ-んァ-ン]*)\\]", entry)
if not m:
continue
entries.add(romkan.to_hiragana(romkan.to_roma(m.groups(1)[0])))
w = open("./hira.list", "w")
for ... | WydD/kana-test | gen-hira.py | Python | mit | 372 |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "TeschaBooks.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that ... | TrapKingg/Tescha-books | manage.py | Python | mit | 809 |
#!/usr/bin/env python
import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
import cv2
from flexbe_core import EventState, Logger
from flexbe_core.proxy import ProxySubscriberCached
from sensor_msgs.msg import PointCloud2
class TakePictureState(EventState):
'''
Stores the pic... | pschillinger/lamor15 | lamor_flexbe_states/src/lamor_flexbe_states/take_picture_state.py | Python | mit | 877 |
#coding=utf-8
#运算符
a = 10
b = 20
list = [1, 2, 3, 4, 5 ];
if ( a in list ):
print "1 - 变量 a 在给定的列表中 list 中"
else:
print "1 - 变量 a 不在给定的列表中 list 中"
if ( b not in list ):
print "2 - 变量 b 不在给定的列表中 list 中"
else:
print "2 - 变量 b 在给定的列表中 list 中"
# 修改变量 a 的值
a = 2
if ( a in list ):
print "3 - 变量 a 在给定的列表中 l... | JianmingXia/StudyTest | PythonPro/demo/operator.py | Python | mit | 3,004 |
"""Home operations."""
from django.http import HttpResponseRedirect
from django.shortcuts import render
from tasklist.app.forms import SignupForm
from tasklist.app.models import User, Task
def main_page(request):
"""Main view."""
if 'user_id' in request.session:
user_obj = User.objects.filter(id=requ... | andrewtcrooks/taskorganizer | tasklist/app/views/home.py | Python | mit | 2,390 |
# -*- coding: utf-8 -*-
################################################################################
# Copyright 2014, Distributed Meta-Analysis System
################################################################################
"""
This file provides methods for extracting data from impact bundles (.nc4 files... | jrising/prospectus-tools | gcp/extract/lib/bundles.py | Python | mit | 7,025 |
#!/usr/bin/env python3
from multiprocessing.managers import BaseManager
class QueueManager(BaseManager): pass
QueueManager.register('get_queue')
m = QueueManager(address=('127.0.0.1', 50000), authkey=b'abracadabra')
m.connect()
queue = m.get_queue()
queue.put('hello')
print(queue.get())
| dubrayn/dubrayn.github.io | examples/multiprocessing/client.py | Python | mit | 289 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2013 Jérémie DECOCK (http://www.jdhp.org)
# 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 withou... | jeremiedecock/snippets | python/pil/python2_pil/get_exif.py | Python | mit | 1,813 |
from .constant import Constant
__NR_ni_syscall = Constant('__NR_ni_syscall',1024)
__NR_exit = Constant('__NR_exit',1025)
__NR_read = Constant('__NR_read',1026)
__NR_write = Constant('__NR_write',1027)
__NR_open = Constant('__NR_open',1028)
__NR_close = Constant('__NR_close',1029)
__NR_creat = Constant('__NR_creat',103... | pwndbg/pwndbg | pwndbg/constants/ia64.py | Python | mit | 26,808 |
from collections import Counter as C
i,s=lambda:C(input()),lambda t:sum(t.values());a,b,c=i(),i(),i();a,b,N=a&c,b&c,s(c);print('NO'if any((a+b)[k]<v for k,v in c.items())|(s(a)*2<N)|(s(b)*2<N)else'YES')
| knuu/competitive-programming | atcoder/corp/codefes2014qb_c_2.py | Python | mit | 203 |
from datetime import datetime
import struct
import pymysql
import os
import json
def clear_string(str):
new_str = ''
for s in str:
return s
def read_data(file,n):
var = []
var = file.read(n)
return var
def toBitArray(val):
return list(map(lambda x: 'false' if (x == '0') else 'ok', '... | volodink/itstime4science | web/backend/modules/decode_aprs.py | Python | mit | 1,929 |
from stage import *
import os
use_gpu = os.environ.get('GNUMPY_USE_GPU', 'yes') == 'yes'
if use_gpu:
import gnumpy as gpu
import gnumpy as gnp
class Map(Stage):
def __init__(self,
outputDim,
activeFn,
inputNames=None,
initRange... | renmengye/imageqa-public | src/nn/map.py | Python | mit | 4,455 |
"""
WSGI config for djdan project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` se... | BL-Labs/annotator_demonstrator | djdan/wsgi.py | Python | mit | 1,132 |
# This file is part of Irianas (Server).
# Copyright (C) 2013 Irisel Gonzalez.
# Authors: Irisel Gonzalez <irisel.gonzalez@gmail.com>
#
import datetime
from mongoengine import \
(Document, DateTimeField, StringField, ReferenceField,
DecimalField, DynamicDocument, IntField)
# Database for irianas-web
class Re... | Irigonzalez/irianas-server | irianas_server/models/__init__.py | Python | mit | 2,702 |
"""Directory Factory"""
# pylint: disable=too-many-arguments
from .. import LAUNCHKEY_PRODUCTION
from ..clients import DirectoryClient, ServiceClient
from .base import BaseFactory
class DirectoryFactory(BaseFactory):
"""Factory for creating clients when representing a LaunchKey Directory"""
def __init__(se... | LaunchKey/launchkey-python | launchkey/factories/directory.py | Python | mit | 1,866 |
from app import app
from fields import PreValidatedFormField
from flask_wtf import Form
from wtforms import (TextField, TextAreaField, FormField, FieldList,
HiddenField, SubmitField)
from wtforms.validators import (DataRequired, Optional, StopValidation)
EMPTY_VALUES = ['', None]
def DynamicList... | murphydavis/turbo-bear | forms.py | Python | mit | 4,475 |
from pprint import pprint as pp
from colorama import Fore
from buffpy.api import API
from buffpy.managers.profiles import Profiles
# check http://bufferapp.com/developers/apps to retrieve a token
# or generate one with the example
token = "awesome_token"
# instantiate the api object
api = API(client_id="client_id"... | vtemian/buffpy | examples/profiles.py | Python | mit | 878 |
# -*- coding: UTF-8 -*-
#! /usr/bin/python
__author__="ARA"
__all__ = ['color_operator', 'color_field', 'color', 'manager',
'manager_operators', 'manager_fields']
__date__ ="$Mai 08, 2014 10:50:00 PM$"
from numpy import asarray
class myList:
def __init__(self):
self._list = []
self._c... | ratnania/pigasus | python/fem/color.py | Python | mit | 6,761 |
# Copyright (c) 2014 The Bitcoin Core developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Helpful routines for regression testing
#
# Add python-bitcoinrpc to module search path:
import os
import sys
sys.path.append... | GNUDimarik/dimecoin | qa/rpc-tests/util.py | Python | mit | 5,261 |
# -*- coding: utf-8 -*-
'''
Column names: Name, Author, Genre, StartDate, EndDate, Pages, Progress
, Finished
'''
from __future__ import division
import sqlite3 as sql
########################################################
# DATA VIEWING #
########################################################
def ... | pattman/Simple-Book-Tracker | book_tracker.py | Python | mit | 3,242 |
import os
import autosar.rte.partition
import cfile as C
import io
import autosar.base
import autosar.bsw.com
innerIndentDefault=3 #default indendation (number of spaces)
def _genCommentHeader(comment):
lines = []
lines.append('/************************************************************************... | cogu/autosar | autosar/rte/generator.py | Python | mit | 42,335 |
<<<<<<< HEAD
<<<<<<< HEAD
"""Extension to format a paragraph or selection to a max width.
Does basic, standard text formatting, and also understands Python
comment blocks. Thus, for editing Python source code, this
extension is really only suitable for reformatting these comment
blocks or triple-quoted strings.
Known... | ArcherSys/ArcherSys | Lib/idlelib/FormatParagraph.py | Python | mit | 22,001 |
# -*- coding: utf-8 -*-
from util.token import token_required
from server import db
from api import api, GlobalError, ERROR_LIKE
from model.wish import Wish, WishLike
from flask import abort
from sqlalchemy.exc import IntegrityError
from util.jsonResponse import jsonSuccess, jsonError
'''
重要提示:Model的设计中,需要确保每个Like的类的... | BillBillBillBill/WishTalk-server | WishTalk/api/like.py | Python | mit | 2,019 |
#!/usr/bin/python
################################################################################
# Bus Supervisor Interface
#
# - interfaces to the MCP23017 and PCF8574 IO expander chips
#
# The logic for this was ported from Dr Scott M. Baker's project:
# http://www.smbaker.com/z80-retrocomputing-4-bus-supervisor
#
... | BleuLlama/LlamaPyArdy | Python/devices/lib_RC2014_BusSupervisor.py | Python | mit | 4,512 |
from Database.Controllers.Curso import Curso
class Periodo(object):
def __init__(self,dados=None):
if dados is not None:
self.id = dados ['id']
self.id_curso = dados ['id_curso']
self.periodo = dados ['periodo']
self.creditos = dados ['creditos']
def getId(self):
return self.id
def setId_curso... | AEDA-Solutions/matweb | backend/Database/Models/Periodo.py | Python | mit | 742 |
from functools import partial
from random import random, randint, choice
import pygame
import init as _
from baseclass import BaseClass
from options import Options
try:
from cython_ import collide
except ImportError:
from python_ import collide
from miscellaneous import further_than, scale
from t... | thdb-theo/Zombie-Survival | src/pickup.py | Python | mit | 3,543 |
"""my_project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-ba... | jessamynsmith/my_project | my_project/urls.py | Python | mit | 837 |
<<<<<<< HEAD
<<<<<<< HEAD
# Copyright (C) 2003-2013 Python Software Foundation
import unittest
import plistlib
import os
import datetime
import codecs
import binascii
import collections
import struct
from test import support
from io import BytesIO
ALL_FORMATS=(plistlib.FMT_XML, plistlib.FMT_BINARY)
# The testdata is... | ArcherSys/ArcherSys | Lib/test/test_plistlib.py | Python | mit | 63,176 |
#!/usr/bin/env python
import time, logging, argparse, json, sys
from es_manager import ElasticsearchSnapshotManager, get_parser
from elasticsearch import exceptions
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('elasticsearch')
def take_snapshot(options):
esm = ElasticsearchSnapshotManager(o... | DomainGroupOSS/elasticsearch-snapshots | es_backup.py | Python | mit | 1,826 |
import pigpio
import time
from multiprocessing import Process, Queue, Lock
#----------------------- SERVO 1 ----------------------------
speed = .1
minP = 30
maxP = 180
currentP = 90
newP = 90
q = Queue() #queue for the new position
q.put(newP)
q2 = Queue() #queue for the current position
q2.put(currentP)
l = Lock()... | arnomoonens/Mussy-Robot | myservo.py | Python | mit | 2,876 |
from httmock import urlmatch
free_proxy_expected = ['138.197.136.46:3128', '177.207.75.227:8080']
proxy_for_eu_expected = ['107.151.136.222:80', '37.187.253.39:8115']
rebro_weebly_expected = ['213.149.105.12:8080', '119.188.46.42:8080']
prem_expected = ['191.252.61.28:80', '167.114.203.141:8080', '152.251.141.93:8080... | pgaref/HTTP_Request_Randomizer | tests/mocks.py | Python | mit | 9,201 |
from django.db import models
class Group(models.Model):
"""Group Model"""
class Meta(object):
verbose_name = 'Група'
verbose_name_plural = 'Групи'
title = models.CharField(
max_length=256,
blank=False,
verbose_name='Назва')
leader = models.OneToOneField(
... | samitnuk/studentsdb | students/models/groups.py | Python | mit | 802 |
import requests
import json
from django.core.management.base import BaseCommand
from django.conf import settings
from django.utils import timezone
from club.models import Club, Member
class Command(BaseCommand):
help = 'Get List of players from lichess for team'
def handle(self, *args, **kwargs):
t... | AfricaChess/lichesshub | club/management/commands/get_teamlist.py | Python | mit | 1,601 |
from typing import Any
from typing import Tuple
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import select
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import composite
Base = declarative_base()
class Point:
def __init__(self, x: int, y: int):
... | sqlalchemy/sqlalchemy | test/ext/mypy/plugin_files/composite_props.py | Python | mit | 1,391 |
#!/usr/bin/env python3
from collections import defaultdict
DEBUG = False
def main():
if DEBUG:
test()
n = int(input())
paths = cycles(n)
print(len(paths))
for p in paths:
print('%d %s' % (len(p), ' '.join([str(v) for v in p])))
def cycles(n):
"""Builds a set of cycles fo... | andreimaximov/algorithms | codeforces/mister-b-and-flight-to-the-moon/main.py | Python | mit | 2,960 |
from pymongo import MongoClient
import multiprocessing
import threading
import datetime
import time
cache = MongoClient(host='10.8.8.111', port=27017, connect=False)['cache25']
db30 = MongoClient(host='10.8.8.111', port=27017, connect=False)['onionsBackupOnline']
events = db30['events']
userAttr = cache['userAttr']
d... | summer-liu/events_cache_scripts | report/cache10.py | Python | mit | 9,568 |
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.conf import settings
from django.views.generic import TemplateView
from views import RobotsView
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', TemplateView.as_vi... | patrickbeeson/diy-trainer | diytrainer/diytrainer/preview_urls.py | Python | mit | 761 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2017-03-07 20:43
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('election_registrar', '0005_auto_20170307_1104'),
]
operations = [
migrations.A... | SCPR/kpcc_backroom_handshakes | election_registrar/migrations/0006_election_election_kpcc_page.py | Python | mit | 544 |
N = int(input())
H = int(input())
W = int(input())
print((N - H + 1) * (N - W + 1))
| knuu/competitive-programming | atcoder/corp/aising2019_a.py | Python | mit | 84 |
"""Tests the surveytools.footprint module."""
import numpy as np
from surveytools.footprint import VphasFootprint, VphasOffset
def test_vphas_offset_coordinates():
"""Test the offset pattern, which is expected to equal
ra -0, dec +0 arcsec for the "a" pointing;
ra -588, dec +660 arcsec for the "b" pointin... | barentsen/surveytools | surveytools/tests/test_footprint.py | Python | mit | 2,130 |
"""finman 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')
Class-bas... | maheswaranm/finman | finman/urls.py | Python | mit | 1,149 |
import errno
import os
import sys
from contextlib import contextmanager
@contextmanager
def open_with_error(filename: str, mode: str = "r", encoding: str = "utf-8"):
try:
f = open(filename, mode=mode, encoding=encoding)
except IOError as err:
yield None, err
else:
try:
... | raphaeldore/analyzr | analyzr/utils/file.py | Python | mit | 2,428 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.