src stringlengths 721 1.04M |
|---|
"""
[2014-11-26] Challenge #190 [Intermediate] Words inside of words
https://www.reddit.com/r/dailyprogrammer/comments/2nihz6/20141126_challenge_190_intermediate_words_inside/
#Description
This weeks challenge is a short yet interesting one that should hopefully help you exercise elegant solutions to a
problem rather... |
import ConfigParser
import os
import sys
# Dealing with registering match and target modules
match_modules_registered = {}
target_modules_registered = {}
def register_target_module(name, func):
target_modules_registered[name.lower()] = func
def get_target_module_func(name):
if name.lower() in target_modules_regi... |
#!/usr/bin/env python
'''
Created on Mars 20 2016
@author: popotvin
'''
import mqtt_zway_test
import mqtt_zway
import paho.mqtt.client as mqtt
import time
import traceback
date_time = mqtt_zway_test.date_time
# Main variables
mqtt_old_payload = []
mqtt_new_payload = []
payload = {}
publish_string = ""
# MQTT confi... |
from __future__ import division
from itertools import product
from nltk.tokenize import RegexpTokenizer
from nltk.translate.bleu_score import sentence_bleu
from nltk.util import skipgrams
from nltk.corpus import wordnet
from treetagger import TreeTagger
import numpy as np
import text2int as t2i
import copy
import sys
i... |
#!/usr/bin/env python2
import re
import os
import sys
import time
import json
import zlib
import argparse
import requests
from dateutil.parser import parse
# Regular expression patterns
re_commit_author = re.compile(
r'^author (?P<name>.+) <(?P<email>.+)> (?P<time>\d+) (?P<tz>[+-]\d+)$',
re.MULTILINE
)
# ... |
from mpl_toolkits.mplot3d import axes3d
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from socket import *
import time
# Объявляем все глобальные переменные
HOST = '192.168.0.76'
PORT = 21566
BUFSIZ = 512
ADDR = (HOST, PORT)
bad_packet = 0
good_packet = 0
# fig, ax... |
import asyncio
import fcntl
import logging
import os
import sys
import threading
import time
import uvloop
import unittest
import weakref
from unittest import mock
from uvloop._testbase import UVTestCase, AIOTestCase
class _TestBase:
def test_close(self):
self.assertFalse(self.loop._closed)
self... |
"""
Stochastic Gradient Descent.
TODO: write more documentation
"""
__docformat__ = 'restructedtext en'
__authors__ = ("Razvan Pascanu "
"KyungHyun Cho "
"Caglar Gulcehre ")
__contact__ = "Razvan Pascanu <r.pascanu@gmail>"
import numpy
import time
import logging
import theano
import th... |
#!/usr/bin/python2.4 -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
# Additional basic string exercises
# D. verbing
# Given a string, if its length is a... |
import logging
from pele.potentials import LJ
from nestedbasinsampling import (
NoGUTSSampler, NestedOptimizerKalman, HardShellConstraint, random_structure,
RecordMinimization, CompareStructures, LOG_CONFIG, Database)
logger = logging.getLogger("LJ31.system")
logger = logging.getLogger("NBS.LJ_syste... |
"""Docblock manipulation utilities."""
from pprint import pformat
def append_to_docs(fn, text):
"""Append text to a functions existing docblock."""
if not text:
return
if fn.__doc__:
min_indent = _getindent(fn.__doc__)
fn.__doc__ = '%s\n\n%s' % (fn.__doc__, _indent(text, min_inden... |
import os
import re
import luigi
import luigi.hadoop
import luigi.hdfs
class InputText(luigi.ExternalTask):
path = luigi.Parameter()
def output(self):
return luigi.hdfs.HdfsTarget(self.path)
class Ngrams(luigi.hadoop.JobTask):
source = luigi.Parameter()
destination = luigi.Parameter()
... |
from __future__ import unicode_literals
from frappe import _
def get_data():
return [
{
"label": _("Form Customization"),
"icon": "fa fa-glass",
"items": [
{
"type": "doctype",
"name": "Customize Form",
"description": _("Change field properties (hide, readonly, permission etc.)")
},
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
0 paikannimi
1 nimen kielikoodi
2 kielen nimi
3 paikkatyypin koodi
4 paikkatyypin selite
5 kkj/pkj pohjoinen
6 kkj/pkj itä
7 kkj/ykj pohjoinen
8 kkj/ykj itä
9 etrs/tm35fin pohjoinen
10 etrs/tm35fin itä
11 kuntakoodi
12 ku... |
# -*- coding: utf-8 -*-
#
# The MIT License (MIT)
#
# Copyright (c) 2014 Edward Mountjoy
#
# 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 th... |
# Copyright 2020 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
"""
SALTS XBMC Addon
Copyright (C) 2015 tknorris
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 3 of the License, or
(at your option) any later version.
T... |
import os
os.environ['CUDA_LAUNCH_BLOCKING'] = '1'
import pandas as pd
import matplotlib
import numpy as np
import math
import matplotlib.pyplot as plt
from sklearn.preprocessing import Imputer
from sklearn.cross_validation import train_test_split
from sklearn import preprocessing
import plotly.tools as tls
import pand... |
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
from dnsimple_zoneimport import meta
f = open('requirements.txt', 'r')
lines = f.readlines()
requirements = [l.strip().strip('\n') for l in lines if l.strip() and not l.strip().startswith('#')]
readme = open('README.rst').read()
setup(name='dnsimple... |
# -*- coding: utf-8 -*-
# Copyright (C) 2012 Yahoo! Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2... |
#!/usr/bin/env python
"""Encoding and decoding of a question once for each codec.
Example execution:
$ ./question.py
ASN.1 specification:
-- A simple protocol taken from Wikipedia.
Foo DEFINITIONS ::= BEGIN
Question ::= SEQUENCE {
id INTEGER,
question IA5String
}
Answer ::= SE... |
# -*- coding: utf-8 -*-
# Copyright (C) 2014 Johannes Baiter <johannes.baiter@gmail.com>
#
# 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, either version 3 of the
# License, or (at your ... |
from cumulusci.core.exceptions import TaskOptionsError
from cumulusci.tasks.metadata_etl import MetadataSingleEntityTransformTask
from cumulusci.utils.xml.metadata_tree import MetadataElement
class AddValueSetEntries(MetadataSingleEntityTransformTask):
entity = "StandardValueSet"
task_options = {
**Me... |
#*************************************************************************************
# Copyright 2018 OSIsoft, LLC
#
# 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... |
# coding: utf-8
#
# Copyright 2014 The Oppia 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 requi... |
"""
orthopoly.py - A suite of functions for generating orthogonal polynomials
and quadrature rules.
Copyright (c) 2014 Greg von Winckel
All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
... |
#coding=UTF-8
'''
Created on 2012-9-29
@author: s00228753
'''
import xml.etree.ElementTree as ET
from com.hws.s3.models.bucket import Bucket
from com.hws.s3.models.owner import Owner
from com.hws.s3.utils.utils import Utils
#罗列存储空间方法返回对象,可解析返回的XML为S3存储空间
class ListBucketsResponse(object):
def __init__(sel... |
from unittest import TestCase
from test.helpers import flatten
from test.fixtures import TreeNode, tree_data
from unimodel.model import Unimodel, Field
from unimodel.types import *
import json
from unimodel.model import ModelRegistry
from unimodel.backends.json.serializer import JSONSerializer, JSONValidationException
... |
import sys
import json
import pylab as pl
import numpy as np
from data import load_responses
songs, responses = load_responses()
# group responses on genre
fo = open('data/mix.genres.json', 'r')
genres = json.loads(fo.read())
cmap = {'pop': 0, 'rock': 1, 'reggae': 2, 'jazz': 3, 'classical': 4}
genre_responses = dict(... |
#!/usr/bin/env python
import sys
import rospy
from moveit_commander import RobotCommander, MoveGroupCommander
from moveit_commander import PlanningSceneInterface, roscpp_initialize, roscpp_shutdown
from geometry_msgs.msg import PoseStamped
from moveit_msgs.msg import Grasp, GripperTranslation, PlaceLocation
from traj... |
## @package TriggerObjectBlock_cfi
# Configuration file that defines the producer of ROOT-tuple for trigger objects.
#
# \author Subir Sarkar
# \author Rosamaria Venditti (INFN Bari, Bari University)
# \author Konstantin Androsov (University of Siena, INFN Pisa)
# \author Maria Teresa Grippo (University of Siena, ... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2004-2010 Edgewall Software
# Copyright (C) 2004 Daniel Lundin <daniel@edgewall.com>
# Copyright (C) 2005-2006 Christopher Lenz <cmlenz@gmx.de>
# Copyright (C) 2006-2007 Christian Boos <cboos@edgewall.org>
# All rights reserved.
#
# This software is licensed as described in the... |
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
... |
class Experience:
def __init__(self, title, description, author_id,
author_username=None, id=None, picture=None, is_mine=False, is_saved=False):
self._id = id
self._title = title
self._description = description
self._picture = picture
self._author_id = autho... |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
from django.test.client import RequestFactory
from social_django.models import UserSocialAuth
from testfixtures import LogCapture
from waffle.testutils import override_switch
from ecommerce.core.constants import ALLOW_MISSING_LMS_USER_ID
from ecommerce.core.exceptions import MissingLmsUserIdException
from ecommerce.... |
error = {
'not_implemented': {
'err_code': 'not_implemented',
'err_description': 'Method is not implemented',
'err_resolution': 'Check your request.'
},
'not_json': {
'err_code': 'not_json',
'err_description': 'Request contains data in other than JSON format.',
... |
from .continued_fractions import convergents_sqrt
from typing import Generator, Tuple
def solve_pells_equation(n: int) -> Generator[Tuple[int, int], None, None]:
convergents = convergents_sqrt(n)
for convergent in convergents:
h = convergent.numerator
k = convergent.denominator
if h... |
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
try:
from inspect import getfullargspec as getargspec # PY3
except ImportError:
from inspect import getargspec # PY2
from copy import deepcopy
from fontTools.misc.py23 import unichr
from fontTools impor... |
# -*- coding: utf-8 -*-
'''
Create ssh executor system
'''
from __future__ import absolute_import
# Import python libs
import os
import tarfile
import tempfile
import json
import shutil
from contextlib import closing
# Import salt libs
import salt.client.ssh.shell
import salt.client.ssh
import salt.utils
import salt.u... |
from typing import Tuple
from .buffer import Buffer
__all__ = ['TextureArray']
class TextureArray:
'''
An Array Texture is a Texture where each mipmap level contains an array of
images of the same size. Array textures may have Mipmaps, but each mipmap
in the texture has the same number o... |
import os
from PyQt5.QtCore import pyqtSignal, pyqtProperty, qDebug, pyqtSlot
from dice.dice_extras.core_app import CoreApp
from dice.dice_extras.tools.json_sync import JsonList
class Home(CoreApp):
def __init__(self, parent=None):
super(Home, self).__init__(parent)
settings_folder = os.path.joi... |
#!/usr/bin/env python
"""A Python version of grep utility.
Search one or more named input files against one ore more given patterns.
Print the line containing the match, if there are any.
"""
from optparse import OptionParser;
import re;
import fileinput;
import os.path;
FILENAME = '\033[92m';
LINENO = '\033... |
"""GGplot like interface"""
import uuid
import matplotlib as mpl
import matplotlib.cm as cm
import numpy as np
from IPython.display import Image, display
from .utils import get_atom_color
from .widget import RepresentationViewer, TrajectoryControls
class AttrDict(dict):
def __init__(self, *args, **kwargs):
... |
# -*- coding: utf-8 -*-
from openerp import models, fields, api, _
from openerp.exceptions import except_orm
from fabric.api import cd, sudo, settings
from fabric.contrib.files import exists
import os
class server_repository(models.Model):
""""""
_name = 'it_infrastructure.server_repository'
_descriptio... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
FieldsMappingWidget.py
---------------------
Date : October 2014
Copyright : (C) 2014 by Arnaud Morvan
Email : arnaud dot morvan at camptocamp dot com
**... |
#!/usr/bin/env python3
# Copyright (c) 2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Class for dashd node under test"""
import decimal
import errno
import http.client
import json
import loggin... |
from conectsim.optics.basenodes import Node, Source
from conectsim.devices.element import Element
from conectsim.signal import Signal
class Device(Element):
'''Something we can handle.'''
def __init__(self, name=None, parent=None):
self.parent = parent
self.children = []
if self.pare... |
import os
import sys
import contextlib
import imp
from subprocess import call, STDOUT
CONFIG = 'okfile'
class OkException(Exception):
pass
########################################
# COMPATIBILITY
########################################
PY2 = sys.version_info[0] == 2
if PY2:
import urllib
else:
import urlli... |
'''This module contains convenience wrappers for ODE objects.'''
from __future__ import division
import collections
import numpy as np
import ode
BodyState = collections.namedtuple(
'BodyState', 'name position quaternion linear_velocity angular_velocity')
class Registrar(type):
'''A metaclass that builds ... |
import sys
n, m = map(int, sys.stdin.readline().split(' '))
es = {}
for i in range(n):
es[(i, i)] = 0
for i in range(m):
i, j, d = map(int, sys.stdin.readline().split(' '))
i -= 1
j -= 1
es[(i, j)] = d
es[(j, i)] = d
ls = map(int, sys.stdin.readline().split(' '))
gs = map(int, sys.stdin.re... |
"""Helpers for cli interaction"""
import sys
import math
from getpass import getpass
def ask_confirm(confirm_event):
print "\n" + confirm_event.get('content')
if confirm_event['cancellable']:
user_input = raw_input("\nContinue? [Y/n]")
return user_input.strip() == "" or user_input.lower().startswith("y")
else:... |
from django.db import models
from mptt.models import MPTTModel, TreeForeignKey
# Create your models here.
from django import forms
from suit.widgets import SuitDateWidget
from django.contrib.admin import widgets
from ore.models import *
# Create your models here.
class Fornitore(models.Model):
rag = models.TextFi... |
# !/usr/bin/python
# Copyright (C) 2015 Red Hat, All rights reserved.
# AUTHORS: Alex Collins <alcollin@redhat.com>
import sys
import json
import subprocess
import collections
from fnmatch import fnmatch as matches
from docker.utils import kwargs_from_env
import docker
import selinux
"""Atomic Utility Module"""
Ret... |
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.assets import Environment, Bundle
from flask.ext.login import LoginManager
from flask.ext.bcrypt import Bcrypt
import config
import logging
import sys
logging.basicConfig(level=logging.DEBUG)
app = Flask(__name__)
app.config.updat... |
# -*- coding: utf-8 -*-
import sys
import os
import pkgutil
from multiprocessing import RLock
from types import StringTypes
def get_root_path(import_name):
"""Returns the path to a package or cwd if that cannot be found. This
returns the path of a package or the folder that contains a module.
Not to be co... |
import json
from rhino import Mapper, get
# Our internal representation
report = {
'title': 'foo',
'author': 'Fred',
'date': '2015-01-09',
'tags': ['a', 'b', 'c'],
}
# Base class for our representations
class report_repr(object):
@classmethod
def serialize(cls, report):
obj = dict([(k... |
from django.contrib.auth.models import User
from django.views.generic import ListView, DetailView, View, CreateView, DeleteView
from django.views.generic.base import TemplateView
from django.db.models import Q
from django.core.urlresolvers import reverse, reverse_lazy
from django.contrib.auth.decorators import login_r... |
# Copyright (C) 2014 Claudio "nex" Guarnieri (@botherder), Accuvant, Inc. (bspengler@accuvant.com)
#
# 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 3 of the License, or
# (at you... |
from attack import Attack
from libmproxy import controller, proxy, platform
from threading import Thread
from zoption import Zoption
import util
class beef_hook(Attack):
""" Injects BeEF hooks into poisoned traffic. Requires libmproxy
and it's dependencies
"""
def __init__(self):
super(be... |
# coding=utf-8
# Author: Dennis Lutter <lad1337@gmail.com>
# Author: Jonathon Saine <thezoggy@gmail.com>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickRage.
#
# SickRage is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published ... |
"""DDNS without TSIG"""
# pylint: disable=invalid-name,line-too-long
import pytest
import misc
import srv_control
import srv_msg
@pytest.mark.v4
@pytest.mark.ddns
@pytest.mark.notsig
@pytest.mark.forward_reverse_add
def test_ddns4_notsig_forw_and_rev_add_success_Sflag():
misc.test_setup()
srv_control.conf... |
"""
Tests for impulse responses of time series
Author: Chad Fulton
License: Simplified-BSD
"""
import warnings
import numpy as np
import pandas as pd
from scipy.stats import ortho_group
import pytest
from numpy.testing import assert_, assert_allclose
from statsmodels.tools.sm_exceptions import EstimationWarning
from... |
from django import template as django_template
from django.template import defaulttags as django_defaulttags
from django.utils import encoding as django_encoding
# pylint: disable=invalid-name, too-few-public-methods
register = django_template.Library()
# pylint: disable=unused-argument
@register.tag
def... |
"""MDWeb SiteMap View Object."""
import datetime
import logging
import numbers
import os
import pytz
import time
from flask import (
current_app as app,
make_response,
render_template_string,
url_for,
)
from flask.views import View
#: Template string to use for the sitemap generation
# (is there a bet... |
from . import RequestHandler
class TypeCorrectorHandler(RequestHandler):
"""
The TypeCorrector class is meant to correct any inconsistencies in the types
of objects provided as query parameters.
Currently this only involves changing boolean values into strings,
as the API only accepts lower case ... |
#!/usr/bin/python
# this script compares the mmff94.expected and mmff94.actual files
# and outputs the differences
import os
import sys
import xml.dom.minidom
COLORS_ENABLED = False
class AtomResults:
def __init__(self, type, charge):
self.type = type
self.charge = charge
class MoleculeResults... |
import os
import getopt
from ajenti.ui import UI
from ajenti.utils import shell
from ajenti.com import *
class Rule:
states = ['NEW', 'ESTABLISHED', 'RELATED', 'INVALID']
flags = ['SYN', 'ACK', 'FIN', 'RST', 'URG', 'PSH', 'ALL', 'NONE']
def __init__(self, line='-A INPUT -j ACCEPT'):
self.reset()... |
<<<<<<< HEAD
<<<<<<< HEAD
#
# iso2022_jp.py: Python Unicode Codec for ISO2022_JP
#
# Written by Hye-Shik Chang <perky@FreeBSD.org>
#
import _codecs_iso2022, codecs
import _multibytecodec as mbc
codec = _codecs_iso2022.getcodec('iso2022_jp')
class Codec(codecs.Codec):
encode = codec.encode
decode = codec.deco... |
# Numerical algebra and methods
# Parcly Taxel / Jeremy Tan, 2018
# https://parclytaxel.tumblr.com
import numpy as np
cc_abscissas = [(np.cos(np.arange(1, 2 ** k, 2) / 2 ** k * np.pi) + 1) / 2 for k in range(2, 11)]
def ccw_generate(n):
"""Clenshaw-Curtis weights for n+1 samples where n is a power of two.
DFT-... |
from tests import setup_test_logging, BZTestCase, __dir__
from bzt.modules.selenium import SeleniumExecutor
from tests.mocks import EngineEmul
from bzt.utils import BetterDict
import os
import shutil
import yaml
import time
setup_test_logging()
class TestSeleniumJUnitRunner(BZTestCase):
"""
java:one/folder/... |
"""Mist Io Model
Here we define the schema of our data structure in an object oriented
way.
Simple, low level, helper functions can also be added to the
following classes. (eg user.get_num_mon_machines(), user.keys.unused()).
It is recommended that only pure functions (no side-effects) are used
as class methods.
How... |
#!/usr/bin/env python
# This file is part of tcollector.
# Copyright (C) 2010 The tcollector Authors.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, o... |
# -*- coding: utf-8 -*-
from lastuserapp import db
import lastuser_core.models as models
from .test_db import TestDatabaseFixture
class TestClient(TestDatabaseFixture):
def setUp(self):
super(TestClient, self).setUp()
self.user = models.User.query.filter_by(username=u"user1").first()
class Test... |
import os
from werkzeug.datastructures import FileStorage
from project.models import UploadedImage
from PIL import Image
from PIL.ExifTags import TAGS
IM_EXTENSIONS = frozenset(['.jpg', '.jpeg', '.gif', '.png'])
def remove_exif_orientation(file_path):
ext = os.path.splitext(file_path)[1].lower()
if ext == ... |
import numpy as np
import skimage.io
from scipy.ndimage import zoom
from skimage.transform import resize
try:
# Python3 will most likely not be able to load protobuf
from caffe.proto import caffe_pb2
except:
import sys
if sys.version_info >= (3, 0):
print("Failed to include caffe_pb2, things mi... |
import media
import fav_movies_web
# Instances of my favorite movies:
# Deadpool movie: movie title, sotryline, poster image and movie trailer
deadpool = media.Movie("Deadpool",
""" Wade Wilson (Ryan Reynolds) is a former Special Forces
operative who now works as a mercenary. His world comes
crashin... |
#!/usr/bin/env python
import glob
import numpy as np
try:
from setuptools import setup
have_setuptools = True
except ImportError:
from distutils.core import setup
have_setuptools = False
try:
from Cython.Build import cythonize
have_cython = True
except ImportError:
have_cython = False
kwa... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Script for generating mock EPrime test data
"""
import pandas as pd
import numpy as np
import io
pd.set_option('display.max_rows', 50)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)
from pypsych.config import Config
def generate_mock_... |
# -*- 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 'HistoricalProject'
db.create_table(u'projects_historicalp... |
#!/usr/bin/python3
import smbus
import time
import sys
import signal
import pygame
import cv2
import numpy
from picamera.array import PiRGBArray
from picamera import PiCamera
# for RPI version 2, we use bus No. 1
bus = smbus.SMBus(1)
# This is the target address we setup in the Arduino Program
address = 0x08
# sen... |
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... |
import datetime
from anthill.common import to_int
from anthill.common.social import APIError
from anthill.common.social.apis import FacebookAPI
from .. social import SocialAPI, SocialAuthenticationRequired
from .. token import NoSuchToken
class FacebookSocialAPI(SocialAPI, FacebookAPI):
def __init__(self, appl... |
#!/usr/bin/env python
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-
#
# NetProfile: IP addresses module
# © Copyright 2013-2014 Alex 'Unik' Unigovsky
#
# This file is part of NetProfile.
# NetProfile is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Publ... |
# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
#Para uso de la funcion HttpResponseRedirect (redireccionar paginas)
from django.http import HttpResponseRedirect
#para conexion con bases de datos externas
import sqlite3 as dbapi
from django.conf import settings
from django.contrib.auth.form... |
from pyhoofinance.defs import *
from pyhoofinance.quotedata import get_quote
from tradingtools.market_metrics.historic_change_and_stdv import s_and_p_historic
from tradingtools.market_metrics.market_cap_index_performance import market_cap_index_performance
from tradingtools.market_metrics.sector_performance import sec... |
"""
sonde.formats.generic
~~~~~~~~~~~~~~~~~
This module implements a generic format.
The files are in .csv format and must conform to the
following guidelines
comments and metadata at top of file in the format:
# name: value
a timezone field: (UTC-?, the data must all be in one UTC of... |
# 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 'Skill.level'
db.add_column('base_skill', 'level', self.gf('django.db.models.fields.Positiv... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
ScriptEdit.py
---------------------
Date : April 2013
Copyright : (C) 2013 by Alexander Bruy
Email : alexander dot bruy at gmail dot com
****************... |
"""Ansible integration test infrastructure."""
from __future__ import absolute_import, print_function
import contextlib
import json
import os
import shutil
import tempfile
from lib.target import (
analyze_integration_target_dependencies,
walk_integration_targets,
)
from lib.config import (
NetworkIntegr... |
"""Defines distributions from which to sample conditional data."""
import numpy as np
from pylearn2.format.target_format import OneHotFormatter
from pylearn2.space import VectorSpace
from pylearn2.utils import sharedX
import theano
import theano.tensor as T
from theano.tensor.shared_randomstreams import RandomStreams
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import codecs
from setuptools import setup
def read(fname):
file_path = os.path.join(os.path.dirname(__file__), fname)
return codecs.open(file_path, encoding='utf-8').read()
setup(
name='pytest-concurrent',
version='0.2.2',
author='James W... |
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='BlogPost',
fields=[
... |
################################################################################
# Copyright (c) 2015 IBM Corporation
#
# 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, in... |
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By:
# Maintained By:
from ggrc import db
from sqlalchemy import event
from sqlalchemy.sql.expression import text
from sqlalchemy.schema import DDL
fro... |
import argparse
import os
import pytest
from tests.test_config import load_tests_params, clean_dirs
from data_engine.prepare_data import build_dataset
from nmt_keras.training import train_model
from nmt_keras.apply_model import sample_ensemble, score_corpus
def test_ConditionalLSTM_add():
params = load_tests_para... |
from .selector import Selector
class MatchEngine(object):
pseudo_fns = {}
selector_class = Selector
def __init__(self):
self.register_pseudo('not', self.pseudo_not)
self.register_pseudo('has', self.pseudo_has)
def register_pseudo(self, name, fn):
self.pseudo_fns[name] = fn
... |
#!/usr/bin/env python
import argparse
import numpy as np
import math
import sys
import pdb
import bisect
ap = argparse.ArgumentParser(description="Print gap support from output of PrintGaps.py.")
ap.add_argument("table", help="Input tabular file")
ap.add_argument("out", help="Output file, stdout implies stdout")
ap.a... |
#!python3
"""
http://pka.engr.ccny.cuny.edu/index.php
Crawler for the pKa Database, retrieving all the pKa values for the calculated PDB proteins.
"""
import re
from io import StringIO
import requests
import pandas as pd
import numpy as np
from bs4 import BeautifulSoup
def ParseTable(soup, id):
"""F... |
from django.db import models
from configs.models import Config
from django.template import defaultfilters
from django.utils.timezone import localtime
class Transaction(models.Model):
"""Represent one transation"""
config = models.ForeignKey(Config)
reference = models.CharField(max_length=255)
ext... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.