code stringlengths 2 1.05M | repo_name stringlengths 5 104 | path stringlengths 4 251 | language stringclasses 1
value | license stringclasses 15
values | size int32 2 1.05M |
|---|---|---|---|---|---|
from glob import glob
import csv
from peewee import *
database = SqliteDatabase(None)
class BaseModel(Model):
class Meta:
database = database
class Location(BaseModel):
postcode = CharField(unique=True, max_length=8)
positional_quality_indicator = IntegerField()
eastings = IntegerField()
... | tomwphillips/oscpo | oscpo.py | Python | mit | 2,725 |
__author__ = 'ajtag'
from pygame import Rect
import collections
import csv
import os.path
MADRIX_X = 132
MADRIX_Y = 70
MADRIX_SIZE = (MADRIX_X, MADRIX_Y)
white = 255, 255, 255, 0xff
black = 0, 0, 0, 0xff
red = 255, 0, 0, 0xff
green = 0, 255, 0, 0xff
blue = 0, 0, 255, 0xff
dark_grey = 0x30, 0x30, 0x30, 0xff
transpar... | ajtag/TrinRoofPlayer | Constants.py | Python | mit | 1,703 |
# Generated by Django 2.2.24 on 2021-10-06 09:26
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('waldur_auth_social', '0002_remoteeduteamsuser'),
]
operations = [
migrations.DeleteModel(name='RemoteEduteamsUser',),
]
| opennode/waldur-mastermind | src/waldur_auth_social/migrations/0003_delete_remoteeduteamsuser.py | Python | mit | 297 |
import re
import os
import shutil
import plasTeX.Renderers
from plasTeX.Renderers.PageTemplate import Renderer
from plasTeX.Filenames import Filenames
from plasTeX.dictutils import ordereddict
from plasTeX.Imagers import Image
class ImageConverter(object):
fileExtension = '.png'
imageAttrs = ''
imageUnits ... | Tarrasch/problemtools | ProblemPlasTeX/__init__.py | Python | mit | 4,443 |
# -*- coding: utf-8 -*-
from django.views.generic import TemplateView
class IndexView(TemplateView):
template_name = "spa/index.html" | rishatsharafiev/crm | project/spa/views.py | Python | mit | 139 |
# found a way to include it more easily.
'''
SDL2 Window
===========
Windowing provider directly based on our own wrapped version of SDL.
TODO:
- fix keys
- support scrolling
- clean code
- manage correctly all sdl events
'''
__all__ = ('WindowSDL', )
from os.path import join
import sys
from typing... | matham/kivy | kivy/core/window/window_sdl2.py | Python | mit | 31,140 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Remove borders on saved figures
"""
import matplotlib.pyplot as plt
import numpy as np
fig, ax1 = plt.subplots(nrows=1, ncols=1, figsize=(8, 6))
x = np.arange(-10, 10, 0.1)
y = np.power(x, 2.)
ax1.plot(x, y)
# Save file and plot ########
output_file = "save_with... | jeremiedecock/snippets | python/matplotlib/save_without_borders.py | Python | mit | 395 |
'''
Calculate the Euclidean distance between all points to inform the querying
'''
import time
import sqlite3
from math import radians, cos, sin, asin, sqrt
import os
import logging
logger = logging.getLogger(__name__)
def calculate(mode, db_fn, db_temp_fn):
'''
Generate the euclidean distance for each orig, ... | t-g-williams/seattle_hackathon | code/query/euclidean.py | Python | mit | 2,056 |
#!/usr/bin/python
# coding: utf8
"""
Contains range related data structures
List of data structures:
- VariableRangeValue
"""
class VariableRangeValue(object):
"""
Contains the range [lower_bound, 0, upper_bound]
Initialize the range to [-inf, 0, +inf]
"""
identifier = ""
bit_vector... | AngelinNjakasoa/Range-analysis-experiments | data_structure.py | Python | mit | 962 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | AutorestCI/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_10_01/models/virtual_network_gateway_sku.py | Python | mit | 1,557 |
#!/usr/bin/env python
# -*- Mode: Python; py-indent-offset: 4; coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 expandtab
## Copyright (C) 2014, University of Zurich and ETH Zurich
## Copyright (C) 2014, Claudio Luck <cluck@ini.uzh.ch>
## Licensed under the terms of the MIT License, see LICENSE file.
import os
from ... | uzh-ethz-ini/uzh-cd-sphinx-theme | setup.py | Python | mit | 1,862 |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^login/', views.login_view, name='login'),
url(r'^logout/', views.logout_view, name='logout'),
url(r'^register/', views.register_view, name='register'),
]
| FeodorM/splitmoney | accounts/urls.py | Python | mit | 244 |
import sys
import re
gtrack_fname = str(sys.argv[1])
with open(gtrack_fname) as gf:
gtrack_file = gf.readlines()
for line in gtrack_file:
line=line.rstrip()
if line.startswith("#"):
print line
else:
line1=re.sub(r'(chr\w+)',r'\1_A',line)
line2=re.sub(r'(chr\w+)',r'\1_B',line)
print line1
... | tharvesh/preprocess_script | make_diploid_gtack.py | Python | mit | 332 |
My=["Kavinda Athapaththu",22,"Kurunegala"]
print(type(My[2]))
My.append(10000)
print(type(My[3]))
My[3]+=504.5
print(type(My[3]))
A="Welcome"
print(A,My[0][:8])
| ksoftlabs/labsheets1001 | Tutorial 3/Tutorial 3 Q3.py | Python | mit | 161 |
"""
WSGI config for market 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.6/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "market.settings")
from django.core.wsg... | tianhuyang/fifty-market | market/wsgi.py | Python | mit | 387 |
#
# Copyright (C) 2017 Dominik Murzynowski
#
# This software may be modified and distributed under the terms
# of the MIT license. See the LICENSE file for details.
#
import unittest
from unittest.mock import MagicMock
from websocket.request_processor import RequestProcessor
class TestWebSocketRequestProcessing(uni... | qiubit/luminis | backend/tests/test_websocket_request_processing.py | Python | mit | 3,567 |
import sublime
import sublime_plugin
class OutputPanelClearCommand(sublime_plugin.TextCommand):
def run(self, edit, string=''):
self.view.set_read_only(False)
self.view.erase(edit, sublime.Region(0, self.view.size()))
self.view.set_read_only(True) | anconaesselmann/ClassesAndTests | classes_and_tests/OutputPanelClear.py | Python | mit | 276 |
'''
Copyleft Nov 24, 2015 Arya Iranmehr, PhD Student, Bafna's Lab, UC San Diego, Email: airanmehr@gmail.com
'''
# import simuPOP as sim
import numpy as np
import pandas as pd
import sys,os
home=os.path.expanduser('~') +'/'
"""
alleleFrea is a dictionary {site:{0:AF0, 1:1-AF0}}
"""
def simuLDDecay(popSize=1000, gen=1... | airanmehr/bio | Scripts/Miscellaneous/Tutorials/SimPop.py | Python | mit | 5,947 |
sign_in_req_schema = {
'$schema': 'http://json-schema.org/draft-04/schema',
'type': 'object',
'properties': {
'email': {
'type': 'string',
'minLength': 1,
'format': 'email',
},
'password': {
'type': 'string',
'minLength': 1,... | codepotpl/codepot-backend | codepot/views/auth/auth_json_schema.py | Python | mit | 2,382 |
#!../../../../virtualenv/bin/python3
# -*- coding: utf-8 -*-
# NB: The shebang line above assumes you've installed a python virtual environment alongside your working copy of the
# <4most-4gp-scripts> git repository. It also only works if you invoke this python script from the directory where it
# is located. If these... | dcf21/4most-4gp-scripts | src/scripts/synthesize_samples/synthesize_demo_stars_2.py | Python | mit | 1,891 |
#! /usr/bin/env python
import codecs
import csv
import os.path
from mutagen.easyid3 import EasyID3
from mutagen.mp3 import MP3
import mutagen
kMetadataFields = ["artist", "title", "album", "tracknumber", "genre", "date", "bitrate", "length", "filename"]
def MsToMinSec(ms):
''' given a duration value in millisec... | bgporter/mp3utilities | meta.py | Python | mit | 4,317 |
import RPi.GPIO as io
from rx.subjects import Subject
from modules import logger
class Pirs:
def __init__(self):
io.setmode(io.BCM)
self.pir_pin = 4
io.setup(self.pir_pin, io.IN)
self.pirStream = Subject()
io.add_event_detect(self.pir_pin, io.RISING, callback=self.hit_call... | rdubigny/home-alarm | modules/pirs.py | Python | mit | 447 |
#!/usr/bin/env python2
# Copyright (c) 2014-2018 The Bitcoin Core developers
# Copyright (c) 2015-2018 The PIVX developers
# Copyright (c) 2018 The Ion developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Test for -rpcbind... | mitchellcash/ion | qa/rpc-tests/rpcbind_test.py | Python | mit | 5,834 |
# Generated by Django 3.0.8 on 2020-07-05 15:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('logtoday', '0003_auto_20200121_0751'),
]
operations = [
migrations.AlterField(
model_name='goaltasks',
name='task_ta... | sundeep-co-in/makegoalsdaily | logtoday/migrations/0004_auto_20200705_1553.py | Python | mit | 445 |
"""
Django settings for guery_manager project.
Generated by 'django-admin startproject' using Django 1.11.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
imp... | BigQueryManager/bigquerymgr | guery_manager/guery_manager/settings.py | Python | mit | 4,869 |
def join_terms(terms):
if len(terms) == 0:
return "0"
rval = ""
first = True
for sign, factors in terms:
if first:
if sign != '+':
rval += sign
first = False
else:
rval += " {} ".format(sign)
if not factors:
rval += "1"
else:
rval += " ".join(factors)
... | andersjel/boxes | src/symmath/format.py | Python | mit | 1,046 |
from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponseRedirect
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.db.models import Q, Co... | CS326-important/space-deer | contentdensity/textifai/views.py | Python | mit | 8,990 |
import os
from coffee.integrations import NotiwireIntegration
app_config = {
'DEBUG': bool(os.getenv('DEBUG', True)),
'REDIS_DB': int(os.getenv('REDIS_DB', 1)),
'REDIS_HOST': os.getenv('REDIS_HOST', '127.0.0.1'),
'REDIS_PORT': int(os.getenv('REDIS_PORT', 6379)),
'REDIS_PW': os.getenv('REDIS_PW', No... | webkom/coffee | coffee/config.py | Python | mit | 575 |
import sys
# Linked list class
class Linked_List:
'''
List_Node is an inner class of the Linked_List class.
It stores a value, and a pointer to the next List_Node.
Note the __repr__ method, which shows the addresses in
the next pointers, so you can compare several nodes and
verify that they ar... | doylew/practice | python/linked_list.py | Python | mit | 9,502 |
#!/usr/bin/env python
import os.path
from distutils.core import setup
README = open(os.path.join(os.path.dirname(__file__), "README.rst")).read()
CLASSIFIERS = [
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"License ::... | ALenfant/django-push-notifications | setup.py | Python | mit | 1,301 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Definition for a binary tree node.
class CNode:
left, right, val = None, None, 0
def __init__(self, val):
# initializes the val members
self.left = None
self.right = None
self.val = val
class CBOrdTree:
def... | lijiali1226/Code | leetcode/python/P226InvertBinaryTree.py | Python | mit | 2,459 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | rjschwei/azure-sdk-for-python | azure-mgmt-compute/azure/mgmt/compute/models/container_service_ssh_configuration.py | Python | mit | 1,130 |
#!/usr/bin/env python3
#
# Usage: update-readme.py
# Prints updated README.md. It substitutes tables of commands
# with newly generated ones.
import sys
import re
import util
import const
import generate_table_of_functions
TARGET_LINE = "There are currently "
TABLES_TARGET_LINE_START = "Below is a list of most usef... | gto76/standard-aliases | scripts/update-readme.py | Python | mit | 2,763 |
# coding:utf-8
from flask import Flask, jsonify, request, abort, render_template, url_for
from flask_sqlalchemy import SQLAlchemy
from marshmallow import Schema, fields
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///articles.sqlite'
app.config['SQLALCHEMY... | abacuspix/NFV_project | Build_Web_With_Flask/Building web applications with Flask_Code/chapter06/ex02.py | Python | mit | 2,720 |
# Generated by Django 2.0.6 on 2018-07-13 20:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('recipes', '0002_auto_20180710_0956'),
]
operations = [
migrations.AlterField(
model_name='recipe',
name='slug',
... | jf248/scrape-the-plate | recipes/migrations/0003_auto_20180713_1354.py | Python | mit | 431 |
import random
from functions import print_bold
from knight import Knight
from orcrider import OrcRider
class Hut():
"""Class to create hut object in the game Attack of the Orcs.
:arg int number: Hut number to be assigned.
:arg `AbstractRider` occupant: The new occupant of the Hut.
:ivar int number:... | helewonder/knightgame | wargame/hut.py | Python | mit | 2,567 |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use("ggplot")
from sklearn.cluster import KMeans
from scipy import sparse
x = [2,3,1,3,1.5]
y = [2,2,1,1,0.5]
plt.scatter(x,y)
plt.show()
X = np.array([[2,2],[3,2],[1,1],[3,1],[1.5,0.5]])
kmeans = KMeans(n_clusters=2)
kmeans.fit(X... | AdiVarma27/Kmeans2D | Kmeans SKlearn/KmeansSKlearn.py | Python | mit | 699 |
import caffe
import numpy as np
import os
import sys
model_prototxt = '../features/deploy.prototxt'
model_trained = '../models/best_citynet/_iter_100000.caffemodel'
mean_path = '../data/mean_image.binaryproto'
layer_name = 'pool5/7x7_s1'
image_list_filepath = '../data/train.txt'
features_filepath = '../features/featur... | wulfebw/LittlePlaNet-Models | scripts/extract_features.py | Python | mit | 1,991 |
# -*- coding: utf-8 -*-
'''
Object explorer in PySide/PyQt4
Created on May 07 2013
@author: Christopher Liman
Features:
represents the following categories of objects in globals() or a root object as a tree:
- sequence-like objects (e.g. lists, numpy arrays)
- mapping-like objects (e.g. dicts, pandas objects)
- classe... | allthedata/objectexplorer | objectexplorer/objectexplorer.py | Python | mit | 11,470 |
from distutils.core import setup
setup(
name='peewee_ckansql',
version='0.1.0dev',
author='Geoffrey Hing',
author_email='geoffhing@gmail.com',
packages=['peewee_ckansql',],
license='LICENSE.txt',
description='Python Database API',
long_description=open('README.rst').read(),
install_... | ghing/python-peewee_ckansql | setup.py | Python | mit | 453 |
import mock
import pytest
from swimlane.core.resources.usergroup import Group, User
def test_group_list(mock_group, mock_swimlane):
mock_response = mock.MagicMock()
mock_response.json.return_value = {'groups': [mock_group._raw for _ in range(3)]}
with mock.patch.object(mock_swimlane, 'request', return_v... | Swimlane/sw-python-client | tests/adapters/test_usergroup_adapters.py | Python | mit | 3,248 |
from marshmallow import fields
__all__ = ['CommaSeparatedList']
class CommaSeparatedList(fields.List):
def _serialize(self, value, attr, obj):
result = super()._serialize(value, attr, obj)
return ','.join(result) if result is not None else None
def _deserialize(self, value, attr, data):
... | despawnerer/theatrics | api/theatrics/utils/fields.py | Python | mit | 557 |
import time
import json
import unittest
import uuid
from api import db
from api.models.user import User
from api.models.recipe import Recipe
from api.models.ingredient import Ingredient, PantryIngredient, RecipeIngredient
from tests.base_test_case import BaseTestCase
from helpers import json_to_ingredient, json_to_us... | reciprep/reciprep-server | flask-api/tests/test_recipe.py | Python | mit | 11,464 |
"""
Functionality to draw using OpenCV functionality.
"""
from collections import namedtuple
import itertools
import numpy as np
import cv2
from . import utils
from . import colors
def blank_canvas(shape, color):
"""Return a blank canvas of the specified shape and color"""
blank = np.array([color] * shape[0]... | christianreimer/treescore | treescore/judge/draw.py | Python | mit | 3,209 |
import os
from functools import partial
from nose.tools import with_setup, eq_
from pollute import modified_environ
#
# Tests
#
def test_no_changes():
old_env = os.environ.copy()
def ensure_no_changes():
eq_(dict(os.environ), old_env)
test_scenarios = partial(
__ensure_usage,
kw... | themattrix/python-pollute | pollute/test/test_modified_environ.py | Python | mit | 2,667 |
class DataFilePath:
def __init__(self):
self.dataDir = '../data/citydata/season_1/'
return
def getOrderDir_Train(self):
return self.dataDir + 'training_data/order_data/'
def getOrderDir_Test1(self):
return self.dataDir + 'test_set_1/order_data/'
def getTest1Dir(self)... | LevinJ/Supply-demand-forecasting | utility/datafilepath.py | Python | mit | 1,210 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# This file is part of bzz.
# https://github.com/heynemann/bzz
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT-license
# Copyright (c) 2014 Bernardo Heynemann heynemann@gmail.com
from mock import Mock, patch
import cow.server as server
import torn... | bzz-framework/bzz | tests/test_auth_hive.py | Python | mit | 24,071 |
"""
WSGI config for soma3 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... | UrQA/URQA-Server | soma3/soma3/wsgi.py | Python | mit | 1,544 |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# Download and build the data if it does not exist.
import unittest
import importlib
from parlai.tasks.task_list import ... | facebookresearch/ParlAI | tests/nightly/cpu/test_urls.py | Python | mit | 1,617 |
# Copyright (c) 2012-2013 Paul Tagliamonte <paultag@debian.org>
# Copyright (c) 2014-2015 Clement Schreiner <clement@mux.me>
#
# 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 restrict... | Debian/debile | debile/master/orm.py | Python | mit | 30,162 |
# SPDX-FileCopyrightText: 2019 Jean-Louis Fuchs <ganwell@fangorn.ch>
#
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Test if the stack stays consistent."""
from build._rbtree_tests import lib, ffi
from hypothesis.stateful import GenericStateMachine
from hypothesis.strategies import tuples, just, integers
class I... | ganwell/rbtree | old_dev/src/test_stack.py | Python | mit | 2,188 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from avenue import Avenue
from avenue import MatchError
from avenue import MethodProcessor
from avenue import PathProcessor
from avenue import Processor
from avenue.processors import Match
from pytest import raises
class TestPro... | CorverDevelopment/Avenue | tests/test_processors.py | Python | mit | 3,830 |
import os
import shutil
from wmt.config import site
from wmt.models.submissions import prepend_to_path
from wmt.utils.hook import find_simulation_input_file
from topoflow_utils.hook import (assign_parameters, lowercase_choice,
scalar_to_rtg_file)
file_list = []
def execute(env):
... | csdms/wmt-metadata | metadata/InfilRichards1D/hooks/pre-stage.py | Python | mit | 1,925 |
import time
import timeit
import signal
from sys import exit, exc_info, argv
from math import sin, cos, sqrt, asin, isnan, isinf, pi
from collections import deque
from references import *
#http://www.forkosh.com/mimetex.cgi?P(s)=\frac{\alpha_2z^2+\alpha_1z+\alpha_0}{\beta_2z^2+\beta_1z+\beta_0}
#http://www.forkosh.com/... | slremy/testingpubsub | myBallPlate/sweep.py | Python | mit | 7,216 |
import argparse
from . import __description__, __program__
from . import PIP
def build_parser():
parser = argparse.ArgumentParser(
prog=__program__,
description=__description__
)
parser.add_argument(
'-u', '--user',
dest='user', action='store',
metavar='USER', defau... | fopina/pyfispip | fispip/__main__.py | Python | mit | 1,774 |
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.views.generic import TemplateView
from django.contrib import admin
from django.conf import settings
from apps import urls
urlpatterns = [
url(r'', include(urls, namespace='apps')),
#url(r'^jet/', include('jet.ur... | eb-intl/eb-intl.com | webapp/webapp/urls.py | Python | mit | 631 |
# This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
from flask import request
from wtforms.fields import BooleanField... | mic4ael/indico | indico/modules/events/persons/forms.py | Python | mit | 2,351 |
from .config import HOME
import os
import os.path as osp
import sys
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
import cv2
import numpy as np
COCO_ROOT = osp.join(HOME, 'data/coco/')
IMAGES = 'images'
ANNOTATIONS = 'annotations'
COCO_API = 'PythonAPI'
INSTANCES_SET = 'insta... | amdegroot/ssd.pytorch | data/coco.py | Python | mit | 7,168 |
v_letters=('a','e','i','o','u','y')
class Thing:
p={} #properties
name=''
def __init__(self,name,properties):
self.name=name
self.p=properties
def description(self):
adj=''
has_n=['','n'][self.name[0].lower() in v_letters]
if '_adjective' in self.p.keys():
adj=self.p['_ad... | untergrunt/untergrunt | outdated/objects.py | Python | mit | 695 |
from pymongo import MongoClient
def insert_item(item):
client = MongoClient()
db = client.douban.movie
result = db.insert_one(item)
def query_document():
client = MongoClient()
db = client.douban.movie
cursor = db.find()
for document in cursor:
print(document)
def delete_item()... | EclipseXuLu/DataHouse | DataHouse/test/pymongo_test.py | Python | mit | 490 |
from django.db import models
# Create your models here.
class Question(models.Model):
qtext = models.CharField(max_length=200)
correctans = models.CharField(max_length=200)
class User(models.Model):
name = models.CharField(max_length=200)
password = models.CharField(max_length=200)
username = models.CharField(ma... | icyflame/test-taking-platform | examsys/models.py | Python | mit | 505 |
#!/usr/bin/python
# coding: utf-8
class Solution(object):
def isAdditiveNumber(self, num):
"""
:type num: str
:rtype: bool
"""
length = len(num)
for i in range(1, length):
for j in range(i + 1, length):
s1, s2 = num[0 : i], num[i : j]
... | Lanceolata/code-problems | python/leetcode_medium/Question_156_Additive_Number.py | Python | mit | 802 |
import httplib, urllib, sys, re
from datetime import datetime
from BeautifulSoup import BeautifulSoup
def error(s):
sys.stderr.write(s + "\n")
sys.exit(-1)
HOST = "intra.fast.sh"
passwd = open(".passwd", "r").read().split("\n")
try:
USER = passwd[0]
PASSWORD = passwd[1]
except IndexError:
error("Invalid .passw... | avuori/intracmd | intra.py | Python | mit | 2,620 |
def hash_style(style):
return tuple(sorted(style.items()))
style_pool = {}
defaultstyle = {}
def create_style(**kwds):
style = defaultstyle.copy()
style.update(kwds)
key = hash_style(style)
try:
return style_pool[key]
except KeyError:
style_pool[key] = style
return s... | ActiveState/code | recipes/Python/577978_Text_Model/recipe-577978.py | Python | mit | 3,496 |
"""TestAuthZ implementations of grading.GradeSystem"""
import datetime
import pytest
from tests.utilities.general import is_never_authz, is_no_authz, uses_cataloging
from dlkit.abstract_osid.authorization import objects as ABCObjects
from dlkit.abstract_osid.authorization import queries as ABCQueries
from dlkit.abstra... | mitsei/dlkit | tests/functional/test_authz/grading/test_grade_system_authz.py | Python | mit | 29,566 |
import requests, json
"""
Get single record
"""
tokenFile = 'token.txt'
hpsaServer = 'mslon001pngx.saas.hp.com'
tenantId = 725867830
entityType = 'Person'
accountId = 80585
layout = 'Name'
def getRecord(server, token, tenantId, entityType, entityId, layout):
rest = 'rest/{0}/ems/Person/{1}'.format(tenantId, acco... | maduma/hpany | record.py | Python | mit | 823 |
#find if the length of the linked list is even or not?
class Node:
def __init__(self, data):
self.data = data
self.next = None
def setData(self, data):
self.data = data
def getData(self):
return self.data
def setNext(self, next):
self.next =... | applecool/Practice | Python/LinkedLists/IsLinkedListLengthEven.py | Python | mit | 2,007 |
from qtlayoutbuilder.api.layouterror import LayoutError
from qtlayoutbuilder.lib.builderassertions import BuilderAssertions
from qtlayoutbuilder.lib.childadder import ChildAdder
from qtlayoutbuilder.lib.layoutscreated import LayoutsCreated
from qtlayoutbuilder.lib.line_parser import LineParser
from qtlayoutbuilder.lib.... | peterhoward42/qt-layout-gen | src/qtlayoutbuilder/lib/builder.py | Python | mit | 5,337 |
"""
KAGGLE dataset loader.
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import time
import numpy as np
import deepchem
from deepchem.molnet.load_function.kaggle_features import merck_descriptors
def remove_missing_entries(dataset):
"""... | rbharath/deepchem | deepchem/molnet/load_function/kaggle_datasets.py | Python | mit | 5,465 |
import os
import sys
import glob
import mechanize
from mechanize._beautifulsoup import BeautifulSoup, Tag
import json
import math
from urlparse import urlparse
from collections import deque
from time import sleep
from random import randint
import httplib
base_url = u"http://ieeexplore.ieee.org"
conn = None
def fetch... | pebbie/BIBINT | scripts/scrape.py | Python | mit | 12,770 |
from .sqlalchemy import SAPlugin
| sourcelyzer/sourcelyzer | sourcelyzer/httpapi/plugins/__init__.py | Python | mit | 33 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('pact', '0002_auto_20150411_1952'),
]
operations = [
migrations.AddField(
model_name='pact',
name='go... | joshmarlow/crowdpact | crowdpact/apps/pact/migrations/0003_auto_20150411_2325.py | Python | mit | 573 |
import ast
from copy import deepcopy
from operator import itemgetter
from functools import partial, wraps
from syn.base_utils import get_typename, ReflexiveDict, assign
from syn.util.log.b import StringEvent
from syn.tree.b import Node, Tree
from syn.base.b import create_hook, Attr, init_hook, Base, Counter
from syn.ty... | mbodenhamer/syn | syn/python/b/base.py | Python | mit | 17,266 |
# -*- coding: utf-8 -*-
import psutil
def get_sysinfo():
result = {}
result['cpu_utilization'] = psutil.cpu_percent()
result['mem_utilization'] = psutil.virtual_memory().percent
result['swap_utilization'] = psutil.swap_memory().percent
for part in psutil.disk_partitions(all=False):
r = psu... | onlytiancai/warning-agent | src/counters/default.py | Python | mit | 1,301 |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program 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 2
# of the License, or (at your option) any later version.
#
# This program is distrib... | morevnaproject/scripts | blender/io_import_lipSync_Importer.py | Python | cc0-1.0 | 25,957 |
import os
path = os.path.dirname(os.path.realpath(__file__))
sbmlFilePath = os.path.join(path, 'MODEL1006230021.xml')
with open(sbmlFilePath,'r') as f:
sbmlString = f.read()
def module_exists(module_name):
try:
__import__(module_name)
except ImportError:
return False
else:
ret... | biomodels/MODEL1006230021 | MODEL1006230021/model.py | Python | cc0-1.0 | 427 |
#################
# codes for testing armor.patternMatching.pipeline and armor.patternMatching.algorithms
import time
import shutil
import os
time0 = time.time()
startTime =time.asctime()
from armor import defaultParameters as dp
from armor import misc
from armor import pattern, pattern2
p2 = pattern2
from ar... | yaukwankiu/armor | start4_taipei_taichung_tainan.py | Python | cc0-1.0 | 4,043 |
import base64
import hashlib
import hmac
import json
from datetime import datetime, timedelta
from flask import request
from timezone import KST, now
def base64_url_decode(inp):
padding_factor = (4 - len(inp) % 4) % 4
inp += "="*padding_factor
return base64.b64decode(unicode(inp).translate(dict(zip(map(or... | funnyplan/Pager | pager/libs/facebook_.py | Python | cc0-1.0 | 1,270 |
import ConfigParser, logging, datetime, os
import mediacloud
from flask import Flask, render_template, request
CONFIG_FILE = 'settings.config'
basedir = os.path.dirname(os.path.realpath(__file__))
# load the settings file
config = ConfigParser.ConfigParser()
config.read(os.path.join(basedir, 'settings.config'))
# se... | shtarbanov/MAS.500 | HW3/startServer.py | Python | cc0-1.0 | 2,704 |
"""Модуль для сортировки чертежей по каталогам."""
import re
import os
import sys
import shutil
DESIGNATION = r'[a-zA-Zа-яА-Я].*\d'
TYPE = r'СБ|МЧ|ВО|УЧ'
NAME = r'[a-zA-Zа-яА-Я].*?\S'
CHANGES = r'\(изм\.\d{2}\))'
EXTENSION = r'\.[^.]+'
SEP = r'[\s_]'
DRAWING = re.compile(
f'^({DESIGNATION})' # обозначение ... | e2t/cli-tools | src/sort_drawings.py | Python | cc0-1.0 | 1,439 |
#
# The OpenDiamond Platform for Interactive Search
#
# Copyright (c) 2012 Carnegie Mellon University
# All rights reserved.
#
# This software is distributed under the terms of the Eclipse Public
# License, Version 1.0 which can be found in the file named LICENSE.
# ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS S... | cmusatyalab/opendiamond | opendiamond/blaster/__init__.py | Python | epl-1.0 | 4,788 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on Jul 22, 2014
@author: anroco
How to use the or operator in an if statement of Python?
¿Cómo usar el operador or en una sentencia if de Python?
'''
#if expression1 or expression2 or expressionN:
# statements
#create two boolean objects
a = False
b = Fa... | OxPython/python_control_flow_if_or_operator | src/control_flow_if_or.py | Python | epl-1.0 | 504 |
import math
def check_digits(n):
check = n
sum = 0
while check > 0:
sum += math.factorial(check % 10)
check = check / 10
if sum == n:
return True
return False
sum = 0
for x in xrange(3,100001):
if check_digits(x):
sum += x
print sum | dlakata/projecteuler | p34.py | Python | gpl-2.0 | 249 |
import cryptopy.cipher.rijndael
from cryptopy.cipher.base import noPadding
class RijndaelCipher(object):
def __init__(self, key, block_size=16):
self.r = cryptopy.cipher.rijndael.Rijndael(key, padding=noPadding(), keySize=16, blockSize=block_size)
def encrypt(self, plaintext):
return self.r.e... | repotvsupertuga/tvsupertuga.repository | script.module.cryptolib/lib/Crypto/Cipher/Rijndael.py | Python | gpl-2.0 | 426 |
# Copyright 2019 Shadow Robot Company Ltd.
#
# This program 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 version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITH... | shadow-robot/sr_common | sr_description/mujoco_models/meshes/arm_and_hand_meshes/conversion.py | Python | gpl-2.0 | 1,773 |
"""
curved_distances.py
Jose Guzman, sjm.guzman@gmail.com
Claudia Espinoza, claudia.espinoza@ist.ac.at
Created: Mon Nov 20 18:13:47 CET 2017
This is an ImageJ-pluging writen in Jython. Jython is the Python
implementation to run the Java platform in ImageJ. Check
https://imagej.net/Jython_Scripting
It calculates... | ClaudiaEsp/inet | Fiji/curved_distances_.py | Python | gpl-2.0 | 19,135 |
states = {
'FL':36,
'NY':35,
'PA':34,
'OH':33,
'MD':32,
'IN':31,
'WA':30,
'CO':29,
'AL':28,
'CT':27,
'TN':26,
'KY':25,
'NV':24,
'MO':23,
'OR':22,
'UT':21,
'OK':20,
'MS':19,
'AR':18,
'WI':17,
'GA':16,
'NH':15,
'ME':14,
'NM':13,
'ID':12,
'RI':11,
'KS':10,
'WV':9,
'IA':8,
'DE':7,
'DC':6,
... | euclides5414/kaggle-allstate-purchase | conv.py | Python | gpl-2.0 | 1,132 |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | morrillo/sale_taxes_report | __init__.py | Python | gpl-2.0 | 1,071 |
from Queue import Queue
from threading import Thread
from test import pystone
import time
from cmd_profile import *
import subprocess
import logging
import os
import sys
__author__ = "alex"
__date__ = "$May 14, 2015 12:22:46 AM$"
# run python indexer.py zc.buildout-2.3.1-py.2.7.egg 1
# file indexer
dirname = os.path.... | Dr762/PythonExamples3.4 | Python2/indexer.py | Python | gpl-2.0 | 1,527 |
from Screens.Screen import Screen
from Components.ActionMap import ActionMap
from Components.config import config, configfile, getConfigListEntry
from Components.ConfigList import ConfigListScreen
from Components.SystemInfo import SystemInfo
from Components.Sources.StaticText import StaticText
from Components.Pixmap im... | idrogeno/FusionOE | lib/python/Screens/UserInterfacePositioner.py | Python | gpl-2.0 | 29,513 |
#!env python
# Copyright (c) Siemens AG, 2013
#
# This file is part of sparring. sparring 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 2
# of the License, or(at your option) any later versi... | siemens/sparring | setup.py | Python | gpl-2.0 | 1,641 |
def great():
number = [1, 1, 10, 8, 15, 8, 85]
count = 0
length = len(number)
currentlarge = number[count]
#latest = currentlarge
for i in number:
count += 1
if count <= length-1:
if currentlarge > number[count]:
latest = currentlarge
else:
currentlarge = number[count]
latest = currentla... | mrniranjan/python-scripts | reboot/math59.py | Python | gpl-2.0 | 348 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
author: Guillaume Bouvier
email: guillaume.bouvier@ens-cachan.org
creation date: 01 10 2013
license: GNU GPL
Please feel free to use and modify this, but keep the above information.
Thanks!
"""
import SOM
import numpy
import re
import matplotlib.pyplot
import ... | bougui505/SOM | ROCSOM.py | Python | gpl-2.0 | 8,985 |
import FWCore.ParameterSet.Config as cms
def getBaseConfig(globaltag, testfile="", maxevents=0, datatype='data'):
"""Default config for Z+jet skims with Kappa
This is used in a cmssw config file via:
import skim_base
process = skim_base.getBaseConfig('START53_V12', "testfile.root")
"""
... | dhaitz/CalibFW | cfg/cmssw/skim_53x_Summer13_untagged.py | Python | gpl-2.0 | 13,843 |
"""
Terminal colouring functions
Copyright 2013 Red Hat, Inc.
Licensed under the GNU General Public License, version 2 as
published by the Free Software Foundation; see COPYING for details.
Taken from the LNST project: https://github.com/jpirko/lnst/
"""
__author__ = """
rpazdera@redhat.com (Radek Pazdera)
"""
impo... | rcocetta/kano-toolset | kano/colours.py | Python | gpl-2.0 | 6,012 |
from django.utils import timezone
from dateutil.relativedelta import relativedelta
from edc_consent.models import ConsentType
from edc_registration.models import RegisteredSubject
from edc_constants.constants import (FAILED_ELIGIBILITY, OFF_STUDY, SCHEDULED, POS, YES,
NO, NEG, NOT_A... | TshepangRas/tshilo-dikotla | td_maternal/tests/test_maternal_ultrasound.py | Python | gpl-2.0 | 10,136 |
# vim: set fileencoding=utf-8 :
# (C) 2012 Guido Günther <agx@sigxcpu.org>
# This program 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 2 of the License, or
# (at your option) any ... | agx/git-buildpackage | tests/14_test_gbp_import_dscs.py | Python | gpl-2.0 | 3,329 |
import sys, os
sys.path.append(os.path.realpath('..'))
import cPickle
import tracts_ped as ped
popdir = os.path.expanduser(sys.argv[1])
outdir = os.path.expanduser(sys.argv[2])
popfiles = [os.path.join(popdir, popfile) for popfile in os.listdir(popdir)
if os.path.splitext(popfile)[1] == '.pkl']
for popfile in pop... | DomNelson/tracts | utils/pklpops_to_bedfiles.py | Python | gpl-2.0 | 735 |
#!/usr/bin/env python
#coding=utf8
'''
Given a sequence of n integers a1, a2, ..., an, a 132 pattern is a subsequence ai, aj, ak such that i < j < k and ai < ak < aj. Design an algorithm that takes a list of n numbers as input and checks whether there is a 132 pattern in the list.
Note: n will be less than 15,000.
E... | mornsun/javascratch | src/topcoder.py/LC_456_132_Pattern.py | Python | gpl-2.0 | 2,020 |
# -*- coding: utf-8 -*-
#
# This file is part of CDS.
# Copyright (C) 2015, 2016 CERN.
#
# CDS 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 2 of the
# License, or (at your option) any later v... | omelkonian/cds | tests/unit/test_access_records.py | Python | gpl-2.0 | 3,858 |