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 |
|---|---|---|---|---|---|
"""
Tutorial - Object inheritance
You are free to derive your request handler classes from any base
class you wish. In most real-world applications, you will probably
want to create a central base class used for all your pages, which takes
care of things like printing a common page header and footer.
"""
import cherr... | ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/lib/cherrypy/cherrypy/tutorial/tut05_derived_objects.py | Python | bsd-3-clause | 2,291 |
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | kevin-coder/tensorflow-fork | tensorflow/contrib/optimizer_v2/momentum.py | Python | apache-2.0 | 4,934 |
import datetime
from django.db import DEFAULT_DB_ALIAS
from django.test import TestCase
from django.utils import tzinfo
from models import Donut, RumBaba
from django.conf import settings
class DataTypesTestCase(TestCase):
def test_boolean_type(self):
d = Donut(name='Apple Fritter')
self.assertFal... | adviti/melange | thirdparty/google_appengine/lib/django_1_2/tests/regressiontests/datatypes/tests.py | Python | apache-2.0 | 4,274 |
# encoding: 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 field 'QueryHistory.server_name'
db.add_column('beeswax_queryhistory', 'server_name', self.gf('django.db.... | vmanoria/bluemix-hue-filebrowser | hue-3.8.1-bluemix/apps/beeswax/src/beeswax/migrations/0003_auto__add_field_queryhistory_server_name__add_field_queryhistory_serve.py | Python | gpl-2.0 | 7,185 |
#!/usr/bin/env python
# JDownloader/src/jd/controlling/LinkGrabberPackager.java
import re
from urlparse import urlparse
def matchFirst(string, *args):
""" matches against list of regexp and returns first match"""
for patternlist in args:
for pattern in patternlist:
r = pattern.search(stri... | manuelm/pyload | module/common/packagetools.py | Python | gpl-3.0 | 4,869 |
# -*- coding:utf-8 -*-
#
#
# Copyright (C) 2013 Michael Telahun Makonnen <mmakonnen@gmail.com>.
# All Rights Reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, eit... | Endika/hr | hr_report_payroll_attendance_summary/wizard/__init__.py | Python | agpl-3.0 | 850 |
"""The ign_sismologia component."""
| fbradyirl/home-assistant | homeassistant/components/ign_sismologia/__init__.py | Python | apache-2.0 | 36 |
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest
# test_records = frappe.get_test_records('Student')
class TestStudent(unittest.TestCase):
pass
| hassanibi/erpnext | erpnext/schools/doctype/student/test_student.py | Python | gpl-3.0 | 270 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Ansible module to manage mysql replication
(c) 2013, Balazs Pocze <banyek@gawker.com>
Certain parts are taken from Mark Theunissen's mysqldb module
This file is part of Ansible
Ansible is free software: you can redistribute it and/or modify
it under the terms of the GNU... | andreaso/ansible | lib/ansible/modules/database/mysql/mysql_replication.py | Python | gpl-3.0 | 13,039 |
# stdlib
import threading
import time
from types import ListType
import unittest
# 3p
from nose.plugins.attrib import attr
# project
from aggregator import MetricsAggregator
from dogstatsd import Server
from jmxfetch import JMXFetch
from tests.checks.common import Fixtures
STATSD_PORT = 8121
class DummyReporter(th... | WPMedia/dd-agent | tests/checks/integration/test_cassandra.py | Python | bsd-3-clause | 2,080 |
#!/usr/bin/python
# Copyright 2003 Vladimir Prus
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
# This tests correct handling of dependencies, specifically, on generated
# sources, and from generated sources.
import Bo... | NixaSoftware/CVis | venv/bin/tools/build/v2/test/core_dependencies.py | Python | apache-2.0 | 3,575 |
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest
# test_records = frappe.get_test_records('Student Batch Name')
class TestStudentBatchName(unittest.TestCase):
pass
| manqala/erpnext | erpnext/schools/doctype/student_batch_name/test_student_batch_name.py | Python | gpl-3.0 | 300 |
######################## BEGIN LICENSE BLOCK ########################
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Con... | Branlala/docker-sickbeardfr | sickbeard/lib/requests/packages/chardet2/escprober.py | Python | mit | 3,094 |
import numpy as np
from numpy.testing import assert_
import scipy.special.orthogonal as orth
from scipy.special._testutils import FuncData
def test_eval_chebyt():
n = np.arange(0, 10000, 7)
x = 2*np.random.rand() - 1
v1 = np.cos(n*np.arccos(x))
v2 = orth.eval_chebyt(n, x)
assert_(np.allclose(v1, ... | lesserwhirls/scipy-cwt | scipy/special/tests/test_orthogonal_eval.py | Python | bsd-3-clause | 4,547 |
# -*- twisted.conch.test.test_mixin -*-
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
import time
from twisted.internet import reactor, protocol
from twisted.trial import unittest
from twisted.test.proto_helpers import StringTransport
from twisted.conch import mixin
class TestB... | sorenh/cc | vendor/Twisted-10.0.0/twisted/conch/test/test_mixin.py | Python | apache-2.0 | 1,110 |
from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .iq import IqProtocolEntity
class PingIqProtocolEntity(IqProtocolEntity):
'''
Receive
<iq type="get" xmlns="urn:xmpp:ping" from="s.whatsapp.net" id="1416174955-ping">
</iq>
Send
<iq type="get" xmlns="w:p" to="s.whatsapp.net" id="1... | felix-dumit/campusbot | yowsup2/yowsup/layers/protocol_iq/protocolentities/iq_ping.py | Python | mit | 555 |
#
# Python Imaging Library
# $Id$
#
# stuff to read simple, teragon-style palette files
#
# History:
# 97-08-23 fl Created
#
# Copyright (c) Secret Labs AB 1997.
# Copyright (c) Fredrik Lundh 1997.
#
# See the README file for information on usage and redistribution.
#
from PIL._binary import o8
##
# File h... | Microvellum/Fluid-Designer | win64-vc/2.78/Python/lib/site-packages/PIL/PaletteFile.py | Python | gpl-3.0 | 1,113 |
"""
Gnome keyring parser.
Sources:
- Gnome Keyring source code,
function generate_file() in keyrings/gkr-keyring.c,
Author: Victor Stinner
Creation date: 2008-04-09
"""
from hachoir_core.tools import paddingSize
from hachoir_parser import Parser
from hachoir_core.field import (FieldSet,
Bit, NullBits, NullBy... | kreatorkodi/repository.torrentbr | plugin.video.yatp/site-packages/hachoir_parser/misc/gnome_keyring.py | Python | gpl-2.0 | 6,255 |
# -*- 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... | diogocs1/comps | web/addons/hw_scanner/__init__.py | Python | apache-2.0 | 1,075 |
"""Get log settings."""
import os
import platform
import sys
from logging.handlers import SysLogHandler
LOG_LEVELS = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']
def get_logger_config(log_dir,
logging_env="no_env",
tracking_filename="tracking.log",
... | zadgroup/edx-platform | openedx/core/lib/logsettings.py | Python | agpl-3.0 | 5,765 |
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.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
# without limitation the rights to use, copy, modi... | ubirch/aws-tools | virtual-env/lib/python2.7/site-packages/boto/sqs/message.py | Python | apache-2.0 | 9,892 |
# -*- coding: utf-8 -*-
try:
import simplejson as json
except ImportError:
import json
import logging
import werkzeug
from openerp import http
from openerp.http import request
_logger = logging.getLogger(__name__)
class SipsController(http.Controller):
_notify_url = '/payment/sips/ipn/'
_return_url... | solintegra/addons | payment_sips/controllers/main.py | Python | agpl-3.0 | 1,864 |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
parse_duration,
int_or_none,
)
class AnySexIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?anysex\.com/(?P<id>\d+)'
_TEST = {
'url': 'http://anysex.com/156592/',
'md5': '023... | apllicationCOM/youtube-dl-api-server | youtube_dl_server/youtube_dl/extractor/anysex.py | Python | unlicense | 2,085 |
__version__ = '0.4'
__author__ = 'Martin Natano <natano@natano.net>'
_repository = None
_branch = 'git-orm'
_remote = 'origin'
class GitError(Exception): pass
def set_repository(value):
from pygit2 import discover_repository, Repository
global _repository
if value is None:
_repository = None
... | natano/python-git-orm | git_orm/__init__.py | Python | isc | 758 |
"""
mod_customized Controllers
===================
In this module, users can test their fork branch with customized set of regression tests
"""
from flask import Blueprint, g, request, redirect, url_for, flash
from github import GitHub, ApiError
from datetime import datetime, timedelta
from decorators import template_... | satyammittal/sample-platform | mod_customized/controllers.py | Python | isc | 5,822 |
"""Identity related views."""
from reversion import revisions as reversion
from django.contrib.auth import mixins as auth_mixins
from django.contrib.auth.decorators import (
login_required, permission_required, user_passes_test
)
from django.shortcuts import render
from django.template.loader import render_to_str... | modoboa/modoboa | modoboa/admin/views/identity.py | Python | isc | 8,529 |
#!/usr/bin/env python
from gi.repository import GObject, Gtk, Gedit, PeasGtk
import ConfigParser
UI_XML = '''<ui>
<menubar name="MenuBar">
<menu name="ToolsMenu" action="Tools">
<placeholder name="ToolsOps_2">
<menuitem name="Change Indent" action="ChangeIndentPlugin"/>
</placeholder>
</me... | jongha/gedit-indent | src/gedit/plugins/indent.py | Python | mit | 4,209 |
# Copyright (c) 2012-2015 Netforce Co. Ltd.
#
# 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, publ... | anastue/netforce | netforce_ecom/netforce_ecom/controllers/ecom_products.py | Python | mit | 11,270 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bidders', '0002_bidder_photo'),
]
operations = [
migrations.AddField(
model_name='bidder',
name='add... | kecheon/yablist | bidders/migrations/0003_bidder_address.py | Python | mit | 407 |
import os
import signal
import subprocess
class Camera(object):
# In order to run mjpg-streamer through Python, make sure
# mjpg-streamer-experimental is installed so the .so objects
# and mjpg-streamer are all on defualt PATH so we don't have
# to specify path (was getting a lot of errors resulting ... | purduerov/X9-Core | rov/camera/camera.py | Python | mit | 2,803 |
import _plotly_utils.basevalidators
class VisibleValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(self, plotly_name="visible", parent_name="heatmapgl", **kwargs):
super(VisibleValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... | plotly/python-api | packages/python/plotly/plotly/validators/heatmapgl/_visible.py | Python | mit | 517 |
from .user import User
from .phone_certificate import PhoneCertificate
| yevgnenll/but | but/users/models/__init__.py | Python | mit | 71 |
import logging
def initLogger():
# create logger
logger = logging.getLogger('cam')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
file_handler = logging.FileHandler('cam.log')
file_handler.setLevel(logging.DEBUG)
# create console handler with a higher log level
console... | jucoba/IpCamMonitorSystem | src/utils/loggerConfig.py | Python | mit | 772 |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 2 10:56:34 2016
@author: jmjj (Jari Juopperi, jmjj@juopperi.org)
"""
from .main import *
| jmjj/messages2json | messages2json/__init__.py | Python | mit | 140 |
from util import app
import hashlib
import os
phase2_url = '/phase2-%s/' % os.environ.get('PHASE2_TOKEN')
admin_password = u'adminpass'
admin_hash = hashlib.sha1(admin_password.encode('utf-8')).hexdigest()
session_key = 'sessionkey'
admin_session_key = 'adminsessionkey'
def init_data(redis):
redis.set('user:test... | nickfrostatx/polyrents-challenge | tests/test_phase2.py | Python | mit | 4,200 |
import click
from do_cli.contexts import CTX
from do_cli.commands.common import host_commands
@click.command('list')
@click.option('-f', '--force-refresh', is_flag=True, help='Pull data from the API')
@click.option('-h', '--host-names', help='Comma separated list of host names')
@CTX
def cli(ctx, force_refresh, host_... | meganlkm/do-cli | do_cli/commands/cmd_list.py | Python | mit | 689 |
class Request(object):
def __init__(self, value):
self.__value = value
def get_value(self):
return self.__value
| danieldeveloper001/Learning | Python/02_DesignPatterns/Behavioral/Command/Request.py | Python | mit | 137 |
# -*- uft-8 -*-
import matplotlib
class SinglePeak():
"""Creat a class as a Peak Container"""
def __init__(self,StandardPeak):
self.StandardPeak=StandardPeak
self.Indicator=False
self.RecordIntegrationTime=0
self.MaxCounts=0
self.PeakPixel=0
self.pixel=[]
self.CountsRange=[20000,50000]
def GetPixel(se... | baojiwei/WavelengthCalibration | SinglePeak.py | Python | mit | 1,344 |
from matplotlib import pylab as plt
(x,y,yEA) = in_object
print(in_object)
plt.plot(x,y/y.max(),label="Fully coherent")
plt.plot(x,yEA/yEA.max(),label="Partial coherent")
plt.xlabel("Z [um]")
plt.ylabel("Intensity [Arbitrary Units]")
plt.legend()
plt.show() | srio/ShadowOui-Tutorial | SCRIPTS/script26_plot.py | Python | mit | 260 |
#!/usr/bin/env python
# -*- coding: utf-8 -8-
"""
By starting at the top of the triangle below and moving to adjacent numbers
on the row below, the maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom of the triangle below:
"""
tri... | goldsborough/euler | 18.py | Python | mit | 1,380 |
# -*- coding: utf-8 -*-
"""
Copyright (c) 2014 l8orre
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, pub... | l8orre/nxtBridge | nxtPwt/nxtBridgeCtrl.py | Python | mit | 2,586 |
"""
Utility functions for atmospheric data wrangling / preparation.
- ndarrays
- netCDF files
- Lat-lon geophysical data
- Pressure level data and topography
"""
from __future__ import division
import numpy as np
import pandas as pd
import collections
import scipy.interpolate as interp
from mpl_toolkits import basema... | jenfly/atmos-tools | atmos/data.py | Python | mit | 62,848 |
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import logging
from pymatgen.core import Molecule
from pymatgen.io.qchem_io.inputs import QCInput
from pymatgen.io.qchem_io.utils import lower_and_check_unique
# Classes for reading/manipulating/writing QChem ... | nisse3000/pymatgen | pymatgen/io/qchem_io/sets.py | Python | mit | 7,003 |
from typing import Any
import pytest
from run_test_service_helper import start_service
def test_invalid_filename(monkeypatch: Any, capsys: Any, loop: Any) -> None:
with pytest.raises(SystemExit):
services, future = start_service("tests/services/no_service_existing.py", monkeypatch)
out, err = capsy... | kalaspuff/tomodachi | tests/test_invalid_services.py | Python | mit | 1,285 |
"""Test that arguments passed to a script Menu.main(loop=True) execute
properly."""
##==============================================================#
## SECTION: Imports #
##==============================================================#
from testlib import *
##===========... | jeffrimko/Qprompt | tests/script_test_1.py | Python | mit | 3,045 |
from app import db
from sqlalchemy import Column, String, Integer, ForeignKey
class VotingVariant(db.Model):
__tablename__ = 'voting_variants'
id = Column(Integer, primary_key=True)
voting_id = Column(Integer, ForeignKey('votings.id'))
title = Column(String(255))
description = Column(String(1000)... | sokil/VotingEngine | models/voting_variant.py | Python | mit | 361 |
# Copyright (c) 2020, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/spherical_functions/blob/master/LICENSE>
### NOTE: The functions in this file are intended purely for inclusion in the Grid class. In
### particular, they assume that the first argument, `self` is an instance of Grid. They ... | moble/spherical_functions | spherical_functions/SWSH_grids/utilities.py | Python | mit | 2,746 |
#!/usr/bin/env python
import os
import sys
sys.path.insert(0, os.pardir)
from testing_harness import TestHarness, PyAPITestHarness
import openmc
from openmc.stats import Box
from openmc.source import Source
class MultipoleTestHarness(PyAPITestHarness):
def _build_inputs(self):
####################
... | bhermanmit/openmc | tests/test_multipole/test_multipole.py | Python | mit | 3,870 |
"""
Serialize data to/from JSON
"""
# Avoid shadowing the standard library json module
from __future__ import absolute_import, unicode_literals
import datetime
import decimal
import json
import sys
import uuid
from io import BytesIO
from django.core.serializers.base import DeserializationError
from django.core.seria... | superisaac/django-mljson-serializer | django_mljson/serializer.py | Python | mit | 2,206 |
#Caleb
#normalizes shapes in size and sets the lower left corner to 0
import math
def calc_dist(a,b):
ax=a[0]
ay=a[1]
bx=b[0]
by=b[1]
return math.sqrt((ax-bx)**2+(ay-by)**2)
def normalize(shapes):
"""Normalize shapes
>>> normalize([[(0,2.5),(2.5,2.5),(0,0),(2.5,0)],[(0,1),(1,1),(0,0),(1,0)],[(0,1),(1,1),... | ctada/napCAD | revisions/basic_cube/normalizer.py | Python | mit | 1,763 |
# Copyright (c) 2013-2016 Christian Geier et al.
#
# 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, ... | dzoep/khal | khal/ui/widgets.py | Python | mit | 14,425 |
class RCInput():
CHANNEL_COUNT = 14
channels = []
def __init__(self):
for i in range(0, self.CHANNEL_COUNT):
try:
f = open("/sys/kernel/rcio/rcin/ch%d" % i, "r")
self.channels.append(f)
except:
print ("Can't open file /sys/kern... | adrienemery/auv-control-pi | navio/rcinput.py | Python | mit | 484 |
from channels.routing import route
from .consumer import party_connected, party_disconnected, party_message
karaoke_routing = [
route("websocket.connect", party_connected, path=r"^/party/(?P<party_id>[a-zA-Z0-9_-]+)"),
route("websocket.receive", party_message),
route("websocket.disconnect", party_disconne... | Katharine/ponytone | karaoke/routing.py | Python | mit | 328 |
# Copyright (C) 2014-2016 Cuckoo Foundation.
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
# Originally contributed by Check Point Software Technologies, Ltd.
import ConfigParser
class Config:
def __init__(self, cfg):
"""@param c... | cuckoobox/cuckoo | cuckoo/data/analyzer/android/lib/core/config.py | Python | mit | 881 |
# Generated by Django 3.0.5 on 2020-04-17 14:12
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import easy_thumbnails.fields
import userena.models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_... | ngageoint/geoq | geoq/accounts/migrations/0001_initial.py | Python | mit | 3,881 |
from distutils.core import setup
setup(
name = 'moretext',
packages = ['moretext'],
version = '0.1',
description = 'Get dummy Chinese text (lorem ipsum) with Handlino serivce.',
author = 'Pomin Wu',
author_email = 'pomin5@gmail.com',
url = 'https://github.com/pm5/python-moretext',
downlo... | pm5/python-moretext | setup.py | Python | mit | 466 |
# 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 ... | fhoring/autorest | src/generator/AutoRest.Python.Tests/Expected/AcceptanceTests/BodyDictionary/autorestswaggerbatdictionaryservice/operations/dictionary_operations.py | Python | mit | 110,391 |
from django.contrib import admin
# Register your models here.
from Aplicacio.models import Movie, Character, Location, Team, Power
admin.site.register(Movie)
admin.site.register(Character)
admin.site.register(Location)
admin.site.register(Team)
admin.site.register(Power)
| danic96/Practica1 | Practica1/Aplicacio/admin.py | Python | mit | 274 |
from decorator import decorator
from inspect import getargspec
# ------------------------------------------------------------------------
# decorators
# ------------------------------------------------------------------------
def lazy_property(func):
"""Decorator that makes a property lazy-evaluated.
"""
... | Quantipy/quantipy | quantipy/core/tools/qp_decorators.py | Python | mit | 6,656 |
# naive is a datetime with no timezone.
# Create a new timezone for US/Pacific, which is 8 hours behind UTC (UTC-08:00).
# Then make a new variable named hill_valley that is naive with its tzinfo attribute replaced with the US/Pacific timezone you made.
import datetime
naive = datetime.datetime(2015, 10, 21, 4,... | CaseyNord/Treehouse | Dates and Times in Python/aware.py | Python | mit | 862 |
#! /usr/bin/env python3
import math, sys
import shtns
import numpy as np
class shtnsfiledata:
#
# Adopted from https://bitbucket.org/nschaeff/shtns/src/master/examples/shallow_water.py
#
def __init__(
self,
rsphere = 1.0
):
self.rsphere = rsphere
def setup(sel... | schreiberx/sweet | mule_local/python/mule_local/postprocessing/shtnsfiledata.py | Python | mit | 3,227 |
# -*- encoding:utf8 -*-
"""
使用mongodb作为缓存器
测试本地缓存
"""
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import json
from pymongo import MongoClient
from datetime import datetime, timedelta
from bson.binary import Binary
import zlib
import time
class MongoCache:
def __init__(self, client=None, expires=timedelt... | basicworld/pycrawler | mongo_cache.py | Python | mit | 1,791 |
#!../../../../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/pipeline/run_pipeline_on_spectrum_library.py | Python | mit | 7,282 |
from api import Api
def full_url(resource):
return Api.url_base.format(resource=resource)
| uhavin/pubbd | tests/api/__init__.py | Python | mit | 96 |
#!/usr/bin/python
###
### in poiFlagEmail() below, write code that returns a boolean
### indicating if a given emails is from a POI
###
import sys
import reader
import poi_emails
def getToFromStrings(f):
f.seek(0)
to_string, from_string, cc_string = reader.getAddresses(f)
to_emails = reader.parseAdd... | napjon/moocs_solution | ml-udacity/feature_selection/poi_flag_email.py | Python | mit | 1,941 |
from __future__ import print_function
from django.core.management.base import BaseCommand, CommandError
from alapage.models import Page
class Command(BaseCommand):
help = 'Creates a page'
def add_arguments(self, parser):
parser.add_argument('name', nargs='+', type=str)
parser.add_argument('url... | synw/django-alapage | alapage/management/commands/create_page.py | Python | mit | 718 |
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone
from .models import UrlShrinked
from .forms import UrlShrinkedForm
from django.shortcuts import render, get_object_or_404,redirect
from django.contrib.sites.shortcuts import get_current_site
from django.http import JsonResponse,HttpR... | Remeic/Squozy | redirector/views.py | Python | mit | 2,951 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Ref: http://doc.qt.io/qt-5/modelview.html#2-1-a-read-only-table
import sys
from PyQt5.QtCore import Qt, QAbstractTableModel, QVariant
from PyQt5.QtWidgets import QApplication, QTableView
class MyData:
def __init__(self):
self._num_rows = 3
self._nu... | jeremiedecock/snippets | python/pyqt/pyqt5/widget_QTableView_edit_print_signal_when_data_changed.py | Python | mit | 2,784 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='WebsiteContact',
fields=[
('id', models.AutoFie... | omerturner/manakinproducts | contact/migrations/0001_initial.py | Python | mit | 618 |
import requests
import os
print('\n***数据与算法 GitHub自动上传脚本***\n')
username = input('输入你在GitHub上的用户名,如 Robert Ying:')
email = input('输入你注册GitHub用的Email:')
print('\n开始配置Git...')
os.system('git config --global user.name "' + username + '"')
os.system('git config --global user.email ' + email)
print('\n你输入的信息如下:')
os.syst... | ee64/data-and-algorithms | upload.py | Python | mit | 3,932 |
"""
scitran.data.meeg
=================
Data format for M/EEG data using mne-python.
"""
import logging
import tempfile
import zipfile
import warnings
import os
from os import path as op
from datetime import datetime, date
import shutil
from mne.io import read_raw_fif
from .. import data
log = logging.getLogger(_... | scitran/data | scitran/data/meeg/meeg.py | Python | mit | 6,305 |
from collections import namedtuple
from pybliometrics.scopus.superclasses import Retrieval
from pybliometrics.scopus.utils import check_parameter_value, get_link
class SerialTitle(Retrieval):
@property
def aggregation_type(self):
"""The type of the source."""
return self._entry['prism:aggrega... | jkitchin/scopus | pybliometrics/scopus/serial_title.py | Python | mit | 7,337 |
#!/usr/bin/python3 -B
exec(open("../index.py").read())
from waitress import serve
serve(application, host='0.0.0.0', port=8080, threads=1, channel_timeout=1)
| shark555/websnake_demo | scripts/serve.py | Python | mit | 161 |
import sys
import numpy as np
if __name__ == '__main__':
print 'Loading word vectors...'
wordvecs = None
wordlist = []
for i, line in enumerate(sys.stdin):
word, vec = line.strip().split(' ', 1)
vec = map(float, vec.split())
if wordvecs is None:
wordvecs = np.ones((400000, len(vec)), dtype=n... | Smerity/glove-guante | cosine_similarity.py | Python | mit | 1,457 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutTuples(Koan):
def test_creating_a_tuple(self):
count_of_three = (1, 2, 5)
self.assertEqual(5, count_of_three[2])
def test_tuples_are_immutable_so_item_assignment_is_not_possible(self):
count_of_three =... | codetestcode/pyintdemo | python2/koans/about_tuples.py | Python | mit | 2,480 |
from axiom.test.historic.stubloader import StubbedTest
from xquotient.compose import Composer, Drafts
class ComposerUpgradeTestCase(StubbedTest):
"""
Test that the Composer no longer has a 'drafts' attribute, that no Drafts
items have been created and that the other attributes have been copied.
"""
... | twisted/quotient | xquotient/test/historic/test_composer4to5.py | Python | mit | 598 |
import astra
def gpu_fp(pg, vg, v):
v_id = astra.data2d.create('-vol', vg, v)
rt_id = astra.data2d.create('-sino', pg)
fp_cfg = astra.astra_dict('FP_CUDA')
fp_cfg['VolumeDataId'] = v_id
fp_cfg['ProjectionDataId'] = rt_id
fp_id = astra.algorithm.create(fp_cfg)
astra.algorithm.run(fp_id)
out = astra.data... | buzmakov/tomography_scripts | tomo/yaivan/dispersion/alg.py | Python | mit | 1,930 |
from __future__ import absolute_import
import json
from django import forms
from django.contrib.auth.models import AnonymousUser
from django.core.exceptions import ObjectDoesNotExist
try:
from django.urls import reverse, resolve
except:
from django.core.urlresolvers import reverse, resolve
from django.core.... | PragmaticMates/django-clever-selects | clever_selects/forms.py | Python | mit | 10,535 |
# Atomic covalent radius data
# http://www.periodictable.com/Properties/A/CovalentRadius.an.html
# Updated Jun. 9th, 2016
class Covalent(object):
x = {
"H": 0.37, "He": 0.32, "Li": 1.34, "Be": 0.90, "B": 0.82, "C": 0.77,
"N": 0.75, "O": 0.73, "F": 0.71, "Ne": 0.69, "Na": 1.54, "Mg": 1.30,
"Al":... | stczhc/neupy | tests/fitting/coval.py | Python | mit | 1,681 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-06-16 22:52
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('transcripts', '0001_initial'),
]
... | harvard-lil/nuremberg | nuremberg/transcripts/migrations/0002_transcriptpage_updated_at.py | Python | mit | 619 |
"""
Load pp, plot and save
8km difference
"""
import os, sys
#%matplotlib inline
#%pylab inline
import matplotlib
matplotlib.use('Agg')
# Must be before importing matplotlib.pyplot or pylab!
from matplotlib import rc
from matplotlib.font_manager import FontProperties
from matplotlib import rcParams
from mpl_to... | peterwilletts24/Python-Scripts | plot_scripts/EMBRACE/plot_from_pp_geop_height_by_day_dkbhu.py | Python | mit | 12,998 |
from __future__ import division
from pyvx import *
from array import array
class TestDiv(object):
def test_div(self):
g = Graph()
with g:
img = Image(3, 4, DF_IMAGE_U8, array('B', range(12)))
sa1 = img / 2
sa2 = img // 2
sa1.force()
sa2.fo... | hakanardo/pyvx | old/test/test_truediv.py | Python | mit | 494 |
from bundleprocessing import interpolateMetric
import pandas as pd
import nibabel as nib
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-templateBundle', '--templateBundle', required = True)
parser.add_argument('-subjectBundle', '--subjectBundle', required = True)
parser.add_argument('-metr... | conorkcorbin/tractometry | call_interpolate.py | Python | mit | 1,231 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
import os
def path(*path_segments):
return os.path.join(os.getcwd(), *path_segments)
def open_file(*path_segments):
file_path = path(*path_segments)
open(file_path, 'w').close()
return open(file_path, 'a')
header = open(path('READM... | Josef-Friedrich/audiorename | _generate-readme.py | Python | mit | 1,114 |
# Copyright (c) 2014 Katsuya Noguchi
#
# 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, dis... | kn/ensembl | ensembl/info/analysis.py | Python | mit | 1,205 |
import sys
from pdb import Pdb
from ipdb.__main__ import update_stdout, def_colors, wrap_sys_excepthook
class Tdb(Pdb):
def __init__(self, *args, **kwargs):
Pdb.__init__(self, *args, **kwargs)
self.botframe = None
self.quitting = False
self.stopframe = None
self.codemap = {}... | dalejung/trtools | trtools/tools/trace.py | Python | mit | 2,904 |
# ----------------------------------------------------------------------
# Copyright (c) 2014 Rafael Gonzalez.
#
# 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... | astrorafael/ema | ema/notifier.py | Python | mit | 6,211 |
# -*- coding: utf-8 -*-
"""
Collection of raw lexer test cases and class constructor.
"""
from __future__ import unicode_literals
import textwrap
swapquotes = {
39: 34, 34: 39,
# note the follow are interim error messages
96: 39,
}
# The structure and some test cases are taken
# from https://bitbucket.o... | calmjs/calmjs.parse | src/calmjs/parse/tests/lexer.py | Python | mit | 21,010 |
#!/usr/bin/env python
"""Provide the standard Python string.Template engine."""
from __future__ import absolute_import
from __future__ import print_function
from string import Template
from . import Engine
class StringTemplate(Engine):
"""String.Template engine."""
handle = 'string.Template'
def __i... | blubberdiblub/eztemplate | eztemplate/engines/string_template_engine.py | Python | mit | 951 |
from django.conf.urls import include
from django.contrib import admin
from django.urls import path
app_name = "transmission"
urlpatterns = [
path("admin/", admin.site.urls),
path("torrents/", include("torrents.urls", namespace="torrents")),
path("shows/", include("shows.urls", namespace="shows")),
]
| onepesu/django_transmission | core/urls.py | Python | mit | 315 |
"""Added a table for timed commands
Revision ID: 4db5dc4bc98
Revises: 514f4b9bc74
Create Date: 2015-12-23 00:00:59.156496
"""
# revision identifiers, used by Alembic.
revision = '4db5dc4bc98'
down_revision = '514f4b9bc74'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
from sql... | gigglearrows/anniesbot | alembic/versions/4db5dc4bc98_added_a_table_for_timed_commands.py | Python | mit | 1,034 |
from colorama import Fore
from rtxlib import info, error, debug
from rtxlib.preprocessors.SparkPreProcessor import SparkPreProcessor
def init_pre_processors(wf):
""" we look into the workflows definition and run the required preprocessors """
if hasattr(wf, "pre_processors"):
pp = wf.pre_processors
... | Starofall/RTX | rtxlib/preprocessors/__init__.py | Python | mit | 779 |
import ctypes
import os
STD_INPUT_HANDLE = -10
STD_OUTPUT_HANDLE= -11
STD_ERROR_HANDLE = -12
FOREGROUND_BLACK = 0x0
FOREGROUND_BLUE = 0x01 # text color contains blue.
FOREGROUND_GREEN= 0x02 # text color contains green.
FOREGROUND_RED = 0x04 # text color contains red.
FOREGROUND_INTENSITY = 0x08 # text color ... | vicyangworld/AutoOfficer | CmdFormat.py | Python | mit | 2,619 |
"""
Handling signals of the `core` app
"""
from django.dispatch import receiver
from core import signals
from reader import actions
@receiver(signals.app_link_ready)
def app_link_ready(sender, **kwargs):
actions.create_app_link()
| signaldetect/messity | reader/receivers/core.py | Python | mit | 238 |
# This file is autogenerated. Do not edit it manually.
# If you want change the content of this file, edit
#
# spec/fixtures/responses/whois.registry.om/status_reserved
#
# and regenerate the tests with the following script
#
# $ scripts/generate_tests.py
#
from nose.tools import *
from dateutil.parser import par... | huyphan/pyyawhois | test/record/parser/test_response_whois_registry_om_status_reserved.py | Python | mit | 984 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This modle will help you put your local file to
QiNiu cloud storage, I use it to share files and
pictures in my blog.
"""
import argparse
# Compatible for Py2 and Py3
try:
import ConfigParser
except ImportError:
import configparser
import os
import qiniu.config
impo... | cheneydc/qnupload | src/qnupload/qnupload.py | Python | mit | 4,668 |
# This file is part of Indico.
# Copyright (C) 2002 - 2022 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from flask import redirect, request
from indico.modules.categories.compat import compat_category
from ind... | indico/indico | indico/modules/categories/blueprint.py | Python | mit | 8,380 |
import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-usuario',
version='0.4',
... | dyachan/django-usuario | setup.py | Python | mit | 1,204 |
#!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Helpful routines for regression testing."""
from base64 import b64encode
from binascii import hexlify,... | btcgroup2/bitcoin | test/functional/test_framework/util.py | Python | mit | 19,182 |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
def dfs(root):
if root is None:
return (True, 0)
lb, ... | jiadaizhao/LeetCode | 0101-0200/0110-Balanced Binary Tree/0110-Balanced Binary Tree.py | Python | mit | 493 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.