repo_name
stringlengths
5
104
path
stringlengths
4
248
content
stringlengths
102
99.9k
stephenhky/PyShortTextCategorization
shorttext/classifiers/embed/sumvec/SumEmbedVecClassification.py
import pickle from collections import defaultdict import numpy as np from scipy.spatial.distance import cosine from shorttext.utils.classification_exceptions import ModelNotTrainedException from shorttext.utils import shorttext_to_avgvec from shorttext.utils.compactmodel_io import CompactIOMachine class SumEmbedded...
zhangtianyi1234/sinaweibo
busdb.py
#coding:utf-8 #bus公交换乘程序 from uliweb.orm import * db= get_connection("sqlite:///beijing.db") class cnbus(Model): xid = Field(int) zhan = Field(str) kind = Field(int) class cnchange(Model): src = Field(int) dst = Field(int) class cnbusw(Model): busw = Field(str) def getcnbusw(xid): b = cnbusw.get(cnbusw.c....
tmetsch/python-dtrace
examples/ctypes/syscall_count_own_walk.py
#!/usr/bin/env python """ Use the Python DTrace consumer and run a syscall counter DTrace script with an own aggregate walk function. Created on Oct 10, 2011 @author: tmetsch """ from __future__ import print_function from ctypes import cast, c_char_p, c_int from dtrace_ctypes import consumer SCRIPT = 'syscall:::en...
adiIspas/Machine-Learning_A-Z
Machine Learning A-Z/Part 5 - Association Rule Learning/Section 28 - Apriori/apriori_me.py
# Apriori # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Data Preprocessing dataset = pd.read_csv('Market_Basket_Optimisation.csv', header = None) transactions = [] for i in range(0, 7501): transactions.append([str(dataset.values[i, j]) for j in range(0, 20)]) ...
SLAPaper/TRPG_bot
Telegram_API.py
import urllib.request, urllib.parse, ssl, mimetypes, mmap, http.client def makeOpener(proxy=None): https_handler = urllib.request.HTTPSHandler(context=ssl.create_default_context()) if proxy: opener = urllib.request.build_opener(https_handler, urllib.request.ProxyHandler(proxy)) else: opene...
Psycojoker/HamlPy
hamlpy/test/test_views.py
import unittest from hamlpy.views.generic import CreateView, DetailView, UpdateView class DummyCreateView(CreateView): template_name = 'create.html' class DummyDetailView(DetailView): template_name = 'detail.htm' class DummyUpdateView(UpdateView): template_name = 'update.xml' class DjangoViewsTest(...
theodox/spelchek
spelchek/checker.py
""" spelchek -------- A cheap-ass, pure-python spellchecker based on Peter Norvig's python bayes demo at http://norvig.com/spell-correct.html The interesting external methods are * known() filters a list of words and returns only those in the dictionary, * correct() returns the best guess for the supplied wor...
evanbiederstedt/RRBSfun
trees/chrom_scripts/cll_chr21.py
import glob import pandas as pd import numpy as np pd.set_option('display.max_columns', 50) # print all rows import os os.chdir("/gpfs/commons/home/biederstedte-934/evan_projects/correct_phylo_files") cw154 = glob.glob("binary_position_RRBS_cw154*") trito = glob.glob("binary_position_RRBS_trito_pool*") print(len(...
Loran425/MegaminerAI_2017_Stumped
games/stumped/ai.py
# This is where you build your AI for the Stumped game. from joueur.base_ai import BaseAI from .classes import * from .behavior import setup_resource # these functions are used by the ShellAI, you can remove them if you wish with the ShellAI code in runTurn() class AI(BaseAI): """ The basic AI functions that are...
feuvan/m3u8
tests/playlists.py
# coding: utf-8 # Copyright 2014 Globo.com Player authors. All rights reserved. # Use of this source code is governed by a MIT License # license that can be found in the LICENSE file. from os.path import dirname, abspath, join TEST_HOST = 'http://localhost:8112' SIMPLE_PLAYLIST = ''' #EXTM3U #EXT-X-TARGETDURATION:52...
berlotto/openjobs-scraper
vagascrawler/items.py
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy class VagaItem(scrapy.Item): link = scrapy.Field() body = scrapy.Field() datetime = scrapy.Field() path = scrapy.Field() titulo = sc...
trading-dev/trading-coin
qa/rpc-tests/maxblocksinflight.py
#!/usr/bin/env python2 # # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * import logging ...
SqueezeStudioAnimation/omtk
tests/test_libFormula.py
import mayaunittest from omtk.libs import libFormula import pymel.core as pymel class SampleTests(mayaunittest.TestCase): def _create_pymel_node(self, val_tx=1, val_ty=2, val_tz=3, val_rx=4, val_ry=5, val_rz=6, val_sx=7, val_sy=8, val_sz=9): t = pymel.createNode('transform') t.tx.set(val_tx) ...
miguelgrinberg/Flask-Migrate
tests/app_compare_type2.py
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) migrate = Migrate(app, db, compare_type=True) class User(db.Mod...
wikimedia/pywikibot-core
scripts/archive/match_images.py
#!/usr/bin/python3 """ Program to match two images based on histograms. Usage: python pwb.py match_images ImageA ImageB It is essential to provide two images to work on. Furthermore, the following command line parameters are supported: -otherfamily Mentioned family with this parameter will be preferred ...
PrefPy/opra
compsocsite/polls/tests.py
import datetime from django.utils import timezone from django.test import TestCase from django.core.urlresolvers import reverse from .models import Question # NOTE: ALL OF THIS IS OUTDATED. def create_question(question_text, days): """ Creates a question with the given `question_text` and published the ...
dirkmoors/drf-tus
rest_framework_tus/routers.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import rest_framework from rest_framework.routers import Route, DynamicListRoute, DynamicDetailRoute, SimpleRouter def get_list_route(): list_route_data = dict( url=r'^{prefix}{trailing_slash}$', mapping={ 'get': 'list', ...
pombredanne/readthedocs.org
readthedocs/rtd_tests/tests/test_celery.py
import os import json import shutil from os.path import exists from tempfile import mkdtemp from django.contrib.auth.models import User from django_dynamic_fixture import get from mock import patch, MagicMock from readthedocs.builds.constants import BUILD_STATE_INSTALLING, BUILD_STATE_FINISHED from readthedocs.builds...
mdpiper/topoflow-cmi-testing
tests/test_topoflow.py
# Nosetests for the TopoFlow SnowDegreeDay component. import os import shutil from nose.tools import assert_is_not_none, assert_equals from cmt.components import TopoFlow as Component from . import example_dir cfg_file = os.path.join(example_dir, 'June_20_67_topoflow.cfg') var_name = 'channel_water_x-section__domain...
CSGreater-Developers/HMC-Grader
app/userViews/common/accounts.py
# -*- coding: utf-8 -*- ''' This module handles login, logout, and settings for user accounts ''' #import the app and the login manager from app import app, loginManager #Import flask functions we need from flask import g, request, render_template, redirect, url_for, flash from flask import abort, send_file from fla...
egor-tensin/aesni
test/toolkit.py
# Copyright (c) 2015 Egor Tensin <Egor.Tensin@gmail.com> # This file is part of the "AES tools" project. # For details, see https://github.com/egor-tensin/aes-tools. # Distributed under the MIT License. import collections from enum import Enum import logging import os.path import subprocess class Algorithm(Enum): ...
latorrefabian/gapmaps
gapmaps/to_corpus.py
from database import session_scope import os import sections from models import Article from topics import to_corpus, to_text import argparse def main(args): path = os.path.join(args.folder, args.name) if os.path.isdir(path): print('corpus ' + path + ' already exists') return _sections = s...
mharnold/spiderosm
spiderosm/spatialref.py
''' Handle Spatial Reference System Specificatioo url - e.g. 'http://spatialreference.org/ref/epsg/nad83-utm-zone-10n/' used to specify srs in geojson output files proj4text - e.g. '+proj=utm +zone=10 +ellps=WGS84 +units=m +no_defs' Needed internally to reproject OSM data to planar coordinates. Also used when spec...
iamweilee/pylearn
time-example-3.py
''' ÔÚһЩƽ̨ÉÏ, time Ä£¿é°üº¬ÁË strptime º¯Êý, ËüµÄ×÷ÓÃÓë strftime Ïà·´. ¸ø¶¨Ò»¸ö×Ö·û´®ºÍģʽ, Ëü·µ»ØÏàÓ¦µÄʱ¼ä¶ÔÏó, Èç ÏÂÀý Ëùʾ. ''' import time # make sure we have a strptime function! # È·ÈÏÓк¯Êý strptime try: strptime = time.strptime except AttributeError: from strptime import strptime print strp...
iTech-/napnac.ga
scripts/build/build.py
import os import shutil import sys import config import pages import path if len(sys.argv) > 1: files_to_render = sys.argv[1:] else: files_to_render = path.get_all_files() print("Rendering pages...") nb_pages_rendered = 0 for file_path in files_to_render: try: template_path = path.get_template(...
patevs/python_chat_app
server.py
import socket import select def run_server(): """ Start a server to facilitate the chat between clients. The server uses a single socket to accept incoming connections which are then added to a list (socket_list) and are listened to to recieve incoming messages. Messages are then stored in a datab...
twilio/twilio-python
tests/integration/conversations/v1/service/test_role.py
# coding=utf-8 r""" This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ from tests import IntegrationTestCase from tests.holodeck import Request from twilio.base import serialize from twilio.base.exceptions import TwilioException from twilio.http.response import Response...
syscoin/syscoin2
test/functional/wallet_resendwallettransactions.py
#!/usr/bin/env python3 # Copyright (c) 2017-2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test that the wallet resends transactions periodically.""" from collections import defaultdict import t...
mpetyx/energagement
energagement/myapp/urls.py
__author__ = 'vasiliki' from django.conf.urls import patterns, url from myapp import views urlpatterns = patterns('', url(r'^home/', views.home, name='home'), url(r'^$', views.home, name='home'), url(r'^main/', views.main, name='main'), url(r'^buildings/', views.buildings, name='buildings'), url(...
imko92/vargram-bot
vargram_bot/strings.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from emoji import emojize def __(string): """Emojize a text, wrapping ``use_aliases``. Args: string (str): string to emojize. Returns: An emojized string. """ return emojize(string, use_aliases=True) START = \ """ :penguin: Ciao! Sono il bot del [Li...
oinopion/foodspot
foodspot/texts/models.py
from datetime import timedelta from django.db import models from django.db.models import permalink from django.core import signing from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from model_utils import Choices from model_utils.fields import AutoCreatedField, AutoLastModifiedFi...
jbradberry/django-postoffice
postoffice/south_migrations/0001_initial.py
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Address' db.create_table(u'postoffice_address', ( ...
msupino/alerta-contrib
plugins/syslog/alerta_logger.py
import os import sys import logging from logging.handlers import SysLogHandler from alerta.app import app from alerta.plugins import PluginBase LOG = logging.getLogger('alerta.plugins.logger') DEFAULT_SYSLOG_FORMAT = '%(name)s[%(process)d]: %(levelname)s - %(message)s' DEFAULT_SYSLOG_DATE_FORMAT = '%Y-%m-%d %H:%M:...
vprime/puuuu
env/lib/python2.7/site-packages/paramiko/ssh_exception.py
# Copyright (C) 2003-2007 Robey Pointer <robeypointer@gmail.com> # # This file is part of paramiko. # # Paramiko is free software; you can redistribute it and/or modify it under the # terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (a...
genkosta/django-editor-ymaps
djeym/templatetags/djeymtags.py
# -*- coding: utf-8 -*- from django import template from django.conf import settings from ..models import Map from ..views import vue_vendors_css_js register = template.Library() @register.inclusion_tag('djeym/includes/ymaps_front.html') def djeym_yandex_map(slug, lang='en'): """Load the map to the front page....
zarautz/pagoeta
pagoeta/apps/places/serializers.py
from geojson import Point from rest_framework import serializers from rest_framework.reverse import reverse from .models import Place from pagoeta.apps.core.functions import get_absolute_uri from pagoeta.apps.core.serializers import TranslationModelSerializer, ImageField class TypeField(serializers.RelatedField): ...
Nekroze/nekrobox
docs/conf.py
# -*- coding: utf-8 -*- # # complexity documentation build configuration file, created by # sphinx-quickstart on Tue Jul 9 22:26:36 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. # # ...
manicmaniac/vimrunner-python
vimrunner/vimrunner.py
# -*- coding: <utf-8> -*- """ Module that implements a client and server interface useful for controlling a vim server. This module could be used for unit testing or integration testing for a Vim plugin written in Python. Or you can use it to interactively control a Vim editor by Python code, for example, in an Ipytho...
yuanchima/Activation-Visualization-Histogram
input_ops.py
import numpy as np import tensorflow as tf from util import log def check_data_id(dataset, data_id): if not data_id: return wrong = [] for id in data_id: if id in dataset.data: pass else: wrong.append(id) if len(wrong) > 0: raise RuntimeError("...
VMatrixTeam/open-matrix
src/webservice/handlers/service/base/filesystem.py
#coding:utf-8 from tornado.web import RequestHandler from handlers.base import BaseController from tornado import gen from model.files import File from model.user import User import os import config class MatrixAvatarHandler(RequestHandler): avatar_file_path = os.path.join(config.get_config()["service"]["file-...
EdLeming/echidna
echidna/output/plot_root.py
from echidna.util import root_help from ROOT import TH1D, TH2D def plot_projection(spectra, dimension, graphical=True): """ Plot the spectra as projected onto the dimension. For example dimension == 0 will plot the spectra as projected onto the energy dimension. Args: spectra (:class:`echidna.c...
Mediaphormedia/gitsummary
setup.py
import os from setuptools import setup, find_packages from gitsummary import VERSION def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() requirements = read('requirements.txt').split('\n') dependency_links = read('dependency_links.txt').split('\n') setup( name = "Gitsummary"...
shosca/django-rest-witchcraft
rest_witchcraft/field_mapping.py
"""Field mapping from SQLAlchemy type's to DRF fields.""" import datetime import decimal from sqlalchemy.dialects import postgresql from sqlalchemy.sql import sqltypes from django_sorcery.db import meta from rest_framework import fields from rest_enumfield import EnumField from .fields import CharMappingField de...
lmazuel/azure-sdk-for-python
azure-mgmt-consumption/azure/mgmt/consumption/operations/__init__.py
# 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 ...
albhu/finance
order.py
class Order(dict): """ Dictionary Object storing the representation of an Order """ def __init__(self, order): """ @symbol eg, GOOGL @orderid eg, 3245 @action eg, A @exchange eg, 3 @quantity eg, 148000 @news eg, 0 @side eg, S @descr...
tgross/flask-riak-sessions
flask_riaksessions.py
# -*- coding: utf-8 -*- """ flask.ext.riaksessions ---------------------- This module provides a Riak-backed session store for Flask sessions. :copyright: (c) 2013 Tim Gross :license: MIT """ __version_info__ = ('0', '1', '0') __version__ = '.'.join(__version_info__) __author__ = 'Tim Gross' __l...
lmazuel/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2017_08_01/models/express_route_circuit_sku_py3.py
# 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 ...
lmazuel/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2016_12_01/models/network_interface_association.py
# 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 ...
shrieking-antshrikes/berrynet
tests/test_sources.py
""" Verifies that all texts in sources.json exist """ import os.path from core import train from core.settings import TEXT_DIR, BASE_DIR from core.extract import format_filename path = os.path.join(BASE_DIR, 'sources.json') trainer = train.Trainer(json_path=path, text_dir=TEXT_DIR, db_url="") def test_sources(): ...
projectjamjar/masonjar
jamjar/jamjar/videos/migrations/0019_jampick.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('videos', '0018_auto_20160508_2213'), ] operations = [ migrations.CreateModel( name='JamPick', fields...
wangyanxing/Judge-at-fgdsb
judge/python/tests/query_intervals_1.py
from common import * from solution import * import copy import sys import datetime num_test = 120 true, false = True, False in_0 = [] in_org_0 = [] in_1 = [] in_org_1 = [] out = [] def load_test(): f = open('judge/tests/query-intervals-1.txt', 'r') global in_0, in_org_0, in_1, in_org_1 in_0 = read_interv...
cginternals/glkernel
scripts/generate.py
import posixpath # instead of os.path, to always use forward slashes import os import re # TODOs: # (more TODOs in code) standardTypes = { "bool", "char", "short", "int", "long", "long long", "unsigned char", "unsigned short", "unsigned int", "unsigned long", "unsigned lon...
danielkraic/status-page
service.py
import requests import time import datetime class Service: def __init__(self, name, url): self.name = name self.url = url def get_status(self): start_time = time.time() status_code = self.get_status_code() elapsed = time.time() - start_time timestamp = datetim...
ywangd/stash
bin/git.py
# -*- coding: utf-8 -*- ''' Distributed version control system Commands: init: git init <directory> - initialize a new Git repository add: git add <file1> .. [file2] .. - stage one or more files rm: git rm <file1> .. [file2] .. - unstage one or more files commit: git commit <message> <name> <email> - ...
opencivicdata/scrapers-ca
ca_municipalities/people.py
from utils import CSVScraper, CanadianPerson as Person from pupa.scrape import Organization, Post from collections import defaultdict import re class CanadaMunicipalitiesPersonScraper(CSVScraper): csv_url = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vRrGXQy8qk16OhuTjlccoGB4jL5e8X1CEqRbg896ufLdh67DQk9nuGm-o...
MikkelSchubert/paleomix
tests/nodes/bowtie2_test.py
from paleomix.nodes.bowtie2 import Bowtie2IndexNode, Bowtie2Node ######################################################################################## # Indexing def test_index_description(): node = Bowtie2IndexNode(input_file="/path/genome.fasta") assert str(node) == "creating Bowtie2 index for /path/g...
oubiwann/ascii-mapper
asciimap/util/__init__.py
import random, signal, sys from asciimap import const def aOrAn(item): if item.desc[0] in "aeiou": return "an" else: return "a" def enumerateItems(items): if len(items) == 0: return "nothing" out = [] for item in items: if len(items) > 1 and item == items[-1]: ...
ccxt/ccxt
examples/py/async-bitstamp-create-order-cancel-order.py
# -*- coding: utf-8 -*- from asyncio import get_event_loop import ccxt.async_support as ccxt from pprint import pprint print('CCXT Version:', ccxt.__version__) async def main(): exchange = ccxt.bitstamp({ 'apiKey': 'YOUR_API_KEY', 'secret': 'YOUR_SECRET', 'uid': 'YOUR_UID', }) m...
maddyloo/miniBibServer
github_api_stuff/get_sha.py
from hammock import Hammock as Github import json import urllib import sys import base64 import filecmp from pprint import pprint github = Github('https://api.github.com') owner = 'maddyloo' repo = 'BibProject' user = 'holtzermann17' password = '' #Github token goes here resp = github.repos(owner, repo).git.refs('he...
bracket/ratchet
ratchet/generator/wave_table.py
import numpy as np from .sound_generator import SoundGenerator class WaveTable(SoundGenerator): def __init__(self, frame_rate, wave_table): super().__init__(frame_rate) self.wave_table = reshape_wave_table(wave_table) def __iter__(self): channels, frames = self.wave_table.shape ...
sdpython/pyquickhelper
src/pyquickhelper/pandashelper/readh.py
# -*- coding:utf-8 -*- """ @file @brief Various ways to import data into a dataframe """ import zipfile from io import StringIO, BytesIO from ..filehelper import read_content_ufs def read_csv(filepath_or_buffer, compression=None, fvalid=None, **params): """ Reads a file from a file, it adds the compression zi...
475Cumulus/TBone
tbone/data/fields/mongo.py
#!/usr/bin/env python # encoding: utf-8 from bson.objectid import ObjectId from bson.dbref import DBRef from tbone.data.fields import BaseField, CompositeField from tbone.db.models import MongoCollectionMixin from tbone.data import ModelMeta class ObjectIdField(BaseField): ''' A field wrapper around MongoDB ...
vdrey/Toolbox
Python/Network/randLocalIP.py
# This generates a random IP on a 192.168.0.0/24 subnet # IP address in form A.B.C.D def randLocalIP(): A = str(192) B = str(168) C = str(0) import random D = random.randint(1,256) D = str(D) Ls = [A,B,C,D] IP = '.'.join(Ls) return str(IP)
jakubtuchol/epi
test/test_primitive.py
from collections import defaultdict from src.primitive import add from src.primitive import check_rectangle_intersection from src.primitive import closest_int_same_bit_count from src.primitive import divide from src.primitive import find_parity from src.primitive import get_intersection from src.primitive import multi...
fhoring/autorest
src/generator/AutoRest.Python.Tests/Expected/AcceptanceTests/BodyString/autorestswaggerbatservice/operations/enum_operations.py
# 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 ...
michalbachowski/pychain
docs/conf.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # complexity documentation build configuration file, created by # sphinx-quickstart on Tue Jul 9 22:26:36 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 # au...
daspots/dasapp
lib/sendgrid/sendgrid.py
import os import python_http_client from .version import __version__ class SendGridAPIClient(object): """SendGrid API.""" def __init__(self, **opts): """ Construct SendGrid v3 API object. :params host: Base URL for the API call :type host: string """ self.pat...
sveetch/django-datebook
datebook/forms/month.py
# -*- coding: utf-8 -*- """ Forms for month forms """ from django.conf import settings from django import forms from django.utils.translation import ugettext as _ from crispy_forms.helper import FormHelper from datebook.models import Datebook from datebook.forms import CrispyFormMixin from datebook.utils.imports impo...
xflr6/features
tests/test_bases.py
import pickle import pytest from features.bases import FeatureSet def test_pickle_base(fs): base = pickle.loads(pickle.dumps(fs.FeatureSet.__base__)) assert base is fs.FeatureSet.__base__ def test_pickle_class(fs): cls = pickle.loads(pickle.dumps(fs.FeatureSet)) assert cls is fs.FeatureSet def t...
tuturto/pyherc
src/pyherc/data/magic/__init__.py
# -*- coding: utf-8 -*- # Copyright (c) 2010-2017 Tuukka Turto # # 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,...
josefdlange/doit
doit/storage.py
# encoding: utf-8 import json import os class DataStore(object): data = None def __init__(self): self.data_dir = os.path.join(os.path.expanduser('~'), '.doit/') self.data_path = os.path.join( self.data_dir, 'data.json' ) self._setup() def _setup(se...
leejjoon/pywcsgrid2
lib/wcs_helper.py
from __future__ import absolute_import import six import numpy as np from .kapteyn_celestial import skymatrix, longlat2xyz, dotrans, xyz2longlat from . import kapteyn_celestial from .astropy_helper import pyfits, pywcs FK4 = (kapteyn_celestial.equatorial, kapteyn_celestial.fk4) FK5 = (kapteyn_celestial.equatorial, ...
DarrenCook/h2o
code/early_stopping_example.py
import h2o h2o.init() datasets = "https://raw.githubusercontent.com/DarrenCook/h2o/bk/datasets/" data = h2o.import_file(datasets + "iris_wheader.csv") y = "class" x = data.names x.remove(y) train, valid, test = data.split_frame([0.75,0.15]) from h2o.estimators.random_forest import H2ORandomForestEstimator m = H2ORand...
arruda/fast-vagrant-django
fast_vagrant_django/models/puppets.py
# -*- coding: utf-8 -*- from __future__ import absolute_import class Manifest(object): """ A simple puppet manifest object """ template_name = "manifest.pp" output_file_name = "manifest.pp" object_name = "manifest" def __init__(self, **kwargs): super(Manifest, self...
leylabmpi/leylab_pipelines
leylab_pipelines/Leylab_pipelines.py
# -*- coding: utf-8 -*- # import ## batteries from __future__ import print_function import os import sys import argparse ## package ### TECAN from leylab_pipelines.TECAN import Map2Robot from leylab_pipelines.TECAN import Dilute from leylab_pipelines.TECAN import QPCR ### LLP-DB from leylab_pipelines.DB import Convert ...
carterandrew/passphrase-gen
passphrase.py
#!/usr/bin/python ''' Generates a string of random words based on several parameters. Note that words with apostrophes in them are removed from the list. Copyright 2014 Andrew C. Carter Released under the terms of the MIT license. ''' import random import os import sys import argparse import re impor...
jnewland/ha-config
custom_components/alarmdotcom/cover.py
"""Alarmdotcom implementation of an HA cover (garage door).""" from __future__ import annotations import logging from typing import Any from homeassistant import core from homeassistant.components.cover import ( SUPPORT_CLOSE, SUPPORT_OPEN, CoverDeviceClass, CoverEntity, ) from homeassistant.config_en...
qrsforever/workspace
python/learn/numpy/l1/type.py
#!/usr/bin/python3 #coding:utf-8 import numpy as np a = np.array([x*2 for x in range(6)], dtype=float) print(a) b = np.array([y*3 for y in range(6)], dtype=np.float64) print(b) print([key for key, value in np.typeDict.items() if value is np.float64]) print(set(np.typeDict.values())) c = a.astype(np.int32) print(c)...
lgerardSRI/pydot
pydot/__init__.py
# -*- coding: Latin-1 -*- """Graphviz's dot language Python interface. This module provides with a full interface to create handle modify and process graphs in Graphviz's dot language. References: pydot Homepage: http://code.google.com/p/pydot/ Graphviz: http://www.graphviz.org/ DOT Language: http://www.grap...
Frozenball/flask-color
flaskext/color.py
# -*- coding: utf-8 -*- """ flaskext.color ~~~~~~~~~~~~~~ Colors the requests in debugging mode :copyright: (c) 2014 by Frozenball. :license: MIT, see LICENSE for more details. """ import time import re class TerminalColors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m'...
lazka/quodlibet-continuous
web/__init__.py
import os import sys import subprocess from flask import Flask, render_template from flask import redirect, send_from_directory, request, Response app = Flask(__name__) @app.route('/') def index(): base_url = request.url_root.rstrip("/") return render_template('index.html', base=base_url) def irc_logs(i...
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_10_01/aio/operations/_network_management_client_operations.py
# 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 may ...
Azure/azure-sdk-for-python
sdk/appconfiguration/azure-mgmt-appconfiguration/azure/mgmt/appconfiguration/operations/_operations.py
# 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 may ...
relic7/prodimages
python/drafts/gcal_scrap/gcalEventMake.py
def sqlQueryEventsUpcoming(): import sqlalchemy orcl_engine = sqlalchemy.create_engine('oracle+cx_oracle://jbragato:Blu3f!y@192.168.30.66:1531/dssprd1') connection = orcl_engine.connect() querymake_eventscal = 'select distinct atg_snp.event.id as "event_id", atg_snp.event.start_date as "ev_start", atg_s...
paypal/baler
setup.py
#!/usr/bin/env python import os from setuptools import setup, find_packages long_description = 'Baler is a tool that makes it easy to bundle and use resources (images, strings files, etc.) in a compiled static library.' if os.path.exists('README.rst'): long_description = open('README.rst').read() if os.path.exi...
dhrproject/mydatasource
DataSource/app/views/service.py
from flask_restful import Resource from app import api from app.config import SERVICE_ID,APP_NAME, CONFIG_URI, CONFIG_USERNAME, CONFIG_PASSWORD from app.handler.error_handler import NotAllowed __author__ = 'Xiaoxiao.Xiong' class ServiceAPI(Resource): """ show service's status """ def __init__(self):...
Brunux/shityjobs
shityjobs/settings.py
""" Django settings for shityjobs project. 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/ """ import os from configurations import Configuration, values class Commo...
tim-sueberkrueb/grout
baka/core/job.py
# -*- coding: utf-8 -*- import os from typing import List, Dict from baka.core.scripting import Scriptable from .container import Container class Job(Scriptable): home_path = '/home/baka' def __init__(self, name: str, source: str, scripts: Dict[str, str]=None, envvars: Dict[str, str]=None, ...
abingham/pyloc
src/pyloc/pie_chart.py
import urllib def by_language(rslt, cat, title): '''create google-chart URL for a particular category over all filetypes ''' types = rslt.types() counts = [] for t in types: try: counts.append(rslt.counts_by_type(t)[cat]) except KeyError: counts.append(0)...
EmadMokhtar/tafseer_api
quran_tafseer/migrations/0002_auto_20180203_1313.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2018-02-03 13:13 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('quran_tafseer', '0001_initial'), ] operations = [ migrations.AddField( ...
pyannote/pyannote-metrics
docs/source/pyplots/tutorial.py
notebook.width = 10 plt.rcParams['figure.figsize'] = (notebook.width, 3) # only display [0, 20] timerange notebook.crop = Segment(0, 40) # plot reference plt.subplot(211) reference = Annotation() reference[Segment(0, 10)] = 'A' reference[Segment(12, 20)] = 'B' reference[Segment(24, 27)] = 'A' reference[Segment(30, 4...
sirrice/scorpionsql
setup.py
#!/usr/bin/env python try: from setuptools import setup, find_packages except ImportError: import ez_setup ez_setup.use_setuptools() from setuptools import setup, find_packages import scorpionsql setup(name="scorpionsql", version=scorpionsql.__version__, description="SQL-related and other shared pa...
erdavila/gitviewfs
tests/utils.py
import os import shutil import subprocess import tempfile import unittest from gitviewfs_objects import Directory class BaseTest(unittest.TestCase): def assertIsDirectoryWithProvider(self, obj, ProviderClass): self.assertIsInstance(obj, Directory) self.assertTrue(any(isinstance(target_item, ProviderClass) for ...
alejo8591/maker
sales/api/urls.py
# encoding: utf-8 # Copyright 2013 maker # License #-*- coding: utf-8 -*- import handlers from django.conf.urls.defaults import * from maker.core.api.auth import auth_engine from maker.core.api.doc import documentation_view from maker.core.api.resource import CsrfExemptResource ad = { 'authentication': auth_engine }...
cwaffles/CMPT225Labs
0/test.py
#!/usr/bin/env python import subprocess import sys,os passed = 0 # Unbuffered stdout. sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) # Yes, these should be in a for loop. # Run test 1 sys.stdout.write("Running test 1... "); subprocess.call("./hello_world < 1.in > 1.out",shell=True) rt = subprocess.call("diff -...
unixxxx/simplecms
models/cmsmodels.py
__author__ = 'ShJashiashvili' import mongoengine as mongo class Users(mongo.Document): username = mongo.fields.StringField(max_length=10, required=True) password = mongo.fields.BaseField(required=True) class Email(mongo.Document): email = mongo.fields.EmailField() class Posts(mongo.Document): titl...
epage/nixnet-python
nixnet/system/databases.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import typing # NOQA: F401 import six from nixnet import _funcs class Databases(collections.Mapping): """Database aliases.""" def __init__(self, handle): self._handle =...
jorik041/clusterd
src/platform/jboss/deployers/http_management.py
from src.platform.jboss.interfaces import JINTERFACES from src.platform.jboss.authenticate import checkAuth from src.module.deploy_utils import parse_war_path from os.path import abspath from log import LOG import utility versions = ["7.0", "7.1"] title = JINTERFACES.MM def deploy(fingerengine, fingerprint): """ D...
pombredanne/geopy
geopy/geocoders/geonames.py
import logging from urllib import urlencode from urllib2 import urlopen import simplejson import xml from geopy.geocoders.base import Geocoder from geopy import Point, Location, util class GeoNames(Geocoder): def __init__(self, format_string='%s', output_format='xml'): self.format_string = format_string...
ntuaha/NewsInsight
src/lab2/rawdata/PTT_LOAN.py
# -*- coding: utf-8 -*- import re import sys import os import datetime import json #處理掉unicode 和 str 在ascii上的問題 reload(sys) sys.setdefaultencoding('utf8') #aha's library from PTT import PTT_DB,PTT if __name__ =="__main__": ptt = PTT('https://www.ptt.cc/bbs/Loan/index.html') db = PTT_DB(os.path.dirname(__file__...