code
stringlengths
1
199k
import sys import json import urllib2 def intersect(*args): """ return the intersection of lists """ if len(args) == 0: return [] s = set(args[0]) for arg in args[1:]: s = s & set(arg) return list(s) def union(*args): """ return the union of lists """ s = set() for arg in...
from django.db import models class Plan(models.Model): pass
""" :Resource: ========== : This is the managed resource between processes. Resources such as queues, locks and data are housed here to allow for synchronization to occur. : :copyright: (c) 9/30/2015 by gammaRay. :license: BSD, see LICENSE for more details. Author: gammaR...
import sys print(("Running on python version %s" % sys.version )) def get_first_name(full_name): return full_name.split(" ")[0] fallback_name = { "first_name": "UserFirstName", "last_name": "UserLastName" } raw_name = input("Please enter your name: ") first_name = get_first_name(raw_name) if not first_name:...
""" Copyright (C) 2015 Stuart W.D Grieve 2015 Developer can be contacted by s.grieve _at_ ed.ac.uk This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) ...
import os import sys import time import logging import errno import xml.dom.minidom as DOM try: import hashlib except ImportError: import md5 as hashlib try: import xml.etree.ElementTree as ET except ImportError: import elementtree.ElementTree as ET from icbuild.utils import fileutils def _parse_isotime...
""" Tags and set of it. Used by optimization to keep track of the current state of optimization, these tags trigger the execution of optimization steps, which in turn may emit these tags to execute other steps. """ allowed_tags = ( # New code means new statements. # Could be a new module, or an inlined exec sta...
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('asset', '0002_auto_20160501_0012'), ] operations = [ migrations.RenameField( model_name='contract', ...
""" stores snapshots of uncommitted changes Configs:: """ from . import commands cmdtable = commands.cmdtable
""" Plotting facility for astronomy. """ import matplotlib as mpl from matplotlib import pyplot as plt from .. import SlipyError from ..Framework.Options import Options, OptionsError from . import Fits, Spectrum plt.ion() class PlotError(SlipyError): """ Exception specific to Plot module. """ pass class SPlot: ...
import subprocess from bejond.basic.const import HEXO_POST_HEAD from bejond.basic.output.write_file import write_head_up_to_post with open('test.txt', 'a') as file: str = HEXO_POST_HEAD.format(a='2020', b='2020-01-02') file.write(str) # 经验:需要是指定string调用format,不可用连接"+",只会对"+"后面的string格式化 write_head_up_to_pos...
from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0008_alter_user_username_max_length'), ] operations = [ migr...
from __future__ import absolute_import from pychess.compat import PY3 from pychess.Utils.const import * from pychess.Utils.repr import reprColor from .ldata import * from .attack import isAttacked from .bitboard import * from .PolyglotHash import * STRICT_FEN = False class LBoard: ini_kings = (E1, E8) ini_rooks...
import werkzeug from odoo import http from odoo.http import request class LinkTracker(http.Controller): @http.route('/r/<string:code>', type='http', auth='none', website=True) def full_url_redirect(self, code, **post): country_code = request.session.geoip and request.session.geoip.get('country_code') or...
import sys import linecache sys.path.append('../heuristics/') from utils import * from heu import * from checker import * from const import * from collections import OrderedDict from operator import * from heu import * def initTmpStructures(lMachines, lItems, cTime): b2tasks = {} m2b = {} b2capa...
""" pyReefCore Model main entry file. """ import time import numpy as np from pyReefCore import (preProc, xmlParser, enviForce, coralGLV, coreData, modelPlot) import cProfile import os import pstats import StringIO class Model(object): """State object for the pyReef model.""" def __init__(self): """ ...
from django.conf import settings from django.contrib.aderit.access_account.views import \ (SignupView as AccessAccountSignupView) from django.contrib.aderit.generic_utils.views import \ (GenericUtilView, GenericProtectedView) from django.utils.translation import ugettext_lazy as _ from django.utils.log import g...
from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django.http import Http404 from .utils import knuth_decode class KnuthIdMixin(object): knuth_id_url_kwarg = 'oid' def get_object(self, queryset=None): if queryset is None: queryset = self.get_querys...
class Singleton: ''' Singleton decorator for classes ''' def __init__(self, cls): self.cls = cls self.instance = None def __call__(self, *args, **kwargs): if self.instance is None: self.instance = self.cls(*args, **kwargs) return self.instance class RunCon...
import asyncio import re from datetime import datetime as dt import discord from discord.ext import commands, vbu class MeowChat(vbu.Cog): VALID_KEYWORDS = ( "mew", "meow", "nya", "uwu", "owo", "x3", ":3", ";3", "rawr", "purr", ...
{ 'name': "Customer Invoice Line Refund", 'summary': """ """, 'author': "Pambudi Satria", 'website': "https://github.com/pambudisatria", # Categories can be used to filter modules in modules listing # Check https://github.com/odoo/odoo/blob/master/openerp/addons/base/module/module_data.xml ...
''' features.py contains a decorator to register features to a global dict, for use in other modules. It also contains the standard features, though others can be added ''' from functools import reduce from function_registry import FunctionRegistry all_features = FunctionRegistry() def register_feature(name=None): ...
import logging from scap.Model import Model logger = logging.getLogger(__name__) class RegistryBehaviors(Model): MODEL_MAP = { 'attributes': { 'max_depth': {'type': 'Integer', 'default': -1}, 'recurse_direction': {'enum': ['none', 'up', 'down'], 'default': 'none'}, 'windo...
import os try: from ConfigParser import ConfigParser as ConfigParser except: from configparser import ConfigParser as ConfigParser def goglib_tags_get(game_name, tags_file): parser = ConfigParser() parser.read(tags_file) if 'goglib tags' in parser.sections(): if game_name in parser.options('...
import math import random PRIME_INDEX_1 = [ 49193, 11887, 23819, 93983, 28283, 87179, 74933, 82561, 29741, 98453, 72719, 48193, 66883, 95071, 12841, 89603, 49261, 52529, 57697, 70321, 54617, 49363, 41233, 39883, 35393, ...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('database', '0005_field_changes'), ] operations = [ migrations.AddField( model_name='userprofile', name='dataID', fiel...
from Content import * from Display import * from KeyProcessor import * class TextEntry( DisplayGenerator ): kBlock = '_' # Character to show at the next position # # Characters to cycle through for a given digit (eg. pressing '2' three # times will leave a 'C' showing) # kDigits =...
"""Handle scheduling of polling jobs.""" import logging import datetime import time from operator import itemgetter from collections import defaultdict from random import randint from math import ceil from twisted.python.failure import Failure from twisted.internet import task, reactor from twisted.internet.defer impor...
""" A platform independent file lock that supports the with-statement. """ import time import atexit import os import threading try: import warnings except ImportError: warnings = None try: import msvcrt except ImportError: msvcrt = None try: import fcntl except ImportError: fcntl = None try: ...
import xbmcaddon import os try: addonPath = xbmcaddon.Addon(id = 'plugin.video.hubmaintenance').getAddonInfo('path') name = 'Maintenance' script = os.path.join(addonPath, 'maintenance.py') version = 1 args = str(version) cmd = 'AlarmClock(%s,RunScript(%s,%s),%d,True)' % (nam...
import os import ray import ray.tune as tune import torch from nupic.research.frameworks.dynamic_sparse.common.loggers import DEFAULT_LOGGERS from nupic.research.frameworks.dynamic_sparse.common.utils import ( Trainable, download_dataset, ) exp_config = dict( device="cuda", # dataset related dataset...
"""Tests for utility functions used in CSV imports. Copyright (C) 2014 A. Samuel Pottinger ("Sam Pottinger", gleap.org) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License,...
from keystoneauth1 import exceptions from keystoneauth1 import identity from keystoneauth1 import loading def _add_common_identity_options(options): options.extend([ loading.Opt('user-id', help='User ID'), loading.Opt('username', help='Username', deprecated=[l...
def cmd_test(raw_in): answer = ['||', 'Passed!', 'I\'m alive!', '👍🏻', '👌🏻'] msg = random.choice(answer) send_msg(raw_in, msg) commands = [['test', cmd_test, False, 'raw', 'Check bot\'s activity.']]
import math from PyQt5.QtCore import (pyqtSignal, QBasicTimer, QObject, QPoint, QPointF, QRect, QSize, QStandardPaths, Qt, QUrl) from PyQt5.QtGui import (QColor, QDesktopServices, QImage, QPainter, QPainterPath, QPixmap, QRadialGradient) from PyQt5.QtWidgets import QAction, QApplication, QMainWindow, QW...
get_ipython().system('pip install -I "phoebe>=2.1,<2.2"') get_ipython().run_line_magic('matplotlib', 'inline') import phoebe from phoebe import u # units import numpy as np import matplotlib.pyplot as plt logger = phoebe.logger() b = phoebe.default_binary() b['q'] = 0.7 b['requiv@primary'] = 1.0 b['requiv@secondary'] =...
import sys import unittest import libsbml class TestRateRule(unittest.TestCase): global RR RR = None def setUp(self): self.RR = libsbml.RateRule(1,2) if (self.RR == None): pass pass def tearDown(self): _dummyList = [ self.RR ]; _dummyList[:] = []; del _dummyList pass def test_RateRul...
import logging import datetime import os import shutil from mimetypes import guess_type import re import zipfile from paste.fileapp import FileApp from pylons import config from pylons import request, response, session, app_globals, tmpl_context as c from pylons import url from pylons.controllers.util import abort, for...
""" tmdbsimple ~~~~~~~~~~ *tmdbsimple* is a wrapper, written in Python, for The Movie Database (TMDb) API v3. By calling the functions available in *tmdbsimple* you can simplify your code and easily access a vast amount of movie, tv, and cast data. To find out more about The Movie Database API, check out the overview...
"""Test of neurosynth module.""" import pytest from .. import neurosynth @pytest.fixture def neurosynth_database(): """Return fixture for handle to neurosynth database.""" nd = neurosynth.NeurosynthDatabase() return nd @pytest.fixture def neurosynth_database_frame(neurosynth_database): """Return fixture...
""" Legend encapsulates a graphical plot legend drawing tool The DIRAC Graphs package is derived from the GraphTool plotting package of the CMS/Phedex Project by ... <to be added> """ from __future__ import print_function from __future__ import absolute_import from __future__ import division __RCSID__ = "$Id$" ...
class Solution(object): def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ if not digits: return [] mapping = { "2": 'abc', "3": 'def', "4": 'ghi', "5": 'jkl', "6": ...
from __future__ import unicode_literals import io import os import mock from six import text_type from flask import current_app from flask import make_response from data.fixtures.test_data import TestFixture from compair.tests.test_compair import ComPAIRAPITestCase from compair.core import db from compair.models import...
from urllib.parse import urljoin from django.conf import settings from django.template.loader import render_to_string from django.utils.translation import ugettext_lazy as _ from . import const from notifications.notifications import UserMessage from common.utils import get_logger from .models import Ticket logger = ge...
""" Django settings for day12bbs project. Generated by 'django-admin startproject' using Django 1.10. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os BASE...
" Ninja Web Util " __version__ = ' 0.8 ' __license__ = ' GPL ' __author__ = ' juancarlospaco ' __email__ = ' juancarlospaco@ubuntu.com ' __url__ = '' __date__ = ' 15/08/2013 ' __prj__ = ' webutil ' __docformat__ = 'html' __source__ = '' __full_licence__ = '' from os import path from sip import setapi try: from urll...
import unittest """883. Projection Area of 3D Shapes https://leetcode.com/problems/projection-area-of-3d-shapes/description/ On a `N * N` grid, we place some `1 * 1 * 1 `cubes that are axis-aligned with the x, y, and z axes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of grid cell `(i, j)`...
happy=False food='YUMMY' def smile(kind): #takes in a string '''documentation goes here''' ''' draws a smile and rates happyness of the user''' #initialize variables here! happyness_factor=0 #0-10 10 is max :) global happy #code here if kind=="happy": print (':)') happyness_factor=10 happy=True elif kind=...
from .colorentry import ColorPropertyEditor from .tkvarentry import TkVarPropertyEditor from .imageentry import ImagePropertyEditor from .propertyeditor import EntryPropertyEditor, SpinboxPropertyEditor from .propertyeditor import TextPropertyEditor, ChoicePropertyEditor from .propertyeditor import CheckbuttonPropertyE...
main(): none if __name__ == "__main__": main();
import its.device import its.caps import its.objects import its.image import os.path import pylab import matplotlib import matplotlib.pyplot def main(): """Verify that the DNG raw model parameters are correct. """ NAME = os.path.basename(__file__).split(".")[0] NUM_STEPS = 4 # Pass if the difference...
import os import stat import ent import grp import pwd import config import signal import subprocess import time import ldap import pytest import ds_openldap import ldap_ent import sssd_ldb import sssd_id from util import unindent LDAP_BASE_DN = "dc=example,dc=com" SSSD_DOMAIN = "LDAP" SCHEMA_RFC2307 = "rfc2307" SCHEMA...
import datetime import hashlib import hmac import requests # pip install requests import xmltodict from bs4 import BeautifulSoup try: from urllib import quote, urlencode except ImportError: from urllib.parse import quote, urlencode URLINFO_RESPONSE_GROUPS = ",".join( ["RelatedLinks", "Categories", "Rank", ...
import re import collections import sys import os import glob def fail(args): print(args) sys.exit(1) def main(): files = [f for f in glob.glob('gen/enum/*')] pattern = re.compile(r'\s*(\w+)\s*(?:=\s*(\d+))?\s*(?:,\s*"([^"]*)")?\s*') tab = " " output_dir = "src/enums/" do_not_modify = "/*...
"""A helper to keep the jvplot docstrings consistent.""" import argparse import ast import importlib import os import pkgutil import re _parser = argparse.ArgumentParser() _parser.add_argument("-o", "--out", default="out", help="directory to store output in") _args = _parser.parse_args() _DOCSTRING...
__all__ = ['LibraryBase', ] from gingerprawn.api.webop import automated as auto class LibraryBase(object): def __init__(self, baseurl, cache=None): self._baseurl = baseurl self._bot = auto.Automator(baseurl) self._lastop = '__init__' LibraryBase.init_cache(self, cache) ...
import math def sine(angle): '''sine(x) -> value Return the sine of x in radians.''' return math.sin(angle) def cosine(angle): '''cosine(x) -> value Return the cosine of x in radians.''' return math.cos(angle) def square_rt(num1): '''squre_rt(x) -> value Return the square root of x.''' return math.sqrt(num1) def ...
from libmain import * def generateMultByValTruthTable(val): result = [] multiplier = hex2bin(val) for i in range(2**octetSize): result.append(galoisMultiplication(multiplier, int2bin(i))) return result def mixColumns(): equa = [] result = ['' for i in range(blockSize)] tt2 = generateMultByValTruthTable('02') ...
ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'network'} DOCUMENTATION = """ --- module: ios_logging version_added: "2.4" author: "Trishna Guha (@trishnaguha)" short_description: Manage logging on network devices description: - This modul...
''' Graphics tests ============== Testing the simple vertex instructions ''' import unittest from kivy.tests.common import GraphicUnitTest class VertexInstructionTest(GraphicUnitTest): def test_circle(self): from kivy.uix.widget import Widget from kivy.graphics import Ellipse, Color r = self...
"""Tasks to check if the incoming record already exist.""" from __future__ import absolute_import, division, print_function import datetime from functools import wraps from flask import current_app from invenio_db import db from invenio_workflows import workflow_object_class from inspire_matcher.api import match from i...
""" Some helper classes """ class reading(): """Simple wrapper for the data of a reading from the p1 interface""" def __init__ (self): self.timestamp = None self.t1 = 0 self.t2 = 0 self.consumption = 0 def isComplete(self): return self.timestamp != None \ ...
""" @author: kevinhikali @email: hmingwei@gmail.com """ from keras.models import Sequential from keras.layers.core import Dense, Activation from keras.utils.visualize_util import plot from visualize_plots import figures from keras.models import load_model import matplotlib.pyplot as plt import numpy as np x_train = np....
import os, sys, glob from Bio import SeqIO, Entrez import argparse def main(): opts=argparse.ArgumentParser(sys.argv[0], description="fetch genbank files given accessions", prefix_chars="-", add_help=True, epilog="Written by Chrispin Chaguza, MLW, 2014") opts.add_argument("-a",action="store",nargs...
import matplotlib matplotlib.backend = 'Qt4Agg' import matplotlib.pyplot as plt import numpy as np np.set_printoptions(precision=4) import os import sys import threading import time from collections import deque import agents import goals import q_networks ARM_LENGTH_1 = 12.0 ARM_LENGTH_2 = 18.0 ANGULAR_ARM_VELOCITY = ...
from tasty.types.driver import TestDriver __params__ = {'la': 32, 'lb': 32} driver = TestDriver() def protocol(client, server, params): la = params['la'] lb = params['lb'] client.a = Unsigned(bitlen=la).input(src=driver, desc='a') client.b = Unsigned(bitlen=lb).input(src=driver, desc='b') client.ga ...
from django.shortcuts import get_object_or_404 from django.utils.translation import ugettext_lazy as _ from exercise.models import LearningObject, CourseChapter, \ BaseExercise, LTIExercise, StaticExercise, ExerciseWithAttachment from course.models import LearningObjectCategory, CourseModule from .exercise_forms im...
import boto3 from infra_data import profiles, regions def lb_report(pth): for account in profiles.profile_list(): print ('Current account: ' + account) for region in regions.region_list(): print ('Current region: ' + region) session = boto3.Session(profile_name=account) ...
xxx = [1, 2, 4, 8, 16, 32] import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import FuncFormatter STR_CONCURRENT_REQS_PER_SERVER = "Concurrent reqs/server" STR_THROUGHPUT = "Throughput" STR_NUMBER_OF_SERVERS = "Number of servers" STR_THROUGHPUT_NEW_ORDER = "Throughput (N...
from __future__ import unicode_literals from frappe import _ def get_data(): return [ { "label": _("Purchasing"), "icon": "fa fa-star", "items": [ { "type": "doctype", "name": "Purchase Order", "onboard": 1, "dependencies": ["Item", "Supplier"], "description": _("Purchase Orders...
""" AM_ifSensorsOK_release Assertion monitor For use in Human-Robot Interaction simulator. Created by David Western, July 2015. Implements assertion: if humanOk and sensorsOk and contact_robot_hand_and_object ==1 then assert contact_robot_hand_and_object == 0 OR: if human and sensors are OK and robot is grabbing piece,...
import RPi.GPIO as GPIO import time import sys GPIO.setmode(GPIO.BCM) enable_pin = 18 coil_A_1_pin = 4 coil_A_2_pin = 17 coil_B_1_pin = 23 coil_B_2_pin = 24 GPIO.setup(enable_pin, GPIO.OUT) GPIO.setup(coil_A_1_pin, GPIO.OUT) GPIO.setup(coil_A_2_pin, GPIO.OUT) GPIO.setup(coil_B_1_pin, GPIO.OUT) GPIO.setup(coil_B_2_pin, ...
"""Interface to Analog to Digital Converters.""" import time import spidev class AnalogToDigitalConverter(): """Class to represent MCP3004 analog to digital Converter""" # Voltage dividers 1kOhm/1kOhm (channel 0-2) - 22kOhm/10kOhm(channel 3) _facCh012 = 2 _facCh3 = 3.195 # Bytes for building read co...
import os import sys if len(sys.argv) > 1 and '--no-sugar' == sys.argv[1]: # Remove the argument from the stack so we don't cause problems # for distutils sys.argv.pop(1) import glob, os.path, string from distutils.core import setup DATA_FILES = [ ('icons', glob.glob('icons/*')), ...
import numpy as np import pandas as pd import statsmodels.api as sm from tqdm import tqdm from ...common import LOCALIZER from ...common.math_helpers import exponential_decay_weight from ...data import wind from ..entities import get_estimation_universe from .base import Descriptor, Factor @Descriptor.register("Beta") ...
from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP from Crypto.Random import get_random_bytes phrase = 'totallyRandomPassphrase' message = open('message.txt', 'rb').readline() key = RSA.generate(4096) encrypted_key = key.exportKey(passphrase=phrase, pkcs=8, protection='scryptAndAES256-CBC') with open...
import os import re import sys import random import argparse def CheckFile(FileName,FileType,Regular = ''): FileName,FileExt = os.path.splitext(FileName) if FileExt[1:].lower() not in FileType: return False if Regular != '': MatchFile = re.match(Regular,FileName) if MatchFile is not None: return False retu...
""" This file is part of BOMtools. BOMtools 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. BOMTools is distributed i...
import logging import gi import glob import os import sh import threading from typing import TYPE_CHECKING, Callable from tailsgreeter.ui import _ from tailsgreeter.config import settings_dir, persistent_settings_dir, unsafe_browser_setting_filename gi.require_version('GLib', '2.0') gi.require_version('Gtk', '3.0') fro...
import Options, Utils, os, Logs, samba_utils, sys, Task, fnmatch, re, Build from TaskGen import feature, before, after abi_type_maps = { '_Bool' : 'bool', 'struct __va_list_tag *' : 'va_list' } version_key = lambda x: map(int, x.split(".")) def normalise_signature(sig): '''normalise a signature from gdb...
from tkinter import * import license import about root = Tk() #Tk initialize root.title("Taller GIT") root.minsize(500,500) root.maxsize(500,500) welcome_lbl = Label(root, text = "Bienvenidos al taller de GIT", font = ("calibri","18"), fg = "#000b98", width= 28, height = 1) welcome_lbl.place(x = 20, y = 20) def fetchLi...
from paraview.simple import * import paraview assert (paraview.compatibility.GetVersion().GetVersion() == None),\ "ParaView modules should never force backwords compatibility to any version" assert ((paraview.compatibility.GetVersion() < 4.1) == False),\ "less-than test should always fail when version is not sp...
import os from GTG import _ class GnomeConfig: current_rep = os.path.dirname(os.path.abspath(__file__)) GLADE_FILE = os.path.join(current_rep, "pluginmanager.glade") CANLOAD = _("Everything necessary to run this plugin is available.") CANNOTLOAD = _("The plugin can not be loaded") miss1 = _("Some py...
import re import string from lib.parser.getcc import * from lib.parser.getmail import * from lib.parser.getip import * from lib.parser.getssn import * class parse: def __init__(self,content): self.content = content def clean(self): """Clean HTML Response""" self.content = re.sub('<em>','',self.content) self.c...
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('rules', '0077_auto_20191002_0820'), ] operations = [ migrations.AlterField( model_name='ruleprocessingfilter', name='action', field=models.CharField(max_leng...
""" latex.preview """ from ..file import File from ..tools import Tool, Job, ToolRunner from ..tools.postprocess import RubberPostProcessor, GenericPostProcessor from ..issues import MockStructuredIssueHandler from environment import Environment from gi.repository import GdkPixbuf class ImageToolGenerator(object): ...
common_globals = {} execfile_('common.py', common_globals) MODELS = [ u'VVX300', u'VVX310', u'VVX400', u'VVX410', u'VVX500', u'VVX600', u'VVX1500', ] VERSION = u'4.1.7' class PolycomPlugin(common_globals['BasePolycomPlugin']): IS_PLUGIN = True pg_associator = common_globals['BasePoly...
from .Localhost import Localhost
from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse from django.template import RequestContext,Template from django.template.loader import get_template from django.shortcuts import render_to_response from datetime import datetime, timedelta from WeatherMappingStudio.WMI.models impo...
import sys sys.path.insert(0,"/home/ahobbs/venv_dir/BallotPath/api") from app import app as application application.run(host='0.0.0.0', port=6112, debug=True);
for j in range(1, len(arr)): key = arr[j] i = j - 1 while i > 0 and arr[i] > key: arr[i + 1] = arr[i] i = i - 1 arr[i + 1] = key
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 model 'UserProfile' db.create_table('findeco_userprofile', ( ('id', self.gf('django.db.models.fields.AutoField')(p...
import urllib,urllib2 import xml.etree.ElementTree as ET import xml.etree as etree def get_woeid(lat,lon): url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.placefinder%20where%20text%3D%22"+repr(lat)+"%2C"+repr(lon)+"%22%20and%20gflags%3D%22R%22" result = urllib2.urlopen(url) tree =...
import urllib import urlparse import json import logging import datetime from tornado import gen from tornado.httpclient import AsyncHTTPClient, HTTPResponse from motherbrain.com.messages import MBMessage fetch_addr = 'http://127.0.0.1/__fetch' GO_ACTIONS = {'fetch_url_data': ['http://127.0.0.1:5100', 'GoFetchUrlDataH...
""" Compute and plot the leading EOF of geopotential height on the 500 hPa pressure surface over the European/Atlantic sector during winter time. This example uses the metadata-retaining xarray interface. Additional requirements for this example: * xarray (http://xarray.pydata.org) * matplotlib (http://matplotl...
import json import io import os try: to_unicode = unicode except NameError: to_unicode = str from .tools import CloudTools from ..pathsandnames import PathsAndNames import uuid class CreateJSON(): def __init__(self): """ Create a subfolder in s3 bucket Creates a JSON in local...
from __future__ import (unicode_literals, division, absolute_import, print_function) """ ---------------------------- NOTE: The "ShowProgressDialog" and ResultsDialog classes given below were taken from the file "dialogs.py" which was part of the Calibre plugin "diaps_toolbag" authored by DiapDe...
from __future__ import unicode_literals from django.db import models from cadastro.models import AtendimentoAbs class Ano(models.Model): _ano = models.CharField(verbose_name='Ano',max_length=4) def get_absolute_url(self): return reverse('ano_detail', kwargs={'pk': self.pk}) def _get_ano(self): return self...
file = open("/Users/quietchallenger/DEV/2. Turner Branches/input.txt", "r") data = file.readlines() for x in data: str(x) host = x.split("/") ip = host[0] netmask = host[1] print (ip) print(netmask)
import unittest import mock from haiku_cnf import search_provides, read_haikuports, firstrun class TestPkgmanHooks(unittest.TestCase): @mock.patch('haiku_cnf.check_output') def test_search_provides(self, patched_check_output): pkgman_out = """Status Name Description -----------------------------...